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.
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.
You need to decompose a monolithic application into microservices. Walk through a pragmatic approach: how you'd identify service boundaries, ensure data integrity during the migration, avoid distributed-transaction anti-patterns, and choose between orchestration and choreography. When would you reach for the strangler fig pattern?
Sample Answer
Direct answer
A pragmatic decomposition starts from real bounded contexts, not code modules, keeps data integrity intact by translating between the old and new models instead of cutting over all at once, and replaces any temptation toward a distributed two-phase commit with sagas built from idempotent, compensable steps. The strangler fig pattern, routing traffic through a facade so old and new implementations coexist during the transition, is the mechanism that makes all of this incremental and reversible rather than a risky big-bang cutover.
Identifying service boundaries
Use domain-driven design to find bounded contexts along business-capability lines (orders, billing, inventory) rather than along existing code-module lines, which usually reflect implementation history more than the current business domain. Within a candidate boundary, look for a vertical slice: API (application programming interface), business logic, and the data that logic owns, so the resulting service can operate independently without still calling back into the monolith for its own core data. Start with a boundary that is both low-risk (not on the critical write path) and clearly bounded (its data isn't heavily shared with other domains), since that combination validates the migration mechanics without betting the business on the first attempt.
Data integrity during migration
- Anti-corruption layer (ACL): a translation layer between the monolith's data model and the new service's API, so the new service isn't forced to adopt the monolith's legacy shape, and the monolith doesn't need to understand the new service's internals.
- Change data capture (CDC): stream changes from the monolith's database into the new service so reads stay consistent while write ownership is still transitioning.
- Dual writes, done carefully: if the monolith and the new service both need to write during the transition, make every write idempotent and reconcile the two stores regularly; prefer event-driven replication (the monolith publishes a change event that the new service consumes) over synchronous dual-writes, which fail if either side is briefly unavailable.
Avoiding distributed-transaction anti-patterns
Don't reach for two-phase commit (2PC) across the new service boundary. It requires every participant to be available and responsive during the commit window, which directly works against the availability and independent-deployability goals that motivated decomposition in the first place. Instead, model multi-step business flows as sagas: a sequence of local transactions, each with a defined compensating action if a later step fails, so the overall flow degrades gracefully instead of blocking on a distributed lock.
| Orchestration | Choreography | |
|---|---|---|
| Control flow | A central coordinator (a saga orchestrator) explicitly sequences each step and its compensation | Each service reacts to events from the previous step and publishes its own; no central coordinator |
| Best fit | Complex flows with non-trivial compensation logic, where you need one place to see and control the whole sequence | Simple, decoupled flows where steps genuinely don't need central sequencing |
| Observability | Easier: the orchestrator's state machine shows exactly where a given flow is | Harder: the flow is implicit in the pattern of events, so tracing a specific request end to end takes more tooling |
| Coupling | Services stay decoupled from each other but are coupled to the orchestrator's contract | Services are decoupled from any coordinator but implicitly coupled to the event schema and each other's reactions |
A common practical split is to orchestrate the core, high-stakes transaction (say, order to payment to shipment) where compensations matter, and let secondary, lower-stakes integrations (send a confirmation email, update an analytics feed) stay choreographed.
When to reach for the strangler fig pattern
Reach for it whenever you need the old and new implementations to coexist safely during a transition, which in practice is almost always for anything beyond a trivial, low-traffic domain. The mechanics, applied specifically at a monolith's gateway:
- Reverse-proxy routing: put a reverse proxy or API gateway in front of both the monolith and the new service, and route requests to one or the other by path, feature flag, or percentage, so the switch is a routing change rather than a deployment event.
- Traffic shadowing: mirror a copy of live production requests to the new service without using its response, so you can compare its behavior and performance against the monolith's real response under real traffic before the new service is trusted to actually serve anyone.
flowchart LR
C[Client] --> RP[Reverse proxy /<br/>API gateway]
RP -->|serves response| M[Monolith]
RP -.->|mirrored, response discarded| NS[New service]
RP -->|once validated,<br/>cut over by %| NS
Only retire the monolith's code path for a given slice once traffic has been fully cut over and the data behind it has been reconciled, not merely once the new service has been deployed.
Worked example: extracting a payments capability
Define the Payments bounded context and its API contract, then stand up an ACL that maps the monolith's existing payment calls onto that contract. Use CDC to populate the new Payments service's data store from the monolith's database so both stay consistent during the transition. Put a reverse proxy in front of the payments endpoints and start with traffic shadowing: every real payment request is also sent to the new service, its result compared against the monolith's, but only the monolith's response reaches the client. During this shadow period, downstream systems the payments path calls (a fraud check, a ledger write) effectively see close to double their steady-state call volume, since both the monolith and the shadowed new service are calling them, which is worth flagging to whoever owns that downstream capacity before shadowing begins. Once results match consistently, cut real traffic over gradually (a small percentage, then a majority, then all of it) via the reverse proxy, with the monolith's code path kept in place and able to take traffic back at any stage until the migration is fully reconciled.
Trade-offs and pitfalls
- Treating dual writes as sufficient data-integrity strategy on their own, without idempotency keys or a reconciliation job; a single missed or duplicated write during the transition window leaves the two stores silently inconsistent.
- Reaching for orchestration everywhere out of caution; it adds a coordinator every downstream service must trust and depend on, which is unnecessary overhead for flows that don't actually need centralized compensation logic.
- Shadowing traffic without accounting for its load on shared downstream dependencies, which can turn a validation exercise into a self-inflicted capacity incident.
- Declaring the migration done once the new service is receiving 100% of traffic, while the monolith's old code path and data are still live as a fallback; the migration isn't actually finished, and the risk isn't actually retired, until that fallback is deliberately removed.
Design connection-pool management for a microservice that serves 500 concurrent request handlers and makes both database and upstream HTTP calls. How would you size the DB connection pool versus the HTTP client pool, choose timeouts and max lifetimes, integrate with circuit breakers, and test pool behavior under a simulated production spike?
Sample Answer
Direct answer
Size each pool from the request rate implied by the concurrency, not from the concurrency number itself: work out how many requests per second actually need a database connection or an outbound HTTP connection at steady state, multiply by how long each connection is held (Little's Law), then add an explicit safety margin. Timeouts must be shorter than the end-to-end service level objective (SLO), and connections need a maximum lifetime shorter than any upstream infrastructure's idle-connection timeout so sockets get rotated before they are silently dropped. A circuit breaker sits in front of each pool so a failing dependency fails fast instead of exhausting the pool while everyone queues for a resource that will not respond.
Sizing the pools
Step 1: convert concurrency to throughput. 500 concurrent handlers is a snapshot of how many requests are in flight, not a rate. Little's Law relates them: concurrency equals arrival rate times average time in system (L=λW). If the average end-to-end request latency is known (or targeted), the implied arrival rate falls out directly.
Step 2: split by dependency. Not every request touches the database, and not every request calls the same upstream. Measure (from application performance monitoring, not guesswork) what fraction of requests hit each dependency and how long that call takes, then apply Little's Law again, this time scoped to that dependency, to get the concurrent connections it needs.
Step 3: timeouts and lifetimes.
- Connect timeout: short, on the order of a few hundred milliseconds for calls inside the same network, since a connection that cannot even establish is not going to succeed on retry within budget.
- Request/read deadline: a slice of the overall SLO, sized so that even if this call takes its full budget, the caller still has time left to respond.
- Idle timeout: closes unused connections after they've sat idle for a while, freeing capacity for other requests.
- Max connection lifetime: rotates connections periodically so no single socket outlives an upstream load balancer's or NAT device's own idle-reap window, which would otherwise cause requests to fail against a connection that looks alive locally but was already dropped upstream.
- Pool checkout timeout: kept short. If a caller cannot get a connection quickly, failing fast and shedding load beats piling requests into an ever-growing queue.
Step 4: circuit breakers and bulkheads. Wrap each pool (or each upstream host) with its own breaker: once the failure rate or consecutive-failure count crosses a threshold, the breaker opens and callers get an immediate fallback or error instead of waiting out a timeout against a resource that is already failing. A bulkhead means giving a critical dependency its own pool, separate from a non-critical one, so a slow or saturated non-critical dependency cannot starve connections a critical path needs. The state-machine mechanics of breakers (closed / open / half-open, backoff between probes, how they interact with retries and cascading failure) are a deeper topic in their own right; what matters here is that the pool and the breaker are wired to the same dependency boundary, so a breaker trip and a pool-exhaustion alert are talking about the same failure.
Step 5: test it. Load test by ramping to the target concurrency and then spiking beyond it, watching pool wait time and saturation rather than just end-to-end latency. Separately, inject faults (added latency, forced errors) on the database and the upstream to confirm the breaker actually trips and the fallback path is exercised, not just that it exists in code. Run a soak test long enough to exercise the max-lifetime rotation at least once, to catch connection leaks that a short test would miss.
Worked example
Assumptions used below (explicitly stated, not measured facts):
- Concurrency L=500 handlers (given).
- Target average end-to-end latency W=200ms (an illustrative SLO target, not a measured value).
- 30% of requests make a database call, averaging 20 ms per call (illustrative).
- 50% of requests call an upstream HTTP service across 5 upstream hosts, averaging 50 ms per call (illustrative).
- Safety factor of 2x on the computed steady-state connection counts (illustrative, tune from observed variance).
Database pool:
DB call rate=0.3×2500=750 calls/s DB connections needed=750×0.02s=15With the 2x safety factor, target pool size = 30, capped at whatever the database server's own connection limit allows (if the DB caps total connections lower than 30 times the number of service instances, add a proxy/pooler in front of the database rather than growing the per-instance pool further).
HTTP client pool:
HTTP call rate=0.5×2500=1250 calls/s HTTP connections needed=1250×0.05s=62.5→63Spread across 5 upstream hosts: 63/5≈12.6→13 per host minimum, times the 2x safety factor = 26 per host target. (For HTTP/2 upstreams that multiplex many logical requests over one connection, this per-connection count would be far smaller; the formula is the same, only the effective "one connection handles many concurrent calls" changes the divisor.)
flowchart LR
C[Request handlers x500] --> CB1{Circuit breaker: DB}
C --> CB2{Circuit breaker: upstream HTTP}
CB1 -->|closed| DBPool[DB connection pool target 30]
CB1 -->|open| FailFast1[Fail fast / fallback]
DBPool --> DB[(Database)]
CB2 -->|closed| HTTPPool[HTTP client pool per host 26]
CB2 -->|open| FailFast2[Fail fast / fallback]
HTTPPool --> Upstream[Upstream service]
Trade-offs and pitfalls
Over-provisioning a database pool is not free: every open connection costs the database server memory and, for some engines, a background process, so "just make the pool bigger" is not a safe default. Under-provisioning causes callers to queue for a checkout instead of failing fast, which turns a capacity problem into a latency-cascade problem for every caller of the service, not just the ones touching the saturated dependency. A common ordering mistake is setting an inner call's timeout longer than the budget the outer caller has left, which wastes the outer request's remaining time waiting on a call that can no longer help it finish in budget; timeouts should shrink, not grow, as you move deeper into a call chain. Finally, a load test that only ramps to the steady-state target and never spikes past it will not catch pool exhaustion, since the whole point of a pool is that it behaves fine until it doesn't.
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.
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.
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.