Interview Study Guide

Guide / System design Fundamentals

1.5 Scaling patterns

How to scale a system step by step: find the bottleneck, make services stateless, autoscale, scale reads and writes differently, scale the database in the right order, and handle spikes.

Created · Updated · 15 min read

“How would you scale this?” is the most common follow-up in any system design round. The wrong answer is a list of technologies. The right answer is a method: measure → find the bottleneck → apply the cheapest pattern that removes it → find the next bottleneck.

Order in this page: Fundamentals (method, patterns by layer) → Most asked questions (including the classic “scale from 1 to 10 million users”) → Senior-level questions → Quiz with answers. Connected pages: Load balancing, Caching, Replication and sharding, Messaging.

Fundamentals#

1.5.1 The method: bottleneck first#

Scaling means keeping latency and error rate acceptable as load grows. Only the current bottleneck matters; improving anything else changes nothing.

  1. Define the target: QPS, data size, latency SLO (e.g. p99 < 300 ms), availability. (Estimation)
  2. Measure: CPU, memory, disk I/O, network, DB query times, queue depth, connection counts, lock waits, per-endpoint latency percentiles.
  3. Identify the saturated resource. Typical order of appearance: database → connection pools → single-threaded or locked code → a downstream service → network/bandwidth → CPU of app servers (usually the easy one).
  4. Apply the cheapest fix, re-measure, repeat.

Two laws worth quoting:

  • Little’s Law: concurrency = throughput × latency. At 1,000 req/s and 200 ms latency you hold ~200 requests in flight; if latency doubles during a slowdown, in-flight work doubles too, exhausting threads and pools. This is how slow dependencies cause cascading failures.
  • Queueing: latency rises gently until utilisation reaches about 70–80%, then explodes. Plan for peak utilisation under ~60–70% and keep headroom for failures (N+1, lose a zone).
  • Amdahl’s law: the serial part (a global lock, one hot row, a single leader) caps the speedup from adding servers.

1.5.2 Vertical vs horizontal, and the scale cube#

Vertical (scale up)Horizontal (scale out)
HowBigger machineMore machines
ProsSimplest; no distribution problems; no code changesNo ceiling; redundancy; incremental cost
ConsHard ceiling, expensive at top end, single point of failure, downtime on resizeNeeds stateless design or partitioning; operational complexity; network failures
UseFirst move for DBs and early stagesStateless services, caches, read replicas, partitioned data

The scale cube gives three axes: X clone identical instances behind a load balancer; Y split by function (microservices: search, orders, payments); Z split by data (sharding by user, region or tenant). Mature systems use all three.

1.5.3 Stateless services (prerequisite for scaling out)#

A service is stateless when any instance can serve any request. Then you can add, remove, or replace instances freely, and an LB can send traffic anywhere.

Move state out:

StateWhere it goes
User sessionRedis, or signed token (JWT/secure cookie)
Uploaded filesObject storage (S3), served via CDN
Application dataDatabase
CachesRedis/Memcached (local in-process caches only as an optimisation)
Background workQueue + workers
Configuration, feature flagsConfig service, environment variables, flag store
Scheduled jobsA scheduler with leader election or leases, not “cron on every instance”

Also: write logs to stdout, don’t store files on local disk, and don’t rely on in-memory counters for correctness.

1.5.4 Autoscaling#

AspectGuidance
MetricCPU is a poor proxy for I/O-bound services. Prefer requests per instance, queue depth / consumer lag, concurrency, or p95 latency. Target-tracking policies (keep RPS/instance ≈ X) are simplest
DirectionScale out fast, in slow. Scale-in with cooldowns avoids oscillation (flapping)
LagNew instances take 1–5 minutes (boot, pull image, warm up). Autoscaling cannot absorb a spike that grows in seconds
Spiky or predictable loadScheduled/predictive scaling before known events (sales, market open), warm pools of pre-initialised instances, over-provision headroom
LimitsMax instances bounded by DB connections, downstream quotas, IPs and budget
SafetyMin instances ≥ 2 per zone for availability; new instances use readiness checks and slow start
WorkersScale consumers on queue depth/age; cap at the number of partitions for Kafka

Watch the hidden bottleneck: 100 more app instances each opening 20 DB connections means 2,000 more connections to a database that handles a few hundred. Use connection pooling proxies (PgBouncer, RDS Proxy) and cap per-instance pools.

1.5.5 Scaling reads#

