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 must decide whether to partition a service's data by customer region or by feature/functional area. Weigh the long-term operational costs, cross-partition call frequency, join complexity, and rebalancing/migration effort of each, then propose a migration plan with a fallback and criteria for success.
Sample Answer
Direct answer
Partition by whichever dimension your dominant query and transaction pattern actually cuts along: region if most operations touch one customer's data end to end within a geography, feature/functional area if most operations touch one capability across many customers regardless of location. Pick the one that minimizes cross-partition calls for your hottest paths, since cross-partition joins and transactions are the recurring cost that compounds for the life of the system, then migrate incrementally behind a routing layer with a fallback rather than cutting over all at once.
Structured elaboration
1. Regional partitioning: what it optimizes and what it costs.
Regional partitioning groups all of a customer's data (across every feature) by geography. It's a strong fit when most transactions are naturally scoped to one region (a customer's orders, profile, and support tickets never need to join against another region's data) and when data residency or latency-to-user requirements favor keeping a region's data physically close to that region's users. The cost shows up whenever a query needs to span regions: cross-region aggregation (global reporting, a global search) requires either a fan-out query across every regional partition or a separate, eventually-consistent aggregation pipeline.
2. Feature/functional partitioning: what it optimizes and what it costs.
Functional partitioning groups data by capability (all billing data together, all inventory data together, regardless of customer or region). It's a strong fit when a feature team owns and evolves its data model independently and when most transactions are scoped to one capability. The cost shows up whenever a single customer-facing operation needs data from multiple functional areas (rendering an order summary that needs billing, inventory, and shipping data together), which becomes a cross-partition join or a fan-out call on every such request.
3. Weigh the four factors concretely.
- Cross-partition call frequency: instrument current query patterns before deciding; the partitioning axis that appears most often as a WHERE clause or join key is a strong signal for which axis is dominant.
- Join complexity: a partitioning scheme that forces joins across partitions for common queries pushes that complexity into application code (scatter-gather, denormalized read models) since the database can no longer do it for you.
- Rebalancing and migration effort: regional partitions rebalance rarely (regions don't change) but can become unevenly sized as one region grows faster; functional partitions can need re-splitting as a single functional area outgrows its partition, which is a more frequent but usually smaller-scope operation.
- Long-term operational cost: whichever axis you don't choose becomes a permanent tax paid on every cross-partition operation for the life of the system, not a one-time migration cost, which is why getting the dominant-access-pattern analysis right up front matters more here than in most partitioning decisions.
Worked example
graph TB
subgraph Regional["Partition by region"]
R1[Region: US data]
R2[Region: EU data]
end
subgraph Functional["Partition by feature"]
F1[Billing data]
F2[Inventory data]
F3[Shipping data]
end
Q1[Customer order lookup] -->|single-region hit| R1
Q2[Global revenue report] -.->|fan-out, all regions| R1
Q2 -.-> R2
Q3[Order summary page] -.->|cross-partition join| F1
Q3 -.-> F2
Q3 -.-> F3
If instrumentation shows 90% of production queries are single-customer, single-region operations (order lookup, profile update) and only 10% are cross-region aggregates, regional partitioning is the right axis: the dominant path stays single-partition, and the 10% cross-region cost is paid by a small, well-understood reporting pipeline rather than by every customer-facing request.
Migration plan. Introduce a routing layer (a lookup service or a consistent mapping table) that resolves "which partition owns this key" before any data moves, and point all reads and writes through it even while everything still lives on the old, unpartitioned store. Migrate one partition's data at a time behind that layer using a dual-write or change-data-capture (CDC, change-data-capture) based sync, verify read parity against the old store for a bake-in period, then cut reads over per partition. The fallback is the routing layer itself: if a newly migrated partition shows correctness or latency problems, route that partition's traffic back to the old store while the issue is fixed, without affecting partitions that have already cut over cleanly. Success criteria: read/write latency at or below the pre-migration baseline per partition, zero data-parity discrepancies during the bake-in window, and no fallback triggered for a defined stability period (for example, two full weeks) before considering that partition's migration complete.
Trade-offs & pitfalls
The most common mistake is picking the axis that matches the org chart instead of the query pattern (functional partitioning because "that's how our teams are structured") without instrumenting actual cross-partition call frequency first; the org chart and the dominant access pattern often agree, but when they don't, the access pattern should win, since it is what determines runtime cost, not team structure. A second pitfall is treating the migration as all-or-nothing: without a per-partition fallback, a correctness or performance problem discovered halfway through forces a full rollback instead of a contained one. A subtler pitfall is not planning for the 10-20% of operations that will always cross whichever boundary you choose; those need a deliberate strategy (a fan-out aggregation service, a denormalized read model) from day one rather than being treated as an edge case to handle later.
Explain backpressure in a distributed system and why it matters for reliability. What mechanisms would you use to implement it between services, such as request quotas, flow control in a messaging system, or reactive streams, and how do they prevent cascading failure?
Sample Answer
Direct answer
Backpressure is a flow-control mechanism where an overloaded consumer signals upstream producers to slow down, so the system stays within its real processing capacity instead of silently queuing work until it runs out of memory or falls over. It matters for reliability because, without it, a slow or overwhelmed component doesn't fail cleanly; it builds an unbounded backlog that eventually causes a resource exhaustion failure, which can then cascade into components that depend on it.
Structured elaboration
The core loop: a consumer reports its available capacity (a credit, a token, an explicit "slow down" signal) back to whatever is sending it work, and the producer honors that signal by slowing down, buffering locally, or rejecting new work rather than forcing it through.
Backpressure versus rate limiting. These are often confused but apply at different points in the request path:
| Backpressure | Rate limiting | |
|---|---|---|
| Who it protects | The receiving component itself, based on its own real-time capacity | The service as a whole, from any single client consuming more than its fair share |
| Where it applies | Internally, between cooperating components (a queue and its consumer, two microservices) | At the edge or ingress, against external or untrusted clients |
| Signal basis | Actual, live capacity (queue depth, in-flight work) | A pre-set policy (N requests per minute), regardless of current internal load |
They compose well together: rate limiting caps what's allowed in at the edge; backpressure handles what happens internally once accepted work outpaces a specific consumer's real capacity.
Concrete mechanisms:
- Reactive Streams (an interface pattern used by libraries like Project Reactor and RxJava): the consumer explicitly calls
request(n)to say how many items it can accept next, rather than the producer pushing an unbounded stream. - TCP windowing (transport layer): a TCP receiver advertises a receive window, the amount of unacknowledged data it's willing to hold, and a sender must stop once that window fills; this is backpressure operating below the application entirely, and it's why a slow reader can stall a writer even with no application-level queue involved.
- gRPC / HTTP/2 flow control: stream-level flow-control windows, multiplexed over one TCP connection, mean a client cannot outrun what the server has said it can currently accept; this is a separate, application-layer analog of the same TCP-level idea, not the same mechanism.
- Kafka consumer-side flow control: a consumer can
pause()/resume()specific partitions, andmax.poll.recordsbounds how many records a single poll returns, both of which let a consumer throttle its own intake rate. - RabbitMQ consumer prefetch: limiting unacknowledged messages delivered to a consumer at once prevents one slow consumer from being handed more work than it can hold.
- Bounded queues with a blocking or rejecting producer: the simplest application-layer mechanism; the queue has a fixed capacity, and a full queue either blocks the producer (creating backpressure) or rejects new work outright (a flow-control protocol decision that trades data loss for keeping the consumer alive).
Worked example
Consider a Go-style worker pool: a hot request-handling path writes work items into a fixed-size in-memory channel that a pool of workers reads from. Under normal load, the channel rarely fills and writes return immediately. Under a sustained spike, the channel fills up. At that point, without an explicit flow-control decision, the sending goroutine (the request handler) blocks on the write, which means the original HTTP request handling itself now blocks, which then makes that server's own request queue back up, which then causes its own health checks or upstream timeouts to start failing, all originating from one bounded channel filling up. This is backpressure working exactly as designed, propagating a real capacity signal backward, but only if the layer receiving that backpressure (the request handler here) has a bounded, timeout-aware way to react to it; without a timeout on the channel write, "backpressure" quietly becomes "the request handler hangs," which is an availability failure with a different shape than an unbounded queue overflowing. This is the same low-level pattern as TCP windowing above, a full buffer stalling a writer, just one layer higher in the stack.
Trade-offs & pitfalls
- Backpressure without a bounded, timeout-aware reaction just moves the failure upstream rather than preventing it, as the worked example shows; the mechanism only helps if every layer that receives a "slow down" signal has a defined, bounded way to act on it.
- A queue that's too generously sized delays the pain instead of preventing it, and the eventual failure (running out of memory) is harder to diagnose than an early, deliberate rejection would have been.
- Backpressure does not by itself prevent data loss, only unbounded resource growth; if a producer's reaction to a "slow down" signal is to drop the work rather than retry or buffer it durably, backpressure alone is not enough, and a durable retry or dead-letter path is a separate design decision.
- This is a distinct concept from cascading-failure prevention mechanisms like circuit breakers, which stop sending traffic to an unhealthy dependency rather than throttling to match a healthy one's real-time capacity; the two are complementary but answer different questions.
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 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.
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.