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.
Cross-shard joins are expensive. Describe three practical strategies to handle queries that join data across shards (e.g., join users to transactions where users are sharded by user_id and transactions by account_id). For each strategy discuss latency, complexity, and when you'd pick it.
Sample Answer
Direct answer
Three practical strategies for a cross-shard join, users sharded by user_id and transactions by account_id: broadcast the smaller side to every shard so the join runs locally, denormalize (co-locate) the needed fields so no join is required at query time at all, or scatter-gather (query every relevant shard and join in the application or coordinator layer). Pick broadcast when one side is small and rarely changes, denormalization when the query pattern is known ahead of time and you can tolerate write-side duplication, and scatter-gather when neither is true and the query pattern is genuinely ad hoc; for heavy analytical cross-shard aggregation specifically, none of the three is usually right, stream the data via change-data-capture into a separate analytical store instead and run the join there.
Structured elaboration
Strategy 1: Broadcast / replicate the smaller side
Copy the small table (here, users) to every shard that holds transactions, so a join against account_id can execute entirely locally on each shard without a network round trip to fetch the other side. A back-of-envelope check on whether "small" actually applies: 5 million users at roughly 200 bytes/row is about 1 GB, comfortably replicable to every shard's local cache; the same approach for 5 billion users, a 1,000x larger population at the same row size, is about 1 TB per shard (5,000,000,000 x 200 bytes = 1e12 bytes), no longer a "just replicate it" decision. Latency: lowest of the three once replicated (fully local join, no fan-out at query time). Complexity: the replication pipeline itself (keeping every shard's copy current as users changes) is the real cost, not the join logic. Pick this when one side is genuinely small and changes infrequently relative to query volume.
Strategy 2: Co-location / denormalization
Duplicate the fields you actually need from the small side directly onto the large side at write time (for example, store a user_region or user_tier column directly on each transactions row), so the query that used to be a join becomes a single-table filter. Latency: lowest possible, no join and no fan-out at all. Complexity: the write path now owns keeping the duplicated fields current whenever the source changes (an update to a user's tier has to fan out to every transaction row that denormalized it, or you accept eventual consistency on the duplicated copy). Pick this when the query pattern needing those specific fields is known in advance and stable, and the write-side cost of keeping duplicates current is smaller than the query-time cost of joining on every read.
Strategy 3: Scatter-gather with an application- or coordinator-side join
Query every shard that could hold matching transactions rows for a given set of user_ids, fetch each shard's local matches, and join the results in the application layer or a coordinator process rather than in the database. Latency: highest of the three, bounded by the slowest of however many shards are fanned out to, and that number grows with cluster size (a scatter-gather query gets slower, not faster, as you shard more finely for scale). Complexity: no schema change and no replication pipeline needed, the tax is paid entirely at query time, in fan-out cost and in application code that now does the join. Pick this for genuinely ad hoc queries where the access pattern is not known well enough in advance to justify broadcasting or denormalizing, accepting the latency cost as the price of flexibility.
A fourth option for analytics specifically: CDC to a separate analytical store
When the real need is aggregation or analytics across shards (dashboards, reports) rather than a single row's lookup, none of the three strategies above, all built for OLTP (online transaction processing: the day-to-day, single-row reads and writes a live application performs) workloads, is the right tool: they either bloat the OLTP write path (denormalization) or put unpredictable load on the OLTP shards at query time (scatter-gather). Stream both users and transactions changes via change-data-capture into a separate analytical store (a columnar warehouse or similar), and run the cross-shard join and aggregation there, off the OLTP critical path entirely. This keeps the transactional shards answering only the queries they were sized for, and gives the analytical workload a store actually built for scanning and joining at scale.
Worked example
Query: "for each region, total transaction amount in the last 30 days," users sharded by user_id, transactions by account_id.
- Broadcast fits if
users(region lookup) is small: replicateusers(user_id, region)to every transaction shard, then each shard runsSELECT region, SUM(amount) FROM transactions t JOIN users u ON t.user_id = u.user_id WHERE occurred_at > now() - interval '30 days' GROUP BY regionlocally, and the coordinator only has to sum the per-shard, per-region partials (an associative merge: summing each shard's partial sum and then summing those partials again gives the same total as summing every row at once), never re-scanning base rows. - Denormalize fits if this exact query runs constantly and users rarely change region: add
regiondirectly to eachtransactionsrow at write time, and the query becomes a single-tableGROUP BYwith no join at all, on any single shard. - Scatter-gather fits if this is a one-off, ad hoc report requested occasionally with varying filters: query all transaction shards for the raw rows in range, fetch the small set of
(user_id, region)pairs needed to resolve them, and join in the application layer, accepting the fan-out cost since it is infrequent. - CDC-to-analytics fits if this kind of report runs routinely across many dimensions, not just region: stream both tables into a warehouse once, and every future report variant is a single query there, none of them touching the OLTP shards.
Trade-offs and pitfalls
- Broadcasting a table that is not actually small (or that grows past "small" without anyone revisiting the decision) silently turns every shard's local storage and cache budget into a scaling bottleneck; put a size or growth-rate alert on any broadcast table, not just a one-time judgment call at design time.
- Denormalization's failure mode is staleness: if the fan-out update on change is missed or delayed, queries silently read a stale duplicated value with no error to signal it; decide explicitly whether that duplicated field needs strong consistency (synchronous fan-out update) or can tolerate eventual consistency, rather than leaving it undefined.
- Scatter-gather's fan-out cost is not fixed, it grows with shard count (more shards fanned out to, more chances one of them is slow), which means a query pattern that was fine at 8 shards can become a tail-latency problem purely from adding shards for unrelated scaling reasons, with no change to the query itself.
- Reaching for CDC-to-an-analytical-store for what is actually a single, simple, frequently-run OLTP-path query is over-engineering; that pattern earns its complexity specifically for genuinely analytical, multi-dimensional, or exploratory workloads, not as a default first choice for every cross-shard read.
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.
List the key metrics and signals you would monitor to detect shard hotspots and imbalance in a production sharded system. Give concrete examples of alerting thresholds (e.g., CPU > 80% for 5m, shard QPS 3x cluster median, tail latency deviation) and propose remediation actions that could be automated.
Sample Answer
Direct answer
I would monitor per-shard request rate, resource utilization (CPU, I/O), and tail latency, each compared against the cluster's own median rather than a fixed absolute number, because "hot" is a relative concept in a sharded system: a shard running at 60% CPU is fine if every shard is at 60%, and a problem if every other shard is at 15%. Concrete alerting thresholds I'd start with: a shard's CPU above 80% sustained for 5 minutes, a shard's QPS (queries per second) at 3x the cluster median, and a shard's p99 latency (the 99th-percentile response time, i.e. the slowest 1% of requests, a better signal than an average because it exposes the tail degradation a hot shard causes even while the average still looks fine) deviating meaningfully from the cluster's own p99. Remediation that can be automated ranges from soft (shed load, route new traffic away) to structural (trigger a rebalance).
Structured elaboration
Why relative thresholds, not absolute ones. A sharded cluster's whole point is even distribution; the signal you actually want is deviation from the cluster's own current norm, not a static number tuned once and then wrong as the cluster grows or the workload shifts. Comparing each shard to the live median (or a trailing baseline) means the alert stays meaningful as the cluster scales up or down.
Concrete metrics and thresholds:
| Metric | Example threshold | What it catches |
|---|---|---|
| CPU utilization | > 80% sustained for 5 minutes | Compute-bound hotspot: a shard doing more work per request, or more requests, than its peers |
| Shard QPS | > 3x cluster median | Traffic-volume imbalance, the most direct signal of an uneven key distribution or a hot key |
| Tail latency (p99) | Deviates from cluster p99 by a set margin (e.g. 2x) | Degradation a hot shard causes for its own requests specifically, visible in the tail well before the average moves |
| I/O operations per second (IOPS) or queue depth | > 3x cluster median, or sustained non-zero queue depth while peers are near-idle | Storage-bound hotspot, common when the imbalance is in write volume rather than compute |
| Per-key request rate (where trackable) | A single key's rate crosses an absolute floor derived from typical key volume | The earliest possible signal, catches a hot key before its shard's aggregate metrics move at all |
Remediation actions that can be automated, roughly from least to most disruptive:
- Shed or delay non-critical load to the hot shard (e.g., defer background/batch jobs that happen to target that shard) automatically when its utilization crosses the threshold, buying time without touching data placement.
- Route new traffic away from the hot shard where the system has any choice in the matter (e.g., a new tenant or key that could reasonably start on a less-loaded shard).
- Trigger an automatic split or rebalance for the identified hot range/key, using whatever online resharding mechanism the system has, this is the structural fix, and automating it safely requires the rebalance mechanism itself to be trustworthy under load, which is worth verifying before wiring it to fire unattended.
- Page a human when the automated steps above don't resolve the imbalance within a defined window, since a persistent hotspot despite automated mitigation usually means the root cause (a genuinely hot key, not just transient skew) needs a human decision, not another automated retry.
Computing per-shard load incrementally, without a full scan. Recomputing each shard's load by scanning all its data periodically does not scale as data grows, and by the time a full scan finishes, the picture it produced is already stale. The alternative is a streaming/incremental approach: each shard emits a lightweight counter (request count, bytes written) at write time, aggregated centrally (or via each node's own metrics pipeline) into a rolling window, so "this shard's load over the last 5 minutes" is always available from a cheap running total rather than a recomputation over the shard's entire dataset. This is the same principle as an exponential moving average: update a running estimate on every event instead of recomputing from scratch.
Worked example
import statistics
shard_qps = {
"shard-0": 1180, "shard-1": 1240, "shard-2": 1190, "shard-3": 1310,
"shard-4": 1090, "shard-5": 4980, "shard-6": 1220, "shard-7": 1150,
}
median = statistics.median(shard_qps.values())
threshold = 3 * median
for shard, qps in shard_qps.items():
ratio = qps / median
flag = "ALERT" if qps > threshold else "ok"
print(f"{shard}: {qps} QPS ({ratio:.2f}x median) -> {flag}")
print(f"cluster median: {median} alert threshold (3x median): {threshold}")
shard-0: 1180 QPS (0.98x median) -> ok
shard-1: 1240 QPS (1.03x median) -> ok
shard-2: 1190 QPS (0.99x median) -> ok
shard-3: 1310 QPS (1.09x median) -> ok
shard-4: 1090 QPS (0.90x median) -> ok
shard-5: 4980 QPS (4.13x median) -> ALERT
shard-6: 1220 QPS (1.01x median) -> ok
shard-7: 1150 QPS (0.95x median) -> ok
cluster median: 1205.0 alert threshold (3x median): 3615.0
shard-5 at 4.13x the cluster's own median crosses the 3x threshold cleanly, while every other shard sits within about 10% of the median, exactly the pattern a relative (not absolute) threshold is designed to isolate.
Trade-offs & pitfalls
- A fixed absolute threshold ages badly. A QPS threshold tuned for today's cluster size becomes meaningless (too sensitive or not sensitive enough) as shards are added or removed; anchoring to the live median avoids re-tuning the alert every time the cluster changes size.
- CPU or QPS alone can miss an I/O-bound or lock-bound hotspot. A shard can be moderately loaded on CPU and QPS while still degrading badly because of lock contention or storage I/O saturation; watching only the metrics that are easiest to collect, instead of the ones that actually explain the user-facing symptom, is a common gap.
- Automating the structural remediation (trigger a rebalance) without first validating that mechanism under load is a real risk. An automated rebalance kicking off during an already-degraded period can itself add load (data movement competes with live traffic) before it relieves any; the earlier, softer remediation steps exist partly to buy time for a rebalance to be triggered deliberately rather than reactively at the worst possible moment.
Tail latency spikes increased after increasing shard count. Outline how you would diagnose root causes (network issues, coordination overhead, compaction/GC, metadata lookups), which tools and traces you'd use, and what optimizations you would try to reduce tail latency in a sharded datastore.
Sample Answer
Direct answer
Diagnose a post-shard-count-increase tail-latency regression by checking, in order, whether queries are actually using the shard key (an un-keyed query now fans out to more shards than before, which alone degrades p99 through pure order-statistics, no per-shard slowdown required), then network and coordination overhead (more shards means more connections, more routing hops, more chances one participant in a fan-out is briefly slow), then compaction/GC pauses and metadata-lookup cost on individual shards. The mechanism that most directly explains "latency got worse specifically because shard count went up" is scatter-gather fan-out width itself, demonstrated below.
Structured elaboration
Root-cause checklist, in likely-impact order
- Un-keyed queries forcing full fan-out: if a query's
WHEREclause does not include the shard key (the column value the router uses to know which single shard should hold a given row), the router cannot route it to one shard, it must scatter-gather to ALL of them. As shard count grows, that same query fans out wider, and p99 latency, the max across the fan-out, degrades purely from that width even if every individual shard's own performance is completely unchanged (demonstrated below). - Full-table scans on individual shards: check the query plan on each shard (
EXPLAIN ANALYZE, the command that prints the actual steps and timing the database used to run a query) for a sequential scan (reading every row in the table, in order, to find matches) where an index scan (using an index to jump straight to the matching rows instead of reading the rest of the table) was expected; this often surfaces alongside symptom 1 above, because a query written assuming it always hits one small, well-indexed shard can silently degrade into a full scan per shard once it starts fanning out to many, especially if the shard-routing key was dropped from an index or from the query itself during some earlier change. - Network and coordination overhead: more shards means more open connections from the router/proxy tier, more routing-table lookups per request, and more individual RPCs to wait on for any multi-shard query; check connection-pool saturation and per-hop latency in a distributed trace, not just aggregate query time.
- Compaction and garbage collection pauses: on LSM-tree-backed storage engines (engines like RocksDB or Cassandra's storage layer that buffer writes in memory and periodically merge them into sorted files on disk instead of updating rows in place) or garbage-collected ones, adding shards (if it meant redistributing existing write load onto more, smaller instances, or if total write volume grew alongside the resharding) can shift the compaction schedule (the background job that merges and rewrites those sorted files to keep reads fast, briefly competing with foreground traffic for CPU and IO while it runs) or GC schedule on individual nodes; check per-node compaction/GC pause metrics for a correlation in time with the latency regression.
- Metadata/routing lookups: confirm the routing-table cache hit rate has not dropped; more shards means a larger routing table, and if any tier is doing an uncached or poorly-cached lookup per request, that cost grows with the size of the table it is searching.
Tools and traces
- Distributed tracing with one span per shard hop for a fan-out query, so you can see the actual per-shard latency distribution behind an aggregate p99, not just the aggregate number.
- Per-shard
EXPLAIN ANALYZEon the specific query pattern that regressed, to catch symptom 2 directly. - Connection-pool and routing-cache metrics (pool wait time, cache hit rate) to catch symptom 3 and 5.
- Storage-engine internal metrics (compaction queue depth, GC pause histograms) correlated by timestamp against the latency regression, to catch symptom 4.
Optimizations to try
- Push the shard key into every query that can legitimately use it, and add monitoring that flags un-keyed queries against a sharded table as a class of technical debt, since they get strictly more expensive as the cluster grows, not just today.
- For queries that genuinely need to touch many shards, narrow the fan-out where possible (route only to shards known to hold relevant data, if any partitioning scheme allows that) rather than always scattering to every shard.
- Keep-alive and pool connections between routers and shards rather than establishing a fresh connection per request, to remove per-hop connection-setup cost from the tail.
- Cache routing metadata aggressively at every router/proxy instance (a local, periodically-refreshed copy of the routing table, not a lookup per request) so metadata lookup cost does not scale with routing-table size on the hot path.
Worked example
The fan-out-width mechanism, isolated: this is an illustration of pure order statistics using synthetic, unitless latency samples (not a measurement of any real system, deliberately unitless to avoid implying otherwise), holding each shard's own latency distribution completely fixed while only the fan-out width N changes, to show that p99 degrades from width alone.
import random
random.seed(42)
def per_shard_latency_au():
return max(0.1, random.gauss(5, 1.5)) # arbitrary units (a.u.), unchanged as N grows
def simulate_fanout(n_shards, n_queries=8000):
samples = sorted(max(per_shard_latency_au() for _ in range(n_shards)) for _ in range(n_queries))
p99 = samples[int(len(samples) * 0.99)]
return p99, sum(samples) / len(samples)
single_shard_samples = sorted(per_shard_latency_au() for _ in range(8000))
single_p99 = single_shard_samples[int(len(single_shard_samples) * 0.99)]
print(f"single-shard p99 (n=1, no fan-out): {single_p99:.2f} a.u. <- unchanged baseline throughout")
for n in (8, 32, 128, 512):
p99, mean = simulate_fanout(n)
print(f"fan-out width N={n:>4}: p99={p99:6.2f} a.u. ({p99/single_p99:.2f}x baseline), mean={mean:5.2f} a.u.")
Output:
single-shard p99 (n=1, no fan-out): 8.48 a.u. <- unchanged baseline throughout
fan-out width N= 8: p99= 9.62 a.u. (1.13x baseline), mean= 7.15 a.u.
fan-out width N= 32: p99= 10.06 a.u. (1.19x baseline), mean= 8.10 a.u.
fan-out width N= 128: p99= 10.66 a.u. (1.26x baseline), mean= 8.88 a.u.
fan-out width N= 512: p99= 11.25 a.u. (1.33x baseline), mean= 9.56 a.u.
p99 climbs from 1.00x to 1.33x baseline purely from widening the fan-out from 8 to 512 shards, with the per-shard distribution never changed. This is the concrete argument for checklist item 1 above: a p99 regression that lines up in time with a shard-count increase, on a query pattern that fans out, does not require ANY individual shard to have gotten slower to be fully explained; it can be the arithmetic of "the tail is the max of more independent draws," and checking for that first, before chasing a per-shard regression that may not exist, saves real investigation time.
Trade-offs and pitfalls
- Jumping straight to compaction/GC tuning (item 4) because it is a familiar lever is a common wrong turn; if the actual cause is fan-out width (item 1), no amount of per-shard tuning will fix a p99 that is fundamentally an order-statistics effect of querying more shards per request.
- A full-table-scan symptom on an individual shard can be a genuine, independent regression OR a downstream consequence of item 1 (a query that used to be a fast, single-shard indexed lookup silently became a per-shard full scan once it started fanning out without its shard-key filter surviving the rewrite); check both, in that order, rather than assuming they are unrelated.
- Reducing fan-out by routing only to "likely relevant" shards is a real optimization but only works if your partitioning scheme actually correlates with the query's filter; applying it blindly to a genuinely unpredictable access pattern just reintroduces missed-data bugs to chase a latency number.
- Treating this as purely a network or infrastructure problem, without first confirming whether the regressed queries are even using the shard key, risks spending real engineering effort on connection pooling and tracing infrastructure when the actual fix is adding a
WHEREclause.
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.