irfan@backend:~/portfolio
Email me
← cd ../blog

System Design / Caching / Databases / Beginner

System Design Basics: one app, from 10 users to a million

A beginner guide to system design: the request path, caching, databases, CAP, replication, sharding, queues, retries and circuit breakers.

On this page
  1. The request path
  2. Stateless app servers
  3. Load balancers: layer 4 and layer 7
  4. Cache-aside
  5. Cache problems and their fixes
  6. The stampede
  7. Many keys expiring at once
  8. Stale data and missing keys
  9. SQL or NoSQL
  10. Pick by the access pattern
  11. A myth to drop: "NoSQL has no transactions"
  12. CAP and PACELC
  13. Replication
  14. Sharding
  15. The problem with "mod N"
  16. Consistent hashing
  17. Queues and logs
  18. A queue for the email workers
  19. A log for every team
  20. Duplicates will happen
  21. Timeouts and retries
  22. Every network call gets a timeout
  23. A retry storm
  24. Backoff with full jitter in code
  25. When to retry, and where
  26. Circuit breakers and rate limits
  27. The same breaker in resilience4j
  28. Rate limiting with a token bucket
  29. Recap

A system design diagram is a lot of boxes and arrows. It gets easier once you can follow one request through them. So this post follows one app as it grows: first the request path, then the data, then the failures.

After this post you can:

  • sketch the path of one request, and add a cache to it safely
  • pick SQL or NoSQL with a reason, and explain how data is copied and split across machines
  • keep a system up when another service it calls (like payments) is slow or down

Most examples use a small made-up URL shortener. A user opens https://short.example/abc123, and the app sends them to the long URL saved for abc123. The data and failure chapters also use a small made-up shop, because orders and payments make the choices easy to see.

The request path#

What happens between pressing Enter and the browser jumping to the long URL? Five boxes, in order: the browser, DNS, the CDN, the load balancer, and the app with its database.

Words you need:

  • DNS: the phone book of the internet. It turns short.example into an IP address.
  • TTL (time to live): how long a saved answer stays valid.
  • CDN (content delivery network): servers close to users that keep copies of files, like images. Your own servers behind it are the origin.
  • Load balancer: one entry point that spreads requests over many app servers.
  • Health check: a small request the load balancer sends to see if a server works.
  • 302: the HTTP status that means "go to this other URL". The new URL is in the Location header.
  • Redis: a fast in-memory data store. Apps use it to share sessions and to keep copies of data.
one-request
  1. The browser asks DNS: what is the IP of short.example?
  2. DNS answers with the CDN address. The browser keeps that answer for the TTL.
  3. The browser asks the CDN for /abc123. The CDN has no copy.
  4. So it forwards the request to the origin. The load balancer picks one app server that passed its health check.
  5. The app looks up abc123 in the database.
  6. The app answers 302 with the long URL, and the browser jumps there.
  7. A request for logo.png stops at the CDN, because the CDN has a copy.
step 1 / 7
Only requests the CDN can't answer reach your own servers.

A DNS answer with a TTL of 300 seconds is reused for 5 minutes, so DNS changes reach users slowly. Ship Without Fear explains why you switch traffic at the load balancer, not in DNS.

Stateless app servers#

Say each app server keeps login sessions in its own memory:

stateful-servers
  1. The user logs in.
  2. The request lands on server A. A keeps the session in its own memory.
  3. The next request goes to server B, which has never seen this user.
  4. So the user is logged out.
step 1 / 4
Server B has no copy of the session, so the user is logged out.

The fix: an app server keeps no state of its own. Sessions and carts go to a shared store, like Redis or the database, so any server can answer any request.

Now you can scale out: add more copies of the app. Scaling up (a bigger machine) stops at the biggest machine you can buy.

quick-check

A user's cart is lost every few clicks. You run 3 app servers. What is the most likely cause?

Load balancers: layer 4 and layer 7#

