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.
You need to shard a user-profile service that is projected to grow from 10 million to 1 billion users. Walk through your shard-key selection criteria, the migration approach from a single shard to many, and how you would rebalance shards with minimal downtime. Compare the trade-offs of consistent-hashing and range-based sharding for this workload.
Sample Answer
Direct answer
For a user-profile service growing from 10 million to 1 billion users, I would shard on a hashed user ID for even distribution, migrate via a dual-write-then-cutover process driven by a routing layer (not a hard-coded formula the application computes itself), and rebalance by moving individual partitions with change-data-capture (CDC) to keep the source and destination in sync until a near-instant cutover. Consistent hashing wins for this workload because access is almost always by single user ID with no need for range scans, and its whole advantage is minimizing data movement when shards are added.
Structured elaboration
Shard-key selection criteria
- Cardinality and uniform distribution: the key must have enough distinct values, and typical access patterns must spread evenly across them. A hashed user ID satisfies this; a raw signup-timestamp-derived ID does not, because recent users cluster on a few shards while old ones sit cold.
- Stability: the key must never change after assignment.
user_idqualifies;emailorusernamedo not, since a rename would require moving the row. - Query locality: does the workload need range scans or joins across users? For a profile service, almost all reads and writes are single-user lookups, so locality by an ordered range is not needed and a hash-based spread is safe.
- Hot-key exposure: a small number of accounts (very active or high-visibility profiles) can dominate traffic on their shard regardless of key choice; the design needs an explicit way to detect and mitigate that (traffic-based alerting plus optional per-key overrides), not an assumption that hashing alone prevents hotspots.
- Geographic skew: if the user base concentrates in specific regions rather than distributing evenly worldwide, a pure hash on user ID can still produce uneven infrastructure load even though key distribution is even, because a shard's users may all be far from the datacenter serving them, or a region's traffic may spike in a way that maps to a subset of shards. This is a distinct problem from key skew: it is about where a shard's traffic originates and lands, not how many keys it owns. The mitigation is to let shard placement (which datacenter/region a shard physically lives in) be a separate decision from the shard key itself.
Routing design: algorithmic versus lookup-service-based
A pure algorithmic router (client computes hash(user_id) mod N or applies consistent hashing directly) is simple and needs no extra network hop, but it hard-codes the shard topology into every client, which makes it painful to move individual users off a hot shard or to change placement for geographic reasons.
The alternative, which is what I would use at this scale, is a shard-map-management routing layer: a small, highly available service that owns the authoritative mapping of user_id → shard, so clients ask the routing layer (or a cached copy of its map) rather than computing the answer themselves. This costs an extra lookup (mitigated with aggressive client-side caching of the map, invalidated on change) but buys the ability to move individual users, override placement for geographic locality, and steer around a hot shard without a client rollout. At the higher end of this growth curve, once the user base is well past a billion (some teams see this discussion framed around roughly two billion users), the routing layer typically also needs sticky routing: caching a client's resolved shard for the duration of a session so repeated requests for the same user do not re-hit the routing layer on every call, trading a small staleness window (the cache might briefly point at a user's old shard mid-migration) for materially lower routing-layer load.
Migration approach: single shard to many
- Stand up the routing layer first, initially mapping 100% of users to the single existing database, so all future migration is just a mapping change.
- Provision the target shards and, for each cohort of users being moved, start a backfill copy from the source into the destination shard.
- Enable dual-write for that cohort: once backfill completes for a user, writes go to both source and destination while reads still come from source.
- Verify the destination has caught up (row counts, checksums, or a CDC-lag check near zero), then flip the routing-layer entry for that cohort to the destination and stop dual-writing.
- Retire the source copy for that cohort once a safety window has passed with no fallback reads observed.
Rebalancing with minimal downtime
flowchart LR
A[Mark partition as migrating in routing layer] --> B[Async bulk copy source to destination]
B --> C[CDC stream captures deltas during copy]
C --> D[Apply captured deltas to destination]
D --> E{Destination caught up?}
E -- No --> C
E -- Yes --> F[Brief write pause, apply final delta]
F --> G[Atomically flip routing-layer entry]
G --> H[Old source marked stale, retired after safety window]
The only downtime is the brief pause in step F while the last few milliseconds of writes replay, typically small enough to be invisible to users; everything else happens while the partition continues serving live traffic from its current location.
Consistent hashing versus range-based sharding, for this workload
Consistent hashing places nodes and keys as points on a circular hash space (the ring); virtual nodes give each physical node many small points on that ring instead of just one, so a topology change only reassigns the affected points.
| Dimension | Consistent hashing (hashed user_id) | Range-based (ordered user_id or signup order) |
|---|---|---|
| Distribution | Even, assuming a reasonable hash function | Skewed toward recently created ranges unless actively rebalanced |
| Rebalancing cost when adding a shard | Low: only keys near the new node's position on the ring move (with virtual nodes smoothing this further) | High: contiguous ranges must be split and large chunks of data physically move |
| Range queries ("all users created this week") | Not supported efficiently; scattered across shards | Efficient; the query touches few, contiguous shards |
| Hot-shard mitigation | Needs explicit hot-key handling since hashing does not fix a single overloaded key | Naturally exposed to hotspots on the newest range unless split proactively |
| Fit for this workload | Strong fit: access is single-user lookups, no range-scan requirement | Weak fit: pays a locality benefit this workload does not need, at the cost of harder rebalancing |
Given a read-heavy, single-user-lookup access pattern with no meaningful range-query requirement, consistent hashing on a hashed user_id, fronted by a shard-map-management routing layer rather than pure client-side computation, is the right choice: it minimizes data movement as the shard count grows from a handful of shards at 10 million users to however many are needed at 1 billion, and the routing layer absorbs the geographic-skew and hot-key concerns that hashing alone does not solve.
Worked example
Starting state: one database serving 10 million users. The trigger to shard is a saturation signal, not a fixed user count: sustained high CPU/IOPS (input/output operations per second) on the primary (concretely: sustained CPU utilization above roughly 70-80%, or IOPS approaching the storage volume's provisioned ceiling). When that signal fires, the team provisions an initial set of shards behind the routing layer, sized so projected per-shard load sits comfortably under those same saturation thresholds, and migrates user cohorts onto them following the steps above. As an illustrative planning input rather than a measured fact, assume a single shard can comfortably sustain roughly 2 million active user profiles' worth of steady-state read/write traffic before crossing that same 70-80%-CPU / near-IOPS-ceiling threshold: that puts the initial split at 10,000,000/2,000,000=5 shards when the 10-million-user primary first hits saturation. From then on, shards are added incrementally whenever the routing layer's per-shard load metrics approach saturation again, all the way to whatever shard count is needed at 1 billion users, which at that same illustrative 2-million-users-per-shard ceiling works out to 1,000,000,000/2,000,000=500 shards. Because the shard key is a hash and the routing layer decouples the shard count from the shard-key formula, each incremental addition only requires migrating the specific user ranges assigned to the new shard, not a full re-partition of the dataset.
Trade-offs & pitfalls
- A pure algorithmic router is simpler to build first but becomes the bottleneck to fix later: teams that skip the routing layer to save one network hop early usually end up building it anyway once they need to move a single hot user off a shard without a client deploy.
- Sticky routing at very large scale trades a small staleness window for routing-layer relief; that staleness window must be bounded and understood, or a mid-migration read can silently hit stale data.
- Consistent hashing does not, by itself, solve a single extremely hot key (a celebrity account); that requires a separate detection-and-override mechanism layered on top, not a property of the hashing scheme.
- Geographic skew and key skew are easy to conflate: even key distribution can still coexist with badly distributed physical load if shard placement ignores where traffic originates.
Describe a practical approach to capacity planning for a brand-new cloud service that has no historical traffic data. How would you make an initial workload estimate, decide on safety margins and headroom, plan for elastic capacity, and define the metrics and experiments you'd run to validate your assumptions after launch?
Sample Answer
Direct answer
With no historical traffic, you do not guess a single number: you build a workload estimate from comparable analogs and top-down business inputs, wrap it in an explicit safety margin, put it behind elastic capacity so the estimate does not have to be exact, and then replace the estimate with real data as fast as possible after launch through staged rollout and monitored experiments.
Structured elaboration
1. Build an initial estimate from two independent angles and reconcile them.
- Top-down: start from a business number you do have (invited users, marketing reach, sales pipeline) and multiply down to requests. This is the only lever available with zero history.
- Analog: find the closest comparable system you or the industry already operates (a similar feature, a similar-sized customer base, a similar product category) and scale its known request-per-user rate to your expected user count.
- Reconcile the two. If they disagree by more than roughly 2-3x, that gap itself is useful information: it tells you where your uncertainty is concentrated and what to instrument first.
2. Convert the estimate into a load shape, not just a total.
A daily total hides the number that actually threatens the system: peak requests per second (RPS, requests per second). Apply a peak-to-average ratio to account for daily cycles and, for a launch specifically, a possible synchronized spike (a launch email, a push notification, a press mention) that behaves nothing like organic steady traffic.
3. Set headroom deliberately, and say why.
Headroom on a zero-history estimate covers two different kinds of error: normal variance (traffic is noisier than a smooth average implies) and estimate error (the whole model could be wrong). Treat these as multiplicative: a peak-shape multiplier for the first, then a separate safety-margin multiplier for the second. Document both numbers as assumptions, not facts, so whoever revisits capacity later knows which parts were guessed.
4. Plan for elastic capacity so the estimate does not have to be right.
Because pre-launch numbers are inherently soft, favor a design where compute scales out automatically (for example an Auto Scaling group, ASG, sized with a low minimum and a generous maximum) over one where you provision a fixed fleet sized to the estimate. Stateless request handlers are what make this possible: any instance can pick up any request, so the ASG can add or remove capacity without session-affinity constraints. Identify the one component that will NOT scale elastically as fast as the rest (usually the database or a rate-limited third-party dependency) and size or protect that one deliberately, since it becomes the real ceiling regardless of how large the compute fleet grows.
5. Define what you will measure and how you will validate the assumption after launch.
Before launch, decide: the metrics that reveal reality (RPS, P95/P99 latency [95th-percentile/99th-percentile], error rate, queue depth, database connection saturation), the rollout mechanism that limits blast radius while those metrics come in (percentage-based ramp or canary release to a small traffic slice first), and the trigger for pausing the ramp (an explicit threshold on any of the above, decided in advance rather than improvised under pressure).
Worked example
Assume, as planning inputs rather than measured facts:
- 10,000 users are active on day one (from a marketing pre-registration count, discounted for expected activation rate).
- Each active user generates 15 requests over the day (from an analog product's per-user request rate).
- A peak-to-average ratio of 4x, reflecting a synchronized launch announcement rather than smooth organic arrival.
- A safety margin of 2x on top of the peak, to absorb estimate error since there is no history to validate the inputs against.
That "14 RPS" is not a forecast you defend, it is a starting point for the ASG's scaling policy and a number you replace with observed data within the first days of traffic.
Trade-offs & pitfalls
Over-provisioning a fixed fleet to the safety-margin number wastes money for a launch that may undershoot; under-provisioning without elastic headroom risks a visible outage on the day traffic is most scrutinized. The middle path (a small guaranteed baseline plus autoscaling) is usually right, but it only works if the service is stateless and the true bottleneck (often the database, not the request tier) is identified and protected separately, since databases scale far less elastically than compute. The most common senior-vs-junior tell is whether the candidate treats the initial number as a fact to defend or as an assumption to instrument and correct quickly after launch.
For a read-heavy product catalog service, weigh the trade-offs between replicating a full cache to every region versus partitioning (sharding) cache entries by product or region. Consider read latency, cache-miss patterns, memory and network cost, consistency, and rebalancing complexity, then recommend an approach for a global retailer that sees traffic bursts from multiple regions.
Sample Answer
Direct answer
For a global retailer with bursty, multi-region traffic, neither pure full replication nor pure partitioning wins outright: full replication gives the best latency and simplest rebalancing but pays for it in memory and cross-region sync cost, while partitioning is cheaper but concentrates risk into hotspots when demand shifts. The right default is a hybrid: keep a small, region-local cache of the hottest slice of the catalog fully replicated in every region for latency, and back it with a sharded cache for the long tail, promoting items into the local cache when a region's traffic to them justifies it.
Structured elaboration
| Dimension | Full replication (every region holds the whole cache) | Partitioned (sharded by product or region) |
|---|---|---|
| Read latency | Best: any product is a local hit | Good only when the request lands on a local shard; a remote shard adds a cross-region hop |
| Cache-miss pattern | Only on first global write or expiry; predictable | Lower miss rate per shard for that shard's hot items, but a burst on one product can overload the single shard that owns it |
| Memory & network cost | High: full catalog held N times, one per region, plus cross-region invalidation traffic | Lower: no duplication of the catalog, and update broadcasts are smaller |
| Consistency | Async replication is simplest and typical; synchronous replication for strong consistency adds real latency | Simpler for the shard that owns a given item, since there's one writer path, but reads from other regions still need a remote call or a replication mechanism |
| Rebalancing complexity | Low: adding a region just means standing up another full copy | Higher: partition migrations and consistent-hashing-style reassignment are needed; hotspots require live re-sharding or targeted replication |
Why a global retailer with bursty traffic needs the hybrid, not either extreme
Bursty, multi-region traffic on a retail catalog is rarely uniform: a small set of products (a flash sale, a viral item) drive a disproportionate share of reads at any given time, and which products are hot can shift quickly. Pure partitioning puts that risk on a single shard, since consistent-hashing-style assignment (products and cache shards are placed as points on a circular hash space, so only nearby points move when shards are added; the mechanics of the hash ring itself are covered in more depth under load balancing's consistent-hashing pattern, and what matters here is the caching consequence) doesn't know a key is about to become hot until it already is. Pure full replication avoids that risk entirely but pays a flat memory and cross-region sync tax for the entire long tail of the catalog, most of which is rarely read in any given region.
The hybrid keeps region-local, fully replicated caches sized to each region's actual working set (the products that region's users actually read), backed by a sharded cache holding the full catalog. A traffic-based promotion rule (an item crossing a per-region hit-rate threshold gets pushed into that region's local cache) handles the shifting-hotspot case without requiring the whole catalog to be replicated everywhere.
Worked example
Assume, as a planning input rather than a measured fact, a product catalog sized at 50 GB, served across 6 regions.
Full replication cost:
50GB×6regions=300GB total cache memory
Partitioned cost (no duplication, split evenly across 6 shards, plus a replication factor of 2 within each shard for availability rather than for cross-region latency):
6shards50GB≈8.3GB per shard,50GB×2=100GB total with the availability replica
The partitioned approach uses roughly a third of the memory of full replication (100 GB versus 300 GB) at this illustrative catalog size. The hybrid sits between the two: if each region's working set is, say, 10% of the catalog (5 GB), replicating just that slice to all 6 regions costs:
5GB×6=30GB
on top of the 100 GB sharded backing store, for roughly 130 GB total, a fraction of full replication's 300 GB while still giving most reads (the ones hitting each region's working set) a local hit.
Trade-offs & pitfalls
- The hybrid's promotion rule needs a threshold and a demotion path; without demotion, the region-local cache grows unbounded as items get promoted but never removed, eventually approaching full replication's cost anyway.
- Cross-region invalidation is still required for the sharded backing store even in the hybrid; underestimating that traffic (versioned, pub/sub-style invalidation messages rather than synchronous broadcasts) is a common way the "cheaper" option ends up not being cheaper.
- A single globally hot product (a flash sale item) can still overload the shard that owns it even with promotion in place, if promotion reacts slower than the traffic spike; this is the scenario that specifically motivates proactive cache warming ahead of known events rather than purely reactive promotion.
- A content delivery network (CDN, a network of edge servers that cache content close to users) is a natural complement for static product assets (images, descriptions) but doesn't solve the dynamic pricing/inventory caching problem this comparison is about; don't conflate the two layers.
- Getting the region-local cache's time-to-live (TTL, how long a cached value is considered valid before refresh) too long trades staleness (wrong price or stock shown) for the latency win; too short and the hybrid starts behaving like the sharded-only design under load.
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.
Walk through the core steps of capacity planning for a service that currently sees 20,000 requests per second and is expected to grow 4x over the next 12 months. What metrics would you collect, what forecasting approach would you use, and how would you build in safety buffers?
Sample Answer
Direct answer
Capacity planning for 4x growth is a five-step loop: clarify the target SLOs (service level objectives, meaning your latency/error/cost targets), collect the metrics that let you translate traffic into resource needs, forecast the growth curve rather than assuming it is linear, convert the forecast into a required footprint with explicit safety buffers, and validate the plan with load tests before you need it for real.
Structured elaboration
1. Clarify requirements. Pin down target latency and error-rate SLOs, acceptable cost ceiling, and what "growth" means concretely (is 4x steady over 12 months, or a step change at a known date?).
2. Collect metrics (traffic, resource, application, business).
- Traffic: requests per second (RPS), request size, per-endpoint queries per second (QPS), and percentile splits (p50/p95/p99, the 50th/95th/99th-percentile response times), not just averages.
- Resource: CPU, memory, disk I/O, network throughput, connection/thread counts.
- Application: latency histograms, error rates by type, queue depths.
- Business: planned launches, marketing pushes, seasonality that could accelerate growth faster than the trend line.
3. Forecast, don't just extrapolate the headline number. A flat 4x multiplier on today's RPS is a starting point, not the plan: fit the trend against historical data (linear or exponential depending on the growth pattern observed) and project percentiles separately, since tail behavior does not always scale with the average.
4. Convert to a required footprint with safety buffers. Measure resource-per-request from load tests or production data, then size for the forecast plus buffers: operational headroom for bursts, a failure-domain buffer so the system tolerates losing a node or a zone, and a smaller uncertainty buffer for forecast error.
5. Validate before you need it. Load-test at intermediate multiples (not just the final 4x), watch SLOs hold, and set a review cadence to re-forecast as real growth data comes in rather than trusting a 12-month-old projection.
Worked example
Take the stated numbers: current load 20,000 RPS, target 4x growth.
4×20,000=80,000 RPS target
Assume, as an illustrative input not given in the question, that load testing shows each node sustains 2,500 RPS at the target CPU/latency envelope:
Current fleet size=2,50020,000=8 nodes
Fleet size at 4x, no buffer=2,50080,000=32 nodes
Add a 25% operational headroom buffer for bursts:
80,000×1.25=100,000⇒2,500100,000=40 nodes
So the plan targets roughly a 5x increase in fleet size (8 to 40 nodes) to serve a 4x traffic increase, once burst headroom is included, before adding any failure-domain buffer on top.
Trade-offs & pitfalls
- A single multiplier hides percentile risk. If p99 latency is already close to its SLO at today's load, a naive 4x-everything projection can understate how close the tail gets to breaching SLO, since tail latency often degrades faster than the average as utilization rises.
- Buffers stack, and stacking them uncritically gets expensive fast. Operational headroom, failure-domain buffer, and forecast-uncertainty buffer applied one after another can inflate cost well beyond what the traffic forecast alone justifies; size each buffer deliberately and be able to justify its percentage.
- Forecasts go stale. A plan built on a 12-month linear projection needs a review cadence; treat the 4x figure as a hypothesis to keep validating, not a fixed target to build once and forget.
- Load-testing only at the final target multiple misses problems that show up earlier. Testing at 1x, 2x, and 4x surfaces bottlenecks (a database connection limit, a downstream dependency's own capacity) that a single test at 4x can mask or misattribute.
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.