Distributed systems reference

Every network call can be slow, fail, or happen twice.

Once work crosses a process boundary — a payment API, a queue, another service — a call no longer simply succeeds or throws. This reference covers the patterns that turn those outcomes into behaviour you chose: bounding the wait, retrying safely, refusing duplicates, and keeping two systems consistent without a shared transaction.

AbortSignal.timeout()

Timeouts and deadlines

A call without a timeout waits as long as the other side lets it, holding a connection, a worker, and the user’s patience the whole time. Give every outbound call a timeout. For a request that fans out to several calls, give it a deadline: one time budget for the whole request that every downstream call draws from.

Use it for

  • Every HTTP, database, and queue call that leaves the process.
  • Passing the remaining budget downstream, so a service does not start work its caller has already given up on.

Watch for

  • Library defaults are often unlimited or minutes long. fetch() has no timeout option of its own; without a signal it waits on the platform’s limits.
  • A timeout does not mean the work did not happen. The server may finish the charge after the client stopped waiting, which is why retries need idempotency keys.
  • Retries multiply time. Three attempts with a 10-second timeout is a 30-second request unless all attempts share one deadline.
const res = await fetch(url, {
  signal: AbortSignal.timeout(3_000), // fail after 3 s, not "eventually"
})

// One deadline for the whole request, shared by every call in it
const deadline = AbortSignal.timeout(8_000)
const [user, plan] = await Promise.all([
  fetch(userUrl, { signal: deadline }),
  fetch(planUrl, { signal: deadline }),
])

exponential backoff · jitter

Retries with backoff and jitter

Many failures are transient: a dropped connection, a 503 during a deploy, a 429. Retrying fixes them, but immediate retries from every client at once turn a short outage into a long one. Exponential backoff spaces attempts out — 100 ms, 200 ms, 400 ms — and random jitter spreads clients apart so they do not all retry in the same instant.

Use it for

  • Network errors, timeouts, 429 and 5xx responses, on operations that are idempotent or carry an idempotency key.
  • Honouring a Retry-After header when the server sends one, instead of the computed delay.

Watch for

  • Retrying errors that will not change — 400, 401, 403, 404, 422 — wastes attempts and hides bugs.
  • Retries at every layer multiply. Three layers with three attempts each is 27 calls to the bottom service during an outage. Retry at one layer.
  • Retrying a non-idempotent POST can charge a card twice. Retries and idempotency keys come as a pair.
  • Cap the attempts and the maximum delay, or a long outage leaves requests sleeping for minutes.
async function withRetry<T>(fn: () => Promise<T>, attempts = 4) {
  for (let i = 0; ; i++) {
    try {
      return await fn()
    } catch (err) {
      if (i + 1 >= attempts || !isTransient(err)) throw err
      const cap = Math.min(5_000, 100 * 2 ** i)
      await sleep(Math.random() * cap) // "full jitter"
    }
  }
}

Idempotency-Key

Idempotency keys

An operation is idempotent if doing it twice has the same effect as doing it once. Reads, PUTs, and DELETEs usually are; creating a payment is not. An idempotency key makes it so: the client generates a unique key per user intent and sends it with every retry, and the server records the key with the outcome, returning the stored result instead of acting again.

Use it for

  • Any create or charge a client may retry after a timeout: payments, orders, sign-ups, outgoing messages.
  • Message consumers under at-least-once delivery: record processed message ids and skip repeats.

Watch for

  • Generate the key once per user intent, not once per attempt. A new key on every retry is no key at all.
  • Check-then-act is a race. Claim the key with a unique constraint — insert, and treat a conflict as a duplicate — before doing the work.
  • A claimed key whose work then fails needs a state (in progress, done, failed) so a retry gets a 409 or a re-run, not an empty response.
  • Store a fingerprint of the request with the key and reject the same key with a different body, or a client bug returns the result of a different request.
