Specialization DepthVol. 17 · Part XVII
0 / 0

Trails / Specialization Depth

SD·194C

SQL, PostgreSQL and Concurrency at L5/L6

Design- and production-level depth in the two topics where most backend correctness bugs live, with experiments on PostgreSQL 16 and native code: ladders for SQL/PostgreSQL and for concurrency; PostgreSQL internals (heap, MVCC, WAL, B-trees, the cost-based planner); isolation anomalies reproduced — a lost update under Read Committed, and write skew that overbooks a kitchen under Repeatable Read but is caught by Serializable; a planner misestimate from correlated columns fixed with extended statistics; the L4 toolkit and L5/L6 decisions (isolation choice, indexing, partitioning, queues in Postgres, vacuum and wraparound, upgrades); concurrency from primitives to models across Java, C, C++, Go, Rust, Zig and Erlang; a racy counter losing 35% of increments and the race detector catching it; false sharing slowing two independent counters 2.6–4.3×; and the decisions between shared memory, message passing, actors and async.

19 topics · ~20 min read · 31-question quiz
Updated Suggest a correction

Start here: what L5/L6 SQL, PostgreSQL and concurrency look like

At L2 you write correct queries and transactions. At L4 you can explain why a query is slow from its plan, why two transactions deadlocked, or why a counter loses updates under load. At L5/L6 you choose isolation levels, indexing and partitioning strategies, connection-pool sizes and concurrency models for a system, and keep them right as the data grows.

One example: how many connections should the app use?

A common instinct is "more connections, more throughput". The lab ran PostgreSQL's own benchmark tool, pgbench, on a 2-CPU machine with a growing number of clients:

Clients Read-only transactions per second Write transactions per second
1 17,289 1,531
4 101,095 4,805
16 69,142 4,800
64 48,683 3,682

Throughput peaked at a handful of connections (about the number of CPU cores, plus a little for waiting on disk) and then fell as more clients fought over the same CPUs and locks, while every transaction got slower (average write latency 0.8 ms at 4 clients, 17 ms at 64). The L5 conclusion: size the pool to the database's capacity, not the application's thread count, and let requests queue in the app (or a pooler like PgBouncer) rather than in the database.

How deep to go in SQL, PostgreSQL and concurrency

Volume 17 defines six mastery levels; for this chapter's topics they look like this:

Level You can…
L1 explain transactions, indexes, isolation and race conditions
L2 write correct schemas, queries and transactions; use locks and atomic operations
L3 explain MVCC, the planner, WAL, isolation anomalies, memory models and contention
L4 diagnose slow plans, lock waits, deadlocks, bloat, races and contention with tools
L5 choose isolation, indexing, partitioning, pooling and concurrency models for a system
L6 run PostgreSQL and concurrent systems at scale: upgrades, failover, capacity, incidents

SQL and PostgreSQL: the ladder

Level Observable behaviour
L1 Knows relational concepts, SQL's main statements, what indexes and transactions are
L2 Writes correct joins, aggregates, window functions, CTEs, upserts; designs normalised schemas with constraints; uses parameterised queries from code
L3 Explains storage (heap pages, tuples, TOAST), MVCC and visibility, WAL and checkpoints, B-tree/GIN/GiST/BRIN indexes, the planner's cost model and statistics, locking and isolation implementation
L4 Diagnoses slow queries from EXPLAIN (ANALYZE, BUFFERS), misestimates, lock waits, bloat, connection exhaustion, replication lag; uses pg_stat_statements, pg_locks, auto_explain
L5 Chooses isolation levels, indexing strategies, partitioning, denormalisation, JSONB vs columns, queue-in-Postgres vs a broker, read replicas, when Postgres is the wrong tool
L6 Operates Postgres at scale: vacuum and transaction-id wraparound, major-version upgrades, failover, backups and PITR (Volume 16), pooling, schema changes without downtime, capacity and cost

