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.
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.
Design an automated failover system for primary-replica database pairs that minimizes split-brain risk. Cover health checks, fencing mechanisms, promotion safety checks, and how you would validate and audit automatic promotions. Also explain what data can be lost during the failover and how RPO and RTO differ between manual and automatic failover.
Sample Answer
Direct answer
An automated failover system for primary-replica pairs needs four pieces working together to minimize split-brain risk: a consensus-based health check (a majority, not a single observer, must agree the primary is actually down), fencing that guarantees the old primary cannot keep accepting writes once it loses leadership, a promotion-safety check that refuses to promote a replica too far behind, and an audit trail proving what happened and when. This is the same design pattern Patroni implements for PostgreSQL clusters, and it generalizes to any primary-replica system.
Architecture
flowchart TD
A[Health check: primary missed N heartbeats] --> B{DCS quorum reachable?}
B -->|no quorum| C[Do not promote: minority side, refuse writes]
B -->|quorum reached| D[Elect candidate: most caught-up in-sync replica]
D --> E[Fence old primary via watchdog/STONITH]
E --> F{Fencing confirmed?}
F -->|no| G[Abort promotion, alert on-call: cannot guarantee safety]
F -->|yes| H[Promote candidate to primary]
H --> I[Update DNS/service discovery to new primary]
I --> J[Audit log: who/what promoted, at what LSN, data-loss window]
J --> K[Old primary rejoins later as a follower once fencing is lifted]
Health checks. A single node observing "the primary didn't respond" is not enough evidence, since that node itself could be the one that is network-partitioned. Route the decision through a distributed configuration store (DCS: a small, separately-replicated coordination service such as etcd, Consul, or ZooKeeper) that requires a majority, or quorum, of its own members to agree before any leadership change proceeds; this is the same mechanism Patroni uses for PostgreSQL. If the surviving side of a partition cannot reach a majority of the DCS, it must not promote, even if it genuinely believes the primary is down, because it cannot distinguish "the primary is dead" from "I am the one who is isolated."
Fencing mechanisms. Before any promotion, the old primary must be guaranteed unable to keep accepting writes. Two layers, used together: revoke its ability to renew its leadership lease in the DCS (a soft fence: it should demote itself once it notices the lease expired), and a hardware or OS-level watchdog that forcibly resets the host if the soft fence has not been confirmed within a bounded time (a hard fence, sometimes called STONITH, "shoot the other node in the head"). The hard fence exists specifically for the case where the old primary is unresponsive rather than well-behaved, since a well-behaved node would have already demoted itself.
Promotion safety checks. Never promote a replica that is more than a defined, bounded amount behind the primary's last known position (measured by comparing log sequence numbers, LSNs). If the most caught-up available replica is still too far behind, the safer action is to alert and wait (accepting downtime) rather than promote and silently accept a larger-than-intended data loss; that threshold (how far behind is "too far") is a deliberate, pre-agreed trade-off between availability and data loss, not a default left unexamined.
Validating and auditing automatic promotions. Every automatic promotion writes an audit record: which node was promoted, what LSN it was at, what the old primary's last known LSN was (which bounds the data-loss window), and what triggered the decision. This is what turns "the system did something" into something a human can verify after the fact, and it is what a chaos-testing exercise (deliberately triggering failures in a controlled way, including in production during low-traffic windows, specifically to verify this pipeline works under realistic conditions rather than only in a lab) should be validating end-to-end, including checking that dependent services handling the failover (connection pools reconnecting, in-flight requests retried safely) do not cascade the failure outward.
Manual versus automatic failover: what data can be lost, and the RPO/RTO difference
| Automatic failover | Manual failover | |
|---|---|---|
| Recovery time objective (RTO) | Seconds to low tens of seconds: bounded by health-check interval, DCS quorum round trip, and fencing confirmation time | Minutes: bounded by human detection, human judgment time, and manual execution of the same steps |
| Recovery point objective (RPO) | Determined mechanically by whichever replica was most caught-up at decision time, which may not be the theoretical best choice if the promotion-safety threshold accepted a replica with some lag | Potentially better: a human can inspect multiple replicas' exact positions, attempt to recover unshipped writes from the old primary's log if it is still reachable in a degraded state, and choose the option with the least data loss, at the cost of the extra time that inspection takes |
| Failure mode if wrong | Fast, but a bug in the automation (an incorrect promotion-safety check, a fencing race condition) can promote unsafely at machine speed, before a human notices | Slow, but a human in the loop can catch an obviously wrong situation (e.g., "the primary is actually fine, this is a monitoring false positive") before acting |
| What can be lost | Any write acknowledged by the old primary but not yet replicated to the promoted replica at the moment of the fence; bounded by the promotion-safety threshold | The same category of loss, but potentially smaller, since a human can wait slightly longer to let a lagging replica catch up, or attempt log recovery from the old primary, trading RTO for a better RPO |
Automatic failover is the right default for a well-tested, generic primary-down scenario, because RTO matters more than shaving the last few seconds of RPO for most services. Manual (or manual-confirmed) failover is worth keeping as an option, or even the default, for a scenario where the failure mode is ambiguous (a regional network partition isolating a meaningful fraction of followers, rather than a clean single-node crash), where an automated system cannot reliably distinguish "promote now" from "wait, this might resolve itself" and a wrong automatic decision (over-eager promotion during a transient blip) is worse than the extra minute a human takes to confirm.
Trade-offs and pitfalls
The most common design flaw is building the health check and the fencing mechanism as two independently-tuned systems that can disagree: a health check that decides to promote faster than the fencing mechanism can guarantee the old primary is actually stopped creates exactly the split-brain window the whole design exists to prevent. The second common flaw is never testing the failover path against a real, partial-partition scenario (only testing against a clean node crash), since a partition that isolates a meaningful fraction, not all, of the followers behaves very differently (some followers see a different quorum than others) than a simple full-node failure, and is the scenario most likely to expose a subtle bug in the promotion-safety logic.
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.
Design a globally-distributed, sharded database for a social network with 200M users across 5 regions. Requirements: 99.99% read availability, 99.9% write availability, <100ms regional read latency for 95% of reads, support friend-graph queries, and obey regional data residency. Provide architecture, replica topology, sharding strategy, cross-shard query approach, and how SREs will monitor and enforce SLOs and error budgets.
Sample Answer
Direct answer
Meeting 99.99% read availability, 99.9% write availability, and sub-100-millisecond regional reads for 200 million users across 5 regions requires three decisions working together: shard by user_id so both writes and storage scale horizontally, replicate each region's shards to every other region for read locality and disaster recovery, and split the data model by entity type (profiles, friend-graph edges, feeds, direct messages) rather than treating "the social network" as one shardable blob, because each entity type has a different access pattern and a different natural shard key (the field a row is routed to a specific shard by).
Architecture
flowchart LR
Client[Client, routed to nearest region] --> Edge[Regional API tier]
Edge --> ProfileShards[(Profile shards, sharded by user_id, replicated per region)]
Edge --> GraphShards[(Friend-graph shards, sharded by user_id, edges + reverse edges)]
Edge --> FeedStore[(Feed store: fan-out-on-write for most users, fan-out-on-read for high-follower accounts)]
Edge --> DMShards[(Direct-message shards, sharded by conversation_id)]
ProfileShards -.cross-region async replicate.-> ProfileShards
GraphShards -.cross-region async replicate for DR.-> GraphShards
- Profiles, sharded by
user_id: read-heavy, small per-row size, natural fit for a leader-replicated shard per region with the leader placed in the user's home region and asynchronous cross-region replicas for read locality elsewhere and for disaster recovery. - Friend-graph edges, also sharded by
user_id(storing both the edge and its reverse for efficient "who follows me" and "who do I follow" queries without a cross-shard join): a friend-graph query for one user is a single-shard read; a query spanning two users' graphs (mutual-friends) is a targeted two-shard fan-out, not a full scatter-gather, since the shard key is known for both sides. - Feeds: the entity type with the sharpest trade-off. Fan-out-on-write (when a user posts, immediately push the post into every follower's precomputed feed) gives fast reads (a feed read is a single-shard lookup) but is expensive for high-follower accounts, since one post fans out into millions of writes. Fan-out-on-read (compute a user's feed at read time by pulling recent posts from everyone they follow) avoids that write amplification but makes reads more expensive and latency-sensitive. The standard resolution, used here: fan-out-on-write for the vast majority of accounts (normal follower counts), and fan-out-on-read (or a hybrid, merging a precomputed feed with a small number of high-follower accounts' posts pulled live) for celebrity-scale accounts specifically, so the expensive case is isolated to the accounts that actually cause it.
- Direct messages, sharded by
conversation_idrather thanuser_id, since a conversation's two (or more) participants need to land on the same shard for that conversation to keep reads and writes single-shard.
Regional replica topology and cross-shard queries
Each entity type's shards are replicated using the primary-per-region pattern for entity types the user's home region should author (profile edits, new posts, new messages) and asynchronous replicas in other regions for read locality and disaster recovery, following the same reasoning as a dedicated geo-partitioning design. A friend-graph or feed query that only touches one user's shard stays single-region and single-shard; a query that must cross shards (a mutual-friends check, a group feed spanning many members) uses a bounded, explicit fan-out to the specific known shards involved, never an unbounded scatter-gather across all shards, which would neither meet the latency target nor scale.
Worked capacity math
import math
users = 200_000_000
row_bytes = 2000 # ASSUMPTION: profile row with denormalized fields, ~2KB
index_overhead = 1.5 # ASSUMPTION: secondary indexes add ~50%
profile_gb = users * row_bytes * index_overhead / 1e9
edges_per_user = 150 # ASSUMPTION: average friend/follow edges, directed both ways
edge_bytes = 40
edge_gb = users * edges_per_user * edge_bytes / 1e9
print(f"profile data: {profile_gb:,.0f} GB")
print(f"friend-graph edge data: {edge_gb:,.0f} GB")
shard_target_gb = 400 # ASSUMPTION: keep each shard small enough to rebalance/backup/restore quickly
print(f"minimum shards by data size alone: profiles={math.ceil(profile_gb/shard_target_gb)}, "
f"graph={math.ceil(edge_gb/shard_target_gb)}")
read_budget_ms = 100
network_ms = 5 # ASSUMPTION: intra-region network round trip
app_ms = 10 # ASSUMPTION: app-tier overhead
db_budget_ms = read_budget_ms - network_ms - app_ms
print(f"DB read budget inside the 100ms p95 target: ~{db_budget_ms}ms, which rules out any cross-region hop")
write_avail = 0.999
read_avail = 0.9999
minutes_30d = 30*24*60
print(f"99.9% write availability allows {minutes_30d*(1-write_avail):.1f} min downtime / 30 days")
print(f"99.99% read availability allows {minutes_30d*(1-read_avail):.2f} min downtime / 30 days")
profile data: 600 GB
friend-graph edge data: 1,200 GB
minimum shards by data size alone: profiles=2, graph=3
DB read budget inside the 100ms p95 target: ~85ms, which rules out any cross-region hop
99.9% write availability allows 43.2 min downtime / 30 days
99.99% read availability allows 4.32 min downtime / 30 days
The data-size math alone implies surprisingly few shards (2 to 3), which is misleading if taken as the actual shard count to build: the real driver of shard count at this scale is avoiding hot shards (a small number of celebrity accounts or viral posts concentrating traffic on one physical node) and future rebalancing flexibility, not raw storage size. The standard fix is to decouple logical from physical sharding: hash user_id into a large, fixed number of logical shards (for example 4096), and map many logical shards onto each physical database cluster. Growth is then handled by remapping logical shards onto additional physical clusters (a metadata change) instead of a full re-hash migration, and a hot logical shard can be split or moved independently of the others.
How the availability and latency targets get enforced
The 85-millisecond database budget (after subtracting network and app-tier overhead from the 100-millisecond target) rules out serving any part of a p95 regional read from a cross-region replica, so read routing must strictly prefer the local region's replica and treat cross-region reads as a fallback only during a regional outage, accepting degraded latency for availability during that window. The 99.99% read availability target (about 4.3 minutes of allowed downtime per month) is met primarily by having multiple read replicas per region, so a single node failure does not take reads down; the 99.9% write availability target (about 43 minutes per month, an order of magnitude looser) reflects that writes depend on a single leader per shard and its automated-failover path (the process of detecting a dead leader and promoting a replica to replace it), which cannot realistically be made as available as a pool of read replicas without the added cost and complexity of a consensus-based multi-writer design: requiring every write to reach quorum across multiple leaders (Raft- or Paxos-style agreement, two standard algorithms that let a set of nodes agree on one shared, ordered sequence of writes even when some nodes fail) before it is durable, trading single-leader simplicity for real coordination overhead on the write path.
SRE monitoring and error-budget enforcement
Per-region, per-entity-type dashboards (profile-shard latency, graph-shard latency, feed fan-out latency, cross-region replication lag) rather than one global number, since a regional degradation would otherwise be averaged away by four healthy regions. Error budgets tie directly to the two availability SLOs (read and write), with burn-rate alerting (fast page on a sharp drop, slower ticket on sustained drift) as the alerting mechanism, applied here to read and write success rate rather than to lag specifically.
Trade-offs and pitfalls
The biggest design trap is treating "sharded social network" as one sharding decision instead of four (profiles, graph, feed, messages), since a single shard key that is right for profiles (user_id) is wrong for direct messages (conversation_id) and produces cross-shard hot spots if forced onto both. The second trap is under-provisioning for the celebrity-account case in the feed design: a fan-out-on-write-only design that looks fine in every load test using realistic average follower counts falls over the first time a genuinely viral account posts, which is exactly why that case needs an explicit, separate code path rather than being handled by "the same system, just under more load".
Write an operational playbook for recovering from a single-shard failure that causes read/write errors for a subset of users. Include detection, immediate mitigation steps, data integrity checks, and post-recovery validation steps relevant to a sharded SQL database.
Sample Answer
Direct answer
A single-shard failure in a sharded SQL database only affects the subset of users whose data lives on that shard, which is both the good news (the blast radius is bounded) and the trap (it is easy to under-react to an outage that "only" affects a fraction of users but is, for those users, a full outage). The playbook is: detect which shard and confirm the primary is actually unreachable (not just slow), fence it so it cannot accept writes if it comes back unexpectedly, promote the most caught-up in-sync replica, repoint the routing layer's shard map, then run data-integrity checks before declaring the incident over.
The playbook
flowchart TD
A[Alert: elevated errors on shard 7] --> B{Is shard 7 primary reachable?}
B -->|no| C[Fence old primary: revoke credentials, block writes]
C --> D[Promote most-caught-up in-sync replica to primary for shard 7]
D --> E[Repoint routing layer: shard map entry for 7 -> new primary]
B -->|yes, but degraded| F[Diagnose: disk, connections, replication lag on shard 7]
F --> G{Root cause fixable in place?}
G -->|yes| H[Mitigate in place, no promotion]
G -->|no| C
E --> I[Run data-integrity checks: row counts, checksums vs other shards' expectations]
H --> I
I --> J[Validate application-level reads/writes on shard 7 succeed]
J --> K[Post-recovery: reconcile any writes lost in the gap, document timeline]
1. Detection. The alert should identify the specific shard, not just "database errors," which means shard-aware monitoring (per-shard error rate, per-shard connection health, per-shard replication lag, meaning how far behind the primary this shard's replica has fallen) has to exist before the incident, not be built during it. Confirm scope immediately: query the shard-to-tenant or shard-to-user-range mapping to know exactly which users are affected, since this drives both the urgency (how many users, and are any high-priority accounts among them) and the communication (what to tell support or status pages).
2. Immediate mitigation. First check whether the primary is truly unreachable versus merely degraded (high load, a stuck query, disk pressure); a degraded-but-reachable primary may be fixable in place (kill a runaway query, add I/O capacity) without the risk of a promotion. If it is genuinely unreachable, fence it (revoke its credentials or otherwise ensure it cannot accept writes if it unexpectedly comes back mid-recovery, which prevents a split-brain where two nodes for the same shard both think they are primary), then promote the most caught-up in-sync replica for that shard specifically, and update the routing layer's shard map so application traffic for that shard's key range goes to the new primary.
3. Data-integrity checks. Before declaring the shard healthy, verify: row counts and, where feasible, checksums on recently-written tables against expectations (comparing against a recent backup or against another shard's equivalent tables if the schema allows structural comparison); confirm the promoted replica's applied position (its last-replayed log sequence number) to bound how many, if any, in-flight writes from the old primary may not have made it across, which tells you the actual recovery point objective (RPO) hit for this specific incident, not a theoretical one; and run a small set of representative application-level read/write operations end-to-end against the shard, not just database-level health checks, since a shard can be database-healthy while still broken from the application's perspective (wrong connection string, stale cached routing entry).
4. Post-recovery validation. Reconcile any writes that were in flight but unconfirmed at the moment of failure (check application-level idempotency logs or an outbox table if one exists, to identify anything that needs replaying or compensating). Document the actual timeline (detection time, fencing time, promotion time, full recovery time) against the shard's specific RTO target, and capture the RPO actually incurred (how many seconds, or how many specific rows, of writes were lost, if any) for the post-mortem, since "we recovered" and "we recovered with zero data loss" are different claims that need different evidence.
Trade-offs and pitfalls
The most common mistake is skipping the fencing step under time pressure ("it's clearly dead, let's just promote"), which is exactly the scenario that produces split-brain if the old primary was actually just network-partitioned rather than dead, and comes back mid-incident still believing it is primary. The second common mistake is declaring victory once the promoted replica is serving traffic without running the data-integrity checks, which defers discovering data loss or corruption from "during the incident, with full attention on it" to "days later, when a user reports a missing record," at which point root-causing it is far harder.
Unlock Full Question Bank
Get access to all 16 Replication, Partitioning, and Sharding interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.