Skip to main content

Key-Range Sharding

By default, Kahuna decides which partition stores a key by hashing the key's key space (the part before the last /). This spreads unrelated data evenly, and you don't need to plan. However, each key space is then on exactly one partition. For a large key space such as users/... or orders/2026/..., that one partition then stores all of its data and takes all of its writes. The key space can't be split.

Key-range sharding removes that limit for the key spaces you choose. Keys remain in sorted order, and the key space is cut into contiguous ranges that can be on different partitions. Kahuna splits a range when it grows too large or too busy. Use key-range sharding in these cases.

  • A key space may outgrow one partition, in data size or in write rate.
  • You read keys in order or by range, such as all orders between two IDs, and want those reads to touch only the ranges they overlap.
  • Transactions on different parts of a large key space should not contend with each other.

Keep the default hash routing for small key spaces and caches, and for data that you access only by exact key. If you only need a small group of related keys on one partition, buckets are simpler.

Key Spaces​

A key space is the same boundary that defines a bucket: the part of a key before the last /. For example, orders/2026/0001 belongs to key space orders/2026.

Kahuna decides the routing mode for each key space. It doesn't decide it for individual keys. This means that hash-routed and range-routed key spaces can coexist in the same cluster.

Hash Routing​

Hash routing is the default because it spreads unrelated workloads across partitions with very little planning.

Hash routing works well for these key spaces.

  • caches
  • service configuration
  • metadata that is read and written by many nodes
  • key spaces where locality does not matter

In hash mode, all keys in the same key space route to the same partition because Kahuna hashes the key space boundary. It doesn't hash the full leaf key. This makes get by bucket possible for prefixes such as services/.

Hash routing can also co-locate related key spaces with a placement group. Rows and their secondary indexes stored under separate prefixes then land on the same partition.

Key-Range Routing​

Key-range routing is for key spaces where adjacent keys should stay adjacent.

Kahuna stores a set of range descriptors for that key space. It doesn't hash the key space to one partition forever. Each descriptor maps a contiguous half-open interval of keys to one partition.

[-inf, users/0250) -> partition A
[users/0250, users/0700) -> partition B
[users/0700, +inf) -> partition C

This gives Kahuna three things that hash routing can't provide.

  • ordered locality for keys such as users/0001, users/0002, users/0003
  • range-scoped reads that only touch the ranges they overlap
  • range-scoped locking and contention, which prevents unrelated slices of a large key space from blocking each other

When a slice grows hot or large, Kahuna can split it into two smaller slices and move the upper half to a different partition while preserving key order. This is the model used by systems such as Spanner and CockroachDB.

Splits, Merges, and Fencing​

When a key-range space grows, Kahuna can split one range into two smaller ranges. When two neighboring ranges become too small, Kahuna can merge them.

For example, splitting the range [users/0250, users/0700) at users/0500 leaves the lower half on its partition and gives the upper half to a new partition.

Automatic splitting has two independent triggers. The count trigger splits a range after it reaches a configured number of keys. The opt-in load trigger splits a range whose persistent write rate and write-ahead log (WAL) backlog remain high, even when the range contains relatively few keys. Load-based splitting selects a split key from observed write distribution and requires leader balancing to relocate work across nodes.

For configuration and limitations, see Load-Based Range Splitting.

Range moves are protected by a generation fence. The client or coordinator routes each write with the range descriptor generation it knows. If the range split or moved before the write is replicated, the write is rejected with MustRetry, and the caller resolves the key again and retries against the new range owner.

This prevents writes from silently landing on stale partitions after a split or merge.

Splits and merges also pause writes to the moving key interval during the copy and cutover window. Kahuna combines a range lock on the source partition with a replicated descriptor deadline. This means that writes that race with movement get a retryable refusal. --range-move-quiesce-ttl bounds this write fence (default 30 seconds, minimum 1 second). If a move uses up its quiesce window, cutover fails with QuiesceExpired. The move must retry. It must not route away from writes admitted after the fence expired.

A write racing a split or merge can receive a retryable error. Before settling transactions and completing the copy, the mover asks the source partition's leader to confirm quorum leadership, apply the quiescing range map, and drain previously dispatched writes. Failure to confirm within five seconds returns QuiesceFailed and leaves cutover for a retry. During a mixed-version upgrade, an older source that lacks this confirmation RPC uses the legacy path with a warning; a later leader change before that leader applies the map also remains a race window. Do not treat the quiesce check as an unconditional guarantee across those cases.

