Highlights

Contents

Part XI
11

Application design and PostgreSQL

Theatre bookings combine constraints, queries, and uncertain retries. Database choice must follow those needs. Connect atomic claims, maintenance, and resource budgets to the application’s actual contract.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Database model2Keys and ER3Algebra and SQL4Dependencies5Storage and indexes6Query execution7Transactions8Concurrency control9Recovery and engines10Distributed databases11Application design12The complete query

#Section 53SQL, NoSQL and access patterns

Heron needs seat invariants, joins, and customer revenue reports. Choose storage from those operations and constraints rather than assuming a key-value lookup is sufficient.

A relational database organizes named relations with declared constraints and relational queries. NoSQL is a broad grouping of database families rather than one storage or consistency protocol. Document, key-value, wide-column and graph systems have different query and update units. Both relational and non-relational databases can enforce schemas, maintain indexes and offer transactions under their own scope and guarantees.

Family Natural access unit Main design question
Relational Rows joined by keys Which constraints and queries must remain local?
Document One aggregate document Which fields change or load together?
Key-value Value under a known key Which lookups require another maintained index?
Wide-column Partition and ordered range Can the key distribute load while serving range access?
Graph Vertices and relationships Which traversals dominate and how are paths stored?
Time-series Time-bounded observations How do retention and aggregation handle ingestion?
PICK THE DATABASE FAMILY BY HOW YOU WILL READ AND WRITE THE DATAPICK THE DATABASE FAMILY BY HOW YOU WILL READ AND WRITE THE DATArelationalconstraints, joins, ad hoc queriesdocument{ order items[] }read and update one aggregatekey-valueget and put by a known keywide-columnpktspktstspktststsordered rows inside a partitiongraphwalk relationshipstime-seriesappend by time, aggregate windows
Figure 1.64Database families compared by access path. Orange marks Heron’s relational booking requirements; no family label alone determines durability or consistency.

A relational query joins booking ownership and aggregates ticket prices without repeating customer facts. A precomputed total trades read work for an explicit update and reconciliation obligation.

The costs include write fan-out for maintained read views, query flexibility, transaction boundaries, migration and operations. A document holding all seats for a show makes aggregate retrieval direct but can concentrate contention and grow beyond a useful update unit. Splitting each seat makes writes independent while requiring a query path for the show’s inventory. Model those operations before choosing a product.

The interview answer should compare joins, constraints, indexes, consistency and scaling strategy. “SQL is structured and NoSQL is unstructured” misses the mechanism. A declared schema can exist in either family, while a flexible value format does not remove the need to validate the business meaning of a reservation.

#Section 54Booking schema, idempotency and outbox

A7 can be booked again for another show. Uniqueness must cover both show and seat, while excluding a second claim for the same performance.

The application schema separates users, events, venues, seats, shows, bookings, booking items and payment attempts. An event describes the production; a show is a dated performance at a venue. A physical seat belongs to a venue, and a show-seat record describes that seat’s inventory state for one show. A booking belongs to a user and its items refer to claimed inventory records.

ONE PHYSICAL SEAT HAS A SEPARATE INVENTORY RECORD FOR EACH SHOWONE PHYSICAL SEAT HAS A SEPARATE INVENTORY RECORD FOR EACH SHOWphysical seat A7matineeA7 | stateeveningA7 | statebooking itemevening + A7identity belongs to the show and the seat together
Figure 1.65Physical seats become inventory only in a show context. Orange marks the show-seat identity that concurrency control must protect.

Primary keys provide identity, foreign keys preserve references, and uniqueness enforces the appropriate business boundary. A unique (show_id, seat_id) inventory key prevents duplicate inventory rows; it does not alone prevent two bookings referencing the same row. The reservation transaction must atomically change availability or enforce a separate unique active claim. A booking-items table needs the matching constraint and cancellation policy if it owns that claim.

Use an application submit key under a database uniqueness rule so a lost response can return the existing booking. Validate that the repeated key names the same payload. The seat claim, booking and outbox event share a local transaction; a relay publishes only committed intent. Payment remains a separate operation when its provider does not share the database transaction.

Adding a booking changes logical records; retained versions and additional outbox or payment records have separate storage. Do not mistake a core-table subtotal for the whole schema.

#Section 55PostgreSQL tuples, MVCC and VACUUM

PostgreSQL preserves tuple versions for permitted snapshots. Reclaiming history is a separate responsibility from publishing the current committed row.

