Scaling from Zero to Millions
- Explain the standard scaling path (single box → separate DB → load-balanced stateless tier → replicas → cache → CDN → multi-DC → queues → sharding) and the bottleneck each step removes
- Distinguish vertical and horizontal scaling, and stateless and stateful components, and choose between them
- Make a service horizontally scalable: externalised sessions, graceful shutdown, idempotent work
- Justify, with numbers, which steps a bank's digital channel or an e-commerce marketplace needs today versus later
TL;DR
- Every step on the path removes one specific bottleneck and adds one specific kind of complexity. Take a step only when the numbers say you hit that bottleneck.
- Vertical scaling (bigger box) is simple and keeps strong consistency, but has a ceiling and a single point of failure. Horizontal scaling (more boxes) has no hard ceiling but demands statelessness, coordination, and distributed failure handling.
- The web/API tier must be stateless: sessions, uploads and in-flight jobs live in shared stores (Redis, DB, object storage, queues), so any instance can serve any request and instances can be killed at will.
- The database is usually the last thing to scale horizontally. The order is: tune and scale up → read replicas → cache → functional split → shard.
- CDNs, caches and queues are load reducers: they make fewer requests reach the expensive, stateful parts.
- Multi-datacenter is primarily an availability and latency decision, not a throughput one, and it forces you to decide how data is replicated across sites.
Why it matters
"Design a system that scales from 1,000 to 10 million users" is the most common opening of a system design interview, and it is a proxy for a real job question: what is the minimum architecture that meets this year's load and availability targets, and what is the plan for next year's?
- An e-commerce marketplace launches on one VM, then 11.11 arrives. Product pages need a CDN, the catalog needs a cache, checkout needs a queue to absorb bursts, and the orders table eventually outgrows one primary.
- A bank's mobile channel serves a few hundred thousand users from a pair of application servers in front of a core banking system that scales vertically on expensive hardware. Growth to millions of users means a horizontally scaled channel layer, a read model so balance and history queries stop hitting the core, and active-passive DR that regulators will audit.
Knowing why each layer exists — not just its name — is what separates an architect from someone who memorised a diagram.
Core concepts
Vertical vs horizontal scaling
| Vertical (scale up) | Horizontal (scale out) | |
|---|---|---|
| How | More CPU, RAM, faster disks on one node | More nodes behind a load balancer or partitioning scheme |
| Ceiling | Hard: the biggest box you can buy | Soft: coordination and data distribution costs |
| Failure | One box is a single point of failure | Individual failures are routine and tolerated |
| Consistency | Easy: one memory, one transaction log | Hard: replication, partitioning, distributed transactions |
| Cost curve | Superlinear at the high end | Roughly linear, plus operational overhead |
In practice you use both. Stateless tiers scale out because it is easy. Databases scale up first because it preserves single-node ACID semantics — many banks still run their core ledger on a large vertically-scaled database cluster for exactly this reason.
Stateless vs stateful
A component is stateless if any instance can handle any request because everything it needs is in the request or in a shared store. It is stateful if a request must reach a particular instance (sessions in memory, a WebSocket connection, a local cache that must be authoritative, a database).
Making the web tier stateless means moving state out:
| State | Where it moves | Notes |
|---|---|---|
| Login session | Redis or a DB-backed session store, or a signed token | Banks usually prefer server-side sessions: instant revocation and enforced idle timeouts |
| File uploads (KYC documents, product images) | Object storage via pre-signed upload URLs | Never local disk |
| Background jobs | A message queue or job table | Instances can die mid-job; work must be retryable and idempotent |
| Rate-limit counters | Redis | Per-instance counters become wrong once you have N instances |
| Shopping cart | Redis or a cart service backed by a DB | Cart abandonment emails need it server-side anyway |
Stateful components still exist — databases, brokers, caches, WebSocket gateways — but you isolate them, replicate them, and scale them with dedicated techniques (replication, partitioning, consistent hashing).
The scaling path
The stages below are cumulative. Each one lists the trigger that should make you take it.
Stage 0 — a single server
Web app, database and files on one machine. DNS points at its IP.
- Fine for: an MVP, an internal tool, a pilot with a few thousand users.
- Breaks when: CPU or memory contention between app and DB, any deploy means downtime, the disk fills, or the box dies and takes everything with it.
Stage 1 — separate the database
Move the database to its own node (or a managed service). Now the app tier and data tier scale independently, and the DB gets dedicated memory for its buffer cache.
- Gain: independent sizing, simpler backups, managed failover with a standby.
- Cost: a network hop per query (≈ 0.5 ms), connection management.
Stage 2 — load balancer plus stateless web tier
Put two or more stateless instances behind a load balancer. Health checks remove dead instances; rolling deploys become zero-downtime.
- Trigger: one instance cannot handle peak, or you need availability during deploys and failures.
- Prerequisite: statelessness (see above) and graceful shutdown.
- Details in Load Balancing.
Stage 3 — database replication
Add read replicas. Writes go to the primary; reads that tolerate slight staleness go to replicas. A synchronous or semi-synchronous standby provides failover.
- Trigger: read load saturates the primary (catalog browsing, order history, account statements), or you need fast failover.
- New problem: replication lag. A customer transfers money, refreshes, and the history page (served by a replica) does not show it yet. You need read-your-writes routing for such flows. See Database Replication & Sharding.
Stage 4 — cache
Put a cache (Redis, Memcached, or in-process) in front of the database for hot, read-mostly data: product details, category trees, exchange-rate tables, feature flags, merchant configuration.
- Trigger: the same data is read far more often than it changes, and DB latency or load is the bottleneck.
- New problems: invalidation, stampedes, hot keys, and stale reads. In a bank, never let a cached balance authorize a debit. See Caching.
Stage 5 — CDN
Serve static assets (JS bundles, images, product photos, PDFs) and cacheable API responses from edge locations near users.
- Trigger: large static payloads, geographically spread users, or spikes that would saturate origin bandwidth (a flash sale product page).
- New problems: cache keys, purge strategy, never caching personalised responses. See CDN & Edge.
Stage 6 — multiple datacenters or regions
Run the stack in two or more sites. Traffic is steered by GeoDNS or a global load balancer; on failure, traffic shifts to the surviving site.
- Trigger: availability targets that one site cannot meet (99.99%+), regulatory DR requirements, or latency for users on other continents.
- Key decision: active-passive (one site takes writes; simpler, common in banking) vs active-active (both take writes; requires conflict-free data partitioning by user or region, or a globally consistent database).
- New problems: data replication across sites (RPO), failover orchestration (RTO), split-brain, config and deploy consistency. See High Availability & Disaster Recovery and CAP & PACELC.
Stage 7 — message queues and asynchronous work
Decouple producers from consumers. Order placed → publish OrderPlaced → inventory, notifications, loyalty points and analytics consume independently.
- Trigger: slow or unreliable side effects on the request path (sending SMS/email, calling a slow partner, generating statements), spiky load that should be smoothed, or many consumers of the same event.
- New problems: at-least-once delivery, idempotent consumers, ordering, poison messages, and the dual-write problem (use a transactional outbox). See Message Queues & Event Streaming and Transactional Outbox & CDC.
Stage 8 — sharding
Split data horizontally across multiple database primaries by a shard key (user id, account id, merchant id).
- Trigger: write throughput or data size exceeds what one primary can handle after you have tuned, scaled up, offloaded reads, cached, and split functionally (orders DB separate from catalog DB).
- New problems: shard key choice, hot shards, cross-shard queries and transactions, resharding. See Database Replication & Sharding and Consistent Hashing.
The resulting architecture
Beyond this point the work is mostly organisational and operational: splitting into services along domain boundaries (Microservices Patterns), observability (Observability & SLOs), automation and deployment strategies (Cloud-Native, Kubernetes & Deployment Strategies).
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Scale up the DB | No code changes, keeps ACID on one node | Ceiling, cost, single failure domain | First response to DB load; core ledgers |
| Read replicas | Cheap read scaling, failover target | Replication lag, read-your-writes complexity | Read-heavy workloads (catalog, history) |
| Cache | Large latency and load reduction | Staleness, invalidation bugs, stampedes | Read-mostly hot data |
| Functional split (DB per domain) | Isolates load and blast radius, simple | Cross-domain joins move to app/events | Before sharding, when domains are clear |
| Sharding | Scales writes and storage horizontally | Cross-shard queries, resharding, ops cost | One primary truly cannot keep up |
| Sticky sessions | No session store needed | Uneven load, lost sessions on node failure | Legacy apps you cannot change yet |
| Server-side session store | Revocation, idle timeout, any-instance routing | Extra dependency on the hot path | Banking and anything with strict session policy |
| Signed tokens (JWT) | No lookup per request | Hard to revoke before expiry | Short-lived tokens between services |
| Active-passive multi-DC | Simpler data model, clear write site | Idle capacity, failover is an event | Banking cores, strong consistency needs |
| Active-active multi-DC | Uses all capacity, local latency | Conflict handling, data partitioning by home region | Global consumer apps partitionable by user |
In practice
- Measure first. Most "we need to scale" problems are a missing index, an N+1 query, or an unbounded connection pool. See Query Optimization.
- Autoscaling of the stateless tier works on CPU or RPS signals with a lag of minutes. For known events (salary day, 11.11), schedule scale-ups ahead of time.
- Connection count grows with the fleet. 100 API pods × 20 connections = 2,000 DB connections, which PostgreSQL handles poorly. Use a pooler (PgBouncer) or cap pools per pod. Little's Law tells you how many you really need.
- Graceful shutdown is part of statelessness. On
SIGTERM, fail the readiness probe, let the load balancer drain, finish in-flight requests, then exit. Without it, every rolling deploy produces a burst of 502s.
package main
import (
"context"
"errors"
"log"
"net/http"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
func main() {
var ready atomic.Bool
ready.Store(true)
mux := http.NewServeMux()
mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {
if !ready.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/v1/orders", handleOrders) // reads session from Redis, never from memory
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
<-ctx.Done()
ready.Store(false) // LB health checks start failing
time.Sleep(10 * time.Second) // give the LB time to stop sending new traffic
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil { // waits for in-flight requests
log.Printf("shutdown: %v", err)
}
}
func handleOrders(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
}
- Banking reality check. The channel tier (mobile/internet banking APIs) follows this path closely. The core banking system often does not: it is vertically scaled, sometimes a vendor product, and protected by an integration layer that caches reference data, queues requests, and serves balances and history from a read model fed by CDC. See Legacy Modernization & Migration.
Common pitfalls
- Sharding too early. A system doing 300 TPS gets twelve shards and spends a year fighting cross-shard reporting. Symptom: every new feature needs a "scatter-gather" query.
- Hidden state in the web tier. In-memory sessions, local file uploads, or a per-instance scheduler. Symptom: users randomly logged out after deploys, cron jobs running N times once you have N instances.
- Stateless app, single-instance dependency. Ten API pods all depending on one Redis without replication — the bottleneck and the single point of failure just moved.
- Reading your own write from a replica. Customer pays, sees "no transaction" on the next screen, pays again. Symptom: duplicate payments and support tickets after enabling replicas.
- Ignoring DB connection explosion. Autoscaling adds pods during a spike, each opens a pool, the DB hits
max_connectionsand falls over exactly at peak. - Multi-DC without failover drills. The DR site exists on paper, but the first real failover reveals missing secrets, stale configs and DNS TTLs of one day.
Interview angle
- Typical prompt: "Start with a single server and evolve the design to support 10 M users", or the scaling segment of any design question.
- Strong answer: evolves the design in steps, naming the bottleneck that triggers each step and the new problem it introduces; uses estimation to decide which steps are needed; mentions statelessness explicitly; keeps the database simple as long as possible.
- Follow-ups: "How do you handle sessions with many instances?", "What happens to a user's write if they read from a replica?", "Active-active or active-passive for a bank, and why?", "What breaks first at 10× load?", "How do you deploy without downtime?"
- Red flags: jumping straight to microservices and sharding, ignoring the data tier while scaling the app tier, treating multi-region as free, no mention of failure modes.
Self-check
1. What makes a service stateless, and list three kinds of state you must externalise.
A service is stateless if any instance can handle any request because the request plus shared stores contain everything needed. Externalise login sessions (Redis/DB), uploaded files (object storage), background job state (queue or job table), rate-limit counters and carts. Instances can then be added, removed or killed without user impact.
2. Your catalog DB primary is at 85% CPU, 95% of it from reads. Order the options you would try and explain why.
First check for missing indexes and bad queries (cheapest). Then add a cache for hot product and category reads, and/or read replicas for the remaining read load. Scale up the primary if needed. Sharding is not indicated: the problem is reads, not writes or data size, so replicas and caching attack it directly with far less complexity.
3. Why do banks often prefer server-side sessions over long-lived JWTs for customer logins?
Server-side sessions can be revoked instantly (stolen device, password change, fraud flag) and idle timeouts can be enforced centrally, which security policies and regulators typically require. A JWT is valid until it expires unless you add a denylist, which reintroduces a lookup. A common compromise is short-lived access tokens plus a server-side refresh/session record.
4. What new problem does each of these introduce — read replicas, cache, queue, sharding?
- Replicas: replication lag, stale reads, read-your-writes routing.
- Cache: invalidation, stale data, stampedes, hot keys.
- Queue: at-least-once delivery and duplicates, ordering, poison messages, dual writes.
- Sharding: shard key choice, hot shards, cross-shard queries and transactions, resharding.
5. Scenario: an e-commerce company wants active-active in two regions for checkout. What must be true about the data for this to be safe?
Writes for a given entity must not conflict across regions. Either partition ownership (each user or order has a home region and is only written there), use a globally consistent database (with latency cost), or design conflict-free data types. Inventory is the hard part: a single SKU's stock decremented in both regions can oversell, so it typically needs a single owner region, pre-allocated per-region stock, or reservation via one authority.
6. Why is graceful shutdown a scalability concern rather than just a nicety?
Horizontal scaling means instances are constantly added and removed by deploys and autoscaling. If an instance exits while requests are in flight or before the LB stops routing to it, each scale-in or deploy causes errors. Failing readiness, draining, and waiting for in-flight work makes instance churn invisible to users.
Exercise
Take a bank's internet-banking platform today: 2 API servers with in-memory sessions, one Oracle/PostgreSQL database shared with the core, nightly statement generation on one of the API servers.
- Draw (on paper or as Mermaid) the target architecture for 5 M users with 99.95% availability.
- For each change, write one line: bottleneck removed and new risk introduced.
- Decide where balances and transaction history are read from, and how you avoid showing a stale balance immediately after a transfer.
- Implement the graceful-shutdown snippet in a small Go service, run two instances behind
nginxorhaproxylocally, and runheyorvegetaduring a rolling restart. Done means zero non-2xx responses during the restart.
Further reading
- System Design Interview – An Insider's Guide, Vol. 1 (Alex Xu), Ch. 1 "Scale From Zero To Millions Of Users".
- Designing Data-Intensive Applications (Martin Kleppmann), Ch. 1 (scalability) and Ch. 5–6 (replication, partitioning).
- The Art of Scalability (Martin Abbott, Michael Fisher) — the "scale cube" (X: clone, Y: split by function, Z: split by data).
- Site Reliability Engineering (Google), chapters on load balancing and handling overload.
- The Twelve-Factor App (12factor.net) — especially "Processes" (stateless) and "Disposability" (fast startup, graceful shutdown).
Related
- Back-of-the-Envelope Estimation — decide which stage you need with numbers.
- Load Balancing — stage 2 in depth.
- Caching — stage 4 in depth.
- Database Replication & Sharding — stages 3 and 8 in depth.
- Message Queues & Event Streaming — stage 7 in depth.
- High Availability & Disaster Recovery — stage 6 in depth.
- Quality Attributes & Trade-off Analysis — framing scalability against cost and complexity.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).