CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·211D

The Data Layer

TiffinBox's data built to the capstone's list: PostgreSQL as the source of truth (schemas per module, migrations, indexes from real queries, pooling, replicas and recovery), Redis for caches, counters and short-lived data, object storage with signed URLs for receipts and documents, search that starts in PostgreSQL and moves out only when needed, and an optional vector index; plus retention and deletion across derived stores; with a lab comparing five ways to search half a million dishes and testing signed, expiring download links.

22 topics · ~12 min read · 16-question quiz
Updated Suggest a correction

Start here: one source of truth, several copies

TiffinBox keeps data in five kinds of store. The most important design decision is which one is the source of truth and which are copies derived from it:

Store Role If it's lost
PostgreSQL source of truth for every module restore from backups and logs: RPO ≤ 5 min
object storage source of truth for files (receipts, kitchen documents, images) versioning and replication protect it
Redis caches, counters, rider positions for the last hour rebuild by reading through; positions simply restart
search index derived from catalogue data rebuild by re-indexing
vector index derived from kitchen documents rebuild by re-ingesting

If every derived store can be rebuilt from the sources of truth, losing one is an inconvenience, not a disaster. If anything is only in a cache or an index, it's not a cache or an index: it's an unprotected database.

Searching dishes, measured

The lab loaded half a million dishes into PostgreSQL and searched them five ways:

Search Time Rows How
ILIKE '%paneer%' on name and description 214 ms 47,500 reads the whole table
ILIKE '%paneer%' on name, trigram index 26 ms 25,000 index on 3-letter fragments
full-text paneer & tikka 2.7 ms 4,750 inverted index of words
full-text, ranked, top 10 27 ms 10 same, plus scoring every match
full-text with a typo, panner 0.0 ms 0 the word isn't in the index
trigram similarity, panner 47 ms 25,000 matches similar spellings

The right index made search ~80× faster. But each method answers a different question: full-text finds words fast and can rank them, yet a single typo finds nothing; trigrams forgive typos at a cost. Good search combines them, and that's still all inside PostgreSQL, with no extra system to run.

How deep to go

Volume 17 defines six mastery levels. For the data layer:

Level What you can do
L1 Say which store holds what and why
L2 Build the schemas, migrations, caches, uploads and search
L3 Explain indexes, MVCC, isolation, cache consistency and inverted indexes
L4 Debug slow queries from plans, stale caches, bloated tables and replica lag
L5 Design data ownership, retention, search and recovery with measured trade-offs
L6 Operate it: upgrades, failovers, restores, growth, cost

Volume 4 (chapters 55–64) and Volume 3, chapter 53 teach each topic in depth.

PostgreSQL: the source of truth

Schemas and ownership

  • One schema per module (catalogue, subscriptions, payments, …), each owned by a database role used only by that module's code; other modules get no grants. A cross-module report reads from an analytics copy, not live tables.
  • Keys: surrogate bigint identity keys (or UUIDv7 for IDs generated outside the database); natural keys get unique constraints.
  • Money as integer paise with a currency column; time as timestamptz (stored in UTC); a kitchen's local cut-off as a time plus its time zone name.
  • Constraints everywhere they're true: NOT NULL, foreign keys within a module, CHECK, UNIQUE, and exclusion constraints for "no overlapping pauses".