Committed data and transaction records are replicated to the destination before cutover, and so are prepared write intents. The partition IDs that a merge retires aren't reused. The mechanics are in Internals: Handoff and Retirement.

Moves also carry revisions at registered snapshot holds, including deletions that occur between copy passes. Other old historical timestamps can return MustRetry after cutover; a merge bounds history across the entire merged range. See history across replica and range moves. A key's selected history must fit in one replication message; a very large value or many held revisions can make a move attempt fail before cutover.

Partition 0​

The range-descriptor map is replicated on partition 0 (the system partition) so that all nodes can resolve key-range ownership consistently.

The system partition has these roles.

  • partition 0 is the system partition
  • the range map is committed on partition 0 beside the cluster partition-map coordinator
  • data ranges live on data partitions starting at partition 1

The descriptor map is therefore durable cluster state. It isn't a local cache.

Choosing Between Buckets and Key Ranges​

  • Buckets are a single-partition grouping technique. They are ideal when a small or moderate prefix such as services/ should stay together on one partition and be read with get by bucket.
  • Key ranges are a scalable locality technique. They are ideal when keys must stay ordered, the key space may grow beyond one partition, and you need range-scoped locality and future splits.

These key spaces often need key-range routing.

  • users/0001, users/0002, users/0003
  • orders/2026/000001, orders/2026/000002
  • time-ordered event or ledger keys

get by bucket is a single-partition operation. It remains the right tool for hash-routed bucket prefixes and for small unsplit key spaces.

Once a key-range space has actually split, treat it as a multi-range ordered space, and use ordered range reads. Don't plan to fetch the complete bucket from one partition. The cluster serves the data consistently, but the request can span multiple ranges.

Split Capacity Limits​

Each split creates another data partition, with separate replication and WAL work. Use --raft-max-partitions to cap the cluster-wide count. Use --range-max-ranges-per-key-space to prevent one hot key space from consuming all available slots. Both default to 0 (unbounded). A positive cluster bound must be at least --initial-cluster-partitions; configure it identically on all nodes, because the system-partition leader enforces it.

At either bound, a manual split returns PartitionLimitReached, determinate: true (HTTP 409), with a reason identifying the bound. No destination partition is created and no descriptor changes. Merge or remove partitions, or raise the relevant bound, before retrying. Initial registration can share an existing data partition; the range quota is checked when splitting.

Automatic count- and load-based splitting also stop at these bounds. After a cluster-limit refusal, the trigger pauses until the committed partition count falls or the cooldown expires (RangeSplitIndivisibleCooldown, embedded only, default 5 minutes). A full key space is skipped until its range count drops below its quota. kahuna.range.split.limit_refusals labels refusals with reason="partition_limit" or reason="key_space_quota".

How a Key Space Becomes Range-Routed​

Key-range routing is an explicit opt-in. The key space must be registered so Kahuna flips that space from hash mode to key-range mode and seeds its initial whole-space descriptor. You register once, and all nodes pick up the routing mode from the committed descriptor map (see Registration and reconciliation).

A new space starts on the partition that hash routing selects for its placement group. If another space in the group already has range descriptors, the new space follows that sibling's first range instead. The sibling named exactly like the group takes precedence; otherwise the lowest ordinal sibling name is used. With this rule, related row and index spaces are together at first, including after the group's anchor range has moved. Later splits can separate them. Registration does not relocate existing data or rewrite existing descriptors.

The CLI contacts the configured endpoints to register and verify their local routing views. If admin authorization is enabled, use a caller that supplies the admin key.

kahuna-cli \
-c "https://kahuna-1:8082,https://kahuna-2:8082,https://kahuna-3:8082" \
--register-key-range users

Committed descriptors propagate the routing mode to other nodes; operators do not need to manually register each node for propagation. CLI fan-out verifies answering nodes. Indeterminate means local descriptor visibility was not established and can follow a committed proposal: read again or retry. Don't assume that registration was rolled back.

The registration response has these fields.

FieldMeaning
successThe answering node routes the space by key range and sees at least one descriptor.
statusOne of these values: Seeded, AlreadySeeded, Indeterminate, InvalidInput, KeyRangeDisabled.
seededThis request committed the initial descriptor. False can be a success if another request already seeded it.
routingModeThe answering node's local routing mode for the key space.
descriptorCountDescriptors visible to the answering node.

