Replication, Partitioning, and Sharding Questions
Scaling and distributing data across nodes: primary-replica and multi-primary replication, read-replica scaling, horizontal partitioning, and sharding strategies with their key-selection and rebalancing challenges. Covers replication lag, failover and split-brain handling, cross-shard operations such as joins, distributed transactions, and global secondary indexes, and the operational cost of a partitioned topology. Key to designing databases that scale horizontally.
A single large tenant generates the majority of writes and creates a hotspot on their shard. Design strategies to mitigate this at scale: dynamic intra-tenant sharding, per-tenant rate-limiting, write queuing, specialized storage tiers, and routing. Explain how to detect the tenant early and how to migrate them with minimal disruption.
Sample Answer
Direct answer
I would treat a single dominant tenant as a special case rather than trying to fix it by tuning the shard key for everyone: detect the tenant early from its write volume relative to the shard's other tenants, then move it to its own dedicated capacity (a dynamically carved-out sub-shard, or its own dedicated instance) while every other tenant stays on the shared, normally-sharded infrastructure. Alongside that structural move, per-tenant rate limiting, write queuing, and (for tenants whose access pattern is more read-heavy or analytical, like reporting) a specialized storage tier keep the rest of the shard protected while the migration happens and going forward.
Structured elaboration
Detecting the tenant early. Track per-tenant request and byte volume as a first-class metric (not just aggregate shard load), and alert when one tenant's share of a shard's total traffic crosses a threshold, say, one tenant consistently above 30 to 40% of a shard's write volume is already a strong signal, since a genuinely even multi-tenant shard should have no single tenant anywhere near that share. Catching this from onboarding or usage-growth metrics, before the shard actually saturates, turns a reactive incident into a planned migration.
The mitigation techniques, and what each is for:
- Dynamic intra-tenant sharding: once a tenant is identified as dominant, split that tenant's own data across multiple physical partitions (using a secondary key within the tenant's data, like a user id or resource id) rather than moving the whole tenant as one indivisible unit. This is the most work but scales the tenant's load the same way sharding scales the whole system, it just applies the technique recursively to one tenant.
- Per-tenant rate limiting: cap the dominant tenant's request rate to protect the shared shard's headroom for every other tenant, at the cost of degrading the dominant tenant's own service during the cap. A fast, low-effort stopgap, not a long-term fix.
- Write queuing: buffer the dominant tenant's writes and apply them at a rate the shard can sustain instead of rejecting excess requests outright, trading latency for the tenant (their writes take longer to land) for protecting the shard's stability for everyone else.
- Specialized storage tiers: if the dominant tenant's workload is distinguishable in kind (e.g. bulk reporting/BI reads rather than transactional writes), route that workload to infrastructure built for it, a read replica or a columnar/analytical store, so it never competes with the shared shard's transactional capacity at all. This is the right fix specifically when the "hotspot" is really a workload-shape mismatch (an analytical access pattern colliding with an OLTP, online transaction processing, shard) rather than pure volume.
- Routing: once the tenant has its own dedicated capacity (via any of the above), the routing/directory layer needs to know to send that tenant's traffic there instead of the shared shard, transparently to the application.
Migrating with minimal disruption. The safe sequence mirrors any online resharding: start dual-writing the tenant's new writes to both the old shared shard and the new dedicated location, backfill the tenant's historical data into the new location, verify the two are consistent, cut reads over to the new location, then stop writing to the old one and reclaim that tenant's rows from the shared shard. Doing this as a background, verified migration (not a live in-place move) is what keeps it invisible to the tenant and to every other tenant sharing that shard.
A reporting/BI-specific instance of this pattern. A multi-tenant reporting system where one tenant runs large, expensive aggregate queries against shared infrastructure is the same root problem, one tenant's load pattern dominating shared capacity, but the mitigation leans harder on the specialized-storage-tier option: give that tenant's reporting workload its own read replica or analytical copy of the data, so its expensive scans never contend with the transactional write path (or other tenants' reads) on the primary shard at all. Rate limiting a reporting tenant's query concurrency is also a reasonable quick stopgap while that replica is being stood up.
Worked example
tenants_writes_per_sec = {
"tenant-A": 40, "tenant-B": 55, "tenant-C": 30,
"tenant-D": 22000, "tenant-E": 48, "tenant-F": 61,
}
total = sum(tenants_writes_per_sec.values())
for t, w in sorted(tenants_writes_per_sec.items(), key=lambda kv: -kv[1]):
print(f"{t}: {w} writes/s ({w/total:.1%} of shard total)")
remaining = total - tenants_writes_per_sec["tenant-D"]
print(f"total shard write rate: {total} writes/s")
print(f"after routing tenant-D to its own dedicated range: "
f"{remaining} writes/s remain on the shared shard ({remaining/total:.1%} of original load)")
tenant-D: 22000 writes/s (98.9% of shard total)
tenant-F: 61 writes/s (0.3% of shard total)
tenant-B: 55 writes/s (0.2% of shard total)
tenant-E: 48 writes/s (0.2% of shard total)
tenant-A: 40 writes/s (0.2% of shard total)
tenant-C: 30 writes/s (0.1% of shard total)
total shard write rate: 22234 writes/s
after routing tenant-D to its own dedicated range: 234 writes/s remain on the shared shard (1.1% of original load)
Moving the one dominant tenant off the shared shard drops its load by nearly two orders of magnitude, from 22,234 to 234 writes/s, without touching the shard key or routing scheme for the other five tenants at all. That asymmetry (one tenant is 98.9% of the problem) is exactly why a structural, tenant-specific fix beats trying to re-tune the shard key for the whole system.
Trade-offs & pitfalls
- Waiting for the shard to actually saturate before detecting the tenant. By the time CPU or I/O alarms fire, the dominant tenant has likely already been degrading every other tenant on that shard for a while; tracking per-tenant share as a leading metric, not just aggregate shard health, is what turns this into a planned migration instead of an incident.
- Rate limiting or queuing as a permanent solution instead of a bridge. Both techniques protect the shard but degrade the dominant tenant's own experience indefinitely if never followed by the structural move (dedicated capacity); a tenant important enough to dominate a shard's load is usually also important enough that permanently degrading their service is not acceptable.
- Treating volume and workload shape as the same problem. A tenant that is simply high-volume (many normal transactional writes) needs capacity; a tenant whose workload is shaped differently (bulk reporting scans) needs a different storage tier, not just more of the same kind of capacity. Misdiagnosing one as the other means the fix doesn't actually relieve the contention.
Top 0.1% of keys account for 80% of traffic, creating severe hotspots. Design an architecture to handle heavy hot keys at scale with minimal latency. Discuss trade-offs among multi-level caching, read/write fan-out, key splitting (sharding subkeys), adaptive throttling, and operational complexity of each approach, and explain how you would migrate a hot key offline to a split representation.
Sample Answer
Direct answer
At this level of skew, the single hottest key can be receiving hundreds of thousands of requests per second while the median key barely gets any traffic at all, so no per-partition capacity you provision will ever be "enough" for that one key without also wasting enormous capacity on every ordinary key. The architecture has to treat the hot key as a special case rather than trying to scale the general partitioning scheme to cover it: put a multi-level cache in front of it to absorb reads, split it into sub-keys (a Redis-style hash-slot-aware cache or a sharded counter behind one logical key) to spread its write load, and use adaptive throttling to protect the rest of the system while the split takes effect, migrating the key offline to its split representation rather than doing it live under load.
Structured elaboration
Why "just add more shards" does not work here. With 0.1% of keys carrying 80% of traffic, no shard count N makes the distribution even: whichever shard the hottest key lands on is overloaded regardless of N, because the problem is the skew of one key's popularity, not the total number of buckets. Scaling the partition count is the fix for aggregate load; a single extreme hot key needs a fix scoped to that key.
The techniques, and what each actually buys:
- Multi-level caching: an in-process (local) cache absorbs the highest-frequency reads with zero network cost, backed by a shared cache tier (a Redis-like in-memory cache, i.e. a fast key-value cache commonly used exactly for this purpose) for reads that miss the local cache but would otherwise hit the database. This is the cheapest lever and the first one to pull, but it only helps reads; a hot key that is primarily written to gets nothing from a cache in front of it, and every cache layer adds an invalidation problem, a write to the hot key now has to propagate to (or expire) both cache levels correctly, or reads start serving stale data past whatever staleness the workload can tolerate.
- Read/write fan-out: replicate the hot key's data to multiple read replicas (for reads) or accept writes through multiple front-ends that later reconcile (for writes), so no single node handles the full request volume alone. Effective, but for writes specifically it reintroduces a conflict-resolution problem similar to multi-primary replication, two write paths for the same logical key need a merge strategy.
- Key splitting (sharding subkeys): rewrite the one logical hot key as several physical sub-keys (
hot_key#0throughhot_key#K-1), route each request to one sub-key (round-robin, or a secondary hash), and merge results (for reads that need the full picture) or leave them split (if per-sub-key reads/writes are each independently valid, like a sharded counter). This is the only technique on the list that actually reduces the load per partition rather than just absorbing or delaying it, but it requires the access pattern to be splittable at all, and it permanently complicates every future operation on that key. - Adaptive throttling: dynamically detect a key's request rate exceeding a threshold and start shedding or queuing excess load for that key specifically, protecting the shared partition's capacity for every other key. This is a stabilizer, not a fix: it trades hot-key latency/availability for cluster-wide stability while a real fix (caching, splitting) is deployed.
Operational complexity, ranked from least to most: caching (an infrastructure addition with a well-understood invalidation problem) < adaptive throttling (a control-plane rule, but needs good detection to avoid false positives) < read/write fan-out (a new consistency problem to own) < key splitting (a permanent schema and access-pattern change that every future consumer of that key must know about).
Migrating a hot key offline to a split representation. Do this as a background migration, not a live cutover: (1) start dual-writing, every write to the hot key also fans out to its new split sub-keys, while reads still go to the original key; (2) backfill historical data into the sub-keys; (3) verify the sub-keys' combined state matches the original key; (4) cut reads over to the split representation (merging sub-key reads at the application layer); (5) stop writing to the original key and retire it. Doing the split live, under the full hot-key load, risks the migration process itself becoming the next hotspot.
A near-real-time leaderboard as a concrete instance of this pattern. A live leaderboard's hot key (the "top scores" aggregate, updated on every scoring event) does not need strong consistency, it needs bounded staleness: fronting the hot aggregate with a short-TTL cache (refreshed on a fixed interval, or invalidated lazily) trades a few seconds of staleness for absorbing what would otherwise be a read-and-recompute on every single request, which is usually an acceptable trade for a feature where "slightly stale" is invisible to users but "slow" is not.
Worked example
The figures below are expressed in QPS (queries per second):
TOTAL_QPS, TOTAL_KEYS = 2_000_000, 1_000_000
HOT_KEY_FRACTION, HOT_TRAFFIC_SHARE, ZIPF_S = 0.001, 0.80, 1.0
n_hot_keys = int(TOTAL_KEYS * HOT_KEY_FRACTION)
n_cold_keys = TOTAL_KEYS - n_hot_keys
hot_qps_total = TOTAL_QPS * HOT_TRAFFIC_SHARE
cold_qps_total = TOTAL_QPS * (1 - HOT_TRAFFIC_SHARE)
qps_per_cold_key = cold_qps_total / n_cold_keys
# Traffic is skewed even within the "hot" bucket itself: rank by a Zipf(s=1) weight
# (a distribution where a small number of items take a disproportionate share, each
# rank getting roughly 1/rank of the top rank's share) to get a realistic single-key peak.
weights = [1.0 / (rank ** ZIPF_S) for rank in range(1, n_hot_keys + 1)]
weight_sum = sum(weights)
hottest_key_qps = hot_qps_total * (weights[0] / weight_sum)
print(f"avg QPS per cold key: {qps_per_cold_key:.2f}")
print(f"single hottest key: {hottest_key_qps:,.0f} QPS")
print(f"hottest key vs an average cold key: {hottest_key_qps/qps_per_cold_key:,.0f}x")
RCU_CEILING_PER_PARTITION = 3000 # per-partition read-capacity-unit ceiling, docs.aws.amazon.com
needed_subkeys = -(-int(hottest_key_qps) // RCU_CEILING_PER_PARTITION)
print(f"sub-keys needed to bring the hottest key under a {RCU_CEILING_PER_PARTITION}/s "
f"per-partition ceiling: {needed_subkeys} ({hottest_key_qps/needed_subkeys:,.0f} req/s/sub-key)")
avg QPS per cold key: 0.40
single hottest key: 213,747 QPS
hottest key vs an average cold key: 533,834x
sub-keys needed to bring the hottest key under a 3000/s per-partition ceiling: 72 (2,969 req/s/sub-key)
The hottest key here needs at least 72 split sub-keys just to bring each sub-key's rate under a single realistic per-partition throughput ceiling (using DynamoDB's published 3,000 read-capacity-units-per-second-per-partition ceiling as the concrete planning input, fetched from AWS's own documentation). That is the scale of splitting "handle heavy hot keys" actually requires once you compute it, not a hand-wave.
Trade-offs & pitfalls
- Reaching for caching alone and declaring victory. A cache absorbs reads; it does nothing for the write side of a hot key (a hot counter, a hot queue). If the 80% of traffic on the hot keys is meaningfully write-heavy, caching addresses only part of the problem and the write path will still saturate a single partition.
- Splitting without a merge strategy for reads that need the whole picture. Turning one hot key into K sub-keys is easy for writes (route by round-robin or hash) but a read that needs the true aggregate (a global counter's exact value, not an approximation) now has to fan out to all K sub-keys and sum them, which is itself a mini scatter-gather; for some access patterns (an approximate leaderboard rank, a rough counter) this is fine, for others (an exact inventory count) it needs care.
- Doing the split live is the single most dangerous mistake here. Migrating a genuinely hot key's representation while it is still receiving full production load risks the migration process (dual-writes, backfill, verification) itself becoming a second source of load on an already-saturated key; the offline/background migration sequence above exists specifically to avoid that.
Design a zero-downtime re-sharding strategy (changing shard key or increasing shard count) for a primary events table expected to grow from 100TB to 800TB. Include steps for data migration, dual-write patterns, backfill, cutover, consistency guarantees during cutover, automated rebalancing, and rollback paths. Explain operational concerns such as migration bandwidth, impact on latency, and verification of data correctness.
Sample Answer
Direct answer
Reshard with a six-phase pipeline: provision the target topology, dual-write new traffic to both old and new shard layouts, backfill historical data with a resumable watermark, verify old and new are byte-for-byte equivalent, cut traffic over atomically behind a versioned routing pointer, and only then decommission the old layout after a bake period. Consistency during the window comes from making every step reversible and idempotent rather than from any single "big atomic moment": the dual-write phase means both layouts are always current, so the cutover itself is just a routing-table flip, not a data-moving event, which is what makes it possible to roll back by flipping the pointer back.
Structured elaboration
Picking a target shard count
Do not reshard to "twice as many shards" by feel; size the target against an explicit operability budget. One reasonable budget: keep any single shard's full backfill or restore time under a fixed ceiling.
import math
TARGET_TOTAL_BYTES = 800 * (1000**4) # 800 TB, decimal
COPY_THROUGHPUT_BPS = 1 * (1000**3) # 1 GB/s sustained per-shard backfill/restore throughput (assumption)
MAX_BACKFILL_MINUTES = 30 # operability budget: any single shard restores in <=30 min (assumption)
max_bytes_per_shard = COPY_THROUGHPUT_BPS * MAX_BACKFILL_MINUTES * 60
min_shards = math.ceil(TARGET_TOTAL_BYTES / max_bytes_per_shard)
print(f"max shard size for a {MAX_BACKFILL_MINUTES}-min backfill budget at {COPY_THROUGHPUT_BPS/1e9:.0f}GB/s: "
f"{max_bytes_per_shard/1e12:.2f} TB/shard")
print(f"shards needed at 800TB total: {TARGET_TOTAL_BYTES/1e12:.0f}TB / {max_bytes_per_shard/1e12:.2f}TB = "
f"{TARGET_TOTAL_BYTES/max_bytes_per_shard:.2f} -> {min_shards} shards (rounded up)")
CURRENT_SHARDS, CURRENT_BYTES = 64, 100 * (1000**4)
print(f"at 100TB today on {CURRENT_SHARDS} shards: {CURRENT_BYTES/CURRENT_SHARDS/1e12:.2f} TB/shard (under budget)")
print(f"at 800TB on {CURRENT_SHARDS} shards, unchanged: {TARGET_TOTAL_BYTES/CURRENT_SHARDS/1e12:.2f} TB/shard "
f"-> {TARGET_TOTAL_BYTES/CURRENT_SHARDS/max_bytes_per_shard:.1f}x over budget")
Output:
max shard size for a 30-min backfill budget at 1GB/s: 1.80 TB/shard
shards needed at 800TB total: 800TB / 1.80TB = 444.44 -> 445 shards (rounded up)
at 100TB today on 64 shards: 1.56 TB/shard (under budget)
at 800TB on 64 shards, unchanged: 12.50 TB/shard -> 6.9x over budget
64 shards is fine today (1.56 TB/shard, under the 1.80 TB ceiling); left unchanged at 800 TB it would sit at 6.9x over budget, confirming a reshard is required, not optional. Round the 445-shard minimum up to a convenient power of two, 512, since binary range-splitting and consistent-hash ring math both work cleanly against powers of two.
The six phases
- Provision: stand up the new (512-shard) topology, empty, with its own routing metadata entry (version N+1, inactive).
- Dual-write: every write path starts writing to both the old shard (source of truth, synchronous) and the new shard (asynchronous, via the application's write path or a change-data-capture stream reading the old shard's write-ahead log). Writes carry an idempotency key (for example a UUID generated by the writer) so a retried write is a no-op on replay, not a duplicate. This is the step with a real latency cost: see Trade-offs below.
- Backfill: bulk-copy historical rows in key order, tracking a resumable watermark (last key copied) so an interrupted backfill resumes instead of restarting; throttle the copy rate against a live I/O budget so it does not starve production traffic.
- Verify: compare old and new for equivalence before trusting the new layout. Bucket rows by a stable key range, compute a per-bucket row count and content checksum on each side, and diff the buckets; a mismatched bucket isolates exactly which range needs re-copying without a full-table diff.
- Cutover: flip the routing pointer from version N to N+1 as a single atomic metadata write (a compare-and-swap on a versioned config record), then have every router or client refresh and start reading and writing exclusively against the new layout.
- Bake and decommission: keep dual-writing to the old layout for a defined bake period (long enough to catch anything the verification step missed) before stopping writes there and reclaiming it.
Consistency guarantees during cutover
The cutover itself moves zero bytes, it only flips a pointer, because phases 2 to 4 already made the new layout current and verified. The remaining risk is a request that started routing under version N completing its write after the pointer flips to N+1: closing that window means the router holds a brief write-barrier (reject or queue new writes for a bounded number of milliseconds) while in-flight version-N writes drain, confirmed by each shard acking that its write queue is empty, before flipping the pointer live for reads.
Automated rebalancing
Once cut over, the new, larger shard count still needs ongoing balance as data grows unevenly across it; that is a separate, continuous concern (splitting hot ranges, merging cold ones) rather than a one-time step of this migration.
Rollback
Because the old layout kept receiving writes through the bake period, rollback is the same pointer flip in reverse, no data movement, as long as it happens before the bake period ends and the old layout is decommissioned. Rolling back after decommission means re-running the backfill in reverse, which is why the bake period length is a real risk decision, not a formality.
Worked example
See the shard-count derivation above. The per-bucket checksum comparison from the Verify phase is the concrete way to confirm cutover correctness: bucket rows by key range, compute a checksum per bucket on both layouts, and diff them; run against a real database and deliberately corrupt one row, and the mismatched bucket isolates the problem immediately, without a full-table diff.
Operational concerns
- Migration bandwidth: the backfill and dual-write catch-up share the same network and disk I/O budget as production traffic; throttle the bulk-copy stream and prefer reading the source's replication log (WAL/CDC) for the dual-write's asynchronous side over re-querying the base table, since a log read is a small, steady stream instead of a query load on the primary.
- Latency impact: synchronous dual-write to two targets adds the slower of the two write latencies to every request; the fix is to make only the OLD write synchronous (correctness-critical, unchanged) and the NEW write asynchronous with its own retry queue, accepting that the new layout can lag by seconds during backfill without affecting user-facing latency, since it is not yet the source of truth.
- Verification of correctness: bucket-checksum comparison (above) over full re-diffing, because it isolates a mismatch to a specific key range instead of forcing a byte-for-byte scan of 800 TB on every check.
Trade-offs and pitfalls
- Choosing a target shard count that is too conservative (for example, doubling instead of sizing against a real growth and operability budget) means repeating this entire six-phase project again soon; size against the actual growth target, not the next obvious power of two.
- Synchronous dual-write to both layouts is the simplest correctness story but pays the tax described above on every write; most production migrations use synchronous-old/asynchronous-new plus CDC catch-up instead, trading a small, bounded staleness window on the new layout (acceptable, since it is not yet serving reads) for materially better write latency during the migration.
- Skipping or shortening the bake period to "move faster" removes your only cheap rollback path; a verification pass that looked clean can still miss an edge case that only a few days of real production traffic surfaces.
- A common mistake is treating the backfill as the hard part and the cutover as trivial; in a well-run migration it is the reverse; nearly all of the engineering risk lives in making the cutover pointer flip truly atomic and the write barrier truly bounded, not in the bulk copy.
What is consistent hashing and how does it reduce data movement when the number of shards changes? Explain the role of virtual nodes and how they improve load distribution on the hash ring.
Sample Answer
Direct answer
Consistent hashing maps both data keys and shard nodes onto the same circular numeric space (a "ring"), so a key belongs to whichever node's position is the next one clockwise from the key's hash. Because a node's ring position is independent of every other node, adding or removing one node only reassigns the keys in the arc next to it, roughly 1/N of all keys for N nodes, instead of remapping almost everything the way hash(key) mod N does when N changes. Virtual nodes (vnodes) give each physical shard many scattered positions on the ring instead of one, which smooths out the uneven arc sizes a handful of random points would otherwise produce and lets you hand a bigger shard proportionally more of the ring.
Structured elaboration
The ring mechanism
- Hash both shard identifiers and keys with the same hash function onto a fixed range, for example 0 to 2^32-1 ("the ring"), and treat that range as wrapping around like a clock face.
- Each physical shard is assigned one or more positions ("tokens") on the ring.
- To find a key's owner: hash the key, then walk clockwise from that point to the first token; that token's shard owns the key.
Why this bounds data movement when the shard count changes
The naive scheme owner(key) = hash(key) mod N recomputes every key's owner from scratch whenever N changes, because the modulus itself changed; in practice that remaps close to all keys (demonstrated below: 85.5% for a 6-to-7 shard change). Consistent hashing only moves the keys whose ring position falls inside the arc that changes ownership. Insert a 7th node's token and it slices a piece off of whichever single node's arc it lands inside; every other node's arc is untouched. The maximum fraction remapped is therefore bounded by roughly the new node's share of the ring (about 1/7, 14.3%, for 6 to 7 shards), and only the new node gains keys; the six existing shards never trade keys with each other.
The role of virtual nodes
A physical shard placed at a single random ring position owns one contiguous arc, and with only a handful of shards those arc lengths vary a lot by chance, so some shards end up owning far more of the ring than others even though the expected share is 1/N for everyone. Giving each shard many small, scattered arcs instead of one large one buys three things:
- Load smoothing: with many small arcs per shard, the total arc length each shard owns converges toward its fair share as vnode count grows (demonstrated below: standard deviation drops from about 50% of the mean at 1 vnode/shard to about 4% at 100 vnodes/shard).
- Uneven capacity, on request: assigning a bigger shard more vnodes than a smaller one gives it a proportionally larger slice of the ring without changing the hashing algorithm at all: a node with twice the capacity of its peers simply gets twice as many tokens, so its expected share of ring traffic scales with its vnode count.
- Even rebalancing on add or remove: because a shard's ownership is spread across many small arcs instead of one, when it joins or leaves, the affected keys come from, or go to, many other shards roughly evenly instead of dumping the whole burden on whichever one shard happened to be its ring neighbor.
Choosing a vnode count
More vnodes improve balance but are not free:
- Metadata and coordination cost: every vnode is an entry the routing layer, or every node in a gossip-based system, must store and keep synchronized; at very high counts (hundreds of thousands across a cluster) that metadata and its propagation traffic become a real operational tax.
- Diminishing returns: balance improves fastest at low counts and flattens out, because it is a statistical variance-reduction effect, not a fixed formula, so moving from 1 to 32 vnodes buys far more balance than moving from 128 to 256 does.
- A concrete, checkable data point: Apache Cassandra (a widely used distributed, wide-column NoSQL database, an example of exactly the kind of node ring described above) shipped for years with 256 tokens (vnodes) per node by default, to guarantee smooth balance through brute-force randomness alone. Cassandra 4.0 lowered the shipped default to 16, paired with a replication-factor-aware token allocation algorithm (
allocate_tokens_for_local_replication_factor) that deliberately places each new node's tokens for balance, rather than relying on a large random count to average out skew. The project's own public debate over the new default (proposals ranged from 4 to 16 tokens) weighed availability and repair blast-radius against small-cluster balance, and settled on 16 as the practical compromise (Apache Cassandra dev mailing list, "num_tokens default in Cassandra 4.0" thread). - Rule of thumb: pick a base vnode count that keeps the worst-case imbalance,
max shard share / mean shard share, under whatever your operations team can tolerate at the smallest cluster size you expect to run, and prefer placement-aware allocation over pure randomness once the vnode count is high enough that its metadata cost is noticeable.
Worked example
This is a full, runnable simulation (Python standard library only, deterministic hashing via hashlib.md5, no randomness) comparing naive mod-N reassignment to consistent hashing at 1 and 100 vnodes/shard when a 6-shard ring grows to 7 shards, then measuring how vnode count affects load balance across a fixed 6-shard ring.
import hashlib, statistics
def h(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
RING_SIZE = 2**32
def ring_hash(key):
return h(key) % RING_SIZE
NUM_KEYS = 20000
keys = [f"key-{i}" for i in range(NUM_KEYS)]
def naive_assign(key, n):
return h(key) % n
moved_naive = sum(1 for k in keys if naive_assign(k, 6) != naive_assign(k, 7))
print(f"naive hash-mod-N: nodes 6->7, keys remapped = {moved_naive}/{NUM_KEYS} = {moved_naive/NUM_KEYS:.1%}")
def build_ring(node_names, vnodes_per_node):
ring = {}
for node in node_names:
for v in range(vnodes_per_node):
token = ring_hash(f"{node}#{v}")
ring[token] = node
return sorted(ring.items())
def lookup(sorted_ring, key):
tok = ring_hash(key)
lo, hi = 0, len(sorted_ring)
while lo < hi:
mid = (lo + hi) // 2
if sorted_ring[mid][0] < tok:
lo = mid + 1
else:
hi = mid
if lo == len(sorted_ring):
lo = 0
return sorted_ring[lo][1]
nodes6 = [f"shard-{i}" for i in range(6)]
nodes7 = nodes6 + ["shard-6"]
for vnodes in (1, 100):
ring6, ring7 = build_ring(nodes6, vnodes), build_ring(nodes7, vnodes)
before = {k: lookup(ring6, k) for k in keys}
after = {k: lookup(ring7, k) for k in keys}
moved = sum(1 for k in keys if before[k] != after[k])
print(f"consistent hashing, {vnodes} vnode(s)/node: nodes 6->7, keys remapped = {moved}/{NUM_KEYS} = {moved/NUM_KEYS:.1%}")
print()
for vnodes in (1, 8, 32, 100, 256):
ring = build_ring(nodes6, vnodes)
counts = {n: 0 for n in nodes6}
for k in keys:
counts[lookup(ring, k)] += 1
vals = list(counts.values())
mean, stdev = statistics.mean(vals), statistics.pstdev(vals)
print(f"vnodes/node={vnodes:>3}: per-shard key counts min={min(vals)} max={max(vals)} mean={mean:.0f} "
f"stdev={stdev:.0f} ({stdev/mean:.1%} of mean) max/mean={max(vals)/mean:.2f}x")
Output:
naive hash-mod-N: nodes 6->7, keys remapped = 17098/20000 = 85.5%
consistent hashing, 1 vnode(s)/node: nodes 6->7, keys remapped = 1924/20000 = 9.6%
consistent hashing, 100 vnode(s)/node: nodes 6->7, keys remapped = 2595/20000 = 13.0%
vnodes/node= 1: per-shard key counts min=1028 max=5885 mean=3333 stdev=1663 (49.9% of mean) max/mean=1.77x
vnodes/node= 8: per-shard key counts min=2170 max=4218 mean=3333 stdev=713 (21.4% of mean) max/mean=1.27x
vnodes/node= 32: per-shard key counts min=2634 max=4290 mean=3333 stdev=538 (16.1% of mean) max/mean=1.29x
vnodes/node=100: per-shard key counts min=3187 max=3574 mean=3333 stdev=136 (4.1% of mean) max/mean=1.07x
vnodes/node=256: per-shard key counts min=3140 max=3696 mean=3333 stdev=213 (6.4% of mean) max/mean=1.11x
Two things to read off this: naive mod-N remaps 85.5% of keys on a one-node change, versus 9.6 to 13.0% for consistent hashing (both close to the roughly 14.3% theoretical minimum of 1/7), confirming the data-movement bound. Separately, going from 1 to 100 vnodes per node shrinks the standard deviation of per-shard load from about half the mean to about 4% of it, confirming the load-smoothing effect; note the 1-vnode run still lands near the 14.3% theoretical remap fraction on average even though its per-shard load is far less even, because the two effects (data moved on a topology change vs. steady-state balance) are related but distinct.
Trade-offs and pitfalls
- Consistent hashing alone still treats every physical shard as equally capable; without weighting via vnode count, a bigger box receives no more traffic than a small one. Fixing that just means scaling vnode count with capacity, more tokens for a bigger box, fewer for a smaller one, so the ring hands out load in proportion to what each shard can actually handle.
- Drawback worth naming directly: the ring's vnode-to-shard mapping is itself state that must be distributed and kept in sync, whether via gossip or a directory service, and a stale copy on any client routes requests to the wrong shard until refreshed. This coordination cost grows with vnode count.
- If the hash function used to place tokens is not close to uniform, the "roughly 1/N" bound degrades; always use a well-distributed hash such as MD5, MurmurHash, or a SHA variant, never something like a raw modulo of a monotonically increasing ID as the ring hash.
- Changing the hash function, or the ring's overall size, on a live cluster is equivalent to changing the entire assignment function and remaps close to 100% of keys; ring parameters are effectively part of the schema, not something to casually redeploy.
Develop a cost model to compare two choices for scaling a sharded datastore: adding more smaller instances versus upgrading to fewer larger instances. Include hardware, licensing, operational overhead, failover impact, and migration complexity in your model and describe how you'd apply it to a decision.
Sample Answer
Direct answer
Hold total capacity fixed and compare the two topologies on the dimensions that actually differ, since raw compute cost is close to a wash: most cloud instance families price roughly linearly with capacity within the family, so 5x the capacity costs close to 5x the hourly rate either way. The real trade-off is fixed per-instance costs (operational overhead, and for per-core-licensed engines, licensing) working in favor of fewer, larger instances, against failover blast radius and migration granularity working in favor of many, smaller ones. Build the model, then apply the workload's actual constraints (how much does an operator-hour cost, and how much write-capacity loss during a single-instance failure is tolerable) to pick a side, rather than defaulting to whichever is cheaper on the compute line alone.
The model
Inputs: a target sustained capacity (queries per second, QPS), a chosen instance size for each topology with its capacity and hourly price, a fixed monthly operational-overhead cost per instance (patch windows, monitoring and alerting setup, on-call cognitive load, backup scheduling, amortized as labor cost), and a redundancy factor (replicas per primary for high availability). From these, compute: total instance count for each topology, total monthly compute cost, total monthly operational cost, and blast radius (the fraction of total write capacity lost if exactly one primary instance fails).
"""Cost model: many-small-instances vs fewer-large-instances for a sharded datastore
holding a FIXED total capacity target. All unit costs below are stated, illustrative
assumptions (labeled as such), not live vendor pricing -- the model's structure and
the resulting trade-off is the point, not the specific dollar figures."""
TARGET_QPS = 400_000 # sustained peak the cluster must serve
REPLICAS_PER_SHARD = 1 # +1 synchronous replica per primary for HA (synchronous: must confirm a write before it counts as committed), both configs
# -- illustrative unit economics (compute pricing assumed LINEAR in capacity within
# a family: 5x the capacity costs 5x the hourly price -- realistic for most
# compute-optimized cloud instance families, stated as a simplifying assumption) --
SMALL_CAPACITY_QPS = 20_000
SMALL_PRICE_PER_HR = 0.68
LARGE_CAPACITY_QPS = 100_000 # 5x the small instance's capacity
LARGE_PRICE_PER_HR = SMALL_PRICE_PER_HR * (LARGE_CAPACITY_QPS / SMALL_CAPACITY_QPS)
FIXED_OPS_OVERHEAD_PER_INSTANCE_MONTHLY = 150 # patch windows, monitoring/alerting
# setup, on-call load, backup scheduling
# -- amortized labor, illustrative
HOURS_PER_MONTH = 730
def cluster_plan(capacity_per_primary, price_per_hr_per_instance):
num_primaries = -(-TARGET_QPS // capacity_per_primary) # ceil
total_instances = num_primaries * (1 + REPLICAS_PER_SHARD)
compute_cost = total_instances * price_per_hr_per_instance * HOURS_PER_MONTH
ops_cost = total_instances * FIXED_OPS_OVERHEAD_PER_INSTANCE_MONTHLY
blast_radius_pct = 1 / num_primaries * 100 # % of write capacity lost if 1 primary fails
return {
"num_primaries": num_primaries,
"total_instances": total_instances,
"compute_cost_monthly": compute_cost,
"ops_cost_monthly": ops_cost,
"total_monthly": compute_cost + ops_cost,
"blast_radius_pct": blast_radius_pct,
}
small = cluster_plan(SMALL_CAPACITY_QPS, SMALL_PRICE_PER_HR)
large = cluster_plan(LARGE_CAPACITY_QPS, LARGE_PRICE_PER_HR)
print(f"target: {TARGET_QPS:,} QPS sustained, {REPLICAS_PER_SHARD} replica/primary\n")
for name, plan in (("many small instances", small), ("fewer large instances", large)):
print(f"-- {name} ({plan['num_primaries']} primaries, {plan['total_instances']} instances total) --")
print(f" compute: ${plan['compute_cost_monthly']:,.0f}/mo")
print(f" ops overhead: ${plan['ops_cost_monthly']:,.0f}/mo")
print(f" TOTAL: ${plan['total_monthly']:,.0f}/mo")
print(f" blast radius if one primary fails: {plan['blast_radius_pct']:.1f}% of write capacity")
print()
savings = small["total_monthly"] - large["total_monthly"]
savings_pct = savings / small["total_monthly"] * 100
print(f"fewer-large saves ${savings:,.0f}/mo ({savings_pct:.1f}%) at this target, driven entirely by "
f"the {small['total_instances'] - large['total_instances']} fewer instances' worth of fixed ops "
f"overhead -- compute cost itself is ~equal by construction (linear pricing assumption).")
print()
# -- resharding friction: how many individual shard-migration operations to move from
# the current topology to 2x capacity, one direction each way --
def split_steps(num_primaries):
# each split takes 1 shard -> 2 shards; going from N to 2N needs N split operations
return num_primaries
print("-- resharding friction: operations needed to DOUBLE total capacity --")
print(f" many-small ({small['num_primaries']} primaries): {split_steps(small['num_primaries'])} "
f"individual shard-split operations, each moving ~1/{small['num_primaries']} of the data")
print(f" fewer-large ({large['num_primaries']} primaries): {split_steps(large['num_primaries'])} "
f"individual shard-split operations, each moving ~1/{large['num_primaries']} of the data "
f"-- {small['num_primaries'] / large['num_primaries']:.0f}x FEWER migrations needed, but each one relocates "
f"{small['num_primaries'] / large['num_primaries']:.0f}x more data and briefly holds "
f"{100 / large['num_primaries']:.1f}% of total capacity at reduced redundancy mid-split")
Output:
target: 400,000 QPS sustained, 1 replica/primary
-- many small instances (20 primaries, 40 instances total) --
compute: $19,856/mo
ops overhead: $6,000/mo
TOTAL: $25,856/mo
blast radius if one primary fails: 5.0% of write capacity
-- fewer large instances (4 primaries, 8 instances total) --
compute: $19,856/mo
ops overhead: $1,200/mo
TOTAL: $21,056/mo
blast radius if one primary fails: 25.0% of write capacity
fewer-large saves $4,800/mo (18.6%) at this target, driven entirely by the 32 fewer instances' worth of fixed ops overhead -- compute cost itself is ~equal by construction (linear pricing assumption).
-- resharding friction: operations needed to DOUBLE total capacity --
many-small (20 primaries): 20 individual shard-split operations, each moving ~1/20 of the data
fewer-large (4 primaries): 4 individual shard-split operations, each moving ~1/4 of the data -- 5x FEWER migrations needed, but each one relocates 5x more data and briefly holds 25.0% of total capacity at reduced redundancy mid-split
At this specific target (400,000 QPS, "small" instances rated at 20,000 QPS each versus "large" instances rated at 100,000 QPS each, 5x the capacity at 5x the hourly price, one HA replica per primary), fewer-large saves about 18.6 percent per month, entirely from having 32 fewer instances' worth of fixed operational overhead to carry, since compute cost is identical by construction (both plans total $19,856/mo in compute). But fewer-large also concentrates 25 percent of total write capacity behind a single instance failure, versus 5 percent for many-small, a 5x difference in blast radius for an 18.6 percent cost saving.
Failover impact
Blast radius scales as 1 divided by the number of primaries: many-small spreads a single-instance failure across a larger denominator, so losing one instance costs less of the total in relative terms, at the (usually acceptable) cost of more moving parts to monitor. This is the sharpest trade-off in the whole model and the one most likely to actually decide the answer: a 25 percent capacity loss during a failover (the process of detecting a dead instance and promoting a replacement to take over its work) is a very different incident than a 5 percent one, and that difference does not show up on the cost line at all.
Migration complexity
Doubling total capacity by splitting each primary in two costs one shard-split operation per existing primary: many-small needs more individual operations (more shards to split), but each one moves a smaller fraction of the data and holds a smaller fraction of total capacity at reduced redundancy during the split. Fewer-large needs fewer operations, but each one is a bigger, riskier undertaking: more data in flight per split, and a larger fraction of total capacity briefly exposed while that split is in progress.
Applying the model to a decision
- Choose fewer-large when: operator time is the actual scarce resource (a small team managing the cluster), the workload can tolerate a real capacity dip during a single-instance failure (redundancy and fast failover elsewhere in the stack absorb it), and the per-instance overhead assumption in the model reflects real toil, not a number picked to make the comparison come out a certain way.
- Choose many-small when: the workload has a tight availability commitment where a 20+ percent capacity loss during a routine failure is unacceptable, resharding needs to happen incrementally and safely (smaller, lower-risk operations), or the engine is licensed per core with a meaningful PER-INSTANCE base fee on top, in which case more instances directly costs more in licensing, not just more operational overhead, and the model above would need that term added explicitly before trusting its conclusion.
- The model's answer is only as good as its inputs. Before applying it, verify the operational-overhead-per-instance figure against real toil (ticket volume, on-call load) rather than a guess, and verify whether the specific engine's licensing model is truly per-core (favors neither topology directly) or has a per-instance component (favors fewer-large).
Trade-offs and pitfalls
- Do not let "compute cost is roughly equal" get mistaken for "the two options are roughly equivalent." The blast-radius and migration-granularity differences are real and often matter more than the modest overhead saving.
- The linear-pricing assumption in the model is a simplification stated explicitly, not a verified fact for every vendor and instance family; re-derive the compute-cost lines with the actual current pricing for the instance types under consideration before using this for a real budget decision, since cloud list pricing changes and sometimes is not perfectly linear at the largest instance sizes.
- A cost model that never gets revisited goes stale. Redundancy requirements, instance pricing, and the team's actual operational capacity all drift over time; treat this as a model to re-run periodically, not a one-time decision.
Unlock Full Question Bank
Get access to all Replication, Partitioning, and Sharding interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.