Most systems are read-heavy (10:1 to 1000:1). Apply in this order:

  1. Query and index tuning: often a 10–100× gain for free (Database scale).
  2. Cache: browser, CDN, application cache, Redis (Caching). Typically the biggest lever.
  3. Read replicas: route reads to replicas; handle replication lag (read-your-writes: read from the primary for a short time after a write, or by session).
  4. CDN for static and cacheable API responses.
  5. Denormalisation and precomputation: materialised views, precomputed feeds, counters, search indexes. Trade write cost and storage for read speed.
  6. Specialised stores: Elasticsearch for search, Redis for leaderboards, column stores for analytics.
  7. Partition the data when one node cannot hold the working set.

1.5.6 Scaling writes#

Writes are harder because they need coordination. In order:

  1. Reduce write amplification: batch inserts, avoid unnecessary indexes, avoid updating hot rows, update only changed columns.
  2. Absorb bursts with a queue: accept the request, enqueue, return 202, and let workers write at a steady rate (Messaging). Needs idempotent consumers.
  3. Batch and buffer: group many small writes into one (write-behind, micro-batches, Kafka producer batching).
  4. Write-optimised storage: LSM-tree stores (Cassandra, RocksDB, DynamoDB) for high-volume appends, time-series DBs for metrics.
  5. Shard by a high-cardinality key so writes spread across nodes (Replication and sharding).
  6. Split hot counters: one likes row updated 10K times/s becomes N sub-counters summed on read, or counts aggregated asynchronously from an event stream.
  7. Move work off the write path: do validation and persistence synchronously; do notifications, analytics, search indexing and emails asynchronously through events.

1.5.7 Scaling the database: the usual order#

  1. Fix slow queries and add the right indexes (EXPLAIN).
  2. Connection pooling; right-size pools.
  3. Cache hot reads.
  4. Scale up (bigger instance): cheap, buys months.
  5. Read replicas for read traffic and analytics.
  6. Move heavy analytics off OLTP (warehouse, CDC to a data lake).
  7. Partition large tables (by time or tenant) for pruning and cheaper maintenance.
  8. Functional split: separate databases per service/domain.
  9. Shard (the last resort because of cross-shard queries, transactions and operations), or move to a natively distributed store (DynamoDB, Cassandra, Spanner/Cockroach).

Interview rule: never jump to sharding first. State the cheaper steps and the numbers at which each stops being enough (“a well-indexed Postgres node handles ~5–20K simple QPS; we shard past a few TB or sustained >10K writes/s”).

1.5.8 Asynchronous and event-driven scaling#

Decouple producers from consumers with a queue or log:

  • Load levelling: a spike of 50K requests/s is absorbed by the queue and drained at 5K/s by workers; users see “processing” instead of errors.
  • Independent scaling: web tier scales on RPS, workers on queue depth.
  • Fan-out: one event feeds search, email, analytics, cache invalidation.
  • Backpressure: bounded queues; when full, reject (429/503) rather than grow memory. A queue only hides overload, it does not remove it: if inflow exceeds drain rate for long, lag grows without bound.

1.5.9 CDN and edge#

A CDN caches content near users. Pull CDN: fetches from origin on first request (default); push: you upload content (large, rarely-changing files). Key points: cache key (URL + selected headers), Cache-Control and Vary correctness, versioned filenames (app.3f2a.js) instead of purges, origin shielding (one regional cache in front of origin to collapse misses), signed URLs for private content, and edge compute for A/B tests, auth checks and personalisation. A CDN also gives DDoS absorption and TLS termination close to users.

1.5.10 Service decomposition: monolith vs microservices#

Start with a modular monolith (clear module boundaries, one deployable). Split a service out when: a part needs to scale independently, teams are blocked on each other, failure isolation is needed, or technology needs differ. Costs of microservices: network latency and failures, distributed transactions (sagas), versioning, observability, deployment complexity. Scaling is rarely the first reason to split; team and release independence usually is.

1.5.11 Isolation patterns that protect scale#

PatternPurpose
BulkheadsSeparate thread/connection pools per dependency or tenant so one slow dependency cannot exhaust all capacity
Timeouts + circuit breakersFail fast on slow dependencies; stop calling a failing service
Rate limits and quotasPer-caller fairness (Rate limiting)
Load sheddingDrop low-priority work when overloaded
Cells / shards of the whole stackEach cell serves a subset of customers with its own stack, so failures and noisy neighbours have bounded blast radius
Graceful degradationServe cached or simplified responses when a dependency fails (hide recommendations, keep checkout)

1.5.12 Handling traffic spikes#

Spike typeStrategy
Predictable (sale, launch, market open)Pre-scale, pre-warm caches and LBs, load test, virtual waiting room, freeze deploys
Unpredictable (viral post)CDN and cache absorb reads, autoscale, shed load, degrade features
Retry storm after an outageBackoff + jitter, circuit breakers, gradual ramp (slow start)
Hot key / hot partitionReplicate hot keys, local caches, salt keys, split counters
Thundering herd on a cache missSingle-flight, stale-while-revalidate, TTL jitter

