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.
#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? |
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.
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.
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.
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.
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.