A PostgreSQL tuple is a stored row version. Its metadata includes transaction information conventionally discussed through xmin and xmax. These fields participate in visibility and locking rules; a naive numeric comparison with the current transaction id is not the full algorithm. Snapshots, transaction status and special states matter. An update can create another version, while old versions remain until no permitted reader can require them.

AN UPDATE ADDS A NEW ROW VERSION; OLD VERSIONS STAY UNTIL NO SNAPSHOT CAN SEE THEMAN UPDATE ADDS A NEW ROW VERSION; OLD VERSIONS STAY UNTIL NO SNAPSHOT CAN SEE THEMversion 1A7 freedeadversion 2A7 heldoldversion 3A7 soldcurrentolder snapshotnewer snapshotVACUUM reclaimsthe dead versiona long-running snapshot keeps old versions alive and bloats the table
Figure 1.66Readers select a version allowed by their snapshot. Orange marks obsolete versions eligible for reclamation once no reader needs them; a current update does not instantly erase history.

Dead tuples and autovacuum

A dead tuple is an obsolete version no longer needed by valid snapshots. VACUUM reclaims reusable space and performs related maintenance, while autovacuum schedules that work automatically. A long-running snapshot can delay reclamation even when an update committed long ago. Repeated updates then accumulate versions and index cleanup work.

Application version tokens are not PostgreSQL transaction IDs. The toy page layout is also separate from the engine’s tuple layout; neither should predict the other.

PostgreSQL 18’s vacuuming reference explains reusable space and transaction-age maintenance. The engine also maintains visibility information used by index-only access. A covering index does not automatically avoid every heap visibility check under every maintenance state.

Processes, WAL and checkpoints

At a high level, client sessions use server processes while shared state and background work manage buffers, WAL and maintenance. WAL preserves recovery ordering and checkpoints bound restart work; neither replaces tuple visibility. A commit can be durable while changed data pages remain dirty in shared buffers. These are the same distinctions established in Part IX, now connected to a concrete engine.

The operational mistake is blaming every growing table on insufficient disk. Inspect old snapshots, dead-version generation and maintenance progress before changing storage. Correct visibility needs retained versions, but forgetting the reclamation side lets correctness machinery become an avoidable resource problem.

#Section 56EXPLAIN ANALYZE, indexes and connection budgets

Compare predicted and visited rows to explain why a plan costs more than expected. Indexing every column skips the actual diagnosis.

EXPLAIN ANALYZE actually runs the query, including writes. Its estimated and observed rows help localize distribution errors before selecting an index or another plan.

PLAN NODES CARRY A GUESS AND A COUNT: 16 EXPECTED, 80 SEENPLAN NODES CARRY A GUESS AND A COUNT: 16 EXPECTED, 80 SEENNested Looprows=16 actual=80Index Scan show_seatsrows=16 actual=80Index Scan bookingsrows=1 actual=1800 × 0.02 = 16 guessed80 ÷ 16 = 5 times offinner side runs once per outer row:80 loops, not 16illustrative numbers, not a PostgreSQL benchmark
Figure 1.67Illustrative planner estimate of 16 versus 80 actual rows. Orange marks the fivefold count error; it is not a measured PostgreSQL benchmark.

Check predicates, data skew, maintained statistics and column dependence. An index can help selective access, but a large fraction of a table may be cheaper to scan. A composite index must match leading-key and ordering needs, and every maintained index adds update work. PostgreSQL 18’s EXPLAIN guide defines its output and the execution boundary.

Connection limits and pools

Connection pools across application instances share one server budget. Reserve operational capacity and bound their combined demand, not each pool in isolation.

80 SERVER CONNECTIONS, 16 RESERVED: 8 APP INSTANCES MUST SHARE 6480 SERVER CONNECTIONS, 16 RESERVED: 8 APP INSTANCES MUST SHARE 64database server slots64 for apps, 16 for admin and migrations8 × 20 = 160asks for 160, server has 80new connections refused under load8 × 8 = 64fits exactly; extra requests queue in the app
Figure 1.68Illustrative application pools must share a global limit. Orange marks eight pools of eight fitting the 64-session application allowance rather than eight independent twenty-session promises.

A connection pool reuses sessions and bounds concurrency; it cannot add database service capacity. Waiting for a pooled connection needs a deadline and a bounded queue. More sessions can increase contention rather than shorten requests. Settings such as max_connections, memory budgets and vacuum controls must be interpreted across the whole deployment, including background work and concurrent operators. Do not invent a universal setting value from this toy fixture.