// Client: one key per intent, reused on every retry
const key = crypto.randomUUID()
await withRetry(() =>
  fetch("/api/orders", {
    method: "POST",
    headers: { "Idempotency-Key": key },
    body: JSON.stringify(order),
  })
)

// Server: claim the key before acting
const { rowCount } = await sql`
  insert into idempotency_keys (key, uid) values (${key}, ${uid})
  on conflict (key) do nothing`
if (rowCount === 0) return storedResponse(key) // a duplicate

closed → open → half-open

Circuit breaker

When a dependency is failing, calling it anyway wastes time and adds load to something already struggling. A circuit breaker counts recent failures. Past a threshold it opens and fails calls immediately for a cool-down period, then lets a trial call through (half-open) and closes again if it succeeds.

Use it for

  • A dependency whose outage should degrade one feature instead of tying up every worker: recommendations, search, a third-party API.
  • Pairing with a fallback: cached data, a default, or a clear “temporarily unavailable” state.

Watch for

  • A breaker per process sees only its own traffic. With many instances, each one discovers the outage separately; that is usually acceptable, but know it is happening.
  • Counting client errors (4xx) as failures trips the breaker on bad input rather than on a sick dependency.
  • An open breaker with no fallback just fails faster. Decide what the user sees while it is open.
class CircuitBreaker {
  private failures = 0
  private openedAt = 0
  constructor(private threshold = 5, private coolDownMs = 30_000) {}

  async call<T>(fn: () => Promise<T>): Promise<T> {
    const open = this.failures >= this.threshold
    if (open && Date.now() - this.openedAt < this.coolDownMs) {
      throw new Error("circuit open") // fail fast, no call made
    }
    try {
      const result = await fn() // closed, or the half-open trial
      this.failures = 0
      return result
    } catch (err) {
      if (++this.failures >= this.threshold) this.openedAt = Date.now()
      throw err
    }
  }
}

version · ETag · If-Match

Optimistic concurrency control

Two clients read the same record, both edit, both save, and the second save silently erases the first. Optimistic concurrency gives each record a version. A write states the version it was based on and succeeds only if that is still the current one; otherwise it fails with a conflict, and the client re-reads and decides. No lock is held while a person is editing.

Use it for

  • Documents and records edited from more than one tab, device, or person.
  • HTTP APIs: return an ETag on read, require If-Match on write, and answer 412 Precondition Failed on a mismatch.

Watch for

  • Reading the version and then updating in a second statement brings the race back. The check and the write must be one atomic statement.
  • Zero rows updated is the conflict signal, not a success. Surface it.
  • Retrying a conflict by re-applying the same write is last-writer-wins with extra steps. Re-read, then merge or ask the user.
update documents
   set body = $1, version = version + 1
 where id = $2
   and version = $3   -- the version this edit was based on

-- 1 row:  saved
-- 0 rows: someone saved first → 409 or 412, re-read

outbox table · relay

Transactional outbox

A service often has to update its database and publish an event about it. As two separate steps, a crash between them leaves the database changed and the event lost, or the event sent for a change that rolled back. The outbox pattern writes the event into an outbox table in the same transaction as the change. A separate relay reads the outbox, publishes, and marks rows sent.

Use it for

  • Any write that other services or consumers must hear about: an order placed, a subscription changed, a user deleted.
  • Replacing dual writes to a database and a message broker, which cannot share one transaction.

Watch for

  • The relay can publish and then crash before marking the row sent, so events arrive at least once. Consumers must be idempotent.
  • One relay preserves order. Several relays for throughput need partitioning by aggregate id, or ordering is lost.
  • The outbox grows forever unless sent rows are pruned.
await db.transaction(async (tx) => {
  await tx.insert(orders).values(order)
  await tx.insert(outbox).values({
    topic: "order.placed",
    payload: { orderId: order.id, total: order.total },
  })
}) // both rows commit, or neither does

