Chapter 08 / 15 · Webster International
Databases, Storage & Data Modelling
SQL versus document stores, relational design, transactions, indexes, caches, search engines, object storage, backups and migrations.
A database is not a giant spreadsheet. It is a persistence system with a consistency model, query capabilities, durability guarantees, access rules and operational costs.
01 / FIELD NOTE
Relational, document, key-value and graph stores
Mental model: choose the authoritative store from invariants and queries, not hype. Relational engines enforce cross-row constraints; documents group aggregates; key-value stores serve known keys; graph stores traverse relationships. None automatically solves tenancy, durability or scale.
The wrong source of truth makes correctness, security and restoration harder. Decide who owns a fact, what can be stale and how to recover it before adding a second store.
A: ticket reservations and payouts belong in transactional relational tables while poster bytes belong in object storage. B: a dog-walking directory can cache public walker profiles, but bookings and payments remain authoritative in a durable ledger.
# ILLUSTRATIVE workload decision, not executable
# tickets + unique seats -> relational primary
# poster image bytes -> object store; metadata row
# public profile by ID -> expiring key-value projection
# musician collaborations -> SQL joins or graph indexHands-on exercise · reveal the verification check
For tickets, biographies, album covers and mutual collaborators, document owner, query, consistency, restore owner and optional projection. Simulate a cache outage.
No duplicate tickets; profiles fall back to primary; object references remain durable; discovery can degrade without losing records.
02 / FIELD NOTE
Schema design, relationships and normalisation
Mental model: a primary key names one fact, foreign keys prove relationships, unique constraints encode invariants, and normalisation avoids competing writable copies. Denormalisation needs an owner and refresh rule; a schema is an executable contract.
Constraints catch concurrent writes and imports that bypass application validation. Include tenant scope in keys where the business invariant is tenant-specific.
A: a many-to-many performance lineup needs a junction table with a composite unique key. B: a CRM invoice number is unique per tenant, not necessarily across the entire platform.
-- RUNNABLE: PostgreSQL disposable session
CREATE TEMP TABLE db_lab_artists(id int PRIMARY KEY,name text NOT NULL);
CREATE TEMP TABLE db_lab_shows(id int PRIMARY KEY,title text NOT NULL);
CREATE TEMP TABLE db_lab_lineup(show_id int REFERENCES db_lab_shows(id),artist_id int REFERENCES db_lab_artists(id),PRIMARY KEY(show_id,artist_id));
INSERT INTO db_lab_artists VALUES(1,'Trio');
INSERT INTO db_lab_shows VALUES(10,'Friday');
INSERT INTO db_lab_lineup VALUES(10,1);
SELECT * FROM db_lab_lineup;Hands-on exercise · reveal the verification check
Insert the same (10,1) pair again, then try artist 999; add a second valid artist.
Duplicate key and unknown foreign key fail; valid second artist succeeds; initial query returns one row.
03 / FIELD NOTE
Indexes and the query planner
Mental model: an index is an auxiliary search structure the planner may use, not a forced lookup. B-tree leading equality columns followed by range/order columns often fit feeds. EXPLAIN ANALYZE executes the statement and reports actual work.
A ten-row demo hides slow million-row scans. Plans distinguish poor selectivity, bad estimates, sorts and expensive heap reads.
A: local news filtered by town and date may benefit from (town_id,published_at DESC). B: a global events calendar filtering by date alone may require a separate date-first index.
-- RUNNABLE: PostgreSQL disposable session
CREATE TEMP TABLE db_lab_news AS SELECT g id,g%10 town_id,now()-(g||' minutes')::interval published_at FROM generate_series(1,20000) g;
CREATE INDEX db_lab_news_ix ON db_lab_news(town_id,published_at DESC);
ANALYZE db_lab_news;
EXPLAIN (ANALYZE,BUFFERS) SELECT id FROM db_lab_news WHERE town_id=2 ORDER BY published_at DESC LIMIT 20;Hands-on exercise · reveal the verification check
Compare the plan with and without the temporary index; try a date-only filter and record plan nodes and buffers.
Results stay correct, work/plans may differ; no fixed speedup is promised because planner choices depend on statistics.
04 / FIELD NOTE
Transactions, ACID and isolation
Mental model: a transaction groups local changes, while isolation determines permitted concurrent outcomes. PostgreSQL Read Committed takes a new snapshot per statement; Serializable can abort a conflicting transaction with 40001. Email and payment APIs are outside the local transaction.
Two requests can observe one remaining seat. A guarded update or serialisable transaction with bounded full-transaction retries protects the invariant.
A: two buyers compete for the final ticket; one guarded decrement succeeds. B: moving funds between project budgets updates both balances atomically, then an outbox triggers a notification.
-- RUNNABLE: PostgreSQL scratch database only
CREATE TABLE db_lab_seats(id int PRIMARY KEY,remaining int NOT NULL CHECK(remaining>=0));
INSERT INTO db_lab_seats VALUES(1,1);
BEGIN;
UPDATE db_lab_seats SET remaining=remaining-1 WHERE id=1 AND remaining>0 RETURNING remaining;
COMMIT;
SELECT remaining FROM db_lab_seats;
DROP TABLE db_lab_seats;Hands-on exercise · reveal the verification check
In a scratch database repeat the guarded update twice before cleanup; test two concurrent sessions.
Only one update decrements the one seat; count never becomes negative. A 40001 requires retry of the whole transaction.
05 / FIELD NOTE
Caching, freshness and invalidation
Mental model: a cache is a derived copy with a freshness contract, owner and invalidation policy. TTL bounds staleness but does not prove correctness. Cache keys must include relevant tenant, locale, permission and filter dimensions.
A fast cached invoice is unsafe if it belongs to another user; a cached cancelled event can mislead visitors.
A: public artist biographies use short TTL and versioned keys after edits. B: client invoices are private and never shared through a public CDN.
# ILLUSTRATIVE HTTP response headers, not shell
# Public artist profile:
Cache-Control: public, max-age=60, s-maxage=300
# Personal invoice:
Cache-Control: private, no-store
# Purge any older shared copies separately.Hands-on exercise · reveal the verification check
Design keys for event town/date filters and invoices; simulate a cancellation and a tenant switch.
Event keys vary by filter and invalidate on cancellation; invoices never share cache entries or bypass authorisation.
06 / FIELD NOTE
Full-text search and vector search
Mental model: structured filters enforce scope, lexical search matches terms, and vector similarity estimates semantic closeness—not factual truth. PostgreSQL tsvector/tsquery supports tokenisation and ranking; relevance needs a labelled test set.
A 'Barrie bassist' result must satisfy both location and instrument filters, not merely resemble the query text.
A: musician directory filters instrument and region before ranking biographies. B: local event discovery uses exact date/town predicates plus full-text titles, not embeddings alone.
-- RUNNABLE: PostgreSQL, no tables needed
SELECT to_tsvector('english','Jazz fusion bassist in Barrie') @@ websearch_to_tsquery('english','fusion bassist') AS matched;
SELECT to_tsvector('english','Classical violin teacher in Barrie') @@ websearch_to_tsquery('english','fusion bassist') AS matched;Hands-on exercise · reveal the verification check
Run both SELECTs and add exact instrument and town filters to a five-profile sample.
First match is true, second false; structured filters still exclude wrong-region profiles.
07 / FIELD NOTE
Migration, seeding and rollback
Mental model: expand → migrate → contract separates compatibility from cleanup. A migration changes durable schema; a seed adds baseline facts without overriding user edits. During rolling deployments old and new code coexist.
One-step renames or NOT NULL changes can break old instances and lock large tables; staged backfills reduce risk.
A: add nullable event source_url, deploy compatible readers, backfill, validate, constrain later. B: venue imports upsert stable external IDs but preserve administrator-edited display names.
-- RUNNABLE: PostgreSQL disposable session
CREATE TEMP TABLE db_lab_events(id int PRIMARY KEY,title text NOT NULL);
INSERT INTO db_lab_events VALUES(1,'Open mic'),(2,'Jam night');
ALTER TABLE db_lab_events ADD COLUMN source_url text;
UPDATE db_lab_events SET source_url='https://example.org/event/'||id WHERE source_url IS NULL;
SELECT count(*) AS missing FROM db_lab_events WHERE source_url IS NULL;Hands-on exercise · reveal the verification check
Run backfill twice and plan a separate constraint release after old clients retire.
Missing count stays zero, titles survive, old reads work and backfill is idempotent.
08 / FIELD NOTE
SQLite, PostgreSQL, object storage and backups
Mental model: persistence, backup and tested recovery are distinct. SQLite needs reliable persistent local storage; PostgreSQL supports multi-client services and WAL recovery. A backup is credible only after an isolated restore and integrity/application checks.
A working app can lose its only database on redeploy. Define recovery point objective (maximum data loss) and recovery time objective (maximum outage) first.
A: single-instance SQLite CRM uses persistent volume, online backup and restore drills. B: multi-instance events use PostgreSQL backups and WAL/PITR, while media objects have their own versioning/recovery.
# RUNNABLE: POSIX shell with sqlite3, scratch files only
sqlite3 db-lab.sqlite "CREATE TABLE notes(id INTEGER PRIMARY KEY,body TEXT); INSERT INTO notes(body) VALUES('verified');"
sqlite3 db-lab.sqlite "PRAGMA integrity_check; VACUUM INTO 'db-lab-backup.sqlite';"
sqlite3 db-lab-backup.sqlite "PRAGMA integrity_check; SELECT count(*) FROM notes;"
# Backup destination must not already exist.Hands-on exercise · reveal the verification check
Run scratch backup, restore independently and draft RPO/RTO, encryption-key and object-store recovery steps.
Both integrity checks return ok; restored row count is 1; runbook records a dated restore drill.
RESEARCH EXPANSION · APPLIED ENGINEERING
Schema choices guided by query patterns
List expected queries, write frequency, data relationships, growth and consistency guarantees before choosing relational, key-value, document, graph or vector systems. Use a relational system until workload evidence requires otherwise.
Each database type optimises a different question; a shiny datastore is not a domain model.
Keep artist-to-album-to-event relations in SQL; store original poster images in object storage, not a text column.
Hands-on exercise · reveal the verification check
Write 5 common queries and map each to tables and indexes.
You can explain which query needs each index and why.
Transactions, isolation and write skew
Read committed, repeatable read and serializable isolation produce different outcomes under concurrency. Use constraints, guarded updates and appropriate retry behaviour rather than assuming a transaction prevents every anomaly.
Two valid-looking concurrent transactions can jointly violate a booking limit.
For a three-seat session, test two users reserving the final seat; guarded stock updates prevent oversell.
Hands-on exercise · reveal the verification check
Run competing transactions in a disposable database.
The availability invariant is preserved and a conflict is explicit.
Index design and query-plan literacy
Use EXPLAIN (ANALYZE, BUFFERS) where safe to compare sequential scans, index scans, join order and row estimates. Indexes accelerate targeted reads but increase write cost and disk use.
More indexes can make ingestion slower without helping real queries.
For an events feed filtered by town and start time, compare a composite index (town_id, starts_at) with a scan.
Hands-on exercise · reveal the verification check
Benchmark a paginated query before/after one useful index.
Latency and examined rows improve without unreasonable write penalty.
Online schema migrations and backfills
Use expand-migrate-contract: add compatible fields, deploy readers that accept both states, backfill in batches with checkpoints, then enforce new constraints and remove old fields later.
One release may coexist with older app instances and mobile clients still writing old shapes.
Add a nullable album_cover_url, backfill verified URLs only, and later require coverage based on real business policy.
Hands-on exercise · reveal the verification check
Draft a rollback and dry-run checklist for one additive column.
Old and new code function during the migration window.
Backups, WAL and restore drills
Protect durable volumes, perform consistent backups and periodic restore tests. Understand transaction logs and retention; copying a live database file without a safe backup mechanism can lose consistency.
Recovery means successfully opening and using restored data, not merely seeing a file in storage.
Restore the news/events database to a disposable environment; verify table counts, media references and application reads.
Hands-on exercise · reveal the verification check
Perform a test restore and run integrity checks.
Restored service reads recent valid records and logs a recovery time.
Provenance, deduplication and freshness
Normalize source URL, external ID, timezone and canonical entity identity; record fetched_at, source_published_at and last_verified_at separately. Use unique constraints or explicit review for fuzzy matches.
Aggregated events can be duplicated, stale or attributed to the wrong city.
An event across two newspapers resolves to one canonical performance with two source references and a verified update history.
Hands-on exercise · reveal the verification check
Import the same event feed twice and change a cancellation status.
No duplicate primary event; source history remains auditable.
15 / FIELD NOTE
Schema invariants: foreign keys, uniqueness and check constraints
A relational schema can enforce identity and state invariants at the storage layer with primary keys, foreign keys, unique constraints and CHECK constraints. Application validation improves feedback but cannot close every concurrency race.
Critical correctness must not depend only on browser checks.
Add tenant-scoped unique event IDs and foreign keys between booking, client and invoice records.
CREATE TABLE bookings (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id BIGINT NOT NULL,
starts_at TIMESTAMPTZ NOT NULL,
UNIQUE(tenant_id, starts_at)
);Hands-on exercise · reveal the verification check
Create a schema with three invariants and attempt invalid inserts.
All invalid records are rejected by the database.
16 / FIELD NOTE
EXPLAIN ANALYZE, selective indexes and query planning
B-tree and other index types speed particular lookups while consuming storage and write work. Query planners consider estimated rows, statistics and available plans; composite index order and partial indexes matter. EXPLAIN ANALYZE supplies observed execution evidence.
Profiling the actual query often outperforms guessing from application code.
Compare a start-time-and-tenant query before and after an index on (tenant_id, starts_at).
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM bookings WHERE tenant_id = 10 AND starts_at >= NOW();Hands-on exercise · reveal the verification check
Explain a real query on representative data.
Record scans, estimated versus actual rows and timing.
17 / FIELD NOTE
Transaction isolation and double-booking races
Transaction boundaries make operations atomic, but isolation levels define what concurrent transactions can observe. Read-then-insert logic may race even when each request is inside a transaction; use appropriate unique constraints, locking or serializable retry behavior.
Scheduling cannot be trusted until conflicting writes are handled atomically.
Race two requests for the final appointment slot and enforce that only one can commit.
BEGIN;
SELECT * FROM appointments WHERE id = 42 FOR UPDATE;
-- Check availability and write atomically here.
COMMIT;Hands-on exercise · reveal the verification check
Run a parallel reservation test ten times.
Exactly one reservation exists on every run.
18 / FIELD NOTE
Safe schema evolution: expand, backfill and contract
Production schema changes should allow old and new application versions to coexist during rollout. Add compatible fields, migrate reads and writes, backfill in bounded work, then remove obsolete columns only after verification and recovery planning.
One destructive migration can break both live web requests and scheduled workers.
Rename a client attribute over multiple releases with a rollback-safe compatibility period.
ALTER TABLE clients ADD COLUMN preferred_name TEXT;
-- Backfill, migrate readers, then consider constraints.Hands-on exercise · reveal the verification check
Write a three-stage migration plan for a live table.
Each stage has checks and a rollback strategy.
19 / FIELD NOTE
SQLite versus PostgreSQL, object storage and recovery
SQLite is embedded and powerful for many single-service deployments; PostgreSQL is suited to networked clients and richer concurrent workloads. Store large media separately where suitable; neither technology substitutes for backups and tested restores.
Storage choices must match concurrency, hosting and recovery targets.
Store CRM records in a relational DB, album covers in object storage and restore a backup to an isolated staging database.
Hands-on exercise · reveal the verification check
Restore a representative snapshot and run integrity checks.
The app starts with expected record counts and relationships.
20 / FIELD NOTE
Full-text search versus vector retrieval and provenance
Structured filters and database full-text search often solve exact names, towns and dates; embeddings support semantic similarity but add indexing, evaluation and update complexity. Require source links and freshness data regardless of retrieval method.
Search quality comes from measured relevance rather than fashionable infrastructure.
Build headline search using text indexes and test semantic retrieval only on deliberately ambiguous queries.
SELECT title FROM events
WHERE search_vector @@ plainto_tsquery('english','jazz festival');Hands-on exercise · reveal the verification check
Label 20 test queries and compare retrieval strategies.
Show source attribution and measured relevance.