Revision and MasteryVol. 20 · Parts XX–XXII
0 / 0

Trails / Revision and Mastery

RV·213B

Concepts to Revisit Forever II: Backend, Data and Distributed Systems

The roadmap's backend, data and distributed lists restated from first principles for retrieval practice: HTTP, REST, transactions, caching, security and concurrency; SQL, indexes, query plans, isolation and replication; idempotency, retries, ordering, consistency, partitions and messaging; each with an explain-it prompt, the common confusion and where to relearn it; with a lab in PostgreSQL that loses 695 of 1,000 increments, fixes it three ways, and shows write skew surviving every isolation level except SERIALIZABLE.

26 topics · ~13 min read · 16-question quiz
Updated Suggest a correction

Start here: the concepts behind most production incidents

Look at any incident review: a lost update, a duplicate charge, a slow query, a stale cache, a retry storm, a message processed out of order. Each traces back to one of the seventeen concepts in this chapter. They're worth revisiting forever because frameworks hide them until the day they don't.

Use the same routine as chapter 213A: heading first, explain from memory, then read, then the prompt, then relearn if shaky.

Two anomalies, measured

The lab ran 4 database sessions each adding 1 to a balance 250 times (1,000 increments in total), and then a classic "two doctors on call" rule (each may go off call only if the other stays on):

Approach Result
read the balance, then write balance + 1 (PostgreSQL default, READ COMMITTED) final balance 305: 695 increments lost
the same at REPEATABLE READ, retrying on serialization errors 1,000 correct, but 2,135 retries
SELECT … FOR UPDATE, then write 1,000 correct, no retries
UPDATE … SET balance = balance + 1 1,000 correct, fastest
two doctors leave at once, READ COMMITTED or REPEATABLE READ both left in 200 of 200 trials: nobody on call
the same at SERIALIZABLE one left, the other got a serialization failure, in 200 of 200

No errors were raised in the broken cases. The database did exactly what it was asked; the application asked the wrong question.

How deep to go

Volume 17 defines six mastery levels. Hold these at L3 permanently; for the ones in your daily work, L4: you can find the bug they cause from symptoms.

Backend

HTTP

A request–response protocol: a method (GET, POST, PUT, PATCH, DELETE…), a target, headers and an optional body; a status code (2xx success, 3xx redirect, 4xx client error, 5xx server error), headers and a body back. Semantics to know cold: GET, HEAD, PUT and DELETE are idempotent, GET and HEAD are safe; caching via Cache-Control, ETag and If-None-Match; conditional updates via If-Match; content negotiation; cookies and their attributes (Secure, HttpOnly, SameSite). HTTP/1.1 sends one request at a time per connection; HTTP/2 multiplexes many over one TCP connection; HTTP/3 runs over QUIC to avoid TCP head-of-line blocking.

Explain it: why is retrying a timed-out PUT safe but a timed-out POST not, by default? Relearn: Volume 3, chapters 44–45; Volume 2, chapter 19.

REST