Migrations

  • Flyway (or Liquibase) in the repository; every change is a versioned migration run by the pipeline before the new code starts.
  • Expand and contract for anything that old code would break on (chapter 212B's lab: a one-step column rename failed every write from the old version during the deploy).
  • Lock awareness: SET lock_timeout = '2s' in migrations; CREATE INDEX CONCURRENTLY for large tables (outside a transaction, and check for INVALID indexes if it fails); add constraints as NOT VALID then VALIDATE separately.
  • Backfills in batches by key range, not one giant UPDATE.

Indexes from real queries

List the top queries per screen (the kitchen's today list, the customer's calendar, the operations search), then index for them: (kitchen_id, date, status) for the dashboard, (subscription_id, date) for skips, partial indexes for hot subsets (WHERE status = 'pending'). Confirm with EXPLAIN (ANALYZE, BUFFERS) on production-sized data, and watch pg_stat_statements for the queries that actually cost the most.

Connections

Databases serve best with a few busy connections: Volume 17's lab measured PostgreSQL throughput peaking at 4 clients on 2 CPUs and halving at 64. Size application pools small (a common starting point is about two connections per database core across all instances), put PgBouncer in transaction mode in front if many instances connect, and set a pool wait timeout so an outage fails fast instead of queueing (chapter 212A).

Replicas, backups and recovery

  • A synchronous or quorum standby in another zone for failover; asynchronous read replicas for reporting.
  • Replica lag breaks read-your-writes: after a customer skips a day, read their calendar from the primary (or wait for the replica to catch up to the write's position), not from a lagging replica.
  • Backups: continuous WAL archiving plus base backups (pgBackRest, or the managed service's PITR), with timed restore drills. Volume 16's lab restored to the second before an accidental DELETE.

Redis: fast, and allowed to forget

Use Pattern Detail
menu and kitchen pages cache-aside with TTL TTL plus random jitter so keys don't all expire together; invalidate on MenuChanged events
expensive aggregates cache with stampede protection one request recomputes (a lock key or "early refresh"), others serve the old value
rate limits counters with expiry INCR + EXPIRE per user per window, or a token bucket in a Lua script
rider positions latest position per rider with a TTL plus Redis pub/sub or Streams to fan out to the tracking gateway
idempotency fast path optional the durable record stays in PostgreSQL

Rules for Redis in TiffinBox:

  • Nothing important lives only in Redis. If it's lost, the app reads through to PostgreSQL or restarts the data (positions).
  • Every call has a short timeout and no long built-in retries, and failures fall back to the database. Chapter 212A's lab measured why: with the client's default retries, a Redis outage made each request wait 4.4 s, the proxy ran out of connections, and over 1,400 of 6,000 requests failed; with fast failure and fallback, none did.
  • Set maxmemory and an eviction policy (allkeys-lru for caches), and monitor memory, evictions and hit rate.

Object storage

  • Private buckets only. Files are referenced by key from PostgreSQL rows (receipts.object_key, documents.object_key, with size, type, checksum and owner).
  • Uploads go directly from the browser to storage with a short-lived presigned upload (or a POST policy) that fixes the key, content type and maximum size. The API issues it after checking permissions, then records the object when the upload completes.
  • Downloads use presigned GET URLs valid for minutes (the lab tests tampering and expiry). In S3 and compatible stores they're signed with HMAC-SHA256 (Signature Version 4); the lab's nginx stand-in uses the same idea with MD5.
  • Untrusted files (kitchen documents for the assistant, menu images): validate type by content, not extension; scan for malware; limit size, page counts and decompression ratios (chapter 212B's zip bomb); process in workers, never in the API.
  • Lifecycle rules: move old receipts to cheaper storage classes; expire temporary uploads; enable versioning so deletions and overwrites are recoverable.

Start in PostgreSQL (the lab shows why it's enough for TiffinBox's catalogue):

  • A generated tsvector column combining name (weight A), cuisine and tags (B) and description (C), with a GIN index; websearch_to_tsquery for user input; ts_rank for ordering, applied to the matched set.
  • pg_trgm for typo tolerance and autocomplete on dish and kitchen names, used when full-text returns few results ("did you mean…?").
  • unaccent and a synonym dictionary for common variants (dosa / dosai, curd / dahi).

Move to a search engine (OpenSearch or Elasticsearch, Volume 4, chapter 63) when relevance tuning, facets, multiple languages or load demand it. Then:

  • The engine is derived data, fed by MenuChanged events from the outbox.
  • Reindex into a new index and switch an alias atomically, so rebuilds have no downtime.
  • Reconcile counts nightly between PostgreSQL and the index, and alert on drift.

The vector index (optional)

The assistant needs semantic retrieval over kitchen documents (chapter 211F). Start with pgvector in PostgreSQL:

  • One table of chunks (document_id, kitchen_id, chunk_text, embedding vector(768)), an HNSW index, and filters on kitchen_id in the same query.
  • Storage: 768 dimensions × 4 bytes ≈ 3 KB per chunk; 200,000 chunks ≈ 600 MB plus index, which is fine for one database.
  • Hybrid retrieval: combine vector similarity with full-text rank (reciprocal rank fusion), as Volume 14B taught.
  • Move to a dedicated vector store only for scale or features you actually need; it's still derived from object storage and must be re-ingestable.

Retention and deletion

  • Write a retention table: orders and payments (7–8 years for tax), rider positions (30 days in detail, summaries after), assistant conversations (90 days unless the user saves them), logs (30 days hot), audit logs (per policy, immutable).
  • Deleting a customer's personal data (right to erasure) touches PostgreSQL (anonymise rather than delete where financial records must remain), object storage, caches, search and vector indexes (re-index), logs (which shouldn't contain it in the first place), and backups (expire on schedule, documented). Make it a tested job, not a manual runbook.

Done when

  • Every module's schema is isolated by role and grants; migrations run in the pipeline with lock timeouts.
  • The top queries have plans checked at production data size; pg_stat_statements is on.
  • A Redis outage degrades latency, not availability (proven in chapter 212A).
  • Files upload and download via signed URLs; buckets are private and versioned; untrusted files are validated and scanned.
  • Search returns ranked, typo-tolerant results within the latency target; derived indexes can be rebuilt with one command.
  • A point-in-time restore has been timed; the retention and erasure jobs run and are tested.

Common traps

  • Caches and indexes treated as sources of truth.
  • LIKE '%…%' on large tables without the right index.
  • Big pools that make the database slower.
  • Public buckets for convenience.
  • Forgotten copies of personal data in derived stores and logs.

Setup. PostgreSQL 16 on the lab machine. A table cp_items with 500,000 dishes: names built from 10 styles × 20 mains × 10 preparations (e.g. "spicy paneer tikka") and six-word descriptions from a 20-word vocabulary, deliberately repetitive so many rows match. Indexes: a GIN index on to_tsvector('english', name || ' ' || descr) and a GIN trigram index (pg_trgm) on name. Each query's execution time is the median of five EXPLAIN ANALYZE runs after a warm-up, data cached in memory. Sizes: table 46 MB, full-text index 4.8 MB, trigram index 13 MB.

Search Median time Rows Plan
name ILIKE '%paneer%' OR descr ILIKE '%paneer%' 214.1 ms 47,500 sequential scan
name ILIKE '%paneer%' 26.4 ms 25,000 bitmap scan of the trigram index
full-text paneer & tikka 2.7 ms 4,750 bitmap scan of the GIN index
full-text paneer & tikka, ranked, top 10 27.3 ms 10 same, plus ts_rank on every match
full-text panner (typo) 0.0 ms 0 the lexeme isn't in the index
'panner' <% name (trigram word similarity ≥ 0.4) 46.8 ms 25,000 bitmap scan of the trigram index

nginx's secure_link module protects /receipts/: a link is valid only with expires (a Unix time) and sig (a hash over the expiry, the path and a secret key). Six requests:

Request Result
valid link, expires in 5 minutes 200, 200,000 bytes
the same signature on another file (order-1002.pdf) 403
expiry pushed a day later, old signature 403
correctly signed but expired a minute ago 410 Gone
signed with the wrong key 403
no signature 403

What it shows

  • Indexes decide everything. The same question took 214 ms or 2.7 ms depending on whether the index matched the query's shape. The unindexed version would also get slower as the table grows; the indexed ones mostly wouldn't.
  • Ranking costs more than matching. Scoring 4,750 matches to pick 10 took 10× longer than finding them. On broad queries ("rice"), limit the candidate set before ranking, or use a search engine whose index stores what ranking needs.
  • Full-text and fuzzy matching complement each other. Use full-text first; when it returns too few results, fall back to trigram similarity and show "did you mean…?". The lab's trigram query matched all 25,000 paneer dishes because its threshold (0.4) is loose; tune the threshold on real queries.
  • A signature binds the exact path and expiry. Changing either breaks it, so links can't be reused for other files or extended. S3-style presigned URLs work the same way with HMAC-SHA256 (nginx's module uses MD5, which is fine for this toy but not what you'd choose today).

Try it yourself

  1. Add a generated tsvector column with weights (name A, description C) and compare ranking quality for "paneer".
  2. Try websearch_to_tsquery('english', 'paneer -fried "tikka masala"') and read the parsed query.
  3. Grow the table to 5 million rows and rerun: which queries change, and by how much?
  4. Generate S3-style presigned URLs with an S3-compatible store (MinIO) and repeat Experiment 2.

Revision sheet: the data layer

Key ideas

  • PostgreSQL and object storage are sources of truth; Redis, search and vector indexes are derived and rebuildable.
  • Schema per module with role grants; migrations with expand/contract, lock timeouts, concurrent indexes and batched backfills.
  • Indexes from real queries, verified with plans at production size; small pools with wait timeouts.
  • Read-your-writes despite replica lag; PITR with timed drills.
  • Redis: TTL with jitter, stampede protection, fast failure and fallback, eviction policy.
  • Files: private buckets, presigned upload and download, content validation, scanning, lifecycle and versioning.
  • Search: PostgreSQL full-text + trigrams first; a search engine fed by events when needed; alias swaps.
  • Retention and erasure across every copy.

Numbers to remember

  • Lab: unindexed substring 214 ms; trigram 26 ms; full-text 2.7 ms; ranked top 10 27 ms; typo → 0 rows; trigram similarity 47 ms.
  • Index sizes: full-text 4.8 MB, trigram 13 MB for a 46 MB table.
  • Embeddings: 768 × 4 bytes ≈ 3 KB per chunk.

Pitfalls

  • Caches as sources of truth; substring search without trigrams; big pools; public buckets; personal data left in derived stores.

Glossary

  • GIN: generalised inverted index.
  • Lexeme: a normalised word in full-text search.
  • Trigram: a three-character fragment used for similarity.
  • Presigned URL: a time-limited signed link to one object.
  • HNSW: graph-based approximate nearest-neighbour index.