Indeterminate means the node-local mode changed but the descriptor is not visible on that node yet. Re-read the range map before writing to the space.

Unregister a key space with this command.

kahuna-cli \
-c "https://kahuna-1:8082,https://kahuna-2:8082,https://kahuna-3:8082" \
--unregister-key-range users

Inspect and Administer Ranges​

Read the applied range map from any node.

kahuna-cli -c "https://kahuna-1:8082" --ranges
kahuna-cli -c "https://kahuna-1:8082" --ranges --key-space users

REST exposes the same map.

GET /v1/ranges
GET /v1/ranges?keySpace=users

The response includes initialized and the answering node's localEndpoint, with one entry for each key space. Each key-space entry includes its node-local routingMode and its ordered descriptors. A descriptor has these fields: startKey, endKey, partitionId, generation.

For metadata-mode clients, GET /v1/cluster/routing also publishes the hash placement rule. The rule includes the algorithm (kahuna.placement-group-jump-xxh32-v1) and the separators (/ for key spaces, | for placement groups). It also includes the hash pool size and the partition offset. Clients that don't understand the exact rule use their fallback. They don't guess.

Range scan page failures are visible through kahuna.kv.scan_page_retry_budget_exhausted and kahuna.kv.scan_page_failed. A non-zero rate means that callers receive retryable or loud scan failures. They don't receive silently truncated results.

Force a split at an exact key.

kahuna-cli \
-c "https://kahuna-1:8082,https://kahuna-2:8082,https://kahuna-3:8082" \
--split-range users \
--split-key users/0500

This is the REST equivalent.

POST /v1/ranges/split
Content-Type: application/json

{"keySpace":"users","splitKey":"users/0500"}

Only the leader of the partition that owns the range map can split. A non-leader returns NotLeader and can include leaderHint.

The split response includes determinate. Check it before you take action.

statusdeterminateMeaning
SucceededtrueThe range split and newPartitionId serves the upper half.
NotLeadertrueNo action was attempted. Retry against the hinted leader or another endpoint.
NoRangetrueThe key space is unregistered or no descriptor covers the split key.
InvalidSplitKeytrueThe key would create an empty range or is outside the covering range.
BelowMinRangeSizetrueThe policy refused the split because one half would be too small.
PartitionLimitReachedtrueCluster partition limit or key-space range quota reached. No partition was created, and the map didn't change. See Split Capacity Limits.
PartitionCreationFailedtrueThe map did not change, though an unused partition may have been created. Retry allocates a fresh partition ID.
TransferFailed, QuiesceFailed, QuiesceExpired, CutoverFailed, ConcurrentSplit, IndeterminatefalseThe map can change later. Read GET /v1/ranges again.

Run the merge pass on demand.

kahuna-cli -c "https://kahuna-1:8082" --merge-ranges

This is the REST equivalent.

POST /v1/ranges/merge

Merge scans all key-range spaces and folds adjacent ranges that are below the configured minimum. A per-key-space merge API isn't available, and a request-level size override isn't either. A non-leader returns NotLeader. It doesn't return 0 merges. This means that 0 shows that a leader executed the pass and found no eligible ranges.

Range admin is also available through gRPC and both clients.

Internals: Handoff and Retirement​

This section describes the mechanics behind splits and merges, and registration. You don't need it to use key-range sharding.

Handoff​

Split/merge quiesce uses a leader-local WriteFence range lock: it blocks new mutations while allowing Shared readers and does not plant per-key intents. Descriptor transitions retain a generation fence and deadline. Data and completion receipts must be replicated at the destination before cutover, and so must transaction records and prepared intents. Handoff uses bounded batches (512 items, with a 1 MiB intent-byte target); a single oversized intent or same-key group can exceed those targets.

Retirement​

Merge cutover records RetiredPartitionIds in replicated metadata. A later partition 0 leader can finish removing the retired groups; partition identifiers are not reused. The backend remains node-global and range ownership determines slices to move or purge. With explicit replica placement, node-global storage doesn't mean that all nodes store all partitions.

Registration and reconciliation​

Registration has two parts.

  • the range-map store reconciles routing modes under its install lock before publishing each committed or restored map; registration waits for local descriptor visibility
  • all map paths use this same projection, for example startup and live range-map apply, and also restore and partition-0 snapshot installation; a route captures the map before reading its mode, then re-reads under the install lock if it raced publication