Now /api/* should go to API servers and /stats/* to a stats service. Which load balancer can do that?

Words you need:

  • Layer 4: the transport layer: TCP or UDP, the protocols that carry bytes between two machines. The load balancer sees IP addresses and ports (like 443 for HTTPS) only.
  • Layer 7: the application layer (HTTP). The load balancer reads the path, the host and the headers.
layer-4-and-7
  1. A layer 4 load balancer sees only an IP and port 443. It can pick a server, but not by path.
  2. A layer 7 load balancer reads the HTTP request: GET /stats/abc123.
  3. It sees the /stats/ path and sends the request to the stats service.
step 1 / 3
Same request, two views. Only layer 7 can route by URL.

AWS has one of each. An Application Load Balancer works at layer 7, and a Network Load Balancer works at layer 4 (AWS docs).

Layer 4Layer 7
SeesIP, port, protocolHTTP path, host, headers, cookies
Can route by URLnoyes
Pick it fornon-HTTP traffic, plain connectionsweb apps and APIs

A common way to pick a server is round robin: the servers take turns. A server that fails its health check gets no traffic.

quick-check

You want /api to go to one server group and /stats to another. What do you need?

Cache-aside#

Every redirect reads the database, but links rarely change. So keep a copy in memory.

Words you need:

  • Cache: a fast store with copies of data you read often. A hit finds the data there, a miss does not.
  • Key: the name a value is saved under, like url:abc123.
  • Stale: old. A stale cache entry no longer matches the database.
  • Valkey: a fork (a copy that became its own project) of Redis, under the Linux Foundation. The Redis commands in this post work on both.

Cache-aside: the app checks the cache first. On a miss, it reads the database and saves the answer in the cache. Two requests for abc123:

cache-aside
  1. Request 1: the app asks Redis for url:abc123. Miss.
  2. The app reads abc123 from the database.
  3. The app saves it in Redis with a TTL of 300 seconds.
  4. Request 2, a second later: Redis has url:abc123. Hit, no database call.
  5. After 300 seconds Redis deletes the key. The next request is a miss again.
step 1 / 5
One database read per link per 5 minutes, however many users click.

Before the code:

  • It needs the redis package (node-redis) version 5 or later (6.x is the newest), plus pg for Postgres.
  • EX sets the expiry in seconds.
  • NOT_FOUND marks a code that is not in the database (next chapter).
  • warn logs a failed Redis call.

The key lines:

// cache.ts (key lines)
const redis = createClient({
  url: process.env.REDIS_URL,
  disableOfflineQueue: true, // while Redis is away, fail at once instead of queueing
  commandOptions: { timeout: 200 }, // a slow Redis call fails after 200 ms
});
redis.on('error', (err) => console.error('redis error', err)); // without a listener, Node crashes
// No await: if Redis is down at boot, the app still starts. Until Redis is ready, commands fail at once.
redis.connect().catch((err) => console.error('redis connect failed', err));
// ...
// Any Redis error counts as a miss, so a cache outage only makes the app slower.
async function cacheGet(key: string): Promise<string | null> {
  try { return await redis.get(key); } catch (err) { warn('get')(err); return null; }
}
// ...
async function loadFromDb(code: string): Promise<string | null> {
  // ...
  const longUrl = rows[0]?.long_url ?? null;
  const ttl = longUrl === null ? NOT_FOUND_TTL_SECONDS : TTL_SECONDS;
  await redis.set(`url:${code}`, longUrl ?? NOT_FOUND, { expiration: { type: 'EX', value: ttl } }).catch(warn('set'));
// ...
export async function getLongUrl(code: string): Promise<string | null> {
  const cached = await cacheGet(`url:${code}`);
  if (cached !== null) return cached === NOT_FOUND ? null : cached; // hit
  return loadFromDb(code); // miss: read the database, then fill the cache
}
// ...
export async function updateLongUrl(code: string, longUrl: string): Promise<void> {
  await db.query('UPDATE urls SET long_url = $2 WHERE code = $1', [code, longUrl]);
  await redis.del(`url:${code}`).catch(warn('del')); // if this fails, the TTL ends the stale copy
}
Show full code: cache.ts
import { createClient } from 'redis';
import pg from 'pg';

const redis = createClient({
  url: process.env.REDIS_URL,
  disableOfflineQueue: true, // while Redis is away, fail at once instead of queueing
  commandOptions: { timeout: 200 }, // a slow Redis call fails after 200 ms
});
redis.on('error', (err) => console.error('redis error', err)); // without a listener, Node crashes
// No await: if Redis is down at boot, the app still starts. Until Redis is ready, commands fail at once.
redis.connect().catch((err) => console.error('redis connect failed', err));

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });

const TTL_SECONDS = 300; // a cached link is at most 5 minutes old
const NOT_FOUND = '__none__'; // marker: this code is not in the database (see the cache problems chapter)
const NOT_FOUND_TTL_SECONDS = 60;

const warn = (what: string) => (err: unknown) => console.warn(`redis ${what} failed`, err);

// Any Redis error counts as a miss, so a cache outage only makes the app slower.
async function cacheGet(key: string): Promise<string | null> {
  try { return await redis.get(key); } catch (err) { warn('get')(err); return null; }
}

async function loadFromDb(code: string): Promise<string | null> {
  const { rows } = await db.query<{ long_url: string }>('SELECT long_url FROM urls WHERE code = $1', [code]);
  const longUrl = rows[0]?.long_url ?? null;
  const ttl = longUrl === null ? NOT_FOUND_TTL_SECONDS : TTL_SECONDS;
  await redis.set(`url:${code}`, longUrl ?? NOT_FOUND, { expiration: { type: 'EX', value: ttl } }).catch(warn('set'));
  return longUrl;
}

export async function getLongUrl(code: string): Promise<string | null> {
  const cached = await cacheGet(`url:${code}`);
  if (cached !== null) return cached === NOT_FOUND ? null : cached; // hit
  return loadFromDb(code); // miss: read the database, then fill the cache
}

export async function createLink(code: string, longUrl: string): Promise<void> {
  await db.query('INSERT INTO urls (code, long_url) VALUES ($1, $2)', [code, longUrl]);
  await redis.del(`url:${code}`).catch(warn('del')); // drop a cached NOT_FOUND for this code
}

export async function updateLongUrl(code: string, longUrl: string): Promise<void> {
  await db.query('UPDATE urls SET long_url = $2 WHERE code = $1', [code, longUrl]);
  await redis.del(`url:${code}`).catch(warn('del')); // if this fails, the TTL ends the stale copy
}
  • On a write, update the database first, then delete the key. Why delete instead of writing the new value into the cache:
delete-not-write
  1. Writer 1 saves A in the database.
  2. Writer 2 saves B in the database. B is the newest.
  3. Writer 2 is fast and writes B into the cache.
  4. Writer 1 is slow and writes A into the cache last. The cache now holds the old value.
  5. Run it again with a delete: Writer 2 only removes the key.
  6. Writer 1 removes the key too. The next read loads B from the database.
step 1 / 6
A delete can't leave an old value behind.
  • A read and a write can still happen in a bad order. For example, a slow read loads the old row, the write and its delete finish, then the slow read saves the old value. So the TTL stays as the safety net.
  • The cache is only a copy. If Redis is down, even at boot, cacheGet returns a miss and the app reads the database. disableOfflineQueue and the 200 ms timeout make Redis calls fail fast (give up at once) instead of hanging. Each failure is logged.
  • Add an error listener on the Redis client. Without one, a Redis error crashes Node.

Use cache-aside for data read much more often than it changes, where a few minutes of stale data is fine. A bank balance does not fit. Before you add a cache, check the slow query. Maybe it only needs an index, which is cheaper. Postgres From the Inside shows how to find one with EXPLAIN.

quick-check

A user changes where abc123 points. In what order should updateLongUrl work?

Cache problems and their fixes#

Words you need:

  • Hot key: one key that gets a huge share of the reads, like a viral link.
  • Lock: a marker that says "one request is already doing this job".
  • NX: set the key only if it does not exist yet. PX: like EX, but in milliseconds.
  • Token: here, a random value that shows which request holds the lock.
  • Lua: a small scripting language. Redis runs a Lua script as one step. Inside it, KEYS[1] is the first key and ARGV[1] the first extra value you pass in.

The stampede#

Link abc123 goes viral: 1,000 requests per second. Its key expires, and in that second all 1,000 requests miss and read the same row. This is a cache stampede. The fix: one request rebuilds the key while the others wait.

stampede-lock
  1. The key expires. Requests A, B and C all miss at the same moment.
  2. A runs SET lock NX first and gets the lock, with its own random token.
  3. B and C also try SET lock NX. The lock is taken, so they wait 50 ms.
  4. A reads the database and fills the cache.
  5. A deletes the lock, but only if it still holds A's token.
  6. B and C read the cache again. Hit. One database read in total.
step 1 / 6
Only one request can win the NX, so only one reads the database.

It builds on the cache-aside code. The key lines:

// getLongUrlOnce (key lines)
// Delete the lock only if it still holds our token.
const UNLOCK = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0";
// ...
const key = `url:${code}`;
const lockKey = `lock:${key}`;
const token = randomUUID(); // proves this request owns the lock
// ...
// Only one request gets the lock. Redis drops it after 5 seconds, even if this server dies.
gotLock = await redis.set(lockKey, token, { condition: 'NX', expiration: { type: 'PX', value: 5000 } });
// ...
await redis.eval(UNLOCK, { keys: [lockKey], arguments: [token] }).catch(warn('unlock'));
  • redis.eval runs the Lua script UNLOCK with KEYS[1] = lockKey and ARGV[1] = token.
  • The 5 second expiry frees the lock if its server crashes. But if A takes longer than 5 seconds, its lock expires and B can take a new one. That is why UNLOCK deletes the lock only if it still holds this request's token.
  • If Redis is down, or the lock is still taken after about 1 second (20 waits of 50 ms), the request reads the database directly.
Show full code: getLongUrlOnce
import { randomUUID } from 'node:crypto';

// Delete the lock only if it still holds our token.
const UNLOCK = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0";

export async function getLongUrlOnce(code: string): Promise<string | null> {
  const key = `url:${code}`;
  const lockKey = `lock:${key}`;
  const token = randomUUID(); // proves this request owns the lock
  for (let attempt = 0; attempt < 20; attempt++) {
    const cached = await cacheGet(key);
    if (cached !== null) return cached === NOT_FOUND ? null : cached;

    let gotLock: string | null;
    try {
      // Only one request gets the lock. Redis drops it after 5 seconds, even if this server dies.
      gotLock = await redis.set(lockKey, token, { condition: 'NX', expiration: { type: 'PX', value: 5000 } });
    } catch {
      return loadFromDb(code); // Redis is down: no lock possible, read the database
    }
    if (gotLock) {
      try {
        return await loadFromDb(code);
      } finally {
        await redis.eval(UNLOCK, { keys: [lockKey], arguments: [token] }).catch(warn('unlock'));
      }
    }
    await new Promise((r) => setTimeout(r, 50)); // another request is loading it
  }
  return loadFromDb(code); // waited about 1 second: read the database directly
}
quick-check

Why is the lock value a random token instead of '1'?

Many keys expiring at once#

A job loads 100,000 links at 09:00, all with a TTL of 3,600 seconds. At 10:00 they all expire, and the database takes 100,000 misses. The fix is TTL jitter: a small random extra per key, like 3600 + Math.floor(Math.random() * 600). The keys now expire over 10 minutes.

Stale data and missing keys#

  • Stale data: delete the key on every write (see cache-aside), and keep the TTL short.
  • Missing keys: a bot asks for /zzz999 again and again. That code is not in the database, so plain cache-aside caches nothing, and every request reaches the database.

The fix for missing keys:

  • loadFromDb saves the NOT_FOUND marker for 60 seconds, so those requests become hits.
  • The waiters in getLongUrlOnce read the marker too.
  • When someone later creates that code, createLink deletes the marker, so the new link works at once:
export async function createLink(code: string, longUrl: string): Promise<void> {
  await db.query('INSERT INTO urls (code, long_url) VALUES ($1, $2)', [code, longUrl]);
  await redis.del(`url:${code}`).catch(warn('del')); // drop a cached NOT_FOUND for this code
}
quick-check

Every night a job fills the cache with 50,000 keys, all with TTL 24 hours. Each night at the same time the database spikes. Best fix?

SQL or NoSQL#

Apps scale out freely because they keep no state. The database holds all of it, so the next chapters are about that last box.

Words you need:

  • Schema: the fixed list of columns and types a table must follow.
  • Relational database (SQL): tables with a schema, joined by keys. Postgres and MySQL are examples.
  • Document store: saves JSON-like documents. MongoDB is an example.
  • Key-value store: saves a value under a key, read by that key. Redis and DynamoDB are examples.
  • Wide-column store: rows with many columns, read by row key and a column range. Apache Cassandra is an example.
  • NoSQL: any database that is not relational. Document, key-value and wide-column stores are all NoSQL.
  • Transaction: a group of writes that all succeed or all fail together, like saving an order and charging for it.
  • Access pattern: which queries you run, how often, and by which keys.

Two features of the made-up shop, as the query each one runs:

-- Feature A: monthly revenue by country
SELECT c.country, sum(i.price_cents * i.qty) AS revenue_cents
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= '2026-10-01'
GROUP BY c.country;
Feature B: get the cart of user_id = 7. Always by user id. Never joined. Read on every page.

Feature A joins three tables and groups the result. A relational (SQL) database is built for that. Feature B is one lookup by one key. A key-value store does that cheaply, on many machines.

Pick by the access pattern#

Ask "what are my top queries?" first. Write down the 3 to 5 queries your feature runs most, then pick the store that makes those cheap.

Store typeGood atWeak atFits
Relationaljoins, reports, rules the database checks for youspreading writes over many machinesorders, payments, most business apps
Documentone record with nested parts, read wholejoins across many recordsa product with its options
Key-valuehuge volume of lookups by one keyany query not by that keycarts, sessions, feature flags
Wide-columnhuge volume of writes, read by key rangead hoc queries (one-off queries you didn't plan for)sensor readings, event logs

A wide-column example: row sensor:7 gets one column per minute, like 10:00 = 21.5 and 10:01 = 21.7. The query "sensor 7 from 10:00 to 11:00" reads one row and one range of columns.

A myth to drop: "NoSQL has no transactions"#

Old cheat sheets say NoSQL means no transactions. That is out of date:

  • MongoDB has multi-document transactions on replica sets (one main server that takes writes, plus its copies) since version 4.0. On sharded clusters (data split over many machines, see the sharding chapter) it has them since 4.2. Source: MongoDB docs. The same docs say: design a good schema first, instead of using transactions everywhere.
  • DynamoDB has TransactWriteItems: up to 100 writes, all or nothing, inside one AWS account and Region (AWS docs).

So pick by the access pattern. A relational database is a good default for most business apps. Add another store when one access pattern needs it. For fast SQL queries, see Postgres From the Inside on indexes.

quick-check

A feature reads a user's settings by user id on every request, and never joins them. Which store fits best?

CAP and PACELC#

What should a database do when two of its servers can't talk to each other? Answer an old value, or refuse?

Words you need:

  • Network partition: the network between servers breaks, but the servers keep running.
  • Consistency: every read sees the latest write. Availability: every request gets an answer.
  • Latency: how long one request takes.

The shop runs one database copy in data center A and one in B:

the-broken-link
  1. The two copies send writes to each other.
  2. The link between A and B breaks, but both still serve users.
  3. A user in A changes their email.
  4. A second later, a user in B reads that profile.
  5. B must choose: answer the old email, or refuse until the link is back.
step 1 / 5
During a partition there is no third option: stale or refused.

Refusing keeps B consistent: the user gets an error, but never wrong data. Answering keeps B available: the user gets an answer, but it is stale.

CAP stands for Consistency, Availability and Partition tolerance (keep working while the network is split). It is the yes branch of the diagram: during a network partition, a system must choose consistency or availability.

CAP is often taught as "pick 2 of 3". Eric Brewer, who stated CAP, wrote in 2012 that this is misleading (InfoQ, "CAP Twelve Years Later"). Partitions are rare, but every network breaks sometimes. Outside a partition, a system can give both. So the real choice is what to do while a partition lasts.

PACELC (Daniel Abadi, 2012) adds the no branch, the normal case:

  • if Partition: choose Availability or Consistency
  • Else: choose Latency or Consistency

With no failure, waiting for all copies to agree takes time.

DynamoDB lets you choose per read. Its reads are eventually consistent by default: a read right after a write may return the old value.

With ConsistentRead set to true, you get the latest data at twice the cost (AWS docs). That is the PACELC "else" choice, made per request. So calling DynamoDB "AP" (available rather than consistent) is too simple.

Ask the CAP question per piece of data: a balance should refuse rather than be wrong, while a like count can be old.

quick-check

There is no network problem. A read waits until all copies agree, so it is slower. Which idea describes this trade?

Replication#

User 7 changes their name from Ana to Anna. The page reloads and still says Ana. The next reload says Anna. Why?

Words you need:

  • Primary: the one database server that takes writes.
  • Replica: a copy that follows the primary and serves reads. Postgres calls it a standby.
  • Commit: the moment a transaction is saved for good and the database says OK.
  • Streaming replication: Postgres sends each change to the standbys as it happens.
  • Replication lag: the time between a commit on the primary and that change showing up on a replica.
replication-lag
  1. The app sends the name change for user 7 to the primary.
  2. The primary commits and says OK.
  3. The page reloads. The read goes to a replica.
  4. The replica has not received the change yet. It returns Ana.
  5. A moment later the change arrives, and the next reload returns Anna.
step 1 / 5
Nothing is broken. The replica is a little behind the primary.

In Postgres, streaming replication is asynchronous by default: the primary says OK without waiting for the standbys. The docs say there is "a small delay between committing a transaction in the primary and the changes becoming visible in the standby" (Postgres docs).

Use replicas when reads far outnumber writes. Each replica takes part of the reads, and one can become the new primary if the primary dies. Writes still all go to the primary.

Fixing "I saved it, but I still see the old value":

  • Read your own writes from the primary. After user 7 saves, send their reads to the primary for a few seconds.
  • Synchronous replication. The primary waits for a standby before it says OK. Reads get fresher, but every write waits longer. That is the PACELC trade again.
Side box: synchronous replication in Postgres

First, put a standby's name in synchronous_standby_names. Until you do, the primary waits for no standby, whatever synchronous_commit says. Then synchronous_commit = on (the default) waits until the standby has saved the commit to disk. A saved change is not yet visible, so a read on that standby can still be old. remote_apply waits until the change is visible there. Source: Postgres 18 docs.

quick-check

Users say their new post vanishes right after they publish it, then comes back. Reads go to replicas. Best first fix?

Sharding#

The orders table is now too big, or too busy, for one primary. You split it across machines. Each piece is a shard that holds part of the rows.

Words you need:

  • Shard key: the column that decides which shard a row goes to.
  • Hash: a function that turns a value into a number that looks random, and is the same every time for the same value.
  • mod: the remainder after division. 7 mod 3 is 1.

Take user_id as the shard key:

  • Range: users 1 to 1,000,000 on shard 1, the next million on shard 2. Ranges are cheap to read. But every new user lands on the last shard, so it takes all their writes.
  • Hash: compute hash(user_id) mod N, where N is the number of shards, and use that shard. Rows spread evenly. But "users 100 to 200" now touches every shard, and adding a shard moves most keys (below).

Pick a shard key most queries filter by. A query without it must ask every shard, and joins across shards are slow.

The problem with "mod N"#

Made-up numbers: 12 keys on 3 shards with key mod 3. Add a fourth shard, and the rule becomes key mod 4. A key stays only if both answers match:

keymod 3mod 4moves?
000no
111no
222no
303yes
410yes
521yes
602yes
713yes
820yes
901yes
1012yes
1123yes

9 of the 12 keys move. On a real system, most of your data gets copied at once.

Consistent hashing#

Consistent hashing puts both servers and keys on a ring of hash values. Each key belongs to the first server clockwise from it. Each server owns an arc: the part of the ring between it and the server before it.

consistent-hashing
  1. Servers A, B and C and every key are hashed onto one ring of numbers. These boxes are one slice of it, in clockwise order. D is the new server: it joins in step 3.
  2. Each key belongs to the next server clockwise. Without D, that is B.
  3. Add server D between A and B.
  4. Now the next server clockwise from k1 is D. Only the keys between A and D move, from B to D.
  5. Keys between D and B still belong to B, and A and C keep theirs. Every other key stays where it was.
step 1 / 5
Adding one server to N servers moves about 1/(N+1) of the keys, not most of them.

With one point per server, arcs can be very uneven, and a new server takes keys from one neighbor only. So each server sits on the ring many times, as virtual nodes. Example: A, B and C each sit at 3 points. New server D also gets 3 points, so it takes a small piece from several servers.

Side box: Redis Cluster uses hash slots instead

Cheat sheets often call Redis Cluster consistent hashing. Redis's docs say it is not. It has a fixed set of 16,384 hash slots. Each key goes to slot CRC16(key) mod 16384, where CRC16 is a simple hash function. Each primary owns a set of slots (cluster spec).

A new node joins empty. You move some slots to it yourself with redis-cli --cluster reshard, and only the keys in those slots move. A hash tag keeps keys together: in {user:7}:cart and {user:7}:orders, only the part inside the braces is hashed, so both land in one slot.

quick-check

You shard by hash(user_id) mod 4 and add a fifth shard. Roughly what happens?

Queues and logs#

Now there are many boxes, and some box is always slow or down. The last three chapters keep the system up anyway.

The shop's orders API: a new order should trigger an email, a stock update and an analytics record. The email provider takes 2 seconds. Should the user wait? No. The API saves the order, puts a message somewhere, and answers. Other programs do the rest.

Words you need:

  • Producer: the program that sends a message (here, the orders API).
  • Consumer: a program that reads messages and does the work, often called a worker.
  • Broker: the server in the middle that holds the messages.
  • Ack: the consumer tells the broker "done, drop this message".
  • Topic: a named stream of messages, like orders.
  • Pub/sub (publish/subscribe): a producer publishes to a channel (a named stream, like a topic), and every subscriber (a consumer that signed up for it) gets a copy.
  • Consumer group: a set of consumers that share the work of reading one topic.

A queue for the email workers#

You run 3 email workers. Each message should go to one of them, so the customer gets one email. That is a queue. Many producers and consumers can use it, but the broker gives each message to one consumer. Amazon SQS and RabbitMQ work like this.

A log for every team#

Email, stock and analytics each want their own copy of every order. Pub/sub gives that, but sends each message only to whoever is listening right now. A log also keeps the messages for a set time. A new service can start next month and still read old orders. Apache Kafka works like this.

Each group reads every message. Inside a group, members split the work.

QueuePub/subLog
Who gets a messageone consumerevery subscriberevery consumer group
After it is readdeleted after the ackgonekept until retention (the topic's set time) ends
ExampleAmazon SQS, RabbitMQRedis Pub/SubApache Kafka, Redis Streams

Two facts cheat sheets get wrong:

  • Redis Pub/Sub keeps nothing. Delivery is at-most-once: once or not at all. If a subscriber is offline, "the message is forever lost". For kept messages, Redis points to Redis Streams (Redis docs).
  • Kafka does not delete events when they are read. Each topic drops old events after its retention time.
  • A Kafka topic is split into partitions, and inside one group each partition is read by exactly one consumer (Kafka docs). A Kafka partition is a slice of a topic, not the network partition from the CAP chapter.

Duplicates will happen#

A standard SQS queue is at-least-once: now and then a message comes twice. AWS says: make consumers idempotent (AWS docs). That means doing the work twice has the same effect as doing it once.

A worker can also crash after the work but before the ack. So "send email for order 42" must first check if it was sent already. For example: save "order 42 emailed", and skip any message for an order already saved. Backend Security from Zero shows how with an idempotency key.

quick-check

A new fraud service must read every order from the last 7 days, then keep up with new ones. What fits?

Timeouts and retries#

The payment service gets slow: 30 seconds per call instead of 200 ms. Your orders API has no timeout. Soon all its worker threads (the threads that handle requests) are stuck waiting, and the orders API is down too.

Words you need:

  • Timeout: the longest you wait for an answer before you give up.
  • Exponential backoff: wait longer after each failed try: 100 ms, 200 ms, 400 ms, up to a cap.
  • Jitter: a random part of the wait, so clients don't retry together.
  • 429: the HTTP status "Too Many Requests". 5xx: the 500-range statuses, which mean the server failed.

Every network call gets a timeout#

Made-up numbers: payments usually answers in 200 ms, and 99.9% of calls finish within 2 seconds. That 2 seconds is the p99.9 latency. AWS's guide picks the timeout from a high percentile like this (AWS Builders' Library).

So the timeout is 2 seconds, in the code and the breaker below. About 1 in 1,000 good calls will time out. That is the cost of never waiting forever.

A retry storm#

retry-storm
  1. Payments has a short hiccup. 1,000 calls fail at the same moment.
  2. No jitter: all 1,000 clients wait exactly 100 ms and retry together, as one wave.
  3. The service is still recovering. The wave knocks it down again.
  4. Full jitter: each client waits a random time between 0 and 100 ms.
  5. Client A retries after 12 ms.
  6. Client B retries after 57 ms.
  7. Client C retries after 91 ms. The retries arrive spread out, and the service recovers.
step 1 / 7
Jitter makes clients stop waiting at different times.

Backoff with full jitter in code#

The code does 4 things:

  • a 2 second timeout per try, and at most 4 tries
  • retries only errors that may go away by themselves: timeouts, network errors, 429 and 5xx
  • waits with full jitter: a random time between 0 and the backoff value, one of the strategies in AWS's backoff simulator
  • obeys the server's Retry-After header, which holds seconds or an HTTP date (RFC 9110)
// withRetry (key lines)
const BASE_MS = 100;
const CAP_MS = 5_000;
const MAX_TRIES = 4;
// ...
return await call(AbortSignal.timeout(2_000)); // never wait forever
// ...
if (attempt + 1 >= MAX_TRIES || !isRetryable(err)) throw err;
const asked = err instanceof HttpError ? err.retryAfterMs : null;
if (asked !== null && asked > CAP_MS) throw err; // server wants a long pause: give up now
const backoff = Math.min(CAP_MS, BASE_MS * 2 ** attempt);
const wait = (asked ?? 0) + Math.random() * backoff; // full jitter, after the server's wait
// chargeOrder (key lines)
// attemptNo goes up only when the user tries again, for example after a declined card
return withRetry(async (signal) => {
// ...
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': `charge:${orderId}:${attemptNo}` },
// ...
await res.body?.cancel(); // free the connection: Node does not do it for you

AbortSignal.timeout(2_000) cancels a call after 2 seconds. asked is the wait the server asked for in Retry-After.

Show full code: withRetry and chargeOrder
export class HttpError extends Error {
  constructor(public status: number, public retryAfterMs: number | null = null) {
    super(`HTTP ${status}`);
  }
}

// Returns null if the header is missing or bad.
export function parseRetryAfter(value: string | null, nowMs = Date.now()): number | null {
  if (value === null) return null;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000;
  const date = Date.parse(value);
  return Number.isNaN(date) ? null : Math.max(0, date - nowMs);
}

function isRetryable(err: unknown): boolean {
  if (err instanceof HttpError) return err.status === 429 || err.status >= 500;
  if (err instanceof Error && err.name === 'TimeoutError') return true; // our timeout fired
  return err instanceof TypeError && err.message === 'fetch failed'; // Node fetch: network error
}

const BASE_MS = 100;
const CAP_MS = 5_000;
const MAX_TRIES = 4;

export async function withRetry<T>(call: (signal: AbortSignal) => Promise<T>): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await call(AbortSignal.timeout(2_000)); // never wait forever
    } catch (err) {
      if (attempt + 1 >= MAX_TRIES || !isRetryable(err)) throw err;
      const asked = err instanceof HttpError ? err.retryAfterMs : null;
      if (asked !== null && asked > CAP_MS) throw err; // server wants a long pause: give up now
      const backoff = Math.min(CAP_MS, BASE_MS * 2 ** attempt);
      const wait = (asked ?? 0) + Math.random() * backoff; // full jitter, after the server's wait
      await new Promise((r) => setTimeout(r, wait));
    }
  }
}
// attemptNo goes up only when the user tries again, for example after a declined card
export async function chargeOrder(orderId: number, attemptNo: number, amountCents: number): Promise<unknown> {
  return withRetry(async (signal) => {
    const res = await fetch('https://payments.example/charges', {
      method: 'POST',
      signal,
      headers: { 'Content-Type': 'application/json', 'Idempotency-Key': `charge:${orderId}:${attemptNo}` },
      body: JSON.stringify({ orderId, amountCents }),
    });
    if (!res.ok) {
      await res.body?.cancel(); // free the connection: Node does not do it for you
      throw new HttpError(res.status, parseRetryAfter(res.headers.get('Retry-After')));
    }
    return res.json();
  });
}
  • Worst case, one call takes 4 tries of 2 seconds (8 s) plus 3 short waits (under 1 s in total): under 9 seconds. If the server asks for a 5 second pause each time, add 3 × 5 s: about 24 seconds. The caller of chargeOrder needs a longer timeout than that.
  • The idempotency key names one payment attempt, counted the way the business counts attempts: charge:42:1 for the first try at order 42. A technical retry, or a queue running chargeOrder again, sends the same key. So the payment service sees "I did this already" and skips it. A new attempt after a decline gets charge:42:2.
  • On an error answer, cancel the body (res.body?.cancel()) before you retry. Node does not free the connection for you.

When to retry, and where#

  • Retry at one layer only. In AWS's guide, 5 layers that each try 3 times give a failing database 243 times the load (3 to the power of 5). Let the other layers fail fast (give up at once and pass the error up).
  • Always set a try limit, or a long outage becomes an endless storm.
quick-check

Your service calls B, and B calls C. Each layer tries 3 times. C is down. How many calls reach C for one user request?

Circuit breakers and rate limits#

If payments is down for 10 minutes, every request still waits through all its retries.

A circuit breaker sits in front of a call and counts failures. When too many fail, it trips, like a fuse, and stops the calls. Made-up numbers: it trips when 50% of the last 20 calls fail. Like an electric circuit, the breaker is closed when calls flow, and open when calls are blocked.

circuit-breaker
  1. Closed: calls go through. The breaker counts results over the last 20 calls.
  2. 10 of the last 20 calls failed. That is 50%, so the breaker opens.
  3. Open: for 30 seconds every call fails at once, without calling payments.
  4. After 30 seconds it goes half-open and lets 3 test calls through.
  5. All 3 succeed: the breaker closes and traffic flows again.
  6. If too many test calls fail, it opens again for another 30 seconds.
step 1 / 6
Open means the circuit is broken: no calls get through.

While it is open, return a fallback, like saving the order as "payment pending" for later.

The same breaker in resilience4j#

Many tutorials still show Netflix's Hystrix. It has had no new features (maintenance mode) since its last release, 1.5.18. Its README points to resilience4j for new projects.

CircuitBreakerConfig config = CircuitBreakerConfig.custom()
    .failureRateThreshold(50)                          // open at 50% failures
    .slidingWindowSize(20)                             // count the last 20 calls
    .minimumNumberOfCalls(10)                          // never trip on fewer than 10 calls
    .slowCallDurationThreshold(Duration.ofSeconds(2))  // a call over 2 s counts as slow
    .slowCallRateThreshold(50)                         // also open at 50% slow calls
    .waitDurationInOpenState(Duration.ofSeconds(30))   // stay open for 30 seconds
    .permittedNumberOfCallsInHalfOpenState(3)          // 3 test calls when half-open
    .build();

CircuitBreaker breaker = CircuitBreaker.of("payments", config);
Supplier<Charge> guarded = CircuitBreaker.decorateSupplier(breaker, () -> payments.charge(order));
  • By default every exception counts as a failure. But a call only counts as slow after 60 seconds (resilience4j docs). So 30 second calls would never trip a default breaker, and the config sets 2 seconds.
  • The breaker counts a call only when it ends. So give the payments client the same 2 second timeout, or a hanging call is never counted.
  • An open breaker makes guarded.get() throw CallNotPermittedException. Catch it and return your fallback.
quick-check

The breaker is open. A new request comes in. What happens?

Rate limiting with a token bucket#

A rate limit stops one client from sending too much. A common way is the token bucket. Made-up numbers: each user's bucket holds 10 tokens and gets 1 new token per second. Each request takes one token.

token-bucket
  1. 10:00:00. User 7 has a full bucket: 10 tokens.
  2. User 7 sends 12 requests at once. 10 take a token and pass.
  3. Requests 11 and 12 find the bucket empty. They get 429 with Retry-After.
  4. One new token drips in every second.
  5. 10:00:05. The bucket has 5 tokens, so 5 more requests pass.
step 1 / 5
Short bursts pass, but the average is held to 1 request per second.
type Bucket = { tokens: number; updatedMs: number };
const SIZE = 10;
const REFILL_PER_SEC = 1;

// nowMs: a clock that only moves forward, like performance.now(). It is per process,
// so a bucket shared in Redis needs Date.now() or the Redis TIME command instead.
function tryTake(b: Bucket, nowMs: number): boolean {
  const elapsedSec = Math.max(0, nowMs - b.updatedMs) / 1000; // a clock jump back adds no tokens
  b.tokens = Math.min(SIZE, b.tokens + elapsedSec * REFILL_PER_SEC);
  b.updatedMs = nowMs;
  if (b.tokens < 1) return false; // answer 429
  b.tokens -= 1;
  return true;
}

const user7: Bucket = { tokens: SIZE, updatedMs: performance.now() }; // starts full

This bucket lives in one process's memory. With many app servers, keep it in a shared store like Redis. Update it atomically (read and write in one step), or two servers can both let the last request through. Backend Security from Zero sets up a shared Redis rate limiter for Express.

quick-check

A client gets a 429 with Retry-After: 5. What should a well-built client do?

Recap#

Box or problemThe ideaThe fix you can now build
one requestDNS, CDN, load balancer, app, databasestateless app servers, so you can scale out
routinglayer 4 sees ports, layer 7 reads HTTProute by path with a layer 7 load balancer
slow readscache-aside with a TTLupdate the database, then delete the key
viral key, mass expiry, missing keysstampede, same TTL, no rowtoken lock, TTL jitter, a NOT_FOUND marker
picking a storeyour top queriesrelational by default, another store per access pattern
a broken networkCAP, and PACELC the rest of the timechoose per piece of data
stale readsreplication lagread your own writes from the primary
too much datarange or hash shardingconsistent hashing or hash slots
slow workqueue, pub/sub or logidempotent consumers
a slow service you calltimeouts and retriesbackoff with full jitter, at one layer
a dead service or a noisy clientcircuit breaker, token bucketfail fast with a fallback, answer 429

Try it yourself:

  • Draw the request path of an app you know, and mark where a cache helps.
  • For one feature you know, write its top 3 queries, then pick a store and a shard key.
  • Take that request path again, and give every call a timeout, a retry rule and a fallback.

Read next: Postgres From the Inside goes inside the database box, and Backend Security from Zero keeps the app in front of it safe.