PostgreSQL internals for L3

  • Heap and tuples. A table is a set of 8 KB pages; each row version is a tuple with a header containing xmin (the transaction that created it) and xmax (the one that deleted or updated it). Large values move out of line into TOAST.
  • MVCC. An UPDATE writes a new tuple version and marks the old one's xmax; readers use a snapshot (which transactions were committed when it was taken) to decide which version is visible. Readers never block writers and vice versa. The price: dead tuples accumulate and must be removed by VACUUM; long-running transactions hold back the horizon, so nothing newer than their snapshot can be cleaned up.
  • HOT updates. If an update changes no indexed column and the page has free space, the new version goes on the same page and indexes needn't change (Heap-Only Tuple). Leaving free space (fillfactor below 100) on hot update tables increases HOT updates.
  • WAL. Every change is written to the write-ahead log before the data pages; commit means "WAL flushed" (synchronous_commit). Checkpoints flush dirty pages so recovery replays only WAL after the last checkpoint. WAL also drives replication and PITR.
  • Indexes. B-tree (equality, ranges, ordering; the default), Hash, GIN (inverted: JSONB, arrays, full-text), GiST/SP-GiST (geometric, ranges, nearest-neighbour), BRIN (block ranges for huge, naturally ordered tables). Index-only scans need the visibility map to say pages are all-visible (another reason vacuum matters).
  • Planner. A cost-based optimiser estimates the cost of alternative plans from statistics (pg_statistic: most common values, histograms, null fraction, distinct count, correlation) and cost parameters (random_page_cost, seq_page_cost, cpu_tuple_cost), then picks the cheapest. Wrong estimates are the root of most bad plans.

Isolation, reproduced

PostgreSQL's isolation levels: Read Committed (default: each statement sees data committed before it began), Repeatable Read (snapshot isolation: the whole transaction sees one snapshot; concurrent updates to the same row raise a serialization failure), Serializable (SSI: snapshot isolation plus detection of dangerous read/write dependency patterns, aborting a transaction to keep results equivalent to some serial order).

Two sessions interleaved step by step (A reads, B reads, A writes and commits, B writes and commits), on PostgreSQL 16:

Python
# 1) Lost update: read-modify-write of a counter (booked starts at 90; each session adds 5)
read  = lambda s: s.execute("SELECT booked FROM kitchen_slot WHERE kitchen=1").fetchone()[0]
write = lambda s, booked: s.execute("UPDATE kitchen_slot SET booked=%s WHERE kitchen=1", (booked + 5,))

# 2) Write skew: two offices each check remaining capacity, then insert bookings (different rows)
def check(s): return 100 - s.execute("SELECT coalesce(sum(meals),0) FROM booking WHERE kitchen=1").fetchone()[0]
def book(office):
    def w(s, remaining):
        if remaining >= 8: s.execute("INSERT INTO booking(kitchen, office, meals) VALUES (1, %s, 8)", (office,))
    return w
Text
lost update, READ COMMITTED : ['A committed', 'B committed']; booked = 95 (expected 100)
lost update, REPEATABLE READ: ['A committed', 'B ROLLED BACK (40001 serialization failure)']; booked = 95 (expected 100)
atomic UPDATE booked = booked + 5 (READ COMMITTED): booked = 100
write skew, REPEATABLE READ: ['A committed', 'B committed']; total meals = 106 (capacity 100)
write skew, SERIALIZABLE   : ['A committed', 'B ROLLED BACK (40001 serialization failure)']; total meals = 98 (capacity 100)

Reading the results at L3:

  • Lost update under Read Committed: both read 90, both write 95; one increment vanished. Repeatable Read detects that B is updating a row changed since its snapshot and aborts B (the application must retry). The simplest fix needs no isolation change at all: an atomic UPDATE … SET booked = booked + 5 (the row lock serialises the increments), or SELECT … FOR UPDATE before the read.
  • Write skew under Repeatable Read: each transaction read the same sum (90), inserted a different row, and no row was written by both, so snapshot isolation sees no conflict: 106 meals booked against a capacity of 100. Serializable detects the read/write dependency cycle and aborts one. Alternatives without Serializable: lock a shared row (SELECT … FROM kitchen_slot WHERE kitchen = 1 FOR UPDATE before checking), or materialise the constraint (a booked column updated atomically with a CHECK (booked <= capacity)).

