Creates a new KVShardMapper instance
Cloudflare KV namespace
Configuration options including hashing preference
Appends a new shard to the list of known shards if it's not already present. This operation is idempotent - adding the same shard multiple times has no effect.
The shard binding name to add
Promise that resolves when the shard is added
Adds additional lookup keys to an existing shard mapping. This allows you to query the same shard mapping using multiple identifiers (e.g., username, email, id).
An existing key in the mapping
New keys to add for lookup
Promise that resolves when the additional keys are added
Deletes ALL shard mappings from KV storage. This is a destructive operation that removes all primary key assignments. After this operation, all keys will be treated as new and may be assigned to different shards.
DANGER: This operation is irreversible and will cause data routing issues if used in production. Only use during development, testing, or complete system resets.
Promise that resolves when all mappings are deleted
Completely removes the shard assignment for a primary key from KV storage. This is typically used when data is being permanently deleted or when cleaning up orphaned mappings. Handles both single-key and multi-key mappings.
WARNING: After deletion, the primary key will be treated as new and may be assigned to a different shard on next access.
The primary key mapping to remove
Promise that resolves when the mapping is deleted
Gets all lookup keys associated with a shard mapping. This is useful for understanding what keys resolve to the same shard.
Any key in the mapping
Promise resolving to array of all keys in the mapping
Scans all shard mappings to find primary keys assigned to the specified shard. This operation requires reading all mappings and can be expensive for large datasets. Consider caching results or using getShardKeyCounts() for statistics.
The shard binding name to search for
Promise resolving to array of primary keys assigned to the shard
Retrieves the list of all shard binding names that have been registered with the system. This is maintained separately from the individual mappings for efficient shard discovery.
Promise resolving to array of shard binding names
Scans all shard mappings to count how many primary keys are assigned to each shard. Returns a mapping of shard names to their key counts. This is useful for load balancing and monitoring shard utilization.
Performance Note: This operation scans all mappings and can be expensive for large datasets. Consider implementing caching for frequently accessed statistics.
Promise resolving to object mapping shard names to key counts
const counts = await mapper.getShardKeyCounts();
console.log('Shard utilization:', counts);
// Output: { 'db-east': 1247, 'db-west': 982, 'db-central': 1156 }
// Find the least loaded shard
const leastLoaded = Object.entries(counts)
.sort(([,a], [,b]) => a - b)[0][0];
console.log('Least loaded shard:', leastLoaded);
Retrieves the shard assignment for a given primary key from KV storage. Returns null if no mapping exists, indicating the key has not been assigned to any shard yet. Supports both single-key and multi-key lookups.
The primary key to look up (will be hashed if hashing is enabled)
Promise resolving to the shard mapping or null if not found
Hashes a key using SHA-256 if hashing is enabled
The key to hash
The hashed key or original key if hashing is disabled
Replaces the entire list of known shards with a new list. This is typically used during system initialization or when shards are added/removed in bulk.
Array of shard binding names to store
Promise that resolves when the list is updated
Creates a new shard assignment for a primary key. This is typically used when a new primary key is first encountered and needs to be assigned to a shard. Sets both created and updated timestamps to the current time.
Note: This will overwrite any existing mapping for the same key. Use updateShardMapping() if you want to preserve creation timestamp.
The primary key to map
The shard binding name to assign
Optional array of additional lookup keys for the same mapping
Promise that resolves when the mapping is stored
Changes the shard assignment for a primary key that already has a mapping. Preserves the original creation timestamp while updating the modified timestamp. Throws an error if no existing mapping is found.
This is typically used during shard rebalancing or data migration operations. Works with both single-key and multi-key mappings.
The primary key to update
The new shard binding name to assign
Promise that resolves when the mapping is updated
The KVShardMapper class provides a persistent storage layer for mapping primary keys to their assigned D1 database shards. It uses Cloudflare KV for global, eventually consistent storage with low latency reads.
Features:
Example