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.
Explain quorum-based consistency with the R + W > N rule. Give an example configuration (N, R, W), show how read and write quorum choices affect failure tolerance and stale reads, and discuss observable behavior during partial failures like a node crash or network partition.
Sample Answer
Direct answer
Quorum-based consistency uses two numbers, a write quorum W and a read quorum R, out of N total replicas, and the rule R+W>N guarantees that every possible read quorum and every possible write quorum share at least one replica in common. That shared replica is guaranteed to have seen the most recent acknowledged write, which is what lets a leaderless system offer a consistency guarantee without a single leader coordinating every operation.
Why the inequality works, and what it buys you
Think of it as a pigeonhole argument: if a write needs W replicas to confirm before it is considered committed, and a read only needs R replicas to answer, then as long as any W replicas plus any R replicas together number more than the total N, they cannot all be disjoint sets; math says the overlap is at least R+W−N replicas. If that overlap is zero or negative (R+W≤N), a read can, in the worst case, hit only replicas that have not yet received the latest write, i.e. a stale read is possible by design, not by bug.
def quorum_overlap(n, w, r):
# minimum guaranteed overlap between any write-quorum set and any read-quorum set
return max(0, w + r - n)
for n, w, r in [(5, 3, 3), (3, 2, 2), (3, 1, 1)]:
overlap = quorum_overlap(n, w, r)
can_lose_for_write = n - w
can_lose_for_read = n - r
print(f"N={n} W={w} R={r}: guaranteed overlap={overlap}, "
f"tolerates losing {can_lose_for_write} node(s) and still writing, "
f"{can_lose_for_read} node(s) and still reading, "
f"strong-read guarantee={'yes' if overlap >= 1 else 'no'}")
N=5 W=3 R=3: guaranteed overlap=1, tolerates losing 2 node(s) and still writing, 2 node(s) and still reading, strong-read guarantee=yes
N=3 W=2 R=2: guaranteed overlap=1, tolerates losing 1 node(s) and still writing, 1 node(s) and still reading, strong-read guarantee=yes
N=3 W=1 R=1: guaranteed overlap=0, tolerates losing 2 node(s) and still writing, 2 node(s) and still reading, strong-read guarantee=no
Worked example: choosing N, R, W for a session store
Take N=5 replicas of a session-token store spread across 5 nodes, with W=3 and R=3. That satisfies 3+3=6>5, so every read is guaranteed to see the latest committed write (the client reconciles any disagreement among the 3 responding replicas by picking the highest version/timestamp, a step called read repair). This configuration tolerates 2 simultaneous node failures and writes still succeed (only need 3 of the remaining nodes to be reachable, which is possible with 2 down out of 5), and tolerates 2 simultaneous failures for reads on the same terms. Compare that to N=5, W=1, R=1: writes and reads both succeed even with 4 nodes down, maximizing availability, but 1+1=2>5, so a read can legitimately return stale data from a replica that has not yet seen the latest write, and under a network partition that isolates one node from the other four, that single isolated node can keep accepting both reads and writes independently of the majority side, producing two diverging histories until the partition heals.
Observable behavior during a partial failure
With N=5, W=3, R=3 and a network partition that splits the cluster into a group of 3 and a group of 2: the group of 3 can still form both a write quorum and a read quorum on its own, so it keeps serving normally. The group of 2 cannot form either quorum (2 < 3), so both reads and writes on that side fail (or block, depending on the client's timeout behavior) until the partition heals or that group's nodes rejoin the majority side. This is the CAP theorem (Consistency, Availability, Partition tolerance: under a network partition, a system must choose to sacrifice either strict consistency or availability, since it cannot guarantee both) made concrete: this configuration chose consistency (the minority side refuses to serve rather than risk a stale or conflicting answer) over availability on the minority side. A crashed single node (rather than a partition) behaves more simply: with 4 of 5 nodes reachable, both quorums (needing 3) are still satisfiable, so the system keeps operating normally with no visible behavior change beyond one fewer replica participating. Many leaderless systems also run hinted handoff alongside this: while that node is down, the coordinator that would have written to it keeps a "hint", a note of the write it still owes that replica, and replays the queued writes to the node once it rejoins, so it catches back up quickly instead of relying only on read repair to fill the gap the next time it happens to be read from.
Trade-offs and pitfalls
The temptation is to set R=1, W=1 for maximum speed and availability and call it "eventually consistent, which is fine for us." That is a legitimate choice for data where staleness is cheap (a view counter, a recommendation cache), but it is a silent correctness bug for anything where "did my last write actually take effect" matters to the caller, like a session token that was just revoked. The other common mistake is forgetting that R + W > N only protects reads and writes that actually go through the quorum protocol: a monitoring job or an ad hoc query that reads from a single replica directly, bypassing the coordinator, gets none of this guarantee no matter how the cluster is configured.
List and explain four properties that make a good shard key. For each property, give a brief example (user_id, timestamp, region, email hash, etc.) and explain why it helps avoid hotspots or cross-shard queries.
Sample Answer
Direct answer
A good shard key has four properties: high cardinality (many distinct values, so there's enough range to spread the data), even distribution (no single value, or small set of values, dominates the traffic), alignment with the dominant query pattern (queries can be answered by hitting one or a few shards, not all of them), and immutability (the value never changes after a row is created, so a row never needs to move shards just because a field it was sharded on was updated). A field like email hash or user_id typically has all four; a field like status (few distinct values, changes over time, and doesn't align with most queries) typically has none of them.
Structured elaboration
| Property | What it means | Example | Why it avoids hotspots or cross-shard queries |
|---|---|---|---|
| High cardinality | Many distinct possible values | user_id, an email hash | Low cardinality (e.g. country, a handful of values) forces many rows onto the same few shards no matter how good the hashing is; you can never have more effectively-used shards than distinct key values |
| Even distribution | No value (or narrow set of values) accounts for a disproportionate share of rows or traffic | A well-hashed user_id (assuming no single user dominates activity) | Prevents a hot partition: a key like region where 80% of users are in one region concentrates load there even though the field has decent cardinality |
| Query alignment | The key matches what most queries actually filter or group by | user_id when the dominant access pattern is "this user's data" | A key with great cardinality and distribution but no relationship to real queries (a random UUID unrelated to any access pattern) forces every query to fan out across all shards to find matching rows, turning every read into a scatter-gather |
| Immutability | The key's value for a given row never changes after creation | user_id (a user doesn't change identity); NOT status or region if a user can relocate | A mutable shard key means an update can require physically moving a row from one shard to another mid-lifetime, which most sharded systems either forbid outright or treat as an expensive, special-cased operation |
Terminology note: primary key vs. partition/shard key are not always the same thing, and conflating them causes real bugs. A traditional relational primary key's only job is uniquely identifying a row; it says nothing about physical placement. A partition (shard) key's job is exactly the opposite concern: where the row physically lives. In some systems they can be the same column (sharding by a table's own primary key), but in many real schemas they should not be: a messages table's primary key might reasonably be message_id (unique, but a poor shard key: queries almost never filter by message_id alone, they ask for a conversation's history, so sharding on message_id would scatter one conversation's messages across every shard), while its shard key should be conversation_id (great alignment, but not unique across rows, many messages share one conversation_id, which is exactly what makes it a good partition key and a poor primary key). Systems like Cassandra make this split explicit in their terminology: the "partition key" (placement) and the rest of the "primary key" (uniqueness and clustering order) are named and reasoned about separately.
Three common mistakes when picking a partition/shard key:
- Choosing a low-cardinality field (a
status,region, or boolean flag) because it seems like a natural grouping, without checking that it actually spreads load: a handful of distinct values can never spread data across more shards than there are values, and real-world skew across those values (most rows beingstatus = 'active') makes it worse. - Choosing a monotonically increasing field (an auto-incrementing id, a
created_attimestamp) under range-based sharding, which concentrates all new writes onto whichever shard currently owns the highest range, a classic write-hotspot failure mode: every new row's key sorts higher than the last, so under range-based sharding every write lands on whichever shard currently owns the top of the range, and added shards never pick up a share of new writes. - Choosing a field that doesn't match the dominant query pattern, purely because it has good cardinality and distribution: a key that spreads data beautifully but forces every real query to search every shard trades one problem (hotspots) for another (permanently expensive scatter-gather reads) that is just as damaging to performance.
Worked example
import hashlib, statistics
def hash_bucket(value: str, n: int) -> int:
return int.from_bytes(hashlib.md5(value.encode()).digest()[:8], "big") % n
N = 8
# Candidate 1: user_id (high cardinality, evenly distributed, aligns with per-user queries)
user_ids = [f"user-{i}" for i in range(200_000)]
c1 = [0]*N
for u in user_ids: c1[hash_bucket(u, N)] += 1
print("user_id buckets:", c1, "stdev/mean:", round(statistics.pstdev(c1)/statistics.mean(c1), 4))
# Candidate 2: status (low cardinality, heavily skewed toward one value)
statuses = ["active"]*180_000 + ["suspended"]*15_000 + ["deleted"]*5_000
c2 = [0]*N
for s in statuses: c2[hash_bucket(s, N)] += 1
print("status buckets: ", c2, "stdev/mean:", round(statistics.pstdev(c2)/statistics.mean(c2), 4))
user_id buckets: [25375, 25130, 25087, 24578, 24870, 25007, 24872, 25081] stdev/mean: 0.0088
status buckets: [15000, 0, 180000, 0, 0, 0, 0, 5000] stdev/mean: 2.3516
user_id, with 200,000 distinct values, spreads within about 1% of perfectly even across 8 buckets. status, with only 3 distinct values, cannot spread at all in a meaningful sense, its bucket assignment is really just "which of 3 fixed positions each status value happens to land on," and 180,000 rows (90% of the data) all land in a single bucket regardless of how good the hash function is. This is what "low cardinality defeats even distribution no matter what" looks like as a number, not just a claim.
Trade-offs & pitfalls
- A key can satisfy three of the four properties and still be wrong. A perfectly high-cardinality, evenly-distributed, immutable key that doesn't align with any real query still forces scatter-gather reads on every request; all four properties matter together, not as a checklist where 3-out-of-4 passes.
- Cardinality and distribution are not the same thing, and conflating them is a common error: a field can have millions of distinct values and still be badly distributed if a small number of those values account for most of the traffic (a power-law key, like a small number of extremely popular products among millions of product ids).
- "Immutable" is about the key's value, not about whether the row can change at all. Plenty of fields on a row can be freely mutable, updated status, updated preferences, as long as the field chosen as the shard key specifically stays fixed once set.
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.
You operate a service with a primary DB and read replicas. One replica reports replication-lag histogram: 90th percentile lag = 2s, 99th percentile = 12s, max = 90s. What conclusions can you draw about staleness risk for user reads, and what immediate SRE actions or alerts would you configure to prevent user-visible anomalies?
Sample Answer
Direct answer
A p90 (90th percentile: 90% of measurements fall below this value) of 2 seconds with a p99 (99th percentile) of 12 seconds and a max of 90 seconds describes a replica that is comfortably caught up most of the time but has a heavy tail: roughly 1% of reads land during a window where the replica is 12 seconds or more stale, and there exists at least one moment where it fell 90 seconds behind. That shape (a moderate p90 but a p99 six times higher, and a max another 7.5 times past that) is the signature of periodic bursts, not steady degradation: something intermittently overwhelms the replica's apply capacity (a batch job, a large transaction, a backup) rather than the replica being uniformly a little behind all the time.
What the shape tells you
If lag were uniformly around 2 seconds, p90/p99/max would all sit close together. The large gap between p90 (2s) and p99 (12s), and the much larger gap between p99 and the max (90s), means the lag distribution is heavily right-skewed: most reads are fine, but a real subset are badly stale, and a rare subset are very badly stale. That points investigation toward looking for periodic, bursty causes (nightly jobs, large migrations, backup windows) rather than a capacity problem that would show up as elevated lag across the whole distribution.
Worked example: estimating user impact
reads_per_sec = 8000 # ASSUMPTION: illustrative traffic level for this replica, stated as an input, not measured
p99_lag_s = 12.0
p90_lag_s = 2.0
# by definition of a percentile, roughly 1% of reads are sampled during a moment
# where lag is at or above the p99 value, and roughly 10% during a moment at or
# above the p90 value (this is an approximation: it assumes read arrival is not
# correlated with lag spikes, which should be validated against real traffic
# patterns before treating it as precise)
bad_at_p99_per_sec = reads_per_sec * 0.01
bad_at_p99_per_day = bad_at_p99_per_sec * 86400
bad_at_p90_per_sec = reads_per_sec * 0.10
print(f"~1% of reads see >= {p99_lag_s}s staleness: ~{bad_at_p99_per_sec:.0f} reads/sec, "
f"~{bad_at_p99_per_day:,.0f} reads/day")
print(f"~10% of reads see >= {p90_lag_s}s staleness: ~{bad_at_p90_per_sec:.0f} reads/sec")
~1% of reads see >= 12.0s staleness: ~80 reads/sec, ~6,912,000 reads/day
~10% of reads see >= 2.0s staleness: ~800 reads/sec
At this traffic level, roughly 80 reads/second (about 6.9 million/day) could see data more than 12 seconds stale, which is a real, user-noticeable staleness window for anything read-your-writes-sensitive, even though the p90 alone (2 seconds) would look acceptable in isolation.
Immediate SRE actions
- Alert on the spread, not just one percentile. Alert on p99 crossing a threshold appropriate to the workload (say, page above 10 to 15 seconds for a user-facing OLTP replica, as in the general lag-alerting guidance for this kind of service), and separately track the max as a leading indicator: a growing max with a stable p99 suggests an emerging, not-yet-widespread problem worth investigating before it grows into the p99.
- Correlate lag spikes against time-of-day to look for a periodic cause (batch jobs, backups, reporting queries) before assuming a capacity problem.
- Take this replica out of rotation for the most staleness-sensitive traffic (read-your-writes paths) while investigating, routing that traffic to the primary or to a replica with better tail behavior, rather than waiting for root cause before limiting user impact.
- Add a per-replica lag SLO (service-level objective: an internal target the team commits to, for example "99% of reads see under 5 seconds of lag") with percentile-aware burn-rate alerting (alerting on how fast that target's allowed error budget is being consumed, not just a single instantaneous threshold check) so a recurring tail spike pattern like this one produces one clear, trackable signal instead of a series of one-off pages each time it happens.
Trade-offs and pitfalls
The mistake to avoid is treating a healthy-looking average or p50 as "replication is fine": with this exact data, a monitoring dashboard showing only average lag could easily read as green while a real, measurable fraction of users are seeing meaningfully stale data. The second mistake is over-reacting to the single max (90 seconds) as if it represents typical behavior; a single outlier data point does not justify architecture changes on its own, but it does justify finding out what specifically caused it, since a 90-second spike today is a plausible p99 tomorrow if its cause is left unaddressed.
You receive reports of stale reads for a small percentage of users. Outline a step-by-step troubleshooting plan to identify root cause: what logs, traces, metrics, and checks would you run; how to reproduce; and how to validate whether the issue stems from replication lag, caching, DNS, or client behavior.
Sample Answer
Direct answer
Stale reads for a small percentage of users almost always trace back to one of four cause categories: replication lag on a specific replica, a caching layer serving an outdated value, a DNS or load-balancer routing quirk sending a subset of users to a stale node, or client-side behavior (a browser cache, a retried request, a session stuck on an old connection). The troubleshooting plan is to check them in that order, cheapest and most likely first, and to reproduce the issue against a specific replica before guessing at a fix.
Step-by-step plan, ordered by cause category
- Reproduce and scope it. Identify whether "a small percentage of users" correlates with a specific replica, a specific region, a specific client version, or a specific time window (for example, only right after a deploy or only during a nightly batch job). Pull the affected users' request logs and check which backend node/replica actually served each stale read; if a distributed trace (a request-scoped record of every service and backend a single request touched, including which specific database replica it hit) exists for these requests, it is the fastest way to pin down the exact replica and timing without guessing from aggregate logs. If neither the logs nor traces currently capture which replica served a given read (many setups only log "database", not "which replica"), fix that first, because without it every other step is guesswork.
- Network/replication category: Check the lag metrics (for example PostgreSQL's
pg_stat_replication.replay_lag, or MySQL'sSeconds_Behind_Source) for the specific replica(s) identified in step 1, at the specific timestamps of the reported staleness, not just current lag. A replica that spiked to 15 seconds of lag for two minutes during a burst and recovered will look perfectly healthy by the time you check it live, which is why historical, not current, lag data matters here. - Config category: Confirm the read-routing configuration actually matches intent: is a connection pooler or load balancer sending reads to a replica that was supposed to be excluded (e.g., a replica dedicated to backups, or one flagged unhealthy but not actually removed from rotation)? Check for a recently changed routing rule or a replica added to the pool without its lag-based health check wired up.
- I/O category: On the suspect replica, check disk I/O saturation and apply-thread backlog around the incident window; a replica falling behind because its own disk cannot keep up with the apply rate (as opposed to a network-caused lag) needs a different fix (more I/O capacity, or removing competing load like backups from that node) than a network issue does.
- Caching category: If the read path includes an application cache or CDN layer, check whether the cache key for the affected records was invalidated at write time; a stale cache entry produces identical symptoms to replication lag but requires cache-invalidation logic fixes, not database fixes, so ruling this in or out early avoids chasing the wrong system.
- DNS/client category: Rule out a stale DNS entry still pointing at a decommissioned or unhealthy node (check DNS time-to-live and recent record changes), and rule out client-side caching or a client stuck on a long-lived connection to a node that was since removed from the healthy pool.
Worked example: BI reporting service-level agreement (SLA)
A business-intelligence dashboard shows a metric that occasionally contradicts a more recent number end users already saw elsewhere in the product. Reproducing it: correlate reported instances against the specific reporting replica's historical lag graph, and find recurring lag spikes to 40 to 90 seconds every night at 02:00, matching a nightly ETL (extract-transform-load) batch job hitting that same replica. Root cause: the reporting replica is shared between BI reads and the nightly batch job, and the batch job's write-heavy phase (if it writes anywhere near this replica's apply path) or its heavy read load starves the replica's apply thread of I/O. Remediation options: move BI reads off the shared replica onto a replica (or dedicated change-data-capture pipeline, CDC: a stream of row-level changes consumed to build a separate, purpose-built analytics store) that is isolated from the nightly job's resource contention, and add a per-replica lag SLA specifically for the reporting path.
Trade-offs and pitfalls
The single biggest time-waster in this kind of investigation is jumping straight to "it's probably replication lag" and tuning replication settings before confirming, with actual per-replica historical data, that lag was even elevated at the reported times; teams have spent days tuning replication only to find the real cause was a stale cache key or a misconfigured routing rule. The second pitfall is checking only current-state metrics instead of the historical window around each report, since transient lag spikes that already recovered are invisible to a live check but are exactly what caused the user-visible symptom.
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.