// Relay, on a loop or a schedule
for (const row of await unsentOutboxRows(100)) {
  await broker.publish(row.topic, row.payload)
  await markSent(row.id) // a crash here means a resend, never a loss
}

steps · compensations

Sagas

A business transaction that spans several services cannot use one database transaction. A saga runs it as a sequence of local transactions, each paired with a compensating action that undoes it in business terms. If step three fails, the saga runs the compensations for steps two and one. An orchestrator can call each step in turn, or the services can react to each other’s events (choreography).

Use it for

  • Checkout across inventory, payment, and shipping; a booking across flights and hotels.
  • Long-running workflows that wait minutes or days on people or external systems.

Watch for

  • Compensation is not rollback. A sent email cannot be unsent, and a refund is not the same as never charging. Design each compensation as a business action.
  • Between steps the system is visibly in an intermediate state — stock reserved, payment pending. Model those states explicitly instead of hiding them.
  • An in-memory orchestrator forgets everything on a crash. Persist each step’s outcome, or run the saga on a durable workflow engine.
  • Choreography across more than a few services makes the overall flow hard to see or change. An orchestrator keeps it in one place.
const steps = [
  { run: reserveStock,   undo: releaseStock },
  { run: chargeCard,     undo: refundCard },
  { run: createShipment, undo: cancelShipment },
]

async function checkout(order: Order) {
  const done: typeof steps = []
  for (const step of steps) {
    try {
      await step.run(order)
      done.push(step)
    } catch (err) {
      for (const s of done.reverse()) await s.undo(order)
      throw err
    }
  }
}

token bucket · 429

Rate limiting

A rate limiter caps how fast one caller can use a resource, protecting the service from overload and each caller from the others. The token bucket is the common algorithm: each caller’s bucket refills at a steady rate up to a maximum, each request spends a token, and an empty bucket means 429 Too Many Requests with a Retry-After header.

Use it for

  • Public and authenticated APIs, per user or per API key, with tighter limits on expensive operations such as sign-up or AI generation.
  • On the client, staying under a third-party API’s published limits instead of discovering them through 429s.

Watch for

  • An in-memory limiter is per instance. With N instances the real limit is N times the configured one; a global limit needs shared state such as Redis.
  • Fixed windows allow twice the rate at the boundary — the end of one window plus the start of the next. Token buckets and sliding windows smooth that out.
  • Limiting by IP address punishes everyone behind one NAT or proxy and is easy to rotate around. Prefer an authenticated identity where there is one.
type Bucket = { tokens: number; at: number }
const buckets = new Map<string, Bucket>()

function allow(key: string, perSecond = 2, burst = 10): boolean {
  const now = Date.now()
  const b = buckets.get(key) ?? { tokens: burst, at: now }
  b.tokens = Math.min(burst, b.tokens + ((now - b.at) / 1000) * perSecond)
  b.at = now
  const ok = b.tokens >= 1
  if (ok) b.tokens -= 1
  buckets.set(key, b)
  return ok // false → 429 with Retry-After
}

Start from the problem

A slow dependency ties up every request
Timeouts and deadlines
Requests fail during deploys and brief outages
Retries with backoff and jitter
A retried request charged a customer twice
Idempotency keys
One broken dependency takes the whole app down
Circuit breaker
Two people save the same record and one edit vanishes
Optimistic concurrency control
The database changed but the event never went out
Transactional outbox
One business action spans several services’ databases
Sagas
One client is starving everyone else
Rate limiting

Keep going

Inside each service, the patterns get smaller.

The design patterns reference covers factory, singleton, adapter, decorator, facade, strategy, observer, command, and state, as they look in TypeScript.

Open the design patterns reference

With your permission, Affonso uses a 30-day cookie to remember which affiliate referred you. Google Analytics measures site usage. Google Ads measures our advertising. Microsoft Clarity records masked session replays. You can use Nodlume with or without these cookies.