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.
A product has 200,000 monthly active users growing 10% month over month. Show how you'd project traffic over the next 12 months and calculate when capacity, measured in RPS, will double. How would a seasonal spike (say, +50% in November) and a marketing campaign that doubles traffic for two weeks change your planning?
Sample Answer
Direct answer
Project monthly active users (MAU) forward with compound growth, MAU(t)=MAU0×(1+r)t, convert that into a traffic curve, and solve for when it crosses 2x today's traffic by taking a logarithm. For 200,000 MAU growing 10% month over month, capacity roughly doubles in about 7.3 months, so plan the next major capacity jump around month 7-8, not month 12. Seasonality and marketing campaigns then layer multiplicatively on top of that sustained-growth curve as separate, temporary spikes, not as part of the underlying trend line.
Projection
MAU(t)=200,000×(1.10)tAfter 12 months:
MAU(12)=200,000×(1.10)12≈627,686When does capacity double?
Solve (1.10)t=2 for t:
t=ln1.10ln2≈7.27 monthsSo baseline traffic, and the required requests-per-second (RPS) capacity that scales with it, doubles in roughly 7.3 months, meaning capacity planning should target month 7 or 8 (rounding up for safety) for the next major scale-up, not month 12 as a straight annual-planning cycle might assume.
Seasonality and campaign effects, layered on top
Both effects are multiplicative spikes on top of the baseline curve above, not adjustments to the growth rate itself:
- Seasonal spike (November, +50%): if November falls at month k in the projection, expected peak MAU (and peak RPS) for that month is MAU(k)×1.5.
- Marketing campaign (2x traffic for 2 weeks): averaged over a 4-week month, this is (2 weeks×2×+2 weeks×1×)/4 weeks=1.5× for that month's average, though the campaign's actual peak within those 2 weeks is the full 2x, which matters more for capacity than the monthly average does.
- If both land in the same month: the combined peak multiplier is 1.5×1.5=2.25× baseline for that month, not simply additive.
A different worked comparator: layering a seasonal spike on a sustained-growth target
A related planning problem shows up for a data-ingestion pipeline sized against a 10x sustained-growth target (a longer planning horizon than the 7-month doubling above): solving (1.10)t=10 gives t=ln(10)/ln(1.10)≈24.2 months, roughly two years to reach 10x baseline at the same 10% monthly growth rate. Layering a 2x seasonal spike on top of that 10x sustained target means the pipeline's peak provisioning needs to cover 10××2×=20× baseline, not just the 10x sustained figure, since the seasonal spike and the multi-year growth trend both have to be true at the same time during that one peak month. This is a materially different exercise from the 2-week campaign case above: a 20x peak on a data pipeline is usually validated with a dedicated load test that replays a realistic ingestion pattern at that multiple, rather than trusted from the arithmetic alone, since ingestion systems often have hard limits (storage throughput, downstream processing capacity) that do not scale as smoothly as a stateless request-handling tier.
Operational planning recommendations
- Use autoscaling with fast ramp policies so capacity can respond within the campaign's 2-week window, not just the multi-month growth trend, since a policy tuned only for gradual growth will react too slowly to a 2x spike that starts and ends within days.
- Load test at the predicted peak multiplier (2.25x for a combined seasonal-plus-campaign month, or 20x for the layered sustained-growth-plus-seasonal case) plus an additional safety margin, rather than testing only at the smoothed monthly-average multiplier.
- Use caching and content delivery network (CDN) offload to reduce the RPS that actually reaches origin infrastructure during a spike, which lowers how much raw compute capacity has to scale to cover the same user-facing multiplier.
- Track real-time metrics against the projected curve, so a campaign or season that outperforms (or underperforms) the assumed multiplier is caught early rather than discovered at the point of user-facing degradation.
Trade-offs and pitfalls
The most common mistake in this kind of projection is treating a marketing campaign's monthly average multiplier (1.5x) as the number to provision for, when the campaign's actual burst behavior within those 2 weeks, and especially within the peak hours of the peak days, is what capacity needs to survive; averaging over a full month smooths away exactly the spike that matters. A second pitfall is planning capacity purely off the compound-growth trend line and treating seasonality as an afterthought, when in a case like the layered 10x-plus-2x data-ingestion example, the seasonal multiplier applied to an already-large sustained-growth baseline can dwarf the trend-line number the team spent the most time modeling.
At scale, a centralized lock can become a bottleneck for high-throughput, write-heavy workloads. What architectural alternatives would you reach for instead? Discuss optimistic concurrency, partitioned ownership, sequence-based approaches, and application-level conflict resolution, and explain how each preserves correctness without a central lock.
Sample Answer
Direct answer
A centralized lock caps throughput at whatever one coordinator can serialize, so the fix is to stop needing a single point of serialization: use optimistic concurrency where conflicts are rare, partition ownership so most operations never contend at all, replace "acquire before act" with a monotonically increasing sequence that orders operations after the fact, or push conflict resolution into the application where domain knowledge can merge concurrent updates without blocking either writer.
Structured elaboration
Optimistic concurrency control. Instead of acquiring a lock before reading and writing, read a version (a row version number or timestamp), do the work locally, then write conditionally: "update only if the version is still what I read." If another writer got there first, the write is rejected and the operation retries. This preserves correctness (exactly one of the racing writers wins, the loser sees a definitive failure rather than silent overwrite) without ever blocking a reader or holding a lock across the work. It is a good fit when conflicts are the exception, not the rule; under high contention the retry rate itself becomes the bottleneck.
Partitioned ownership. Instead of one lock guarding the whole resource, split the resource (by key range, by tenant, by shard) so each partition has its own independent point of coordination, or no coordination need at all if each partition is owned by exactly one writer. Correctness comes from the partitioning key guaranteeing that concurrent operations on different partitions never touch the same data; cross-partition operations are the residual hard case and usually need one of the other three approaches or a higher-level transaction pattern.
Sequence-based approaches. Instead of gating access before the fact, assign every operation a monotonically increasing sequence number (from a counter, a log offset, or a timestamp with a tie-breaker) and let operations apply in sequence order, detecting and resolving out-of-order arrivals after the fact rather than blocking to prevent them. This is the pattern behind append-only logs and event sourcing: writers never wait for each other, and correctness comes from every reader processing the sequence in the same order.
Application-level conflict resolution. When two writers legitimately modify the same data concurrently and neither should simply lose, encode a merge rule in the application: last-write-wins with a well-defined tiebreak, a domain-specific merge (like summing two concurrent counter increments instead of picking one), or a conflict-free replicated data type whose merge function is mathematically guaranteed to converge regardless of arrival order. Correctness here means "any order of application produces the same final result," which is a stronger and harder-to-verify property than the other three approaches, but it is the only one of the four that never rejects or retries a write.
Worked example
Assume, as a planning input illustrating the shape of the trade-off rather than a measured fact: a single mutex-protected counter, serialized through one lock, sustains roughly 500 operations/sec before lock contention and context-switch overhead dominate. Partitioning it into 16 independent shard counters, each capable of the same per-shard throughput since they no longer share a lock, gives:
16×500=8,000 operations/sec aggregateThe cost of that 16x gain is that no single read sees an exact real-time global total; a caller who needs the true total sums all 16 shards, which is eventually consistent with in-flight writes rather than instantaneously exact. That is the general shape of the trade-off across all four techniques: throughput is bought by relaxing some property (blocking-free correctness for retries, or a single serialization point for a scan-and-sum read) that the centralized lock previously gave you for free.
Trade-offs & pitfalls
Optimistic concurrency degrades under high contention (retries compound instead of resolving), so it is the wrong default for a hot key with many concurrent writers, exactly the case a centralized lock was protecting. Partitioning shifts, rather than removes, the hard problem to any operation that spans partitions. Sequence-based approaches move complexity from "prevent the race" to "make every consumer correctly handle re-ordering and idempotent replay," which is a real engineering cost, not a free lunch. Application-level merge functions are the hardest to get right and the easiest to get subtly wrong (a merge rule that is not truly associative and commutative will produce different results depending on arrival order, defeating the whole point); they deserve the most scrutiny and the smallest blast radius when first deployed. The senior-level judgment call is matching contention pattern to technique, not defaulting to one everywhere.
Explain the basic queueing-theory concepts behind capacity planning: arrival rate, service rate, utilization, and the M/M/1 queue. Walk through a simple numeric example showing how a small increase in utilization can produce a disproportionate increase in average latency.
Sample Answer
Direct answer
Queueing theory formalizes something every engineer has felt intuitively: as a system gets busier, wait time does not grow in proportion to how busy it is, it grows much faster the closer utilization gets to 100%. The core quantities are the arrival rate (how fast work shows up), the service rate (how fast a server can finish work), and utilization (the ratio of the two). The M/M/1 queue is the simplest model that makes this precise, and its formulas show exactly why "we're at 80% capacity, that's fine" and "we're at 95% capacity, that's fine" are very different claims.
Core concepts
- Arrival rate (λ): the average number of requests arriving per second.
- Service rate (μ): the average number of requests a single server can complete per second, equivalently 1 divided by the mean time to handle one request.
- Utilization (ρ): the fraction of capacity in use, ρ=λ/μ for a single server. The system is only stable (queue length stays bounded over time) if ρ<1; at or above ρ=1, work arrives faster than it can be finished and the queue grows without bound.
- M/M/1 queue: a single server where arrivals follow a Poisson process (arrivals are independent and memoryless) and service times are exponentially distributed (also memoryless). "M" stands for "Markovian" (memoryless) on both the arrival and service side; "1" means a single server. This memorylessness is what makes the formulas below solvable in closed form, which is why M/M/1 is the standard first model even though real service-time distributions are rarely exactly exponential.
M/M/1 formulas (steady state)
ρ=μλAverage number of requests in the system (waiting plus being served):
L=1−ρρAverage time a request spends in the system (waiting plus service):
W=μ−λ1The denominator μ−λ is the key structural fact: as λ approaches μ, that denominator approaches zero and W diverges, which is the mathematical reason latency blows up near saturation rather than growing smoothly.
Worked numeric example
Take a single server with μ=100 requests/second.
λAλBλC=50=80=90ρAρBρC=50/100=0.5=80/100=0.8=90/100=0.9WAWBWC=1/(100−50)=0.02s=20ms=1/(100−80)=0.05s=50ms=1/(100−90)=0.10s=100msGoing from 50% to 80% utilization (a 1.6x increase in arrival rate) increases average latency from 20ms to 50ms, a 2.5x increase. Going from 80% to 90% utilization (only a 1.125x increase in arrival rate) still nearly doubles latency again, from 50ms to 100ms, a 2x increase on its own, and 5x relative to the 50% case. A modest-looking rise in utilization near the high end produces a disproportionate jump in latency; the same modest rise near the low end (say, 20% to 30%) would barely move the needle.
How this informs capacity planning
- Do not operate near ρ≈1. Pick a target maximum utilization based on the latency the service level objective (SLO) actually tolerates, commonly somewhere in the 50-70% range for workloads with real variability, leaving room for the nonlinear region above that.
- To hit a target average latency W, the required spare capacity is μ−λ≥1/W; this converts a latency target directly into a minimum service-rate requirement.
- Real service-time distributions are usually not exactly exponential, and real arrivals are usually not exactly Poisson (traffic bursts, batches, and diurnal patterns all violate the memoryless assumption), so treat the M/M/1 formulas as a directionally correct first estimate, then validate with a load test against the real distribution rather than trusting the closed-form number exactly.
- Multiple servers (an M/M/c queue) change the curve's shape but not the underlying lesson: latency still grows nonlinearly as aggregate utilization approaches saturation, it just takes more concurrent servers to keep the whole system away from that region.
Trade-offs and pitfalls
The most common mistake is reading "80% utilization" as "20% headroom, therefore safe," without accounting for how close that already is to the steep part of the latency curve; on this M/M/1 model, the jump from 80% to 90% utilization alone nearly doubles latency. A second pitfall is capacity planning entirely off average utilization while ignoring burstiness: even if average ρ looks comfortable, a service whose real arrivals come in bursts (not the smooth Poisson process the model assumes) can spend meaningful time at effective utilization far above the average, and M/M/1's steady-state numbers say nothing about that transient behavior.
A producer spike is causing your downstream consumers to fall behind. Design a strategy to handle the backpressure and prevent data loss: queue sizing, partitioning, autoscaling the consumers, rate-limiting the producers, and a retry/dead-letter-queue design, plus monitoring to detect consumer lag. How would you implement backpressure propagation back to the producers?
Sample Answer
Direct answer
Handling a producer spike safely means combining five things: size the queue and its partitions to absorb a bounded amount of lag, autoscale consumers off a lag metric rather than a fixed count, rate-limit or throttle producers once the queue's high-watermark is crossed, retry transient failures with a bounded backoff before routing to a dead-letter queue (DLQ, a holding area for messages that repeatedly fail processing), and propagate the backpressure signal back to producers so they slow down instead of continuing to push into an already-saturated pipeline.
Structured elaboration
flowchart LR
P[Producer] -->|publish| RL[Ingress rate limiter]
RL -->|accepted| Q[Partitioned queue / broker]
Q --> CG[Consumer group]
CG -->|success| DS[Downstream service]
CG -->|retries exhausted| DLQ[Dead-letter queue]
Q -->|lag metric| AS[Autoscaler]
AS -->|scale consumers| CG
Q -->|429 / Retry-After past watermark| RL
RL -->|backpressure signal| P
1. Partitioning and queue sizing. Partition by a key that spreads load evenly (and watch for a hot key overwhelming a single partition). Size the buffer so it can absorb the maximum lag you're willing to tolerate before you consider the system degraded:
buffer size≈peak message rate×max tolerable lag (s)×avg message size
2. Consumer autoscaling. Scale consumer count off consumer-group lag (how far behind the latest message the consumer group is), not CPU alone, since a slow downstream dependency can starve consumers of CPU while lag still grows. Use a sticky partition-assignment strategy to avoid unnecessary rebalancing churn when scaling.
3. Producer rate limiting and backpressure propagation. A token-bucket limiter at the ingress accepts bursts up to a defined rate. When the broker's queue depth or lag crosses a high-watermark, ingress starts returning a rejection (HTTP 429 with a Retry-After header, or the internal-service equivalent) so well-behaved producer clients back off with exponential backoff and jitter rather than continuing to push.
4. Retry and DLQ design. Consumers retry transient failures a bounded number of times with exponential backoff, tracking attempt count in message metadata. After the retry budget is exhausted, the message moves to a DLQ with enough context (original offset, error, timestamp) to investigate and replay later. Retries that would otherwise repeatedly hammer a struggling downstream dependency should integrate with a circuit breaker (a separate high-availability pattern that stops sending traffic to an unhealthy dependency; not re-derived here, just named as the mechanism this design composes with) so a consumer stops attempting work it already knows will fail, and rejects at a rate proportional to the downstream's observed health rather than retrying blindly.
5. Ordering, priority, and duplicates. If different message classes have different urgency, separate priority queues (or topics) let urgent work skip the line, but this breaks strict cross-class ordering; combined with at-least-once delivery, reordering across priority tiers increases the chance of duplicate or out-of-order processing at the consumer. If ordering matters within a given key, route that key to a single partition; consumers must be idempotent (safe to process the same message twice) regardless, since at-least-once delivery is the realistic guarantee here.
6. Monitoring and alerting. Track consumer lag per partition, queue size in bytes, incoming and outgoing throughput, DLQ growth rate, and producer-rejection rate. A per-partition lag heatmap surfaces hot partitions that an aggregate lag number would hide.
Worked example
Queue sizing. Given a peak message rate of 5,000 messages/second, a maximum tolerable consumer lag of 300 seconds, and an average message size of 2 KB:
5,000×300×2KB=3,000,000KB=3,000MB=3GB
Adding 1.5x headroom for burst variance beyond the stated peak:
3GB×1.5=4.5GB
Message-pattern choice for a real-time notification system. A concrete system illustrates why the messaging pattern matters, not just the queue sizing:
| Pattern | Use in a real-time notification system | Trade-off |
|---|---|---|
| Fan-out / pub-sub | One "user action occurred" event needs to reach email, push, and in-app notification services independently | Each subscriber gets every message; delivery guarantees are typically per-subscriber, not transactional across all of them |
| Work-queue / competing consumers | A pool of workers sends the actual push notifications, sharing the workload | Good for horizontal throughput; ordering across the pool isn't guaranteed unless you partition by recipient |
| Delayed retry | A push notification failed because the device was offline; retry in 30 seconds, then 5 minutes, then an hour | Needs a scheduling mechanism (a delay queue or a timer-based re-publish), not just an immediate retry loop |
Autoscale cost-blowup case. A team scaling consumers directly off instantaneous lag saw a scale-out storm: every consumer group scaled up in lockstep at the exact same lag threshold, adding far more capacity than the actual backlog needed and driving cost up without proportionally reducing lag, because the scale signal itself spiked in a coordinated, self-reinforcing way. The fix was two-fold: batch messages per consumer poll so each consumer does more useful work per unit of scaling, and smooth the autoscale trigger by scaling off a windowed average of lag rather than its instantaneous value, so a brief coordinated spike doesn't trigger a coordinated scale-out.
Trade-offs & pitfalls
Anti-patterns to avoid, all variants of "the queue or the pattern doesn't actually distribute the load":
- A single global queue serving millions of messages with no partitioning, which caps throughput at whatever one consumer thread can pull.
- Long-running, lock-holding database transactions inside a message handler, which serialize otherwise-parallel consumers against each other.
- Cron jobs scheduled to run at the same wall-clock time on every node, creating a synchronized load spike instead of smoothed background work.
- Synchronous cross-service call chains inside the consumer path, which mean one slow downstream service directly throttles the whole pipeline's throughput.
Choosing among load-shedding strategies. These are not interchangeable; they trade off differently:
| Strategy | What happens under overload | Best suited for |
|---|---|---|
| Bounded queue, blocking producer | Producer stalls until space frees up | Internal pipelines where slowing the producer is acceptable and safe |
| Client-side throttling | Producer proactively limits its own send rate before hitting a limit | Well-behaved internal clients that can self-regulate |
| Circuit breaker | Stops sending to a dependency entirely once it's judged unhealthy | Protecting against a failing downstream, not against a merely slow-but-healthy one (an HA/DR-owned mechanism, named here as one lever among several) |
| Adaptive load shedding | Selectively drops or degrades lower-priority work while keeping critical work flowing | Systems where not all requests are equally important, and graceful degradation beats uniform slowdown |
- Aggressive autoscaling reduces lag but increases cost and rebalance frequency; warm standby consumers and a sticky assignor reduce the churn cost of scaling.
- DLQ messages are not "handled," they're deferred. A growing, unmonitored DLQ is a silent failure; alert on DLQ growth rate, not just its existence.
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.
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.