1.5.13 Capacity planning and testing#

  • Load test (expected peak), stress test (find the breaking point), soak test (hours, finds leaks), spike test (sudden jump), chaos test (kill instances and zones).
  • Plan for N+1 or N+2: capacity after losing one zone or node must still handle peak.
  • Measure cost per request and look for non-linear growth (fan-out, N+1 queries, cache misses).
  • Track the headroom metric (peak utilisation vs limit) in dashboards, and set alerts at 60–70%.

1.5.14 Symptom → pattern cheat table#

SymptomLikely causePattern
DB CPU high, same reads repeatedHot readsCache, replicas, indexes
DB write latency risingWrite contention or too many indexesBatch, queue, shard, reduce indexes
p99 high, p50 fineTail latency: slow shard, GC, fan-outHedged requests, timeouts, reduce fan-out
Errors only at peakPool exhaustion or no headroomPool tuning, autoscale, shed load
Consumer lag growingSlow processing or hot partitionScale consumers (≤ partitions), batch, fix key skew
One tenant slows everyoneNoisy neighbourPer-tenant limits, bulkheads, cells
Global users slowDistanceCDN, regional deployments, geo-routing
Costs growing faster than trafficInefficient queries, over-provisioningProfile, cache, rightsizing, tiered storage

Most asked questions#

1. How would you scale a web application from 1 user to 10 million users? Walk the stages and say what breaks at each:

StageUsersArchitectureWhat breaks next
11–1KSingle server: app + DBSingle point of failure, resource contention
21K–10KSeparate DB from app server; managed DB with backupsApp server saturation
310K–100KLB + multiple stateless app servers; session in Redis; static files on S3 + CDNDB reads
4100K–1MRead replicas, Redis cache, connection pooling, async jobs via a queueDB writes, tail latency
51M–10MAutoscaling, multi-AZ, sharding or partitioned stores, search engine, event streaming, service split, observabilityCross-region latency, ops complexity
610M+Multi-region active-active, cells, tiered storage, per-tenant isolation, cost optimisationOrganisational scale

2. Horizontal vs vertical scaling? Vertical first for simplicity (especially databases); horizontal for stateless tiers, caches and when you need redundancy or exceed the biggest machine. Horizontal requires statelessness or partitioning.

3. What makes a service stateless and why does it matter? Any instance can serve any request because session, files and data live outside it. It allows autoscaling, rolling deploys, and trivial load balancing and failover.

4. How do you scale a read-heavy system? Cache (CDN, Redis), read replicas, indexes, denormalisation and precomputation, with a plan for invalidation and replica lag.

5. How do you scale a write-heavy system? Batch and queue writes, use LSM-tree or partitioned stores, shard by a high-cardinality key, split hot counters, move non-critical work off the write path.

6. When do you shard and how do you choose the key? After indexes, caching, replicas and vertical scaling are exhausted (TB-scale data or sustained high write rate). Key: high cardinality, even distribution, present in most queries (user_id, tenant_id); avoid time-based keys alone (hot latest partition). Cross-shard joins and transactions become your problem. See Replication and sharding.

7. How do you handle a sudden 10× traffic spike? Cache and CDN, autoscale (but know the lag), queue writes, rate-limit and shed low-priority traffic, degrade non-critical features, and pre-scale for known events.

8. How do you decide what to scale first? Find the bottleneck with metrics (utilisation, saturation, errors per component), fix the one that saturates first, re-measure.

9. What is a CDN and when does it not help? Edge caching of static and cacheable content near users. It does not help with personalised, uncacheable or write traffic (though it still terminates TLS and absorbs attacks).

10. How do you scale a service that calls a slow third party? Timeouts, circuit breaker, bulkhead pool, async via queue with retries, cache results, degrade gracefully.

Senior-level questions#

1. “You doubled the app servers and latency got worse. Why?” The bottleneck is downstream and more clients made it worse: DB connection exhaustion, lock contention on a hot row, a shared cache or a rate-limited third party. More app instances multiply concurrent queries, queue lengths and connection counts. Check DB active connections, lock waits, slow queries. Fix with pooling, query/index changes, caching, limiting concurrency per instance, and scale the real bottleneck.

2. “Autoscaling kicks in but users still see errors for 3 minutes at the start of a spike. What do you change?” Scale-out lag: pre-scale on schedule or predictive signals, keep headroom (target 50% utilisation), use warm pools or faster boot (smaller images, pre-baked AMIs), scale on a leading indicator (RPS, queue depth, not CPU), add a queue or waiting room to absorb the first minutes, enable load shedding so partial capacity serves critical traffic.

