Scalability Patterns and Techniques Questions
Scaling a system to handle growth in traffic and data: horizontal versus vertical scaling, statelessness, sharding and partitioning strategies, read replicas, and connection pooling. Covers capacity estimation, identifying bottlenecks, and the tradeoffs each scaling axis introduces. The general toolkit for taking a design from thousands to millions of users.
Design an operational plan and technical implementation to reshard a live sharded database with minimal downtime. Cover choosing the new shard key or shard count, the data-migration strategy (online migration, dual writes, change-data-capture), routing updates, throttling the migration, validation steps, and your rollback procedure.
Sample Answer
Direct answer
Resharding a live database with minimal downtime is an online migration: keep the old topology serving traffic while you copy data to the new one under a throttle, use dual writes or change-data-capture (CDC) to keep the copy current, validate it against the source before trusting it, and cut routing over in a small, reversible step rather than a single big-bang switch. The hard parts are rarely the copy itself; they are choosing a shard key/count that won't need redoing soon, keeping writes ordered correctly during the overlap window, and having a rollback that is actually exercised, not just documented.
Structured elaboration
Choosing the new shard key or shard count
- Analyze real access patterns (write hotspots, cardinality, range-vs-hash trade-offs) from production telemetry rather than guessing; target per-shard headroom (commonly keeping any shard well under its saturation point) so the new topology doesn't need revisiting immediately.
- For a hot single shard suffering write contention, the two concrete techniques are rekeying (choosing a shard key that spreads the contended writes, if the current key is the root cause) and range-splitting (dividing the shard's existing key range into two or more ranges, each becoming its own shard, when the key itself is fine but the range has outgrown one node).
- For a lookup-based versus algorithmic shard-mapping layer: an algorithmic mapping (consistent hashing, which places nodes and keys as points on a circular hash space called a ring, so a topology change only reassigns the small slice of keys near it, or the simpler hash-mod-N) needs no metadata lookup and scales trivially, but it distributes tenants roughly evenly by key, which fails badly when tenant sizes vary by orders of magnitude (a large enterprise tenant next to hundreds of tiny ones). A lookup-based mapping (an explicit tenant-to-shard table) costs a metadata hop per request but lets you place large tenants on dedicated shards and pack small tenants together deliberately. For a multi-tenant system with that kind of size skew, prefer lookup-based mapping, or a hybrid: algorithmic mapping for the default pool of ordinary tenants, with a lookup override for the small number of outsized ones.
Data-migration strategy
- Online copy under CDC: stream changes from the source shard(s) via a CDC pipeline (e.g., a log-based change stream) into the target topology while a background job bulk-copies existing data in ranges. The CDC stream and the bulk copy have to be reconciled (apply CDC events that land inside an already-copied range, buffer or replay ones that land ahead of the copy cursor).
- Dual writes with a quiesce window: to guarantee transaction ordering is preserved for records that are actively being migrated, briefly pause (quiesce) writes to the specific key range being cut over, drain the in-flight CDC backlog for that range so source and target agree, flip routing for just that range, then resume writes. This bounds the ordering risk to a small, deliberately-chosen window instead of trying to reason about ordering across an open-ended dual-write period for the whole dataset.
- Split-and-merge at scale: for a large, contended shard, resharding is a split (one shard's range divides into two, each getting its own routing-table entry) rather than a full-dataset migration; the reverse operation, merge, combines two under-loaded shards back into one when growth was over-provisioned. At terabyte scale, both operations are driven by range boundaries and routing-table updates rather than moving the whole dataset, which keeps a single split or merge bounded in time and blast radius.
- A cross-topology special case: migrating a stateful store (for example, a session store) from a single-region deployment to a multi-region sharded cluster follows the same dual-write skeleton, but adds a proxy layer in front of both topologies so the application never talks to the store directly during the migration; the proxy performs parity verification (comparing responses from the old and new paths for the same key) before fully cutting traffic over, which catches migration bugs before they're user-visible.
flowchart TD
A[Old shard topology] -->|CDC stream| B[Change pipeline]
A -->|throttled bulk copy| C[New shard topology]
B --> C
C --> D[Shadow reads: compare old vs new]
D -->|parity confirmed| E[Routing cutover, range by range]
D -->|mismatch| F[Pause cutover, reconcile]
E --> G[Quiesce window per range: drain, flip, resume]
G --> H[Old topology retired]
Routing updates
Introduce a migration-aware routing layer (gateway or client-side routing table) so application code never encodes shard topology directly. Roll the new routing out in stages: internal/test traffic, a small canary of production traffic, then full cutover, with each stage able to fall back to the previous routing table without a code deploy.
Throttling
Throttle the copy and CDC-apply workers adaptively against replication lag, tail latency, and source-shard CPU/I/O, not a fixed rate, so migration traffic backs off automatically when it's competing with production load. As a worked illustration of sizing a per-shard step against an operational target: suppose the team's service-level agreement (SLA) is for each per-shard rebalance step to complete in well under two minutes even across a 200+ node cluster, and a given shard holds roughly 50 GB of data with the copier capped at 500 MB/s per shard to protect production I/O. The data-transfer portion alone takes
which leaves about 20 seconds of headroom under the 120-second target for updating ring/routing metadata and completing leader election (the process by which the new shard's replica-set nodes agree on which one of them becomes the active primary/writer) for the new shard's replica set, before the step is considered done. That headroom is the number to watch: if metadata propagation or leader election routinely eats into it, the fix is a faster metadata path, not a bigger copy-bandwidth cap.
Automating rebalancing across many shards
When rebalancing hundreds of shards simultaneously rather than one at a time, the automation has to cap total concurrent migrations (global throttle, not just per-shard), and it must keep secondary-index consistency in scope explicitly: an index that's rebuilt or re-pointed on a different schedule than its base table will silently return wrong results for the window in between, so index cutover needs to be part of the same per-range quiesce step as the base data, not a follow-up job.
Validation
- Row counts and per-range checksums between source and target.
- Shadow reads: serve a fraction of real production reads from the new topology in parallel with the old one (without returning the shadow result to the client) and compare, which surfaces correctness bugs under real traffic patterns before any client depends on the new path.
- Client-side cache invalidation during cutover: if clients or edge caches hold entries keyed by the old routing, cutting a range over without invalidating those cached entries serves stale-routed responses; the cutover step has to include a cache-invalidation signal (a version bump on the routing key, or explicit invalidation) for anything caching downstream of the router.
- End-to-end application-level smoke tests against the new topology before removing fallback to the old one.
Rollback
Keep dual writes (or the CDC stream) active until validation passes; if a problem surfaces, stop applying new CDC events, revert routing to the old topology for the affected range, and resume from the last confirmed-consistent checkpoint rather than restarting the whole migration. Because cutover happens range-by-range behind a quiesce window, rollback scope is bounded to the ranges already flipped, not the whole dataset.
Trade-offs & pitfalls
- A migration that skips the quiesce window to avoid any write pause will have an ordering gap for records touched during the exact moment of cutover; a short, well-instrumented pause on a narrow key range is a better trade than an unbounded consistency risk.
- Algorithmic shard mapping is simpler to build and reason about, but for multi-tenant systems with orders-of-magnitude tenant-size variance, defaulting to it produces shards that are balanced by tenant count and wildly unbalanced by load; verify the mapping choice against actual per-tenant load, not tenant count.
- Skipping shadow reads to save migration time is the single most common way correctness bugs escape into production, because checksums catch data-copy errors but not query-behavior differences (an index that returns results in a different order, a range boundary edge case).
- Treating secondary-index rebuild as a background job that can lag the base-table cutover is a frequent source of silent incorrect reads immediately after a migration; keep index and base-data cutover atomic per range.
Explain how read replicas for relational databases improve read throughput. Describe the common replication modes (asynchronous versus semi-synchronous) and the operational pitfall of replication lag. What monitoring and safeguards would you put in place to detect and handle a lagging replica?
Sample Answer
Direct answer
Read replicas are read-only copies of a primary relational database that let you route read-heavy traffic away from the primary, so read throughput scales roughly with the number of replicas instead of being capped by one machine's capacity. The two common replication modes trade off write latency against durability: asynchronous replication is fast but can lag, semi-synchronous replication waits for at least one replica to acknowledge before confirming a write, trading some write latency for a stronger durability guarantee. Replication lag, the gap between a write landing on the primary and appearing on a replica, is the operational pitfall that follows directly from choosing asynchronous replication for speed.
Structured elaboration
Why read replicas scale reads
A single primary database has a ceiling on how many queries per second (QPS, the standard measure of database or API load) it can serve before CPU, memory, or I/O saturates. Since most application workloads are read-heavy relative to writes, adding replicas that each hold a full copy of the data lets read queries fan out across many machines while writes still funnel through the one primary that owns correctness. This is a read-scaling pattern specifically: it does nothing for write throughput, which is bounded by the primary alone (write scaling is a separate problem, addressed by partitioning or sharding rather than replicas).
Replication modes
- Asynchronous: the primary commits and returns success to the client without waiting for any replica to apply the change. Write latency stays low and unaffected by replica health, but a replica can fall arbitrarily behind under load, and if the primary fails before a replica caught up, those last writes are lost from that replica's perspective.
- Semi-synchronous: the primary waits for acknowledgment from at least one replica (that the write was received, not necessarily fully applied) before confirming the commit to the client. This bounds the worst-case data loss to writes that hadn't yet reached any replica, at the cost of added write latency and a risk that a slow replica introduces a stall on every write.
This is standard terminology in an online transaction processing (OLTP) context, meaning a workload of many small, individual reads and writes (as opposed to large analytical scans); read replicas are one of the first tools reached for once a single OLTP primary starts to strain under read load.
Replication lag as the operational pitfall
Lag arises from network delay, I/O contention on the replica, or the replica processing a backlog of changes slower than the primary produces them. Its consequence is stale reads: a client that just wrote data may query a replica and not see its own write, or two clients may observe the data in different states depending on which replica they hit.
Read-routing design to minimize stale reads while maximizing throughput
The application layer, not just the database, needs a policy for which reads are allowed to be stale:
- Reads that must reflect the client's own very recent write (a user viewing the profile they just edited) should go to the primary, or to a replica only after confirming its lag has caught past that write's position.
- Reads that tolerate a small staleness window (a public dashboard, a search index, an analytics report) should go to replicas by default, since that is where the throughput gain comes from.
- A hybrid policy, sometimes called read-your-writes routing, pins an individual client to the primary (or to a replica known to be caught up) for a short window right after that client writes, then lets subsequent reads fall back to any replica.
Monitoring and safeguards
| What to watch | Why |
|---|---|
| Replication lag (seconds and/or log position gap) | Direct measure of staleness risk; the number a routing or alerting decision should key off |
| Replica apply rate versus primary write rate | Rising divergence predicts lag will keep growing rather than catch up |
| Replica CPU/IOPS (input/output operations per second)/network | Identifies whether the replica itself is the bottleneck causing lag |
| Query load on replicas (especially long-running analytical queries) | A single expensive query can starve the replication-apply thread and cause a lag spike |
Safeguards built on that monitoring: alert when lag crosses a threshold tied to the application's staleness tolerance; throttle or move expensive ad hoc/analytical queries off replicas that also serve latency-sensitive reads; and, for any workflow that promotes a replica (to primary, during a failure), require lag to be at or near zero before promotion, since promoting a lagging replica means accepting the unreplicated writes as lost. That promotion and failover mechanics belong to the high-availability side of the system, not to the read-scaling pattern itself, but the monitoring described here is exactly what feeds that decision when it happens.
Worked example
A social-media-style application serves 9,000 reads per second and 1,000 writes per second against a single primary that is now CPU-saturated on reads. Adding 3 asynchronous read replicas and routing all reads except "read-your-own-write" cases to a round-robin pool across them reduces the read load on the primary from 9,000 QPS to roughly 0 (reads move off entirely), leaving the primary handling only the 1,000 writes/second plus the small share of reads that require read-your-writes freshness. Each replica now carries roughly 9,000 / 3 = 3,000 reads/second on average, well within a single replica's typical headroom, illustrating the linear-ish scaling read replicas provide as long as write volume itself stays within what one primary can sustain.
Trade-offs & pitfalls
- Read replicas scale reads only; teams sometimes reach for them to fix a write-contention problem, which they cannot, because writes still funnel through one primary.
- Asynchronous replication's low write latency is attractive, but skipping the read-routing design above (treating every replica as equally fresh) is the most common way stale reads leak into user-facing behavior.
- Semi-synchronous replication reduces data-loss risk but can introduce write stalls if the acknowledging replica itself becomes slow; it shifts risk from data loss to latency, it does not eliminate risk.
- Promoting a lagging replica during an incident, without checking lag first, can silently drop the most recent committed writes; this is a data-loss event dressed up as a recovery action.
During a large traffic spike, your cloud autoscaler hit a quota limit and the service breached its SLOs. As the incident commander, what immediate mitigations would you take (manual scaling, throttling), how would you communicate with your cloud provider and stakeholders, and what medium-term fixes (quota monitoring, predictive scaling) would you put in place? How would you update runbooks and alerts to prevent a repeat?
Sample Answer
Direct answer
As incident commander, the first move is to stabilize without waiting on the cloud provider: manually add capacity wherever quota headroom still exists, and shed or queue the traffic you can't serve so the SLO (service level objective, the target you've committed to for availability or latency) breach doesn't get worse. In parallel, escalate to the provider and give stakeholders a clear, honest status. The incident is not resolved by root-causing; it's resolved by capping the damage now and then building the quota monitoring, predictive scaling, and updated runbooks that make sure a known quota ceiling never again gets discovered mid-spike.
Structured elaboration
Immediate mitigations (first 0-30 minutes)
- Manually provision capacity in a region, account, or instance family that still has quota headroom, preferring larger instance types over more instances if the limiting quota is instance count rather than vCPU.
- Throttle non-critical traffic at the edge: return 429 (rate limited) or 503 (unavailable) with a
Retry-Afterheader for low-priority requests (bulk exports, background jobs), preserving capacity for the traffic that actually matters. - Apply admission control instead of dropping traffic uniformly: if only a fraction of demand can be served, let requests in up to capacity (first-come or a fair queue with an ETA) rather than randomly failing a percentage of everyone's requests. This is what separates "everyone gets a slow, unfair experience" from "most users are unaffected and the rest see a clear queue."
- If a queue sits in front of a write-heavy path, let it absorb the burst rather than pushing writes straight through to the database at spike rate.
Communication
- Cloud provider: open a severity-1 support case immediately with the quota metric, current usage, and requested limit; this is not a channel to wait on for immediate relief, so treat it as a parallel track, not the mitigation itself.
- Internal: post a structured status (what's affected, current mitigation, next update time) to a single incident channel on a fixed cadence, not ad hoc.
- Stakeholders and, if customer-facing, a status page: state the actual impact honestly and give a concrete next-update time rather than a resolution promise you can't back.
Medium-term fixes
The underlying gap this incident exposes is that scaling was purely reactive with no advance knowledge of demand. The fix is to design ahead for the traffic patterns you can actually anticipate, which fall into a few recognizable shapes:
- A short, extreme, scheduled burst (for example, a flash sale expected to run around 100,000 requests/second for roughly 10 minutes): because the timing is known in advance, pre-scale capacity ahead of the event rather than relying on the autoscaler to react to it live, put a queue in front of the write path to smooth the burst instead of hitting the database at peak rate, and stage the pre-scale as a monitored, reversible step (canary the added capacity, keep an automatic rollback if error rates rise) rather than a one-way commit.
- A sharp, less-precisely-timed spike (for example, a marketing email that drives a 10x jump within about 30 minutes): the exact start time is fuzzier than a scheduled sale, so the plan needs a short-term component (aggressive reactive scaling plus throttling as a backstop for the first few minutes) and a separate medium-term component (pre-notifying the team before large sends go out, and pre-warming capacity ahead of known send windows so the reactive layer isn't starting from a cold baseline).
- An extreme, unscheduled-feeling spike far above baseline (for example, roughly 100x normal traffic during a flash sale): at that magnitude, no autoscaler reacts fast enough on its own, so the design has to include pre-warmed capacity sized to the expected peak and admission control that treats all waiting users fairly (a first-come or randomized queue with a visible position or ETA) instead of an uncontrolled scramble where whoever's request happens to land first wins and everyone else gets errors.
Across all three shapes, the common fix is the same: stop treating "quota is sufficient" as an assumption and start treating it as a monitored, tested constraint, with permanent quota increases requested ahead of realistic peak-plus-buffer, not discovered during an incident.
Runbook and alert updates
- Add a dedicated quota-exhaustion playbook: exact commands for manual provisioning in each region/account, the throttling levers available, the provider escalation contact path, and a decision matrix for when to degrade vs. scale vs. fail over.
- Add quota-utilization alerts at conservative thresholds (for example, flagged at 60/75/90% of the current limit as an illustrative staging, not a universal standard) so the team requests an increase before hitting the wall, not after.
- Add an alert specifically for "autoscaler issued a scale-out that did not result in additional serving capacity within an expected window," which is a different failure than "no scale-out was attempted" and needs its own signal.
- Schedule runbook drills (tabletop or live) that specifically simulate a quota ceiling being hit, since a runbook that has never been rehearsed against this exact failure mode is unlikely to be followed correctly under real pressure.
Worked example
Assume, as stated planning inputs rather than measured facts: steady-state traffic of 5,000 requests/second (RPS) served by 50 instances, giving a baseline capacity ratio of
50 instances5,000 RPS=100 instanceRPSA flash-sale spike hits 100,000 RPS for about 10 minutes, which is a total request volume of
100,000 sreq×600s=60,000,000 requestsAt 100 RPS/instance, serving the full spike needs 100,000 / 100 = 1,000 instances. If the account's instance quota is capped at 200, the achievable capacity at that ceiling is
200 instances×100 instanceRPS=20,000 RPSwhich is only a fifth of demand, so the fraction of traffic that has to be shed or queued once the quota ceiling is hit is
100,000100,000−20,000=0.80an 80% shortfall. That number is the case for admission control over random shedding: dropping 80% of requests indiscriminately produces a bad experience for everyone, while admitting exactly the 20,000 RPS the fleet can serve and fairly queuing the rest (with a visible wait, not a silent failure) turns the same shortfall into a bounded, predictable degradation instead of a chaotic one. It's also the case for the medium-term fix: a permanent quota request sized to at least the 1,000-instance peak, not the 200-instance historical average, is what prevents this specific ceiling from being hit again.
Trade-offs & pitfalls
- An emergency quota increase request is not instant relief; the mitigation plan cannot depend on the provider responding within the incident window, only the medium-term fix (a pre-approved higher baseline quota) removes that dependency.
- Manually bringing up capacity in a different region can violate data-residency or added-latency assumptions the service normally relies on; that trade-off needs to be made consciously during the incident, not discovered afterward.
- Throttling everyone equally punishes both low- and high-value traffic the same way; admission control that's blind to request importance is only marginally better than dropping randomly.
- Alerting only on "the autoscaler failed to scale" misses the earlier, more useful signal: quota utilization climbing toward its ceiling before a scale-out attempt ever fails.
You need to vertically scale a production stateful database (increase CPU and memory on the primary instance) while minimizing downtime and preserving data consistency. Walk through the runbook you would execute: pre-checks, rolling steps, fallback options, and monitoring to verify success. Assume cloud-managed instances and the ability to create a temporary read replica to help with the cutover.
Sample Answer
Direct answer
Use the temporary read replica as the mechanism that turns an in-place resize (which can mean real downtime) into a controlled cutover: provision the replica already at the larger CPU/memory spec, let it fully catch up to the primary, briefly pause writes, promote the replica to primary, and repoint the application. The actual write-unavailability window is bounded by how long it takes to drain in-flight writes and flip the connection target, not by the resize operation itself, which is why this pattern minimizes downtime even though it isn't strictly zero-downtime.
Structured elaboration
Pre-checks
- Confirm the exact target CPU/memory spec against measured load, not a guess, and confirm a maintenance window and a communicated service level objective (SLO, the measurable target for allowed downtime or latency impact) for the operation.
- Take a fresh on-demand snapshot immediately before starting, independent of the replica strategy, as a last-resort fallback.
- Verify current replication lag baseline and that the environment supports creating a same-region replica sized larger than the current primary.
- Confirm the automation (scripts, IaC) for promotion and connection-string cutover has been tested outside of this incident, not written live.
Rolling steps
- Create a read replica provisioned at the new, larger instance spec. Let it catch up and monitor replication lag until it's negligible and stays that way for a sustained period, not just a single low reading.
- Briefly quiesce writes on the current primary (put the application into a short read-only or write-paused mode).
- Promote the replica to primary. Because it was fully caught up at the moment of promotion, this preserves the data that existed at quiesce time.
- Repoint the application's write target to the newly-promoted primary (a connection-string or routing change, ideally something that doesn't require an application redeploy).
- Resume writes and run smoke tests against critical read and write paths.
- Rebuild redundancy: the original (smaller) instance can be resized and re-added as a replica, or replaced, restoring the topology's normal read-replica count.
Fallback options
- If the replica fails to catch up before the maintenance window closes, abort the promotion; investigate whether replication is network- or I/O-bound, and either wait for a longer window or address the bottleneck before retrying.
- If a data mismatch or unexpected inconsistency is detected after promotion, the fallback is the pre-operation snapshot, not the old primary (which may now be behind); restore from snapshot to a fresh instance if this happens.
Monitoring
- Before: replication lag trend over a real observation window, not a single point-in-time check, plus baseline CPU/memory/connection counts to compare against post-cutover.
- During: replication lag right up to the promotion moment, since promoting a replica that's meaningfully behind means losing whatever writes happened after its last applied transaction.
- After: error rates, write and read latency, and a targeted data check (row counts or checksums on a few critical tables, or confirming the most recent known transactions are present) rather than assuming success from the absence of alarms.
Worked example
A safe promotion policy might require replication lag to stay under 1 second for a sustained 5-minute window before promotion is allowed (a stated operational threshold for this runbook, not a universal rule that applies to every workload). The actual write-pause duration during cutover isn't a fixed number worth quoting as a general fact, since it depends on the application's connection pool behavior, not on the database resize itself: it's bounded by how long the app takes to drain in-flight writes and how quickly its clients reconnect to the new endpoint after the connection target flips, which is exactly why this pattern is described as minimizing downtime, not eliminating it. If the application's reconnect and retry logic is slow or missing, the same database-side runbook produces a much longer perceived outage even though the database steps themselves didn't change.
Trade-offs & pitfalls
- This is not truly zero-downtime: promoting a replica that isn't fully caught up loses whatever writes landed after its last applied transaction, so the safety of the whole procedure hinges on verifying lag is genuinely near zero at the moment of promotion, not assuming it.
- If the application cannot tolerate even a brief write-pause, this pattern isn't sufficient on its own; a true zero-downtime requirement needs a different approach, such as a proxy layer that queues writes during cutover.
- Before building a custom replica-promotion runbook, check whether the cloud provider's native "modify instance class" operation already performs an equivalent internal promote-and-swap; if it does, it may be simpler and better-tested than a hand-rolled version of the same idea.
- The replica-promotion mechanics here (catching up, promoting, cutting over) are a practical means to a scaling end; the deeper mechanics of replication modes and failover consensus are a related but distinct topic from the scaling procedure itself.
You're investigating data corruption in an order service that turns out to be caused by cache-invalidation races: concurrent writes and cache updates left stale or missing order state. Walk through the likely race conditions behind this, propose a fix, and explain how you'd roll it out safely without risking a repeat of the corruption.
Sample Answer
Direct answer
The likely cause is a gap between when the database write commits and when the cache reflects it, combined with concurrent writers racing each other: one request's update gets silently overwritten by another (a lost update), and a reader in between sees data that matches neither writer's final state (a read-after-write violation surfaced through the cache rather than the database). The fix is to remove the ambiguity about ordering, either by making the cache update part of the same atomic step as the write, or by making concurrent writes detect and reject conflicting the ones based on stale reads, and to roll it out behind instrumentation and a staged rollout so a repeat of the corruption is caught before it reaches every order.
Structured elaboration
How the race actually happens
Two request paths that both read-modify-write the same order, with an asynchronous cache refresh in between, create two related but distinct failure patterns:
- Lost update: Request A reads the order, computes a new value based on that read, and writes it. Request B does the same concurrently, based on the same stale read. Whichever writes last overwrites the other's change, and the DBMS has no way to know a conflict occurred because neither write technically failed.
- Read-after-write (surfaced via the cache): even if the database itself resolves writes correctly, the cache refresh that's supposed to reflect a new write can fire out of order relative to a concurrent write, or can itself be built from a stale read, leaving the cache holding a value that never actually existed as a single consistent database state.
Fix options, with the trade-off each one makes
- Write-through caching: update the cache synchronously as part of the same operation that writes the database, instead of via a separate asynchronous invalidation step. This closes the window between "database write commits" and "cache reflects it" entirely, at the cost of higher write latency and the need to handle a cache write failure without silently diverging from the database.
- Versioned objects with optimistic compare-and-swap: attach a version (or timestamp) to the order, and require a write to specify the version it read; the write only succeeds if the version still matches, otherwise it's rejected and the caller must re-read and retry. This directly prevents lost updates without taking a lock, but it pushes retry logic onto every caller and adds a field to reason about.
- Single-flight cache refresh: ensure only one in-flight refresh per key at a time (a mutex or an in-process/distributed single-flight guard), so concurrent cache misses for the same order don't trigger redundant, possibly conflicting reads and writes back to the cache. This prevents cache stampede and duplicate refresh work, but needs a coordination mechanism that works across all instances if the service runs on more than one.
- Append-only event store: instead of overwriting order state in place, store each change as an immutable event and derive current state by replaying (or materializing) the event stream. This removes the overwrite race entirely, since nothing is ever overwritten, but it's a genuine architecture change: existing read paths, the cache itself, and any code that assumes "the order row" as the source of truth all need to be rebuilt around the event stream.
Safe rollout plan
- Add instrumentation before changing anything: log version numbers and cache-refresh timing so you can see the race happening in production traces (application performance monitoring, APM, tooling is the natural place for this), rather than inferring it from corrupted orders after the fact.
- Reproduce the failure deliberately in staging with concurrent writers hitting the same order, to confirm the fix actually closes the window rather than just narrowing it.
- Start with the least invasive fix that addresses the immediate cause, typically single-flight cache refresh, since it requires no data-model change and directly stops the concurrent-refresh part of the problem.
- Introduce optimistic versioning on the write path behind a shadow mode (write the version check's would-be result to logs without enforcing it yet) to confirm it wouldn't reject legitimate traffic before making it authoritative.
- Roll out write-through caching or the versioning enforcement behind a canary on a small slice of order traffic, watching for rejected-write rate and cache-DB divergence checks, with a fast rollback (a feature flag reverting to the old refresh path).
- Treat the append-only event store as a separate, longer-term project scoped to one bounded context first, not part of the immediate corruption fix.
Worked example
A concrete interleaving that produces both failure patterns in one incident, starting from order O123 with qty = 2, version = 5, cached:
| Step | Actor | Action | Database state after | Cache state after |
|---|---|---|---|---|
| t0 | - | starting state | qty=2, v5 | qty=2, v5 |
| t1 | Request A (update quantity to 3) | reads qty=2, v5 | qty=2, v5 | qty=2, v5 |
| t2 | Request B (cancel order) | reads qty=2, v5, independently of A | qty=2, v5 | qty=2, v5 |
| t3 | Request A | writes qty=3 without checking version | qty=3, v6 | qty=2, v5 (invalidation not yet applied) |
| t4 | Request B | writes status=cancelled based on its t2 snapshot, overwriting the whole record including quantity | status=cancelled, qty=2, v7 | qty=2, v5 |
| t5 | Async cache invalidation for A's write | fires late, evicts the stale entry | status=cancelled, qty=2, v7 | empty; next read repopulates from the database |
At t3, any reader hitting the cache sees qty=2 even though the database already committed qty=3, a read-after-write violation. By t4, Request A's quantity update is gone entirely, overwritten by Request B's write, which was computed from a snapshot that predates A's change: a lost update. Neither the database's final state (status=cancelled, qty=2) nor the cache's intermediate state at t3 (qty=2, v5) reflects what actually happened; both writers "succeeded," but the system lost information a version check would have caught at t4 (Request B's write would have been rejected because its assumed version, 5, no longer matched the current version, 6).
Trade-offs & pitfalls
- Fixing only the cache side (single-flight refresh, write-through) does not fix the underlying database-level lost update if two writers can still race each other there; the two failure modes need addressing separately, even though they were discovered together.
- Optimistic versioning shifts work onto callers (they must handle a rejected write and retry), which is a real API contract change, not just an internal implementation detail; every caller needs to be audited, not just the one that triggered this incident.
- A rollback plan that only reverts code but leaves already-corrupted orders in place doesn't fix the incident; the rollout plan needs a separate reconciliation step to identify and correct orders affected before the fix shipped.
- Testing "under load" without deliberately forcing the specific interleaving (two writers targeting the same key, timed to overlap) can pass even with the race still present, since races are timing-dependent and won't reliably reproduce under generic load alone.
Unlock Full Question Bank
Get access to all Scalability Patterns and Techniques interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.