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.
For a system that must support high write throughput, heavy reads, and analytical queries all at once, how would you choose between replication, partitioning (sharding), and CQRS? Discuss read/write separation, the latency and consistency trade-offs, isolating the analytical workload, and the operational complexity each approach adds.
Sample Answer
Direct answer
Start from the workload shape, not the pattern name: replication scales reads and adds availability but does nothing for write throughput; partitioning (sharding) scales both reads and writes by splitting data across nodes at the cost of cross-shard operations; CQRS (Command Query Responsibility Segregation) separates the write model from one or more purpose-built read models, which is the only one of the three that cleanly isolates an analytical workload from live transaction processing. Most systems that need all three properties (high write throughput, heavy reads, analytics) end up combining them rather than picking one: shard for write scale, replicate each shard for read scale and availability, and feed a CQRS-style read model or warehouse from a change stream for analytics.
Structured elaboration
Clarify the inputs first. Before choosing, pin down: peak write rate, read queries per second (QPS, queries per second) and their latency service-level objective (SLO, service-level objective), how stale a read is allowed to be, whether analytical queries are ad-hoc (online analytical processing, OLAP, style: broad scans, aggregations) or a handful of known dashboards, and how much operational tooling the team can realistically own.
| Dimension | Replication | Partitioning (sharding) | CQRS |
|---|---|---|---|
| Read/write separation | Reads go to replicas, writes to the primary (or a designated writer) | Both reads and writes spread across shards by key | Explicit: a write model optimized for correctness, separate read model(s) optimized for query shape |
| Write throughput | Not improved; every write still funnels through the primary's replication path | Scales close to linearly with shard count, if the key distributes evenly | Depends on the underlying write store; CQRS itself does not add write capacity, it isolates what happens to reads after the write |
| Latency / consistency | Synchronous replication raises write latency for stronger consistency; asynchronous replication keeps writes fast but reads on replicas can lag | Strong consistency is straightforward within one shard; a transaction that spans shards is slower and harder to keep atomic | Read models are typically eventually consistent, updated asynchronously after the write commits |
| Analytical isolation | Weak: an analytics query on a replica competes with replication apply and any other read traffic on that node | Weak to none: aggregating across shards requires scatter-gather or a separate pipeline | Strong: a dedicated analytical read model or warehouse can be fed from the write path without touching the online transaction processing (OLTP, online transaction processing) system at all |
| Operational cost | Lowest: failover, replication lag monitoring, backup policy | Highest ongoing cost: rebalancing, hot-shard mitigation, cross-shard routing logic | High setup cost: event or change-data-capture (CDC, change-data-capture) pipeline, idempotent consumers, projection rebuild tooling; lower marginal cost once running |
Decision heuristic.
- If the bottleneck is read volume and the dataset still fits comfortably on one primary's write path, replication with read replicas is the cheapest fix. Route analytics away from the primary onto a replica only if you can tolerate its replication lag as staleness; this is a leaky form of isolation, not a real one.
- If write volume or dataset size outgrows a single writer, shard. Pick a partition key that spreads both storage and write load evenly and keeps the transactions your application actually needs (usually single-entity updates) inside one shard.
- If the real requirement is "let analytics run hard queries without ever affecting the live system," reach for CQRS or a streaming pipeline regardless of whether you also shard. This is a workload-isolation problem, not a scaling-throughput problem, and only an explicit read/write split solves it.
- These are not mutually exclusive. A sharded OLTP layer, each shard replicated for local read scale and failover, streaming change events into a CQRS read model or a warehouse, is a common end state for a system that genuinely needs all three properties at once. The pattern briefly touches on how leader election and failover are handled per shard: each shard's own replica set runs a consensus protocol so its nodes agree on which one is the current writable primary (leader election), and if that primary becomes unreachable, the remaining replicas in that shard's set automatically elect a new primary so writes have a single owner again within seconds (failover); the deeper mechanics of that consensus protocol belong to high-availability design and are not repeated here beyond noting that each shard's own replica set needs it.
flowchart LR
C[Client writes] --> P1[Shard 1 primary]
C --> P2[Shard 2 primary]
P1 --> R1[Shard 1 replica]
P2 --> R2[Shard 2 replica]
P1 --> CDC[Change stream]
P2 --> CDC
CDC --> RM[CQRS read model / warehouse]
R1 --> Q[Live read queries]
R2 --> Q
RM --> A[Analytical queries]
Worked example
A payments service currently runs on one primary database and is starting to miss its latency target. Measured: 4,500 writes/sec at peak, 60,000 read QPS at peak, and a finance team that wants ad-hoc OLAP queries over the last 90 days of transactions without ever slowing down checkout.
Assume, as planning inputs rather than measured facts: a single well-provisioned primary sustains around 3,000 sustained writes/sec before latency degrades, and a single read replica comfortably serves about 10,000 QPS.
- Writes: 4,500 / 3,000 = 1.5, so one primary is already past its comfortable ceiling. Add a 40% growth buffer: 4,500 × 1.4 = 6,300 target writes/sec. 6,300 / 3,000 = 2.1, so plan for 3 shards to leave real headroom rather than sitting at the edge of 2.
- Reads: 60,000 / 10,000 = 6 replicas needed at peak with zero slack. Add the same 40% buffer: 60,000 × 1.4 = 84,000; 84,000 / 10,000 = 8.4, so plan for 9 replicas total, distributed across the 3 shards (3 per shard keeps it even).
- Analytics: rather than pointing the finance team's OLAP queries at any of those 9 replicas (which would eat into the buffer just computed), stream committed writes via change-data-capture into a separate read-optimized store. That store's capacity is sized independently and never competes with the 6,300 writes/sec or 84,000 QPS budgeted above.
This is the concrete version of the heuristic above: sharding solved the write ceiling, replication solved the read ceiling, and CQRS-style stream-out solved the isolation requirement, each sized from its own number rather than assumed to fall out of the others.
Trade-offs & pitfalls
- Treating CQRS as a performance pattern rather than an isolation pattern is a common wrong turn: it does not make the write path faster by itself, and adopting it just to "scale" without an actual analytical-isolation or read-shape need adds eventual-consistency complexity for no return.
- Picking a shard key optimized for even distribution but ignored for query patterns creates a system that scales storage and writes fine while every common query becomes a cross-shard scatter-gather.
- Reading from an async replica as a substitute for real analytical isolation looks cheap until the replica's replication lag becomes contended with the analytics load itself, and both the online workload and the analytics workload get worse.
- Under-budgeting the operational tooling is the most common failure in practice: resharding runbooks, projection-repair tooling, and replication-lag alerting are not optional extras, they are what keeps the "solved" architecture solved six months later.
- A senior answer names the concrete headroom numbers and states them as assumptions, rather than presenting a diagram with no sizing behind it.
Design an operational plan and technical implementation to reshard a live sharded database with minimal downtime. Cover choosing the new shard key or shard count, the data-migration strategy (online migration, dual writes, change-data-capture), routing updates, throttling the migration, validation steps, and your rollback procedure.
Sample Answer
Direct answer
Resharding a live database with minimal downtime is an online migration: keep the old topology serving traffic while you copy data to the new one under a throttle, use dual writes or change-data-capture (CDC) to keep the copy current, validate it against the source before trusting it, and cut routing over in a small, reversible step rather than a single big-bang switch. The hard parts are rarely the copy itself; they are choosing a shard key/count that won't need redoing soon, keeping writes ordered correctly during the overlap window, and having a rollback that is actually exercised, not just documented.
Structured elaboration
Choosing the new shard key or shard count
- Analyze real access patterns (write hotspots, cardinality, range-vs-hash trade-offs) from production telemetry rather than guessing; target per-shard headroom (commonly keeping any shard well under its saturation point) so the new topology doesn't need revisiting immediately.
- For a hot single shard suffering write contention, the two concrete techniques are rekeying (choosing a shard key that spreads the contended writes, if the current key is the root cause) and range-splitting (dividing the shard's existing key range into two or more ranges, each becoming its own shard, when the key itself is fine but the range has outgrown one node).
- For a lookup-based versus algorithmic shard-mapping layer: an algorithmic mapping (consistent hashing, which places nodes and keys as points on a circular hash space called a ring, so a topology change only reassigns the small slice of keys near it, or the simpler hash-mod-N) needs no metadata lookup and scales trivially, but it distributes tenants roughly evenly by key, which fails badly when tenant sizes vary by orders of magnitude (a large enterprise tenant next to hundreds of tiny ones). A lookup-based mapping (an explicit tenant-to-shard table) costs a metadata hop per request but lets you place large tenants on dedicated shards and pack small tenants together deliberately. For a multi-tenant system with that kind of size skew, prefer lookup-based mapping, or a hybrid: algorithmic mapping for the default pool of ordinary tenants, with a lookup override for the small number of outsized ones.
Data-migration strategy
- Online copy under CDC: stream changes from the source shard(s) via a CDC pipeline (e.g., a log-based change stream) into the target topology while a background job bulk-copies existing data in ranges. The CDC stream and the bulk copy have to be reconciled (apply CDC events that land inside an already-copied range, buffer or replay ones that land ahead of the copy cursor).
- Dual writes with a quiesce window: to guarantee transaction ordering is preserved for records that are actively being migrated, briefly pause (quiesce) writes to the specific key range being cut over, drain the in-flight CDC backlog for that range so source and target agree, flip routing for just that range, then resume writes. This bounds the ordering risk to a small, deliberately-chosen window instead of trying to reason about ordering across an open-ended dual-write period for the whole dataset.
- Split-and-merge at scale: for a large, contended shard, resharding is a split (one shard's range divides into two, each getting its own routing-table entry) rather than a full-dataset migration; the reverse operation, merge, combines two under-loaded shards back into one when growth was over-provisioned. At terabyte scale, both operations are driven by range boundaries and routing-table updates rather than moving the whole dataset, which keeps a single split or merge bounded in time and blast radius.
- A cross-topology special case: migrating a stateful store (for example, a session store) from a single-region deployment to a multi-region sharded cluster follows the same dual-write skeleton, but adds a proxy layer in front of both topologies so the application never talks to the store directly during the migration; the proxy performs parity verification (comparing responses from the old and new paths for the same key) before fully cutting traffic over, which catches migration bugs before they're user-visible.
flowchart TD
A[Old shard topology] -->|CDC stream| B[Change pipeline]
A -->|throttled bulk copy| C[New shard topology]
B --> C
C --> D[Shadow reads: compare old vs new]
D -->|parity confirmed| E[Routing cutover, range by range]
D -->|mismatch| F[Pause cutover, reconcile]
E --> G[Quiesce window per range: drain, flip, resume]
G --> H[Old topology retired]
Routing updates
Introduce a migration-aware routing layer (gateway or client-side routing table) so application code never encodes shard topology directly. Roll the new routing out in stages: internal/test traffic, a small canary of production traffic, then full cutover, with each stage able to fall back to the previous routing table without a code deploy.
Throttling
Throttle the copy and CDC-apply workers adaptively against replication lag, tail latency, and source-shard CPU/I/O, not a fixed rate, so migration traffic backs off automatically when it's competing with production load. As a worked illustration of sizing a per-shard step against an operational target: suppose the team's service-level agreement (SLA) is for each per-shard rebalance step to complete in well under two minutes even across a 200+ node cluster, and a given shard holds roughly 50 GB of data with the copier capped at 500 MB/s per shard to protect production I/O. The data-transfer portion alone takes
which leaves about 20 seconds of headroom under the 120-second target for updating ring/routing metadata and completing leader election (the process by which the new shard's replica-set nodes agree on which one of them becomes the active primary/writer) for the new shard's replica set, before the step is considered done. That headroom is the number to watch: if metadata propagation or leader election routinely eats into it, the fix is a faster metadata path, not a bigger copy-bandwidth cap.
Automating rebalancing across many shards
When rebalancing hundreds of shards simultaneously rather than one at a time, the automation has to cap total concurrent migrations (global throttle, not just per-shard), and it must keep secondary-index consistency in scope explicitly: an index that's rebuilt or re-pointed on a different schedule than its base table will silently return wrong results for the window in between, so index cutover needs to be part of the same per-range quiesce step as the base data, not a follow-up job.
Validation
- Row counts and per-range checksums between source and target.
- Shadow reads: serve a fraction of real production reads from the new topology in parallel with the old one (without returning the shadow result to the client) and compare, which surfaces correctness bugs under real traffic patterns before any client depends on the new path.
- Client-side cache invalidation during cutover: if clients or edge caches hold entries keyed by the old routing, cutting a range over without invalidating those cached entries serves stale-routed responses; the cutover step has to include a cache-invalidation signal (a version bump on the routing key, or explicit invalidation) for anything caching downstream of the router.
- End-to-end application-level smoke tests against the new topology before removing fallback to the old one.
Rollback
Keep dual writes (or the CDC stream) active until validation passes; if a problem surfaces, stop applying new CDC events, revert routing to the old topology for the affected range, and resume from the last confirmed-consistent checkpoint rather than restarting the whole migration. Because cutover happens range-by-range behind a quiesce window, rollback scope is bounded to the ranges already flipped, not the whole dataset.
Trade-offs & pitfalls
- A migration that skips the quiesce window to avoid any write pause will have an ordering gap for records touched during the exact moment of cutover; a short, well-instrumented pause on a narrow key range is a better trade than an unbounded consistency risk.
- Algorithmic shard mapping is simpler to build and reason about, but for multi-tenant systems with orders-of-magnitude tenant-size variance, defaulting to it produces shards that are balanced by tenant count and wildly unbalanced by load; verify the mapping choice against actual per-tenant load, not tenant count.
- Skipping shadow reads to save migration time is the single most common way correctness bugs escape into production, because checksums catch data-copy errors but not query-behavior differences (an index that returns results in a different order, a range boundary edge case).
- Treating secondary-index rebuild as a background job that can lag the base-table cutover is a frequent source of silent incorrect reads immediately after a migration; keep index and base-data cutover atomic per range.
Explain vertical scaling (scale up) versus horizontal scaling (scale out). List three advantages and three disadvantages of each. Then describe the concrete signals or thresholds (CPU, memory, disk, latency) you would monitor to decide that vertical scaling is no longer sufficient and horizontal scaling is needed for a service.
Sample Answer
Direct answer
Vertical scaling (scale up) gives one machine more resources: a bigger CPU, more RAM, faster disks. Horizontal scaling (scale out) adds more machines and spreads load across them. Vertical scaling is the faster first move because it needs no application changes; horizontal scaling is the one that actually removes a ceiling, because a single machine's capacity is always finite no matter how large you buy.
Structured elaboration
Vertical scaling: advantages
- Simplicity: resizing an instance or VM (virtual machine) usually requires no code or architecture change.
- Lower operational surface: one system to patch, back up, and monitor instead of a fleet.
- No distributed-systems tax: no partitioning, no cross-node consistency, no coordination overhead, so single-threaded or tightly-coupled workloads keep their natural performance profile.
Vertical scaling: disadvantages
- Hard ceiling: even the largest cloud instance sizes (high-memory or high-CPU tiers) top out, and that ceiling arrives faster than most teams expect.
- Single point of failure: one node down means the service is down, unless it is paired with a passive standby (a high-availability concern, not a scaling one).
- Non-linear cost: the largest instance tiers carry a steep price premium per unit of CPU/RAM versus a few mid-tier instances doing the same aggregate work.
Horizontal scaling: advantages
- No hard ceiling: capacity grows by adding nodes, which is why it is the pattern behind "web-scale" systems.
- Failure isolation: losing one node out of many degrades capacity slightly rather than taking the service down.
- Elastic cost matching: nodes can be added and removed to track demand, so spend tracks load instead of being sized for peak year-round.
Horizontal scaling: disadvantages
- Requires statelessness or externalized state: a node must be replaceable, which usually means a rewrite if the service was built assuming local state.
- Coordination overhead: partitioning, request routing, and (for data) replication or sharding all add moving parts that a single node never needed.
- Operational complexity: more instances to deploy, patch, and observe, plus the need for a load-distribution layer in front of them (a load-balancing concern, out of scope here, but worth naming as the piece that makes horizontal scaling actually work end to end).
Signals that vertical scaling has run out of road
| Signal | Threshold to watch | Why it matters |
|---|---|---|
| Sustained CPU utilization | Consistently above roughly 70-80% during normal peak, not just brief spikes | Headroom for traffic growth and failover capacity is gone |
| Memory pressure | Sustained high usage with frequent garbage-collection pauses, swapping, or out-of-memory events | The next vertical step is a discrete, expensive jump, and swapping degrades latency badly |
| Disk I/O | High utilization or growing queue depth with rising I/O wait | The disk, not the CPU, has become the bottleneck, and disk throughput on a single node caps out |
| 95th/99th-percentile (p95/p99) latency | Rising tail latency and service-level objective (SLO) breaches under load even after a resize | The vertical lever has already been pulled and stopped helping |
| Cost trajectory | Each further resize costs disproportionately more per unit of added capacity | You are paying the non-linear premium described above with no ceiling relief |
| Availability requirement | Any requirement to survive a single-node failure without downtime | Vertical scaling cannot provide this by itself; only redundancy (horizontal) can |
Cloud-specific version of this decision. The same signals drive the same move on every major cloud, just through different primitives: on AWS you resize the EC2 instance type first, then hand scaling over to an Auto Scaling Group (ASG) that adds instances instead of resizing further; on Azure the equivalent fleet-level primitive is a VM Scale Set; on GCP it is a Managed Instance Group. All three exist because the same lesson applies everywhere: resizing is the cheap first lever, and a policy-driven fleet is the lever that removes the ceiling.
The often-missed factor: licensing. For commercial database or middleware software billed per-core or per-instance, vertical scaling can look artificially attractive on infrastructure cost while licensing cost scales the same way (or worse) as horizontal scaling would, once you account for per-node license fees across a fleet. Model total cost of ownership, not just the compute bill, before committing to either path.
Worked example
A checkout service starts on one 4 vCPU / 16 GB instance. Traffic doubles over two quarters. The team resizes to 8 vCPU / 32 GB (still vertical), which buys headroom for a while. CPU utilization is now steady at 78% during business hours and p99 latency has grown from 220 ms to 410 ms even after the resize, with no code regression identified. Disk and memory are not saturated; only CPU and tail latency are trending against the thresholds above. That combination, a saturated resource plus a latency SLO breach that resizing no longer fixes, is the signal to stop resizing and horizontally scale: put the service behind a fleet (ASG-equivalent) of smaller instances instead of chasing a bigger single one.
In practice, most teams do not choose purely one or the other. A common hybrid: keep the primary datastore vertically scaled as far as practical (since horizontally scaling stateful stores is the harder, sharding-level problem: splitting the data itself across nodes means picking a partition key, routing each query to the node that owns the relevant data, and rebalancing data when nodes are added or removed, none of which a stateless tier ever has to do), while horizontally scaling the stateless application tier in front of it, because the application tier is the cheaper piece to make replaceable first.
Trade-offs & pitfalls
- Resizing repeatedly without a plan for the ceiling is a common trap: teams keep buying the next instance size up until they hit the largest tier available, at which point the horizontal rewrite happens under emergency pressure instead of as a planned migration.
- Horizontal scaling only pays off if the service was made stateless or its state externalized first; bolting a load balancer in front of a stateful service without that groundwork just distributes the same single point of failure.
- Watch resource signals together, not in isolation: CPU can look fine while disk I/O or memory is the real ceiling, and treating the wrong resource as the bottleneck leads to buying the wrong upgrade.
- Cost is not a tie-breaker in only one direction: nonlinear pricing at the top of the vertical tier can push toward horizontal even before a technical ceiling is hit, and licensing cost can push the other way.
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.
Describe stateless versus stateful service designs, and explain why statelessness enables easier horizontal scaling. Include strategies to externalize state (databases, caches, session stores), and discuss scenarios where a stateful service is genuinely necessary, for example leader election or long-lived sticky connections.
Sample Answer
Direct answer
A stateless service keeps no client- or session-specific data in process memory between requests: every request carries (or looks up) everything needed to handle it. A stateful service holds that context in memory across requests, such as an open socket or an in-memory session. Statelessness enables horizontal scaling because any instance can serve any request, so a load balancer can distribute traffic with no per-node reconciliation and instances become disposable: add, remove, or replace them freely.
Structured elaboration
Why statelessness is the enabler, mechanically
- Interchangeability: since no instance holds unique data, a request routed to any instance gets the same result, which is what makes simple, even load distribution possible.
- Painless scaling events: adding capacity means starting new instances with no data migration; removing capacity means stopping instances with no data loss, because nothing lived there that mattered.
- Simpler recovery: a crashed stateless instance is replaced, not repaired; there is no in-memory state to reconstruct.
- Simpler rolling deploys: instances can be cycled one at a time without draining session state first.
Strategies to externalize state
- Durable application state moves to a database (relational or NoSQL) instead of process memory.
- Fast shared access to hot data moves to a distributed cache (an in-memory key-value store shared across instances) rather than a per-instance local cache.
- Session data specifically has two common paths: a centralized session store, or client-held tokens (such as a signed JSON Web Token, JWT) that let the server stay stateless entirely because the client presents its own state on every request.
- Large binary objects move to an object store rather than local disk.
- Asynchronous or queued state (work in flight, not yet durable) moves to a message queue.
- Small amounts of shared coordination state (configuration, leader pointers, locks) move to a dedicated coordination service built for that job.
Where a stateful service is genuinely necessary
| Scenario | Why statelessness does not fit | Typical mitigation |
|---|---|---|
| Leader election | A cluster needs exactly one active decision-maker at a time; that role is inherently shared, coordinated state, not a per-request fact | Use a purpose-built coordination service to hold and arbitrate the leader pointer, and design fast, automated re-election on failure |
| Long-lived connections (WebSocket, gRPC streams) | The connection itself is state; a mid-stream request cannot be freely handed to a different node without breaking the stream | Route stream traffic with connection affinity (a load-balancing mechanic, out of scope here) and design the client to reconnect and resume cleanly on node loss |
| Low-latency in-memory computation | Externalizing every read adds network latency that some workloads cannot absorb | Keep a local cache as a performance optimization layered on top of an externalized source of truth, not as the only copy |
| Stateful stream processing (windowed aggregation) | The computation's correctness depends on an accumulating window that must survive across events | Checkpoint local state to durable storage continuously so a replacement node can resume from the last checkpoint instead of from scratch |
The SRE angle: operating a stateful service you cannot avoid. When a stateful service is genuinely required, the operational burden shifts from "how do I scale it" to "how do I keep it reliable despite being pinned." That means treating the stateful nodes as a smaller, more carefully managed subset of the fleet: automated health checks tied to a fast failover or re-election path, regular drills that exercise that failover before it is needed under real incident pressure, and monitoring that specifically watches for the failure modes unique to statefulness (a stuck leader, a connection that never drains, a checkpoint that falls behind). The mitigation is never "make it stateless anyway"; it is "shrink the stateful surface to the minimum and instrument that minimum heavily."
Worked example
A web application currently stores logged-in session data in each server's memory, so a user's second request must land on the same server (sticky routing) or their session appears to vanish. To make the tier horizontally scalable: move session data out of process memory into a shared session store, or better, switch to a signed token that the client holds and presents on each request so the server does not need to look anything up at all. Either change means any instance can now serve any request, sticky routing is no longer required, and the fleet can be scaled up or down purely on load, with new instances immediately able to serve full traffic with zero data migration.
Trade-offs & pitfalls
- Do not confuse "stateless service" with "no state exists": the state still exists, it has just moved to a system designed to hold it reliably. That external system becomes a new dependency and a new potential bottleneck, so it needs its own scaling plan.
- Client-side tokens remove server lookups but push size and revocation concerns onto the client and the token design; server-side session stores keep revocation simple but add a network hop and a shared-store scaling problem.
- Treating "sticky sessions" as a free fix for statefulness is a common wrong turn: it works, but it silently reintroduces a form of per-node state ownership and undermines the failure-isolation benefit that horizontal scaling was meant to provide.
- For the genuinely stateful cases, skipping the failover-drill discipline is the most common production failure: the coordination logic works in testing and then fails silently the first time it is needed in an incident, because it was never exercised under realistic conditions.
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.