L5 decision. Serializable makes correctness easy to reason about (every transaction behaves as if alone) at the cost of retries (the application must catch SQLSTATE 40001 and rerun the whole transaction, idempotently), some overhead for predicate locks, and more aborts under contention. Many teams default to Read Committed and handle the specific invariants with explicit locks or constraints; others use Serializable for the money paths. Either is defensible; not knowing which anomalies your choice allows is not.

A planner misestimate, fixed

The planner assumes predicates on different columns are independent and multiplies their selectivities. With correlated columns (every pincode belongs to exactly one city) it underestimates:

SQL
-- 1M subscriptions; city and pincode are perfectly correlated (each pincode belongs to one city)
CREATE TABLE office_sub AS
SELECT g AS id,
       (ARRAY['Hyderabad','Bengaluru','Pune','Chennai'])[1 + (g % 400) / 100] AS city,
       500000 + (g % 400) AS pincode,
       (g % 7) AS plan
FROM generate_series(1, 1000000) g;
CREATE INDEX ON office_sub (city, pincode);
ANALYZE office_sub;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM office_sub WHERE city = 'Hyderabad' AND pincode = 500042;
--   Bitmap Heap Scan on office_sub  (cost=10.97..1892.98 rows=639 width=0) (actual rows=2500 loops=1)

CREATE STATISTICS office_sub_city_pin (dependencies) ON city, pincode FROM office_sub;
ANALYZE office_sub;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM office_sub WHERE city = 'Hyderabad' AND pincode = 500042;
--   Bitmap Heap Scan on office_sub  (cost=37.98..4848.05 rows=2493 width=0) (actual rows=2500 loops=1)

Estimated 639 rows, actual 2,500 (about ¼ × 1/400 × 1,000,000 ≈ 625, the independence assumption); with extended statistics (functional dependencies) the estimate becomes 2,493. In this single-table query the plan shape didn't change, but a 4× underestimate feeding a join is how a planner picks a nested loop that runs 10,000 times instead of once, which is the L4 skill: compare estimated rows to actual rows at every node of EXPLAIN ANALYZE, find the first node where they diverge by an order of magnitude, and fix the cause (stale statistics → ANALYZE; correlated columns → CREATE STATISTICS; skew → raise the statistics target; non-sargable predicates → rewrite or an expression index).

The PostgreSQL L4 toolkit

Question Tool
Which queries cost the most in total? pg_stat_statements ordered by total_exec_time (not mean: a 2 ms query run 10 M times beats a 5 s query run twice)
Why is this query slow? EXPLAIN (ANALYZE, BUFFERS): estimates vs actuals, buffers hit/read, sorts spilling to disk, loops
Why was it slow last night? auto_explain with log_min_duration; logs
Who's blocking whom? pg_stat_activity + pg_blocking_pids(); pg_locks
Is the table bloated? pg_stat_user_tables (n_dead_tup, last autovacuum), pgstattuple
Is vacuum keeping up? age(datfrozenxid), pg_stat_progress_vacuum, autovacuum logs
Why are connections exhausted? pg_stat_activity grouped by state (idle in transaction is the usual culprit), pooler stats
Is replication lagging? pg_stat_replication (replay_lag)

