Skip to main content

Scaling from Zero to Millions

Learning objectives
  • 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)
HowMore CPU, RAM, faster disks on one nodeMore nodes behind a load balancer or partitioning scheme
CeilingHard: the biggest box you can buySoft: coordination and data distribution costs
FailureOne box is a single point of failureIndividual failures are routine and tolerated
ConsistencyEasy: one memory, one transaction logHard: replication, partitioning, distributed transactions
Cost curveSuperlinear at the high endRoughly 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:

StateWhere it movesNotes
Login sessionRedis or a DB-backed session store, or a signed tokenBanks usually prefer server-side sessions: instant revocation and enforced idle timeouts
File uploads (KYC documents, product images)Object storage via pre-signed upload URLsNever local disk
Background jobsA message queue or job tableInstances can die mid-job; work must be retryable and idempotent
Rate-limit countersRedisPer-instance counters become wrong once you have N instances
Shopping cartRedis or a cart service backed by a DBCart 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​

OptionStrengthsWeaknessesChoose when
Scale up the DBNo code changes, keeps ACID on one nodeCeiling, cost, single failure domainFirst response to DB load; core ledgers
Read replicasCheap read scaling, failover targetReplication lag, read-your-writes complexityRead-heavy workloads (catalog, history)
CacheLarge latency and load reductionStaleness, invalidation bugs, stampedesRead-mostly hot data
Functional split (DB per domain)Isolates load and blast radius, simpleCross-domain joins move to app/eventsBefore sharding, when domains are clear
ShardingScales writes and storage horizontallyCross-shard queries, resharding, ops costOne primary truly cannot keep up
Sticky sessionsNo session store neededUneven load, lost sessions on node failureLegacy apps you cannot change yet
Server-side session storeRevocation, idle timeout, any-instance routingExtra dependency on the hot pathBanking and anything with strict session policy
Signed tokens (JWT)No lookup per requestHard to revoke before expiryShort-lived tokens between services
Active-passive multi-DCSimpler data model, clear write siteIdle capacity, failover is an eventBanking cores, strong consistency needs
Active-active multi-DCUses all capacity, local latencyConflict handling, data partitioning by home regionGlobal 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_connections and 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.

🧠 Flashcards0/8 learned · 0 retries

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.

  1. Draw (on paper or as Mermaid) the target architecture for 5 M users with 99.95% availability.
  2. For each change, write one line: bottleneck removed and new risk introduced.
  3. Decide where balances and transaction history are read from, and how you avoid showing a stale balance immediately after a transfer.
  4. Implement the graceful-shutdown snippet in a small Go service, run two instances behind nginx or haproxy locally, and run hey or vegeta during 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).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).