DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·65

Database Projects

Eight build-it-yourself projects that grow one data platform, the tiffin centre's, from a well-designed schema to a tuned, concurrent, replicated, backed-up, searchable and analysable system: what each teaches, a milestone plan, measurable definitions of done, and stretch goals for experienced readers.

12 topics · ~8 min read · 5-question quiz
Updated Suggest a correction

How to approach the projects

One data platform, built up in layers

The labs in this volume isolate one mechanism at a time. These projects combine them on one dataset: the same South Indian tiffin centre whose frontend and backend Volumes 2 and 3 built, now with a realistic amount of data. Generate it once (a script producing 50,000 customers, 200 dishes, 5 million orders over two years with daily and seasonal patterns, and skewed popularity) and keep it in version control, so every measurement is reproducible.

# Project Main chapters Roughly
1 Schema, constraints and data generator Start Here, 55 a weekend
2 The reporting query pack 56 1 week
3 Performance tuning with evidence 57, 58, 60 1–2 weeks
4 Concurrency-safe stock and table bookings 59 1 week
5 Events at scale: partitioning and analytics 61, 62 1 week
6 Hybrid menu search 63 1 week
7 High availability and failover drill 57, 61 1 week
8 Backup, recovery and the restore drill 64 1 week

New to databases? Do them in order after the Start Here chapter's warm-up exercises. Experienced? Skim 1–2 and treat the later projects' stretch goals as the assignment.

The working method

  1. Write the definition of done first: each project lists measurable checks. Copy them into a checklist.
  2. Measure before and after every change, with EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements, pgbench or your own load script, on the full dataset.
  3. Reproduce the failure first: for concurrency, failover and recovery, write the script that demonstrates the problem before the fix.
  4. Keep migrations as files (Flyway, Liquibase, sqitch or plain numbered SQL), applied by a script, never by hand.
  5. Write a README per project with the decisions, alternatives and measurements.

The eight projects

Project 1: schema, constraints and data generator

Goal. A normalised schema for customers, addresses, dishes and prices over time, orders, order lines, payments, deliveries and reviews, plus a deterministic data generator.

Milestones. An entity-relationship diagram → tables with keys, types and constraints (NOT NULL, CHECK, UNIQUE, foreign keys with deliberate ON DELETE actions) → price history modelled so orders keep the price they were charged → indexes on every foreign key used for joins or deletes → a seeded generator producing the full dataset with realistic skew (Zipf-distributed dish popularity, lunch and dinner peaks, festival spikes).

Done when. The migrations build an empty database from scratch; the generator loads 5 million orders in under 10 minutes (using COPY); a script of 15 bad inserts (negative prices, orders for unknown customers, duplicate emails, overlapping price periods) is rejected by the database, each with the expected SQLSTATE; you can explain every nullable column.

Stretch. Exclusion constraints preventing overlapping price periods; UUIDv7 keys for orders created by offline clients; a comparison of the same model in MongoDB with embedded order lines, listing what each design makes easy and hard.

Project 2: the reporting query pack

Goal. The owner's ten standard reports, correct and fast.

Milestones. Daily revenue with zero-sales days, revenue by dish category and month, top dishes per category (window functions), customer cohorts by first-order month and their retention, average basket size, repeat-customer rate, busiest hours heatmap, running monthly totals, year-on-year comparison, and an outlier list (orders over three standard deviations) → each verified against a small hand-checked dataset.

Done when. Every report matches hand calculations on the test dataset (write these as automated tests); no report double-counts through joins (assert count(*) before and after each join step); each runs in under 2 seconds on the full dataset, or has a documented reason and a materialised view.

Stretch. The same reports in DuckDB over a Parquet export, and a comparison of speed and SQL dialect differences; a ROLLUP/CUBE version for a pivot table.

Project 3: performance tuning with evidence

Goal. Make the application's 20 most frequent queries (from Volume 3's projects, or a workload script you write) fast, and prove it.

Milestones. Enable pg_stat_statements and run a realistic mixed workload → rank queries by total time → for each of the top ten, record the plan, the estimate errors and buffer counts → fix with composite, partial, covering or expression indexes, extended statistics, or query rewrites → remove unused and redundant indexes → tune autovacuum for the two hottest tables and work_mem for the reports.

Done when. Total database time for the workload falls by at least 5× (state the before and after); every fix has a before/after plan in the README; no query in the top ten has a node whose estimated and actual rows differ by more than 10× without explanation; write throughput hasn't dropped by more than 10% from the added indexes (measure).

Stretch. A plan-regression test that fails CI when a key query's plan changes shape; compare G1-style "bigger box" (more shared_buffers, faster storage) against the indexing work for cost per unit of improvement.

Project 4: concurrency-safe stock and table bookings

Goal. Limited-stock specials and table reservations that never oversell or double-book under concurrent requests.

Milestones. A load script with 50 concurrent clients ordering the last 100 portions of a special → the naive read-then-write implementation, reproducing oversells → three correct implementations: atomic conditional UPDATE … WHERE qty >= n, SELECT … FOR UPDATE, and Serializable with retries → table bookings with an exclusion constraint on (table, time range) → a measured comparison of throughput and failures.

Done when. The naive version oversells in at least one run (captured in the README); every correct version sells exactly 100 portions across 20 runs; overlapping bookings are rejected by the database even when the application check is removed; you can explain which anomaly each failing version exhibited.

Stretch. A deadlock reproduced and fixed by lock ordering; a waiting-list queue using SKIP LOCKED; the same guarantees in DynamoDB with conditional writes.

Project 5: events at scale: partitioning and analytics

Goal. Store every app event (views, searches, add-to-cart) for two years at 50 million events per month, keep 13 months online, and analyse them cheaply.

Milestones. A monthly range-partitioned events table with automated creation of future partitions and detaching of old ones → BRIN indexes on time, B-tree indexes only where needed → a nightly export of closed months to Parquet → a funnel analysis (view → cart → order) in DuckDB over the Parquet files.

Done when. Ingestion sustains at least 5,000 events per second for 10 minutes; retiring a month takes under a second and leaves no bloat; the funnel query over 12 months runs in under 10 seconds in DuckDB, with the PostgreSQL equivalent timed for comparison; storage per month is documented for both.

Stretch. ClickHouse instead of DuckDB with a materialised view for live dashboards; change-data capture from PostgreSQL into the analytical store.

Goal. Customers find dishes by name, misspelling, ingredient or description ("something light and not spicy").

Milestones. A judged query set of at least 40 real-style queries with relevant dishes → lexical search (PostgreSQL full-text or a search engine) with stemming, synonyms and typo tolerance → embeddings for dish descriptions and semantic search (pgvector or a vector store) → hybrid fusion → filters (vegetarian, price, category) and facets → an indexing pipeline that updates search within seconds of a menu change.

Done when. nDCG@5 on the judged set improves on lexical-only by at least 10% (report all three: lexical, semantic, hybrid); p95 search latency under 50 ms with filters; a menu change is searchable within 5 seconds; zero-result queries in the judged set are below 5%.

Stretch. A cross-encoder reranker on the top 20; autocomplete with edge n-grams; offline evaluation automated in CI.

Project 7: high availability and failover drill

Goal. Survive the loss of the primary with known data loss and downtime.

Milestones. A primary with two replicas (one synchronous, one asynchronous) using replication slots → Patroni (or your managed service's equivalent) for automatic failover with fencing → PgBouncer in front for connection routing → application read routing with read-your-writes handling → a failover drill under a write load.

Done when. During a drill killing the primary under load, the measured RPO is zero for synchronous commits and documented for asynchronous ones; RTO (first failed write to first successful write) is under 30 seconds; the old primary cannot accept writes after failover; replica lag and slot retention are on a dashboard with alerts.

Stretch. Cross-region replica with a documented manual failover; logical replication used to perform a zero-downtime major version upgrade.

Project 8: backup, recovery and the restore drill

Goal. Recover from the worst plausible mistakes, and prove it on a schedule.

Milestones. pgBackRest, Barman or WAL-G with full plus incremental backups and continuous WAL archiving to object storage with object lock (immutability) → encryption with keys stored separately → a delayed replica (recovery_min_apply_delay) → runbooks for: accidental DELETE, dropped table, corrupt page, lost region → an automated weekly restore drill that restores to a scratch server, runs integrity checks (pg_amcheck, row counts, report totals) and records the restore time.

Done when. A scripted "accidental DROP TABLE orders" is recovered with no loss of other tables' later writes, following the runbook, by someone else; the restore drill has run successfully three times with its RTO recorded; deleting backups with the application's credentials fails; archive failures raise an alert within 5 minutes.

Stretch. Restore a single table from PITR into the live database without downtime; a full disaster-recovery exercise in another region with measured RTO.

Tracking your progress

Portfolio checklist

Keep one repository with the migrations, generator, scripts and a README per project: goal, design decisions and alternatives, and measurements against the definition of done. For data work, evidence is everything: "5 million orders; workload database time cut from 41 min to 6 min per hour; 0 oversells in 20 concurrent runs; failover RTO 14 s with zero loss of synchronous commits; weekly restore drill RTO 9 min" is what makes a portfolio credible.

Mapping to mastery levels

Completing projects 1–3 with their checks puts you at L2 across the volume. Doing the stretch goals and explaining every plan, anomaly and failure you reproduced is L3–L4. Designing and defending the choices in projects 4–8 (concurrency strategy, partitioning and analytics architecture, search design, HA and backup objectives) is L5 work, the level senior database and backend interviews probe.