An architectural style: resources identified by URLs, manipulated through a uniform interface (HTTP methods with their meanings), representations exchanged statelessly (each request carries what's needed), and responses that say whether they're cacheable. In practice: model nouns not verbs, use status codes and problem details correctly, paginate, version by evolving additively, make important POSTs idempotent with keys, and use conditional requests for concurrency. It's a style, not a law: RPC-style endpoints are fine where actions don't fit resources.

Explain it: design the endpoints for "skip a day" and "undo a skip". Relearn: Volume 3, chapter 45; Volume 12, chapter 132.

Transactions

A transaction groups operations so they're atomic (all or nothing), consistent (constraints hold), isolated (concurrent transactions don't see each other's partial work, to a chosen degree) and durable (committed means it survives a crash, via the write-ahead log). Keep them short, never wrap remote calls in them, put boundaries at the business operation, and handle the errors isolation can produce (serialization failures, deadlocks) by retrying the whole transaction.

Explain it: what exactly does COMMIT wait for, and why is it safe to return success afterwards? Relearn: Volume 4, chapters 58–59; Volume 3, chapter 49.

Caching

Keeping a copy closer to where it's needed: CPU caches, the browser, a CDN, Redis, an in-process map. Every cache answers: what's the source of truth, how stale may this be (TTL), how is it invalidated (on write, by event, by expiry), what happens on a miss storm (stampede protection), what happens when the cache is down (fallback), and how big may it get (eviction). Cache-aside is the default pattern. The hard bug is the race where a stale value is written back after an invalidation; short TTLs bound how long it can last.

Explain it: sketch the race in which cache-aside leaves a stale value indefinitely. Relearn: Volume 3, chapter 53; Volume 12, chapter 126.

Security

Authenticate (who are you?), authorize (may you do this, to this object?), and protect data in transit (TLS) and at rest (encryption, access control). Most real breaches come from a short list: broken access control (top of the OWASP Top 10:2025), misconfiguration, supply-chain compromise, injection, and failures of authentication. Principles: least privilege, defence in depth, secure defaults, validate input at boundaries, never trust the client, and keep secrets out of code.

Explain it: why is broken access control the most common serious flaw, and how do you test for it? Relearn: Volume 10, chapters 106–113.

Backend concurrency

A server handles many requests at once: thread pools, event loops, or virtual threads. Shared state in the process (caches, counters, singletons) needs thread-safe structures; shared state in the database needs transactions and the right isolation or locking (this chapter's lab). Pools are queues: when demand exceeds a pool (threads, connections), requests wait, and latency grows sharply near saturation. Limits and timeouts at every pool turn overload into fast, explicit failures.

Explain it: a service has 200 threads and a database pool of 20; what happens at 300 concurrent requests that each need the database? Relearn: Volume 3, chapter 38; Volume 19, chapters 211C and 212A.

Data

SQL

A declarative language over relations: you say what (SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY), the planner decides how. Know joins (inner, left, semi and anti joins via EXISTS/NOT EXISTS), aggregates, window functions (row_number, running totals, lag), CTEs, NULL semantics (three-valued logic: NULL = NULL is unknown; NOT IN with a NULL returns nothing), and set operations. Write queries that express intent; then check the plan.

Explain it: why can WHERE x NOT IN (SELECT y …) return no rows unexpectedly? Relearn: Volume 4, chapter 56.

Indexes

An index is a separate structure that maps values to rows. B-trees (the default) keep keys sorted for equality, ranges and ordering; composite indexes work on their leftmost prefix; covering indexes (INCLUDE) avoid visiting the table; partial indexes cover only hot rows; GIN for full-text and arrays, trigram for substrings, BRIN for naturally ordered huge tables. Every index costs space and slows writes. An index is used only if the query's shape matches and the planner estimates it's cheaper than scanning.

Explain it: why might PostgreSQL ignore your index on status for WHERE status = 'delivered'? Relearn: Volume 4, chapters 58, 60.

Query plans

The planner estimates the cost of alternative plans (scan types, join methods: nested loop, hash join, merge join; join order) from table statistics, and picks the cheapest estimate. EXPLAIN ANALYZE (with BUFFERS) shows what actually happened. Read plans bottom-up; compare estimated vs actual rows (big mismatches mean stale or insufficient statistics); look for sequential scans on large tables, nested loops over many rows, sorts spilling to disk, and filters removing most rows after the fact.

Explain it: a query is fast in staging and slow in production with the same indexes; list three reasons. Relearn: Volume 4, chapter 60.

Isolation

Isolation levels define which anomalies concurrent transactions may see. PostgreSQL: READ COMMITTED (default; each statement sees data committed before it began: allows lost updates in read-then-write code and write skew), REPEATABLE READ (snapshot isolation: one snapshot per transaction; detects concurrent updates to the same row with errors; still allows write skew), SERIALIZABLE (equivalent to some serial order; aborts transactions that could violate it; you must retry). The lab shows all three. Practical tools at lower levels: atomic updates, SELECT … FOR UPDATE, constraints, and conditional writes.

Explain it: describe write skew with a real example from your domain and two ways to prevent it. Relearn: Volume 4, chapter 59.

Replication

Copying data to other nodes for availability and read scaling. Synchronous replication waits for a replica before confirming a commit (no data loss on failover, higher latency); asynchronous doesn't (lag means recent commits can be lost on failover, and replicas serve stale reads). Failover promotes a replica; split brain (two primaries) is prevented by fencing and consensus. Logical replication streams changes for migrations and CDC.

Explain it: what is lost, and what do users see, if an asynchronous primary fails with 2 seconds of lag? Relearn: Volume 4, chapters 61, 64; Volume 5, chapter 71.

Distributed systems

Idempotency

An operation is idempotent if doing it more than once has the same effect as doing it once. Distributed systems need it because messages and requests are retried and redelivered, and senders can't distinguish "lost request" from "lost response". Achieve it with idempotency keys stored with results, natural keys and upserts, state machines that ignore repeated transitions, and deduplication tables for consumers. Make external side effects idempotent too (pass the key to the payment provider).

Explain it: why isn't "check whether we already did it, then do it" enough without a unique constraint or lock? Relearn: Volume 5, chapter 74; Volume 19, chapter 212B.

Retries

Retries recover from transient failures and cause outages when done badly. Rules: only retry what's safe (idempotent); bound attempts; back off exponentially with jitter so clients don't retry in sync; respect Retry-After; use retry budgets (e.g. at most 10% extra load); retry at one layer, not every layer (3 layers × 3 attempts = 27 calls); and set timeouts shorter than the caller's timeout so work isn't wasted after the caller gave up.

Explain it: how does a retry storm turn a 30-second blip into a 30-minute outage? Relearn: Volume 3, chapter 52; Volume 19, chapter 212A.

Ordering

There's no global clock: physical clocks drift and are adjusted, so timestamps from different machines can't order events reliably. Order comes from a single sequencer (one partition, one primary), from logical clocks (Lamport clocks; vector clocks to detect concurrency), or from per-entity versions. Design so that only what must be ordered is ordered (per order, per account), and make consumers tolerate reordering elsewhere (ignore older versions).

Explain it: two updates for one order arrive out of order at a consumer; how do you make it converge to the right state? Relearn: Volume 5, chapter 75.

Consistency

Consistency models describe what reads may return. Linearizable (strong): every read sees the latest write, as if one copy; sequential, causal (effects follow causes), read-your-writes, monotonic reads, and eventual (replicas converge if writes stop). Stronger models cost latency and availability, especially across regions (PACELC: else, latency vs consistency). Choose per operation: money and inventory strong; feeds, counters and search eventual with bounded staleness.

Explain it: which TiffinBox operations need strong consistency, and which can be eventual? Relearn: Volume 5, chapters 69–70.

Partitions

Two meanings, both essential. Network partitions: nodes can't reach each other but are still running; each side must decide whether to keep serving (risking inconsistency) or refuse (losing availability): CAP's choice. Data partitioning (sharding): splitting data across nodes by key (hash for spread, range for scans), which scales writes but makes cross-partition queries and transactions expensive and makes hot keys a risk.

Explain it: why is "pick a good shard key" mostly a question about your queries? Relearn: Volume 5, chapters 70, 78; Volume 4, chapter 61.

Messaging

Queues (a message goes to one consumer, then disappears) and logs (Kafka: messages are retained; consumers track their own offsets and can replay) decouple producers from consumers in time and load. Delivery is at-most-once, at-least-once (the practical default) or effectively-once (at-least-once plus idempotency). Ordering is per partition or queue; failures need retries, DLQs and replay. The outbox pattern makes "change data and publish" atomic.

Explain it: why choose a log over a queue for order events? Relearn: Volume 5, chapters 66–68; Volume 19, chapter 211E.

Lab: lost updates and write skew in PostgreSQL

Setup. PostgreSQL 16 on the lab machine, driven by Python (psycopg 3) with one connection per thread.

Experiment 1: lost updates

A table wallet(id, balance) with one row at 0. Four threads each perform 250 transactions that add 1 to the balance, so the correct final balance is 1,000. Serialization failures and deadlocks are retried by rerunning the whole transaction.

Approach Final balance Lost Retries Time
SELECT balance, then UPDATE … SET balance = <read + 1> at READ COMMITTED 305 695 0 0.35 s
the same at REPEATABLE READ 1,000 0 2,135 0.93 s
SELECT … FOR UPDATE, then update, at READ COMMITTED 1,000 0 0 0.45 s
UPDATE wallet SET balance = balance + 1 1,000 0 0 0.30 s

Experiment 2: write skew

A table oncall(doctor, on_call) with two doctors on call. Two transactions run at the same time; each counts doctors on call and, if the count is at least 2, takes its own doctor off call (a barrier makes both read before either writes). 200 trials per isolation level:

Isolation Both left (nobody on call) One left Serialization failures
READ COMMITTED 200 0 0
REPEATABLE READ 200 0 0
SERIALIZABLE 0 200 200 (one per trial)

What it shows

  • Lost updates are silent. 70% of increments vanished with no error. The read-then-write pattern is the bug, and it's common in ORM code (entity.setBalance(entity.getBalance() + 1); save()).
  • Three correct fixes with different costs: an atomic statement (fastest, when the logic fits in SQL), a row lock (simple, serialises access to that row), or a stronger isolation level (works for complex logic, but the application must retry, here more than twice per success under heavy contention).
  • Snapshot isolation doesn't prevent write skew. Each transaction wrote a different row, so REPEATABLE READ saw no conflict. Only SERIALIZABLE (or an explicit lock on the rows the rule depends on, or a constraint that encodes the rule) prevented it.
  • The rule to remember: if a transaction's decision depends on rows it doesn't update, ask which isolation level or lock protects that decision.

Try it yourself

  1. Fix write skew at READ COMMITTED with SELECT … FOR UPDATE on both doctors' rows, and compare with SERIALIZABLE.
  2. Increase the threads to 16 and measure retries at REPEATABLE READ and SERIALIZABLE.
  3. Reproduce the lost update through an ORM (JPA or SQLAlchemy) and fix it with an optimistic @Version column.
  4. Encode "at least one doctor on call" as a constraint or trigger and test whether it holds under concurrency at READ COMMITTED.

Revision sheet: backend, data and distributed concepts

One line each

  • HTTP: methods with meanings (safe, idempotent), caching and conditional headers, versions 1.1/2/3.
  • REST: resources, uniform interface, stateless, cacheable; idempotency keys for POST.
  • Transactions: ACID; short; no remote calls; retry on serialization failures.
  • Caching: source of truth, staleness, invalidation, stampedes, fallback, eviction.
  • Security: authn, authz per object, TLS, least privilege; broken access control tops the list.
  • Backend concurrency: pools are queues; limits and timeouts everywhere.
  • SQL: declarative; joins, windows, NULL logic.
  • Indexes: shape must match the query; costs on writes.
  • Query plans: estimated vs actual rows; read bottom-up.
  • Isolation: RC allows lost updates and write skew; RR detects same-row conflicts; SERIALIZABLE aborts anomalies.
  • Replication: sync vs async; lag; failover and fencing.
  • Idempotency: same effect twice; keys, upserts, dedupe.
  • Retries: safe operations, bounded, jittered, budgeted, one layer.
  • Ordering: no global clock; sequence per key; tolerate reordering.
  • Consistency: choose the model per operation.
  • Partitions: network splits (CAP) and data sharding (keys follow queries).
  • Messaging: queues vs logs; at-least-once + idempotency; outbox.

Numbers to remember

  • Lab: 695 of 1,000 increments lost at RC with read-then-write; 2,135 retries at RR; write skew 200/200 at RC and RR, 0/200 at SERIALIZABLE.
  • 3 layers × 3 retries = 27 calls.

Glossary

  • Write skew: two transactions read overlapping data and write different rows, together violating a rule.
  • Snapshot isolation: each transaction reads one consistent snapshot.
  • Lamport clock: a logical counter ordering events causally.
  • Fencing token: a number that lets storage reject a stale leader's writes.
  • Retry budget: a cap on retries as a share of normal traffic.