3. “Walk through scaling Postgres to 100× its current load without migrating off it.” Profile and fix the top queries, add composite indexes, pooler, cache hot reads, replicas for reads and reporting, partition by time or tenant, archive cold data, vertical scale, separate write-heavy tables into their own database, move analytics to a warehouse via CDC, then shard with a tenant-based key (Citus, Vitess-style routing, or application-level), designing for cross-shard queries via denormalisation or a search/analytics store.

4. “How do you scale WebSocket/stateful services?” Connections are sticky, so scale by connection count (memory, file descriptors): gateway tier that only holds sockets, stateless business logic behind it, pub/sub backplane (Redis, Kafka, NATS) for cross-node delivery, connection registry, graceful drain with reconnect jitter, per-node connection caps, autoscale on connections.

5. “A hot partition is limiting throughput on a sharded store. What do you do?” Diagnose the key skew (celebrity user, hot tenant, time-based key). Options: add a salt/suffix and fan reads out (key#0..#N), cache the hot key locally, split the hot entity’s data into sub-partitions, move the heavy tenant to a dedicated shard, adaptive capacity features (DynamoDB), or change the partition key to a composite with higher cardinality.

6. “How do you know your system is ‘scalable’, not just ‘big enough today’?” Show that throughput grows near-linearly with added nodes in load tests (and identify the serial fraction), that no component is a single point of contention, latency stays flat under headroom, and cost per request is stable. Then document the next three bottlenecks and their thresholds.

7. “Your architecture scales on paper but the bill explodes. How do you scale cost-efficiently?” Cache and CDN offload, right-size instances, spot/preemptible for stateless and batch, tiered storage (hot/warm/cold), compress and downsample, avoid cross-AZ and cross-region chatty traffic, reduce fan-out and payload sizes, autoscale in as aggressively as is safe, and measure cost per request and per tenant.

8. “Your queue-based architecture hides an overload for hours. How do you detect and handle it?” Monitor queue age (oldest message), not just depth; alert on drain rate < inflow; apply backpressure (reject or degrade when age exceeds the SLO); scale workers; prioritise queues (interactive vs batch); TTL on stale messages; dead-letter poison messages; communicate status to users (“processing, ~10 min”).

9. “Design for 10× growth in 12 months with a team of five.” Prefer boring, managed technology; keep the modular monolith; invest in observability, load testing and automated scaling first; cache and replicas before sharding; design data keys (tenant_id) now so sharding later is feasible; identify a few scaling cliffs with numbers and write a runbook for each; avoid premature microservices.

Quiz#

1. By Little's Law, 2,000 req/s at 150 ms average latency means how many requests in flight?

2,000 × 0.15 = 300 in flight on average. If latency rises to 600 ms during a slowdown, in-flight doubles four-fold to 1,200, which can exhaust thread and connection pools.

2. What makes a service horizontally scalable?

It is stateless (state externalised), instances are interchangeable and sit behind a load balancer, and there is no single serialised resource (global lock, single writer) in the request path.

3. Give the usual order for scaling a relational database.

Fix queries and indexes, add connection pooling, cache, scale up, read replicas, move analytics out, partition tables, split by function, shard as a last resort.

4. Why is CPU a weak autoscaling signal for an I/O-bound API?

Threads wait on I/O so CPU stays low while latency and queues grow. Use requests per instance, concurrency, latency or queue depth.

5. How do you scale a counter that receives 20K increments per second on one row?

Shard the counter into N sub-counters (random one per write) and sum on read, or aggregate asynchronously from an event stream/in Redis and flush periodically.

6. What is the scale cube?

X axis: clone instances; Y axis: split by function (services); Z axis: split by data (sharding by customer, region or ID).

7. When does a queue help and when does it just hide the problem?

It helps for bursts above the steady drain rate (load levelling). If sustained inflow exceeds drain rate, the queue grows without bound and latency grows: you need more consumers, backpressure or shedding.

8. Why scale in slowly?

Premature scale-in causes oscillation (flapping) and capacity loss right before the next burst; instances take minutes to come back.

9. What is a bulkhead?

Isolated resource pools (threads, connections, instances) per dependency or tenant so that failure or slowness in one cannot exhaust shared resources.

10. Why can adding application servers overload the database?

Each server opens its own connections and issues concurrent queries; total connections and concurrency scale with server count while the database capacity is fixed. Use pooling, limit concurrency, cache, and scale the DB tier.

11. What do you plan for beyond peak load?

Headroom (utilisation below 60–70%), N+1/N+2 redundancy (survive losing a node or zone), and growth margin; plus autoscaling lag and failover traffic.

12. How do you avoid the thundering herd when a large autoscaled fleet starts?

Stagger startup, use readiness and slow start, jitter on cache warm-up and reconnect timers, pooled connections with limits, and a warm pool.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes