Chapter 29 — Scalability Building Blocks: Statelessness, LB, Caching, Replicas, Sharding, Estimation
Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 23–Ch 24, Ch 21 | Builds: Pulsely scaled horizontally with caching layers and read replicas
Parts III and IV taught you to build one correct backend: a handler that runs the membrane, a database that holds the truth, transactions that keep it consistent. Parts of Part V then taught you what breaks the moment that one backend becomes two — failure detectors, consistency models, idempotency, queues. This chapter assembles those lessons into the standard kit every backend engineer eventually reaches for: how to take a service that runs on one machine and run it on fifty without lying to your users about what they'll see. Statelessness, load balancers, caches, read replicas, shards. Each is a way of duplicating something that was previously singular.
But the headline of this chapter is not the kit. It's the discipline: find the bottleneck before you scale anything. Most "we need to scale" emergencies are one missing index, one synchronous third-party call, one unbounded query wearing a scary costume. The engineers who reach for shards first and measurements never are the ones who spend a quarter building distributed complexity to solve a five-minute problem. We'll build the kit — and we'll build the instinct to not use it until the numbers say so.
1. The problem: one box is one blast radius
Here's the night this chapter exists to prevent.
Pulsely runs fine. It's one Node process on one decent EC2 instance, talking to one Postgres. For months the dashboards are boring green, which is exactly what you want. Then a batch of lab results is released to the patient portal at 6:14 pm — evening peak, right as the day-shift clinics close and patients pick up their phones — and every notified patient logs in at once. Traffic triples. CPU on the API box climbs to 90%. The event loop — which you've already met — starts falling behind; requests pile up waiting for a turn. p99 latency walks from a healthy 80 ms to 1.2 s to 4 s. Patients and front-desk staff staring at slow, spinning pages start double-clicking Submit and retrying, which doubles your write load — duplicate portal messages, duplicate check-ins — at precisely the wrong moment. Then the process crosses its memory ceiling, the kernel OOM-kills it, and Pulsely is down — not slow, down — for the ninety seconds it takes to restart and reconnect its pool.
Nothing was hacked. No code was wrong in the "throws an exception" sense. You simply asked one machine to do more than one machine can do, and one machine is one failure domain. When it's saturated, everything served by it is saturated. When it dies, everything dies with it. There is no graceful degradation available to a singleton; it's binary.
The first instinct is almost universal and almost always wrong as a first move: buy a bigger box. Scale up. Double the vCPUs, double the RAM. This works, briefly, and it's genuinely the right call more often than internet architecture diagrams admit — but it has three hard limits you must see clearly. First, there's a ceiling: the largest instance type your cloud sells is a real wall, and you cannot rent a machine bigger than the biggest machine. Second, cost goes super-linear near the top — the jump from a large box to the largest box costs far more than 2× for far less than 2× the work, because you're paying for exotic hardware. Third, and most damning: a bigger box gives you zero redundancy. You still have one failure domain. The OOM-kill still takes the whole product down; it just takes longer to get there. You've bought headroom, not resilience.
So the real answer is to scale out: run many identical boxes and spread the load across them. Now a single box dying takes out 1/N of capacity, not 100%. Now you can add capacity by adding boxes, with no ceiling in sight. This is horizontal scaling, and it is the foundation of every large backend you've ever used.
Except — and here is the trap that makes this a chapter and not a sentence — a second box doesn't help you if requests can't be freely spread across boxes. If box #1 is holding your logged-in session in its memory, then your next request must go to box #1, and box #2 sitting idle next to it can't take your load. If box #1 has the scanned document you just uploaded on its local disk, box #2 can't serve it. If box #1 has an in-memory counter tracking your rate limit, box #2 disagrees about how many requests you've made. Each of these silently pins a user to one machine, and a fleet of pinned users is just a singleton wearing a fleet costume. The work of horizontal scaling is mostly the work of making boxes interchangeable. That work has a name — statelessness — and it's beat 2.
🧭 A useful distinction. "We need to scale" almost never means "we need more machines." It means "one resource is saturated." The senior move is to name the saturated resource — CPU, database connections, disk I/O, a single lock, event-loop lag — before touching the architecture. Adding app servers to a database-bound system doesn't add capacity; it adds clients hammering the same overloaded database, and you make the outage worse. Scaling is removing the one specific thing that can't currently be duplicated. Find it first.
2. The mental model: walk the path, duplicate what's singular
Here's the picture to carry. Take the request spine you've already walked — client → DNS → TLS → load balancer → server → handler → database — and walk it hop by hop asking one question at every box:
"Can I run two of these and split traffic across them?"
That question, asked honestly at each hop, is the scaling plan. Wherever the answer is "yes," you've found a thing you can duplicate for capacity and redundancy. Wherever the answer is "no" — wherever something is irreducibly singular — you've found either a thing to make duplicable (the app server, once it's stateless) or a thing whose singularity you must design around (the database's single writer). Scaling is the systematic removal of "no" answers.
Two axes organize the whole kit:
- Scale up (vertical): a bigger node. Simple, no distributed-systems tax, real ceiling, no redundancy.
- Scale out (horizontal): more nodes. No ceiling, gives redundancy, but only works if the work units are independent.
That independence caveat is everything. You can only split a workload across N machines if request A and request B don't need to share a machine to be correct. The job of this chapter is to manufacture that independence.
Hold one rough equation in your head as a reasoning tool — not a formula to compute, a shape to think with:
capacity ≈ throughput_per_node × node_count × efficiency_factor
Adding nodes raises node_count. But efficiency_factor is the silent killer: it's the fraction of that theoretical capacity you actually realize, and it collapses toward zero as coordination between nodes grows. Statelessness is what keeps efficiency_factor near 1 — independent nodes that never need to talk to each other to serve a request scale almost linearly. The moment nodes must coordinate (sticky sessions, distributed locks, shared in-memory state), efficiency_factor drops and your fiftieth box adds far less than your second did. This is also why, as you've already seen, coordination doesn't scale linearly: every node that must agree lowers the ceiling.
Now the kit itself, framed so you never confuse the pieces:
- Load balancer — the thing that makes "the server" plural without the client knowing. One address,
Ninterchangeable backends behind it. - Cache — a bet that "this read repeats and rarely changes." You trade freshness (and a coherence problem) for latency and load relief. Place the bet as close to the reader as your staleness budget allows.
- Replicas vs shards — the two orthogonal database moves, and the ones beginners most often blur:
- Replicas multiply the read capacity of the same data. Copies. Every replica holds the whole dataset; you've cloned the library so more people can read at once. Writes still funnel to one place.
- Shards split one dataset across nodes by key. Different data on different boxes. You've torn the library into sections housed in different buildings; this scales writes and storage, not just reads.
You often need both, for different reasons, and confusing them leads to scaling the wrong axis. Read-bound? Reach for replicas and caches. Write-or-storage-bound? That's where sharding eventually lives. We'll build them in that order, because that's the order you should reach for them.
🧭 Mental model. Replicas are copies of everything; shards are pieces of one thing. A cache is a copy too — just a partial, lossy, fast one that lives closer to the reader. Every one of these is "the same fact, now stored in more than one place," which means every one of them inherits the consistency problem you've already met: the copies can disagree, and you must decide which anomalies you'll tolerate and for how long. Scaling is, almost entirely, the deliberate management of stale copies.
3. Theory & invariants
A mental model tells you what to picture. Invariants tell you what must stay true or the whole edifice tips over. These are the load-bearing rules of horizontal scale.
Statelessness, defined precisely
🔑 The relocatable-request invariant. No request may depend on in-process memory left behind by a previous request. Everything durable or session-scoped lives in a shared backing store — the database, Redis, or object storage — that every node can reach equally. A handler must be able to run, correctly, on any node in the fleet, with no knowledge of what any node did before.
This is the precise statement of a promise the book borrowed on credit early on. "Stateless" does not mean the system has no state — of course it has state; that's the whole point of a backend. It means the application tier holds no state between requests. Durable truth lives in the database. Session truth lives in a shared store. The process itself is disposable: you can kill it, redeploy it, scale it to zero and back, and no user-visible truth is lost, because none of it was ever in the process.
What breaks this invariant, concretely — the list of offenders to hunt for in any codebase before you put it behind a load balancer:
- In-memory sessions. The default
express-sessionstore keeps session data in the process's heap. Node A knows the clinician is logged in; Node B has never heard of them. - Local file writes. A scanned document saved to
./uploads/lives on one box's disk. Every other box returns 404 for it. - In-process counters. An in-memory rate-limit map, a hit counter, a "requests served" gauge — each node has its own, they diverge, and none is authoritative.
- Per-process caches that diverge. A cache in local memory is fine if you accept that node A and node B can hold different, contradictory values for the same key. Often you don't accept that, and then it's a bug.
🔑 Any node serves any request. This is the invariant the load balancer relies on. It picks a healthy node at random (or by some cheap heuristic) and trusts that node to answer correctly. The instant that trust is false — the instant a request needs a specific node — you've reintroduced singularity and capped your scale. Sticky sessions are the canonical way teams violate this while telling themselves they haven't (more in §6).
Load-balancing algorithms and what they guarantee
The load balancer's job is to pick which backend gets each request. The algorithm matters more than beginners expect:
- Round-robin. Node 1, 2, 3, 1, 2, 3… Dead simple, fair if every request costs the same. It doesn't know that request A is a cheap
GETand request B is an expensive report; it can pile heavy requests on one node by bad luck. - Least-connections. Send the next request to whichever node currently has the fewest in-flight connections. A decent proxy for "least busy," and a better default than round-robin when request costs vary.
- Weighted. Bigger boxes get a larger share. Useful during a migration where the fleet is heterogeneous.
- Power-of-two-choices. Pick two nodes at random, send to the less-loaded of the two. A beautiful result from queueing theory: this gets you almost the benefit of "always pick the least-loaded" while paying almost none of the global-coordination cost. It's the sweet spot for large fleets. In plain terms: checking a single random node often lands you on a busy one; checking two and taking the lighter almost always dodges the hot node, because for a request to get unlucky both of its two picks would have to be busy at the same moment — which is rare. You get near-perfect balancing without any node having to track the load of every other node.
- Consistent hashing. Picture every node and every key placed around a clock face; each key is handled by the first node you reach going clockwise from it. Add or remove a node and only the keys in that one slice need a new home — everyone else stays put. Compare a plain modulo hash (
node = hash(key) % N), where bumping the node countNreshuffles almost every key at once. Mechanically: hash the request (by patient ID, by cache key) to a point on the ring and route to the node owning that arc — you've seen this idea before. Its guarantee: when a node joins or leaves, only~1/Nof the keys move, instead of nearly all of them remapping. You reach for it when you want a stable mapping from key → node — for example, routing a patient always to the same node so a local cache stays warm. (Note the tension: that's a deliberate, bounded reintroduction of affinity. Use it consciously.)
Cache vocabulary and the central tension
Caching has more jargon than any other piece of the kit; pin it now so the rest of the chapter is readable.
- Hit / miss ratio — fraction of reads the cache answers without touching the origin. The single most important cache metric. A 95% hit ratio means the origin sees 1/20th of the read load.
- TTL (time to live) — how long an entry is allowed to live before it's considered stale and refetched.
- Eviction policy — what gets thrown out when the cache is full. LRU (least-recently-used) and LFU (least-frequently-used) are the common ones.
- Cache-aside — the application checks the cache; on a miss it reads the origin and populates the cache itself. The default pattern; the application owns the logic.
- Read-through / write-through / write-behind — the cache layer itself owns the origin interaction. Read-through fetches on miss; write-through writes to cache and origin synchronously; write-behind writes to cache now and origin later (fast, but a crash loses the un-flushed writes).
- Thundering herd / stampede — a popular key expires and a thousand concurrent requests all miss simultaneously, all hammer the origin at once, and the origin falls over. A self-inflicted DoS born of a cache, covered in §4.
🔑 The cache coherence tension. The moment the same fact lives in the database and in a cache, you have two copies that can disagree, and you must answer one question: who invalidates, and when? Ch 21 owns the deep theory of cache coherence; here we apply it. Your strategies, weakest-but-simplest to strongest-but-costliest:
- TTL-only — the entry just expires after
Nseconds. Dead simple, zero write-path coupling, but serves stale data for up to one TTL. Eventual consistency, by the clock.- Explicit invalidation on write — when you update the database, you also delete (or update) the cache key. Fresh, but now your write path is coupled to your cache and a missed invalidation is a silent staleness bug.
- Versioned keys — the key embeds a version (
encounter:42:v7); a write bumps the version, so old readers naturally miss and old entries age out. Splits the difference: no explicit delete, no long staleness.Every choice here is the same trade: staleness window vs write-path complexity. There is no free freshness.
Replication and sharding semantics (applied from the distributed-systems theory)
You've already worked through these; here's the subset you apply when scaling.
Replication. A primary takes writes and streams them to read replicas. Synchronous replication waits for a replica to confirm before acking the write (no data loss on failover, but write latency is hostage to the slowest replica). Asynchronous acks on the primary alone (fast, but a crash loses un-replicated writes, and replicas lag). That lag is the source of the two anomalies you'll fight:
- Read-your-writes — a user who just wrote must see their own write. Broken when their read lands on a lagging replica that hasn't caught up. "I just signed that note and it's gone."
- Monotonic reads — a user must not see time run backwards. Broken when consecutive reads bounce between a fresh replica and a stale one. "The result was there, then it vanished, then it came back."
Sharding. When one primary can no longer hold the writes or the storage, you split the dataset by a shard key. The theory you must respect:
- The shard key must give even key distribution — a key that clumps (shard by signup date → all new patients on one shard) creates a hot shard while others idle.
- Even perfect hashing can't save you from a hot-key problem: one enormously high-volume monitoring device, or one large provider's panel, is a single key, and a single key can't be split by the shard function alone — skew is a property of the data, not the hash.
- Cross-shard queries are the tax. A
JOINor a globalORDER BYthat spans shards becomes scatter-gather: fan out to every shard, merge the results, and you're only as fast as the slowest shard. Global ordering and pagination get genuinely hard. - Resharding is a near one-way door. Changing the shard key on a live dataset is a multi-week project (dual-write, backfill, cutover). You do not do it casually, which is why you defer sharding as long as honestly possible.
The load-reasoning primitive
📎 Borrowed on credit: Little's Law. Start with the plain question: how many requests is the system handling at once? Just multiply how fast they arrive by how long each one takes. Arrive at 500/sec, each taking 0.2 s → about 100 are in flight at any instant. Formally that's
L = λ × W— the average number of requests in flight (L) equals the arrival rate (λ, requests/sec) times the average time each spends in the system (W, seconds). If you've watched a React app's pending fetches pile up, it's the same count: more requests-per-second or slower responses both raise how many are simultaneously in flight. We use this here as a sizing tool: those 100 in-flight requests mean you'd better have at least 100 units of concurrency (pool slots, workers) or requests queue. The intuition it buys you right now: when latencyWspikes, in-flight countLballoons at fixed arrival rate, and you exhaust your concurrency budget — so a latency spike silently shrinks your effective capacity. The full queueing-theory derivation, the utilization-vs-latency curve, and tail-latency math belong to Ch 30, which owns performance engineering. Here, just hold the shape: concurrency = rate × latency.
4. Under the hood: building the scaled path, piece by piece
Let's make it concrete. We'll take Pulsely from one box to the full scaled topology, in the order you'd actually do it, with real Node/TS. Each piece earns its place by removing one "no" from the walk-the-path question.
Step 0: make the app stateless
Before a load balancer helps you at all, the app must survive being run as N interchangeable processes. The fastest way to prove you have a statelessness bug is to run two processes locally — Node's cluster mode or PM2 with instances: 4 — and watch what breaks. (Even multi-process on one box forces statelessness, which is why this is a great local test: you don't need a fleet to find the bug.)
Sessions. The default in-memory store is the first thing to die:
// BROKEN across instances: session lives in THIS process's heap.
import session from 'express-session';
app.use(session({ secret: process.env.SECRET!, resave: false, saveUninitialized: false }));
// Node A creates the session; the LB sends your next request to Node B,
// which has no memory of it → the clinician is randomly logged out.
The fix is to move session state into a shared store every node can reach — Redis — or to carry identity inside the request as a signed token so there's no server-side session at all:
// FIXED option A: shared session store. Any node reads the same Redis.
import { RedisStore } from 'connect-redis';
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SECRET!, resave: false, saveUninitialized: false,
}));
// FIXED option B: stateless JWT in a cookie — no server-side session at all.
// Identity travels in the request; any node verifies the signature locally.
// (Full auth treatment, including why JWT revocation is hard, is Ch 32.)
Document uploads. Writing to local disk pins the file to one node — every other node 404s it.
// BROKEN: file lives on ONE box's disk.
app.post('/patients/:id/documents', upload.single('doc'), (req, res) => {
fs.writeFileSync(`./uploads/${req.file.originalname}`, req.file.buffer); // pinned!
res.sendStatus(201);
});
// FIXED: push scanned docs / imaging to object storage (S3); every node reads the same bucket.
// (Object storage as a backing service — you've already used it.)
await s3.putObject({ Bucket: 'pulsely-documents', Key: `patients/${id}/${name}`, Body: buf });
In-process counters. That in-memory rate limiter has N independent, disagreeing copies. Once stateless, all shared counters move to Redis (which is why centralized rate limiting in §8 becomes necessary — local counters lie across nodes).
Step 1: put a load balancer in front
Now that any node can serve any request, fan traffic across them. The load balancer comes in two flavors, and the distinction is worth owning:
- L4 (transport-layer). Operates on TCP. Fast, cheap, opaque — it forwards bytes without understanding HTTP. It can't route by URL path or header because it can't read them.
- L7 (application-layer). Understands HTTP. It can route
/api/*to one fleet and/admin/*to another, terminate TLS (decrypt once at the edge so your app servers don't each pay the handshake — see Ch 6), do per-request retries, and run smart health checks. The cost is more CPU per request.
Most web backends want L7 — Nginx, HAProxy, or a cloud ALB — sitting in front of the Node fleet. The two non-negotiable operational details:
Health checks, split into liveness and readiness. The LB continuously asks each node "are you healthy?" and routes only to the yeses. But "alive" and "ready for traffic" are different questions:
// Liveness: "is the process up?" If this fails, RESTART me.
app.get('/healthz', (_req, res) => res.sendStatus(200));
// Readiness: "should I get traffic RIGHT NOW?" If this fails, stop routing
// to me but DON'T restart — I might be warming a cache or draining.
app.get('/readyz', async (_req, res) => {
const dbOk = await db.ping().catch(() => false);
const cacheWarm = cache.isWarm(); // false during startup warmup
res.sendStatus(dbOk && cacheWarm ? 200 : 503);
});
The distinction matters because a node that's alive but cold (just booted, cache empty, pool not yet filled) will serve slow, error-prone responses if the LB sends it traffic immediately. Failing readiness during warmup keeps it out of rotation until it's actually useful.
Connection draining on deploy. When you redeploy, you don't yank a node mid-request. You flip it to "not ready" so the LB stops sending new traffic, let in-flight requests finish (drain), then shut down. Without draining, every deploy returns a burst of 5xxs to whoever was mid-request.
Step 2: add caching layers (and decide where)
Now the read path. Pulsely's chart timelines and provider worklist pages are read-heavy and change slowly — perfect cache candidates. The key question is which layer, because the layers form a gradient from "closest to the reader" to "closest to the truth":
client ─▶ [browser cache] ─▶ [CDN/edge] ─▶ [app-tier Redis] ─▶ [DB buffer pool] ─▶ truth
Cache-Control static + cache-aside for Postgres pages
ETag scanned docs worklist/encounter already in RAM
closest to reader ◀─────────────────────────────────────────▶ closest to truth
best latency, worst freshness worst relief, best freshness
- Browser cache (
Cache-Control,ETag) — for assets and responses safe to cache on the user's device. Zero server load on a hit, but you can't invalidate it (you can't reach into a user's browser). Use short TTLs or content-hashed URLs. (For PHI, be conservative here — a cached chart page on a shared clinic workstation is a leak.) - CDN / edge — for static assets and non-PHI media. The CDN serves them from a POP near the user; your origin never sees the request. This is where bandwidth savings are enormous (see the estimate in §5).
- App-tier Redis — the workhorse for dynamic reads like a rendered worklist or an encounter's detail. This is cache-aside, and it's the code you'll write most:
async function getEncounter(id: string): Promise<Encounter> {
const key = `encounter:${id}:v${await encounterVersion(id)}`; // versioned key
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // HIT
const row = await db.query('SELECT * FROM encounters WHERE id = $1', [id]);
if (!row) {
await redis.set(`encounter:${id}:missing`, '1', 'EX', 30); // negative cache, short TTL
throw new NotFoundError();
}
// jittered TTL: spread expirations so they don't all fire at once (anti-stampede)
const ttl = 300 + Math.floor(Math.random() * 60);
await redis.set(key, JSON.stringify(row), 'EX', ttl);
return row;
}
Three details that separate a toy cache from a production one are visible here:
- Key design —
encounter:{id}:v{version}so bumping the version on a write atomically invalidates without an explicit delete. - Negative caching — cache the absence of a row (briefly!) so a flood of requests for a non-existent ID doesn't hammer the DB. Keep its TTL short, or a row created moments later stays invisible.
- Jittered TTL — never give a class of keys the same expiry, or they all expire together and stampede.
The stampede fix proper. Jitter helps, but for a genuinely hot key the real fix is single-flight (request coalescing): when a key misses, only one request fetches from the origin while the others wait for that result, instead of all of them piling onto the database:
const inflight = new Map<string, Promise<Encounter>>();
async function getEncounterCoalesced(id: string): Promise<Encounter> {
const key = `encounter:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
if (inflight.has(key)) return inflight.get(key)!; // join the in-flight fetch
const p = fetchAndCache(id).finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
Step 3: add a read replica and split reads from writes
Caches relieve hot, repeated reads. But Pulsely also has a large, varied tail of less-cacheable reads — patient search, provider worklists, the long scroll of a chart timeline — and those still all hit the one primary, contending with writes. The fix is a read replica: a second Postgres that streams the primary's changes and serves reads, leaving the primary free for writes.
In Node, this is two connection pools and a routing rule:
const writer = new Pool({ connectionString: process.env.PRIMARY_DSN });
const reader = new Pool({ connectionString: process.env.REPLICA_DSN });
// writes → primary, always
async function signEncounterNote(n: NewNote) {
return writer.query('INSERT INTO chart_entries ... RETURNING *', [...]);
}
// general reads → replica (tolerates a little lag)
async function getWorklist(providerId: string) {
return reader.query('SELECT ... FROM worklist WHERE provider_id = $1', [providerId]);
}
Postgres streams WAL — the write-ahead log, its running journal of every change — to the replica; pg_stat_replication.replay_lag is your lag metric, and you alert on it. (ORMs expose this too: Prisma and TypeORM both support a read-replica config so you don't hand-route every query.)
But you've just bought the read-your-writes bug. A provider signs a note (→ primary), immediately reloads the encounter or their worklist (→ replica), and the replica hasn't caught up — the note they just wrote is gone. In a marketplace a vanished post is annoying; in a chart it's alarming, and it erodes a clinician's trust in the record. Three fixes, cheapest first:
// FIX: route the WRITER's own subsequent reads to the primary for a short window.
async function getWorklistReadYourWrites(providerId: string) {
const pool = (await recentlyWrote(providerId)) ? writer : reader; // e.g. wrote in last 5s
return pool.query('SELECT ... FROM worklist WHERE provider_id = $1', [providerId]);
}
The more precise version gates on replication position. Postgres stamps every write with a steadily increasing position marker — an LSN (log sequence number), which you can picture as a byte offset into that write-ahead log. When a provider writes, you record that marker. Before serving their next read from a replica, you check whether the replica has replayed up to at least that marker:
- If it has, the replica already contains their write, so it is safe to read there.
- If it hasn't, you fall back to the primary.
More work, but it releases the read to the replica the instant it's actually safe, instead of for a blanket five seconds.
🛑 What we deliberately did not explain here. How Postgres ships WAL, the
synchronous_commitlevels, quorum overlap math, Raft, failover and fencing — all of that is the machinery of Ch 24, and we lean on it rather than re-deriving it. We also haven't touched cloud autoscaling — how a cloud provider adds and removes nodes automatically in response to load — because managed infrastructure and autoscaling policy belong to the delivery part of the book, not here. And the queueing math behind "why latency explodes past ~70% utilization," plus the general cure for N+1 query patterns, is Ch 30's to own. This chapter assembles the building blocks and the estimation discipline; the adjacent chapters own the physics and the platform.
A note on the JVM, where it teaches
(Skippable if you're not on the JVM — the transferable payoff is the last sentence.) If your background is Spring, the same principles wear different clothes. Read/write routing is declarative: @Transactional(readOnly = true) combined with an AbstractRoutingDataSource sends read-only transactions to a replica automatically. Caching is the Spring Cache abstraction — @Cacheable on a method is cache-aside, and @CacheEvict is explicit invalidation, made into annotations. The ergonomics differ; the contract — "check cache, fetch on miss, evict on write, route reads to a replica" — is identical. Frameworks are conveniences layered over the same skeleton, exactly as promised at the outset.
And sharding — which Pulsely defers
Sharding lives at the bottom of the kit for a reason: a single replicated Postgres still has enormous headroom. You shard only when one primary genuinely can't hold the writes or the storage — and Pulsely, at 1M patients (we'll size it in §5), is nowhere near that. So we design for it without building it. The routing logic, when it comes, lives either app-side (you compute the shard from the key) or in a proxy like Vitess or Citus that presents many shards as one logical database. The strategies — directory-based (a lookup table of key → shard), hash-based, range-based — you've already met. The decision to defer is itself an architectural decision, and we record it in the ADR.
5. In production: measure first, then size
The topology above is the answer. Production is about earning the right to apply each piece — and that means measurement and estimation, not vibes.
The bottleneck-first ritual
This is the single most important operational habit in the chapter, and it's a loop:
- Load test. Drive synthetic traffic with
k6orwrkuntil something gives. You cannot find a bottleneck the system isn't under. - Read the four golden signals — latency, traffic, errors, saturation. (Saturation is the one beginners skip and the one that matters most here: which resource is full?)
- Identify the ONE pinned resource. CPU? DB connections exhausted? Disk I/O? A single hot lock? Event-loop lag? There is almost always exactly one binding constraint at a time.
- Fix that one thing. Re-measure. The bottleneck moves — fix the database and now the app CPU is the limit; fix that and now it's the network. You chase it; you don't guess it.
The failure mode this ritual prevents is the most expensive mistake in this whole chapter: scaling the wrong layer. You add five app servers, feel productive, and discover the database was the bottleneck — so now you have five times as many clients exhausting the same connection pool, and you've made it worse. Measure saturation before you scale, every time.
🏭 The reason teams skip the ritual is that scaling feels like progress and measuring feels like delay. It's backwards. The five minutes spent finding that the "we need to shard" emergency is one missing index on
claims(patient_id)saves you the quarter you'd otherwise spend building a sharding layer to route around a query the planner could have answered in 2 ms. The premature-scaling trap is not a beginner mistake; senior engineers under pressure make it constantly. The discipline is the defense.
Capacity estimation: the Pulsely numbers
Capacity estimation — "back-of-the-envelope" math — is a routine deliverable, not an interview parlor trick. Here's the full Pulsely estimate for a network of 1M patients under management, the way you'd actually write it on a whiteboard. The goal is an order-of-magnitude answer you can defend, not false precision.
QPS (queries per second). Work down the funnel:
1,000,000 patients under management
× 20 interactions/patient/day (patient portal views + the provider work
on that chart: worklist refreshes, note opens, order entries, result reviews)
─────────────
20,000,000 interactions/day
÷ 86,400 seconds/day
─────────────
~230 average QPS
× 4 peak-to-average factor (morning clinic rush + evening portal peak)
─────────────
~920 peak QPS → call it ~1,000 QPS to size against
A modern Node instance comfortably serves a few hundred simple QPS. So ~1,000 peak QPS is 3–5 app instances with headroom — not a sharding problem, not even a large fleet. That number alone refutes most "we need to scale dramatically" panic.
One healthcare-specific wrinkle rides alongside this: RPM devices (home blood-pressure cuffs, glucose meters, weight scales) stream readings continuously, and at scale that's a steady write firehose independent of the interactive traffic above — enrol 100k patients on devices reporting every few minutes and you have a background stream that dwarfs the click traffic. Those readings don't belong on the transactional charting path: they land in a denormalized, write-optimized store (the high-read vitals stream) and get summarized into the chart. That's the exact read/write separation this chapter is about, applied to a stream instead of a click.
Storage growth. Size the rows, multiply by volume, project forward:
chart entries: 1M patients × ~2 entries/day × 365 = ~730M rows/yr
× ~1 KB/row (note text + coded data) = ~730 GB/yr of structured chart data
media: scanned docs and imaging are the real weight — but those live in object
storage (S3), NOT the database. ~2 documents/encounter × 200 KB (DICOM is far
larger) = ~290 TB/yr in S3, pennies/GB.
The lesson is in the split: ~0.7 TB/yr of structured data is trivially within one replicated Postgres for years — confirming the defer-sharding decision — while the genuinely large data (scanned documents, imaging) never touches the database at all. Misplacing imaging in the database is how teams manufacture a sharding emergency that didn't need to exist.
Bandwidth. Responses per second times payload, plus media egress:
API: ~1,000 QPS × ~30 KB/response = ~30 MB/s = ~240 Mbps from the API tier
media: this is where a CDN earns its keep. If documents come from origin, egress
dwarfs everything. Behind a CDN with a ~95% hit ratio, the ORIGIN sees ~5%
of media bandwidth — a 20× reduction in egress cost and origin load.
This is the concrete justification for the CDN in §4: it's not a nicety, it's the difference between a manageable origin and one drowning in document bytes. (For PHI-bearing documents, the edge cache must be access-controlled and short-lived — the bandwidth win is real, but not at the cost of serving a chart to the wrong person.)
Headroom. Never size for 100% utilization. Plan to run resources at ~50–70% so a traffic spike, a failed node, or a deploy doesn't tip you over the cliff. (Why the cliff is at ~70%, and how sharply latency rises past it, is the utilization curve Ch 30 derives. Here, just respect the number.) If 1,000 QPS needs 3 instances at full tilt, you run 5 — never 3.
Operating the pieces
Each building block has its own production hygiene:
- Caches — monitor hit ratio per key class (a global ratio hides a cold key class); set a
maxmemoryand an eviction policy on Redis so it can't OOM; pick TTLs from the staleness budget, not from vibes; warm the hottest keys on deploy; namespace and version keys so a bad cache class can be wiped without flushing everything. - Replicas — alert on replication lag with a real threshold; have a written failover/promotion plan (untested failover is broken failover); size the connection pool per replica; route analytics, reporting, and search reads off the primary to protect write latency.
- Health & shutdown — readiness fails during cache warmup so cold nodes stay out of rotation; graceful shutdown stops accepting, drains in-flight requests, and closes pools cleanly.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
In-memory session or state. Signature: works perfectly in dev (one process), then in production users are randomly logged out or see another user's data the instant the LB reroutes them to a node that's never seen them. Fix: externalize all cross-request state to a shared store (Redis) or carry it in a signed token. The app process holds nothing important between requests. This is the relocatable-request invariant; violating it caps your scale at one box.
Sticky sessions hiding statefulness. Signature: you "fixed" the session problem by pinning each user to one node (session affinity) — and now one node runs hot while others idle, and every deploy drains and loses those sessions. Fix: sticky sessions are the pattern that works until it doesn't. They re-introduce state and uneven load while letting you pretend you're stateless. Make the nodes genuinely stateless and drop affinity. (Consistent-hash routing for cache-warmth is a deliberate, bounded exception — not a license for general affinity.)
Cache stampede. Signature: a hot key expires and 10,000 concurrent requests miss simultaneously, all hit the database in the same instant, and the database falls over — an outage caused by your cache. Fix: jittered TTLs so a key class doesn't expire in lockstep, plus single-flight (request coalescing) so only one request refetches a missed key while the rest wait for that result. Optionally early/background refresh before expiry.
Stale-after-write (read-your-writes). Signature: a provider signs a note, refreshes, and their own note is missing because their read hit a lagging replica. Fix: route the writer's own subsequent reads to the primary for a short window, or gate the replica read on the replication position passing the write's LSN. Don't make the whole system linearizable to fix one user's view.
Caching per-patient data under a shared key.
Signature: one clinician loads a chart timeline and sees another patient's chart, because the cache key was chart instead of chart:{tenantId}:{patientId}. In healthcare this isn't a cosmetic bug — it's a cross-patient PHI leak, a reportable HIPAA breach.
Fix: include the patient, the tenant, and anything else the response varies on in the cache key — or don't cache PHI-bearing responses at all. A cache that ignores who the data belongs to is a data-leak channel (see §8).
Unbounded cache memory.
Signature: Redis grows until it OOMs, then mass-evicts, then the hit ratio collapses and the database gets the full read load back at the worst moment.
Fix: set maxmemory plus an eviction policy (LRU), and size the cache from the actual working set. A cache without a bound is a time bomb.
Routing a must-be-fresh read to a lagging replica. Signature: you check a slot's availability, or a provider's access/consent status, against a replica that's seconds behind — and you double-book the 9:00 slot, or keep showing PHI to a clinician whose access was just revoked (or a patient who just withdrew consent). Fix: an explicit read/write split policy (the ADR). Classify every read: tolerates-stale → replica; must-be-fresh (patient safety, authorization, consent) → primary. Eventual consistency is the wrong default for safety- and compliance-critical reads.
Bad shard key. Signature: you shard by signup date or an autoincrement ID, and all the new, hot traffic lands on one shard while the rest sit cold. Fix: choose a high-cardinality, evenly-distributed key, and model your access patterns before committing — the shard key bakes into every query and resharding is a one-way door. (And first ask whether you need to shard at all; usually you don't yet.)
Scaling the wrong layer. Signature: p99 is bad, so you add app nodes — and now the database connection pool is exhausted because you added clients to a database-bound system, and it's worse than before. Fix: run the bottleneck-first ritual. Measure saturation, name the one pinned resource, fix that. Adding capacity to a layer that isn't the constraint adds load to the layer that is.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand. The scaling kit is nothing but spectra.
Vertical ↔ horizontal scaling. Vertical is simpler, cheaper early, and dodges the entire distributed-systems tax — no statelessness work, no coherence problems, one box to reason about. Horizontal buys redundancy and a near-limitless ceiling at the cost of the statelessness work and operational complexity. You lean vertical when load is modest and ops headcount is scarce — a bigger box genuinely is the right first move for a small product. You lean horizontal the moment you need redundancy (you can't afford the singleton's blast radius) or you've hit the vertical ceiling. The mistake is treating these as ideological rather than as a function of your actual load and team.
Where to cache. Closer to the client (browser, CDN) = best latency and least origin load, but worst staleness control — you can't reach into a browser to invalidate. Closer to the database (app-tier Redis, DB buffer pool) = freshest and easiest to invalidate, but least relief (the request still traveled all the way in). The right answer is per data type: cache immutable assets at the edge aggressively, cache slowly-changing dynamic reads in app-tier Redis with explicit invalidation, and don't cache must-be-fresh reads at all. This is exactly what the cache-placement ADR exists to record.
TTL-only ↔ explicit invalidation. TTL-only is simple and decoupled but serves stale data for up to one TTL. Explicit invalidation is fresh but couples your write path to your cache, and a missed invalidation is a silent staleness bug that's miserable to debug. Versioned keys split the difference. Choose by your staleness budget: a patient's unread-message count can be TTL-stale for a minute; a medication allergy or an active order after an edit usually can't.
Read replica ↔ cache for read load. They solve different read problems. A cache wins on latency and absolute load reduction for hot, repeated keys — it removes the work entirely. A replica wins for large, varied, less-cacheable read sets and additionally gives read redundancy. You almost always want both, layered: cache the hot tail, replica the long tail. Reaching for one when you needed the other is a common misdiagnosis — a cache does nothing for a million unique chart reads, and a replica does nothing for a single white-hot key.
Synchronous ↔ asynchronous replication. Sync = no data loss on failover, but write latency is hostage to the slowest replica. Async = fast writes, but a lag window where a primary crash loses un-replicated writes. The pragmatic default is async replication plus a read-your-writes carve-out — fast writes, and you route the few reads that must be fresh to the primary. You'd switch a specific table (claims, payment postings) to sync only when failover data-loss on that data is genuinely unacceptable.
Shard now ↔ shard later. Sharding is a near one-way door — resharding a live dataset is a multi-week project. So defer it until a single replicated primary genuinely can't hold the writes or the storage, which (per the §5 estimate) is much later than anxiety suggests.
🚫 A framing this book rejects. "Shard early to be safe." It sounds prudent and it's almost always a net loss. Sharding imposes a permanent tax — cross-shard queries become scatter-gather, global ordering and pagination get hard, every join is a question, and the shard key constrains every future query you'll ever write — in exchange for write/storage headroom you usually don't need for years. "Safe" here means "paying a large, certain, ongoing cost now to avoid a manageable cost later that you might never incur." Defer the one-way door. Reach for caches and replicas — the reversible moves — first, and let the bottleneck-first numbers, not fear, tell you when a single primary has actually run out of room.
8. Security & scale notes
Security and scale are properties of everything, so the scaling kit has its own threat surface — and most of it comes from the same root cause: every copy of data is a new place to secure, and every shared chokepoint is a new place to attack. In a PHI system the stakes are sharper: a copy served to the wrong person is a reportable breach, not an embarrassment.
The cache as an accidental PHI-leak channel. A cache is a copy of authorized data sitting outside the authorization check. If you cache a chart or worklist under a key that doesn't include the patient and the tenant — chart instead of chart:{tenantId}:{patientId} — one clinician gets another patient's data on a cache hit, and you've built a cross-patient leak with no exploit required. The rule: a cache must respect authorization and minimum-necessary access. Key by patient and tenant, and never cache the authorization decision loosely — "is this provider allowed to see this chart?" cached without the provider and patient in the key is a privilege-escalation bug.
Cache poisoning via unkeyed inputs. If a response varies on a header (auth, tenant, language) but your cache key (or the CDN's, without a correct Vary) ignores it, an attacker can prime the cache or edge with a response that then gets served to other users. The defense is disciplined keying: every input the response varies on must be in the cache key, at every layer including the CDN.
The load balancer as both a chokepoint and a defense. Concentrating all traffic at one entry point concentrates risk — it's the obvious DDoS target — but it's also where centralized defenses belong: rate limiting, connection limits, TLS termination. And here's the statelessness consequence biting back: once your app is stateless, local rate-limit counters lie, because each node sees only its own slice of a user's traffic. Rate limiting must move to a shared, centralized counter (Redis at the app tier, or the edge/LB itself) or it doesn't actually limit anything across the fleet.
Thundering herd as self-inflicted DoS. This bears repeating as a security concern, not just a performance one: a cache expiry colliding with aggressive client retries — or a fleet of RPM devices all re-POSTing after a blip — amplifies load into an outage you caused yourself. Jitter, backoff with jitter on the client, and single-flight on the server are the mitigations — and they're the same shape as defending against a real attack, because a retry storm and a DDoS load the system identically.
Replicas and shards widen the breach surface. Every read replica is a full copy of PHI — encrypt it at rest, restrict its network, audit its access exactly as you would the primary (a replica is not "less sensitive" because it's read-only). The replication stream itself crosses the network carrying every write; tap it and you read everything, so it must be TLS-encrypted and authenticated. And a subtle, compliance-relevant staleness bug: a revoked provider access, or a patient's withdrawn consent, read from a lagging replica or a stale cache means the system keeps serving PHI to someone you just locked out, for the duration of the lag. Access and consent checks are must-be-fresh reads — route them to the primary.
Behavior under load is where the design pays off — or doesn't. A cache designed to serve stale on origin failure turns a database outage into "degraded but up" — clinicians see slightly old data instead of an error page (with the staleness clearly bounded, and never for safety-critical reads). A cache not designed for it gives you nothing when the origin dies. Without caches and replicas absorbing read load, one slow dependency saturates every stateless node equally — the load balancer faithfully spreads the failure across the whole fleet, and "we scaled horizontally" buys you nothing because every node is stuck waiting on the same overloaded database.
🔑 Every copy is a copy to secure, and a copy that can be stale. The cache, the replica, the CDN edge, the shard — each is the same fact stored in a new place for performance, and each inherits two liabilities at once: it's a new attack/breach surface and a new opportunity to serve data that's out of date. Scaling is duplication, duplication is copies, and copies are exactly the thing security and consistency both worry about. Hold those two liabilities together; they're the same liability.
9. Interview lens & exercises
Interview questions
Scaling questions are where interviews most reward reasoning and most punish reciting a stack of buzzwords. The tell is whether you measure before you architect.
"Design how you'd scale this read-heavy API to 10× traffic."
- Junior answer: "Add more servers and put Redis in front." Immediately reaches for tools, no measurement.
- Senior answer: walks the request path, measures the bottleneck first ("I'd load-test and find the pinned resource before changing anything"), then layers the reversible moves in order — make it stateless, add the load balancer, cache the hot reads, add a read replica for the varied tail — naming the staleness tradeoff at each layer and explicitly deferring sharding until a replicated primary is genuinely out of write/storage headroom. Same tools, but ordered by measurement and reversibility.
"What does it mean for a service to be stateless, and why does horizontal scaling need it?"
- Junior: recites a definition of stateless.
- Senior: ties it to the relocatable-request invariant — any node must be able to serve any request — and names the concrete offenders that break it (in-memory sessions, local file writes, in-process counters, divergent per-process caches), then explains that without it
efficiency_factorcollapses and your fiftieth box adds nothing.
"Where would you cache, and how do you keep it coherent?"
- Junior: "Use Redis with a TTL."
- Senior: picks the layer per data type from a staleness budget (edge for immutable assets, app-tier Redis for slow-changing dynamic reads, no cache for must-be-fresh PHI), names an invalidation strategy (TTL-only vs explicit vs versioned keys) with its tradeoff, and adds a stampede control (single-flight + jitter). Mentions keying by patient and tenant so the cache doesn't leak PHI.
"You added a read replica and providers complain their just-charted notes vanish — what happened and how do you fix it?"
- Junior: stumped, or "increase the TTL" (wrong layer entirely).
- Senior: immediately names replication lag breaking read-your-writes, and fixes it by routing the writer's own reads to the primary for a short window or gating on the replica's replay position — without throwing away the replica's value by reading everything from the primary.
"Estimate the QPS and storage for a network of 1M patients on Pulsely's worklist and chart reads."
- Junior: guesses a number.
- Senior: shows the funnel out loud — patients × interactions/day ÷ seconds × peak factor for QPS; rows × row size × growth for storage; separates media (object store, not DB) from structured chart data, and calls out the RPM write firehose as its own stream; states the ~50–70% headroom assumption — and lands on an order-of-magnitude answer they can defend, concluding (correctly) that 1M patients is a handful of app nodes and one replicated Postgres, not a sharding project.
Exercises & the Pulsely increment
Do these for real — a load generator and two terminals teach more than any diagram.
-
Make Pulsely stateless. Move sessions out of process (
connect-redisor JWT-in-cookie), move document uploads to object storage, and run 3 instances behind Nginx or HAProxy with/healthzand/readyz. Prove statelessness with a rolling deploy: restart instances one at a time under load and assert no user is logged out and no in-flight request 5xxs. If anyone gets logged out, you still have in-process state — hunt it. -
Add cache-aside Redis for the worklist and encounter-detail reads, with versioned keys, jittered TTLs, negative caching, and a single-flight guard. Load-test before and after with
k6; report the hit ratio and the p99 delta. Then deliberately expire a hot key under load without single-flight and watch the stampede hit the database — then turn single-flight on and watch it vanish. -
Stand up a Postgres read replica. Split reads and writes across two pools, route worklist/search reads to the replica, and deliberately reproduce the read-your-writes bug: sign a note, immediately reload the encounter, see it vanish. Then fix it (primary-read window, then the LSN-gated version) and prove it. Chart
replay_lagunder write load and watch it grow exactly when you'd most want to offload reads. -
Write the one-page capacity estimate (QPS, storage/yr, bandwidth, CDN origin offload) for 1M patients — the §5 funnel, on one page, with your assumptions stated. Then write the two ADRs:
- ADR-029a — Cache placement. For each data type (scanned documents / imaging, encounter detail, worklist page, patient unread-message counts), record the chosen layer (browser / CDN / app-Redis / none), the TTL, and the invalidation strategy (TTL-only / explicit / versioned). Record the rejected alternatives — e.g., "we rejected caching the worklist at the CDN because it's per-provider and PHI, so a shared edge copy is both useless and a leak risk."
- ADR-029b — Read/write split policy. Classify every read path as tolerates-stale → replica or must-be-fresh → primary, with the reasoning. Slot-availability checks, authorization, allergy/active-order checks, and consent/access-revocation status go to the primary; worklist, patient search, and chart-history reads tolerate the replica. Record that sharding is deferred until a single replicated primary can't hold writes/storage, with the §5 numbers as the justification.
-
The bottleneck drill. Take a Pulsely endpoint that's slow under load. Before changing anything, load-test it and identify the one pinned resource from the four golden signals. Only then fix it, and re-measure to watch the bottleneck move. The deliverable is the narration — "saturation was DB connections, not CPU, so adding app nodes would have made it worse" — because that narration is the entire skill this chapter teaches.
Key takeaways
- One box is one blast radius. Vertical scaling (bigger box) has a ceiling, super-linear cost, and zero redundancy. Horizontal scaling (more boxes) removes the ceiling and adds redundancy — but only if work units are independent.
- Statelessness is the enabler. The relocatable-request invariant — any node serves any request — is what lets the load balancer spread traffic and keeps
efficiency_factornear 1. Externalize sessions, files, and counters; the app process holds nothing important between requests. - Cache as close to the reader as the staleness budget allows. Browser → CDN → app-Redis → DB, trading freshness for relief. Every cache is the coherence question "who invalidates, and when?" — answered by TTL-only, explicit invalidation, or versioned keys — and for PHI, keyed by patient and tenant so it never leaks.
- Replicas multiply read capacity of the same data; shards split one dataset's writes and storage. Different problems, often both needed. Replicas buy you the read-your-writes bug — route the writer's reads to the primary, and route safety/consent reads to the primary too.
- Measure the bottleneck before scaling anything. Load test → four golden signals → name the one pinned resource → fix that → re-measure. Scaling the wrong layer makes outages worse.
- Estimate capacity as a routine deliverable. Patients × interactions × peak factor for QPS; rows × size × growth for storage; CDN slashes media egress; RPM streams are their own write firehose; run at ~50–70% utilization. For Pulsely's 1M patients: a handful of app nodes and one replicated Postgres — not a sharding project.
- Defer the one-way doors. Caches and replicas are reversible; sharding is (nearly) not. Reach for the reversible moves first, and let the numbers — not fear — tell you when a single primary has truly run out of room.
← Previous: Ch 28 — Realtime & Streaming Backends · Up: Part V overview · Master TOC · Next: Ch 30 — Performance Engineering & Tail Latency →