PostgreSQL L5 and L6 decisions

  • Indexing: index for the queries you run (composite index column order follows equality-then-range; partial indexes for hot subsets; covering indexes with INCLUDE for index-only scans); every index costs write amplification and vacuum work; drop unused ones (pg_stat_user_indexes.idx_scan = 0).
  • Partitioning (declarative, by range/list/hash): for very large tables where queries filter on the partition key, and for data lifecycle (drop an old month's partition instead of deleting rows). It's not a general speed-up: queries without the key touch every partition.
  • JSONB vs columns: JSONB for genuinely variable attributes, with GIN indexes; columns for anything you filter, join, constrain or aggregate on regularly. Constraints and statistics work far better on columns.
  • Queues in Postgres: SELECT … FOR UPDATE SKIP LOCKED makes a reliable job queue with transactional enqueue (the outbox from Volume 16), fine into the thousands of jobs per second; move to a broker when you need fan-out to many consumer groups, replay, or much higher throughput.
  • Read replicas: for read scaling and analytics isolation, with replication lag handled (read-your-writes routing for a user who just wrote).
  • Vacuum and wraparound (L6): transaction ids are 32-bit; old tuples must be frozen before about 2 billion transactions pass, or PostgreSQL stops accepting writes to protect data. Autovacuum normally handles it; long-running transactions, abandoned replication slots and prepared transactions block it. Monitor age(datfrozenxid) and alert well before 1 billion.
  • Upgrades (L6): minor versions by restart (apply them; they're bug and security fixes); major versions via pg_upgrade (minutes of downtime with --link) or logical replication to a new cluster for near-zero downtime; test extensions and query plans (planner changes between majors) in staging first.
  • Connections (L6): each connection is a process with its own memory; hundreds are fine, thousands aren't. Use a pooler (PgBouncer in transaction mode, with its caveats for session state and prepared statements) and size app pools from Little's law.
  • When not Postgres: very high write throughput on time-series (consider TimescaleDB or a column store), analytics over billions of rows (a warehouse or columnar engine like ClickHouse/DuckDB), global multi-region writes with low latency (a distributed SQL database, with its own trade-offs).

Concurrency: the ladder

Level Observable behaviour
L1 Knows threads, processes, race conditions, locks, deadlock as terms
L2 Uses the language's standard tools correctly: executors and CompletableFuture, goroutines and channels, async/await, Mutex and Arc in Rust; avoids shared mutable state where possible
L3 Explains memory models (194B), atomics and CAS, how mutexes are built (futexes, spinning then parking), condition variables, how schedulers multiplex tasks (work stealing, M:N scheduling), cache coherence
L4 Diagnoses races (race detectors, TSan), deadlocks (thread dumps, lock graphs), contention (lock profiling), false sharing, priority inversion, starvation, async runtime blocking
L5 Chooses the model for a problem: shared memory with locks, lock-free structures, message passing, actors, async I/O, data parallelism; designs for minimal sharing; sizes pools and concurrency limits
L6 Operates concurrent systems under load: tail latency from contention, thread pool exhaustion cascades, backpressure across services, safe rollout of concurrency changes

Races, seen

Eight goroutines each increment a counter a million times, three ways:

Go
var racy int64
run("racy", func() { racy++ })                                  // read-modify-write, unsynchronised
run("mutex", func() { mu.Lock(); locked++; mu.Unlock() })
run("atomic", func() { at.Add(1) })
Text
racy     19ms  count=5179712 (expected 8000000)
mutex    793ms  count=8000000
atomic   172ms  count=8000000

The racy version is fastest and wrong: 35% of increments lost, because racy++ is load, add, store, and two goroutines interleave between the load and the store. go run -race reports it immediately:

Text
WARNING: DATA RACE
Write at 0x00c000012188 by goroutine 9:

The mutex is correct but slowest (each increment takes and releases a lock, and the lock bounces between cores); the atomic is a single hardware instruction (LOCK XADD on x86) but still contends on one cache line. Under real contention, the L5 answer is often not to share at all: per-goroutine counters summed at the end, or a sharded counter (Java's LongAdder does exactly this).

A compare-and-swap (CAS) loop is the building block of lock-free code: read the current value, compute the new one, and swap only if nobody changed it meanwhile; otherwise retry.

// Java: CAS loop on AtomicLong (what incrementAndGet does internally, conceptually)
static long casIncrement(java.util.concurrent.atomic.AtomicLong a) {
    long cur;
    do { cur = a.get(); } while (!a.compareAndSet(cur, cur + 1));
    return cur + 1;
}
// Under heavy contention prefer LongAdder: per-thread cells, summed on read

Lock-free isn't automatically faster: CAS loops under heavy contention retry repeatedly, and lock-free data structures bring hard problems (the ABA problem, memory reclamation via hazard pointers or epochs). Use them through well-tested libraries (java.util.concurrent, crossbeam in Rust, folly/Abseil in C++).

False sharing

CPUs keep caches coherent in units of cache lines (64 bytes on x86 and most ARM). Two threads writing different variables that share a line force the line to bounce between their cores' caches, as if they shared one variable:

C
// False sharing: two threads increment two different counters that share (or don't share) a cache line
struct shared  { _Atomic long a; _Atomic long b; };                          // same 64-byte line
struct padded  { _Alignas(64) _Atomic long a; _Alignas(64) _Atomic long b; }; // separate lines
// each of two threads does 100,000,000 relaxed fetch_add on its own counter
Text
same cache line:      1.95 s          (second run: 3.80 s)
separate cache lines: 0.74 s          (second run: 0.88 s)
sizeof(shared)=16 sizeof(padded)=128

The padded version is 2.6–4.3× faster for doing logically independent work. This is why Java has @Contended (used inside LongAdder cells and ConcurrentHashMap counters), Rust's crossbeam has CachePadded, Go's runtime pads per-P structures, and C++17 offers std::hardware_destructive_interference_size. An L4 symptom: "adding threads makes it slower", with CPU counters (perf c2c) showing cache-line contention.

Concurrency models: the L5 choice

Model Idea Languages/frameworks Strengths Costs
Shared memory + locks Threads share data guarded by mutexes Java, C/C++, Rust (Mutex<T> owns the data), Go (sync) Familiar; efficient for fine-grained state Races, deadlocks, contention; reasoning gets hard as it grows
Lock-free / atomics CAS-based structures All systems languages No blocking; progress guarantees Very hard to get right; ABA, reclamation
Message passing (CSP) Goroutines/threads communicate over channels Go, Rust (mpsc, crossbeam), Kotlin channels, Clojure core.async Ownership transfer is explicit; fewer shared states Deadlocks on channels; backpressure design needed
Actors Isolated entities with mailboxes, processing one message at a time; supervision trees Erlang/Elixir (BEAM), Akka (Scala/Java), Orleans (.NET) Isolation, location transparency, fault tolerance ("let it crash") Mailbox overflow, message ordering subtleties, harder debugging of flows
Async I/O (event loop / futures) Non-blocking I/O, tasks yield at await Node.js, Python asyncio, Rust tokio, C# async, Java reactive Huge concurrency with few threads Function colouring; blocking calls stall the loop; harder stack traces
Virtual / green threads Cheap threads with blocking style, runtime multiplexes Go goroutines, Java virtual threads, Erlang processes Simple code, high concurrency Runtime-specific pitfalls (pinning; unbounded concurrency moves bottlenecks)
Data parallelism Same operation over partitions of data Java parallel streams/ForkJoin, Rayon (Rust), OpenMP (C/C++), SIMD, GPUs Near-linear speed-up for CPU-bound bulk work Only for divisible, independent work; overhead on small inputs
STM Transactions over memory Clojure, Haskell Composable atomicity Retries, limited mainstream support

Design principles that hold across models (L5): minimise shared mutable state; make ownership explicit (Rust enforces it; elsewhere design for it); bound everything (queues, pools, concurrency) and decide what happens when full (block, drop, reject); acquire locks in a global order to prevent deadlock; never hold a lock while calling unknown code or doing I/O; prefer higher-level constructs (executors, channels, concurrent collections) over raw threads and locks.

L6 concerns: a thread pool shared by fast and slow work lets slow calls starve fast ones (bulkheads: separate pools per dependency); retries and timeouts interact with concurrency limits (Volume 16, ch. 189); async runtimes in production need detection for blocking calls on event-loop threads (tokio-console, Node's event-loop lag metric, BlockHound for Reactor); changes to concurrency settings are rolled out with canaries because they change failure modes, not only speed.

Lab: the connection-count curve

Setup. PostgreSQL 16 and pgbench on the lab machine (2 CPUs); pgbench -i -s 10 (1 million pgbench_accounts rows, about 150 MB, fully cached); 8-second runs with -j 2 client threads. Two workloads: select-only (-S, one primary-key read per transaction) and the default TPC-B-like transaction (three updates, one select, one insert). Client and server share the 2 CPUs, as an application and a small database often share a small node.

Results

Clients Read-only tps Read-only avg latency Write tps Write avg latency
1 17,289 0.058 ms 1,531 0.653 ms
2 99,003 0.020 ms 3,162 0.633 ms
4 101,095 0.040 ms 4,805 0.832 ms
8 87,919 0.091 ms 4,579 1.747 ms
16 69,142 0.231 ms 4,800 3.334 ms
32 54,951 0.582 ms 4,112 7.782 ms
64 48,683 1.315 ms 3,682 17.384 ms

What the curve says

  • Throughput peaks early and then declines. Reads peaked at 2–4 clients and lost half their throughput by 64; writes plateaued at 4–16 and lost a quarter by 64. Beyond the peak, every extra connection only adds queueing inside the database (CPU run queues, lock and buffer contention), so latency rises linearly while throughput falls.
  • Little's law holds: at 64 clients, 64 / 3,682 tps = 17.4 ms, exactly pgbench's reported average.
  • One oddity worth explaining: a single read-only client managed only 17,289 tps (0.058 ms per transaction) but two clients reached 99,003 (≈ 0.020 ms each). With one client, every transaction is a ping-pong between two processes that go to sleep and must be woken: the latency is dominated by wake-up and scheduling, not query work. With two, both CPUs stay busy and the hand-offs overlap. It's a reminder that "latency per query" on an idle system can be dominated by the operating system, not the database.
  • The L5 rule of thumb (PostgreSQL wiki's "connections ≈ cores × 2 + effective spindles", often a few dozen on real servers) is a starting point; measure the curve on your hardware and workload, size the pool just past the knee, and queue the excess in the application or PgBouncer.

Try it yourself

  1. Add -M prepared and compare read-only throughput at 4 clients.
  2. Run 64 clients through PgBouncer in transaction mode with a pool of 4 and compare tps and latency.
  3. Run the write workload at -c 16 while watching pg_stat_activity wait events; which waits dominate?
  4. Repeat with synchronous_commit = off (chapter 186 of Volume 15) and explain the change in the write curve.

Revision sheet: SQL, PostgreSQL and concurrency at L5/L6

Key ideas

  • PostgreSQL internals: heap and TOAST, MVCC with xmin/xmax, visibility map, VACUUM and freezing, WAL, checkpoints, buffer cache, planner statistics.
  • Isolation: read committed (default), repeatable read (snapshot), serializable (SSI); anomalies: lost update, non-repeatable read, phantom, write skew.
  • Planner: cost model, estimates vs actuals, extended statistics, join methods, index types (B-tree, GIN, GiST, BRIN), partial and covering indexes.
  • L4 toolkit: EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements, pg_stat_activity, pg_locks, auto_explain, bloat checks.
  • L5 decisions: pooling and pool size, partitioning, replicas and read routing, isolation per use case, schema evolution.
  • Concurrency: races, atomics and locks, memory visibility, false sharing, contention; models: threads and locks, actors, CSP, async/await, STM.

Numbers to remember

  • Lab: read tps peaked ~101k at 4 clients, fell to ~49k at 64; write tps peaked ~4.8k, fell to ~3.7k at 64.
  • Lab: Little's law: 64 clients / 3,682 tps = 17.4 ms.
  • Pool sizing starting point: about cores × 2 (+ spindles), then measure.

Pitfalls

  • Pools sized to app threads (hundreds of connections).
  • Read-modify-write without locks, atomics or retries.
  • Trusting plans without comparing estimated and actual rows.
  • Long transactions blocking VACUUM and DDL.
  • Shared mutable counters on hot cache lines.

Glossary

  • MVCC: multi-version concurrency control.
  • SSI: serializable snapshot isolation.
  • Write skew: two transactions each read a condition and write different rows, jointly violating it.
  • PgBouncer: a lightweight PostgreSQL connection pooler.
  • False sharing: contention on a cache line shared by unrelated variables.