Explore
WEBSTER / SOFTWARE ENGINEERING← Senior DeveloperEducational reference · continually evolving

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.

← Complete index

The big idea

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.

Why it matters

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.

In practice

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 decision matrix
# 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 index
Hands-on exercise · reveal the verification check
Try it

For tickets, biographies, album covers and mutual collaborators, document owner, query, consistency, restore owner and optional projection. Simulate a cache outage.

Check your result

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.

Why it matters

Constraints catch concurrent writes and imports that bypass application validation. Include tenant scope in keys where the business invariant is tenant-specific.

In practice

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 SQL
-- 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
Try it

Insert the same (10,1) pair again, then try artist 999; add a second valid artist.

Check your result

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.

Why it matters

A ten-row demo hides slow million-row scans. Plans distinguish poor selectivity, bad estimates, sorts and expensive heap reads.

In practice

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 SQL
-- 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
Try it

Compare the plan with and without the temporary index; try a date-only filter and record plan nodes and buffers.

Check your result

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.

Why it matters

Two requests can observe one remaining seat. A guarded update or serialisable transaction with bounded full-transaction retries protects the invariant.

In practice

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 SQL (scratch only)
-- 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
Try it

In a scratch database repeat the guarded update twice before cleanup; test two concurrent sessions.

Check your result

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.

Why it matters

A fast cached invoice is unsafe if it belongs to another user; a cached cancelled event can mislead visitors.

In practice

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 headers
# 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
Try it

Design keys for event town/date filters and invoices; simulate a cancellation and a tenant switch.

Check your result

Event keys vary by filter and invalidate on cancellation; invoices never share cache entries or bypass authorisation.

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.

Why it matters

One-step renames or NOT NULL changes can break old instances and lock large tables; staged backfills reduce risk.

In practice

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 SQL
-- 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
Try it

Run backfill twice and plan a separate constraint release after old clients retire.

Check your result

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.

Why it matters

A working app can lose its only database on redeploy. Define recovery point objective (maximum data loss) and recovery time objective (maximum outage) first.

In practice

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 shell + SQLite CLI
# 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
Try it

Run scratch backup, restore independently and draft RPO/RTO, encryption-key and object-store recovery steps.

Check your result

Both integrity checks return ok; restored row count is 1; runbook records a dated restore drill.

RESEARCH EXPANSION · APPLIED ENGINEERING

09 / APPLIED RESEARCH

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.

Why it matters

Each database type optimises a different question; a shiny datastore is not a domain model.

In practice

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
Try it

Write 5 common queries and map each to tables and indexes.

Check your result

You can explain which query needs each index and why.

10 / APPLIED RESEARCH

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.

Why it matters

Two valid-looking concurrent transactions can jointly violate a booking limit.

In practice

For a three-seat session, test two users reserving the final seat; guarded stock updates prevent oversell.

Hands-on exercise · reveal the verification check
Try it

Run competing transactions in a disposable database.

Check your result

The availability invariant is preserved and a conflict is explicit.

11 / APPLIED RESEARCH

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.

Why it matters

More indexes can make ingestion slower without helping real queries.

In practice

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
Try it

Benchmark a paginated query before/after one useful index.

Check your result

Latency and examined rows improve without unreasonable write penalty.

12 / APPLIED RESEARCH

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.

Why it matters

One release may coexist with older app instances and mobile clients still writing old shapes.

In practice

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
Try it

Draft a rollback and dry-run checklist for one additive column.

Check your result

Old and new code function during the migration window.

13 / APPLIED RESEARCH

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.

Why it matters

Recovery means successfully opening and using restored data, not merely seeing a file in storage.

In practice

Restore the news/events database to a disposable environment; verify table counts, media references and application reads.

Hands-on exercise · reveal the verification check
Try it

Perform a test restore and run integrity checks.

Check your result

Restored service reads recent valid records and logs a recovery time.

14 / APPLIED RESEARCH

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.

Why it matters

Aggregated events can be duplicated, stale or attributed to the wrong city.

In practice

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
Try it

Import the same event feed twice and change a cancellation status.

Check your result

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.

Why it matters

Critical correctness must not depend only on browser checks.

In practice

Add tenant-scoped unique event IDs and foreign keys between booking, client and invoice records.

SQL
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
Try it

Create a schema with three invariants and attempt invalid inserts.

Check your result

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.

Why it matters

Profiling the actual query often outperforms guessing from application code.

In practice

Compare a start-time-and-tenant query before and after an index on (tenant_id, starts_at).

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM bookings WHERE tenant_id = 10 AND starts_at >= NOW();
Hands-on exercise · reveal the verification check
Try it

Explain a real query on representative data.

Check your result

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.

Why it matters

Scheduling cannot be trusted until conflicting writes are handled atomically.

In practice

Race two requests for the final appointment slot and enforce that only one can commit.

SQL · conceptual
BEGIN;
SELECT * FROM appointments WHERE id = 42 FOR UPDATE;
-- Check availability and write atomically here.
COMMIT;
Hands-on exercise · reveal the verification check
Try it

Run a parallel reservation test ten times.

Check your result

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.

Why it matters

One destructive migration can break both live web requests and scheduled workers.

In practice

Rename a client attribute over multiple releases with a rollback-safe compatibility period.

SQL
ALTER TABLE clients ADD COLUMN preferred_name TEXT;
-- Backfill, migrate readers, then consider constraints.
Hands-on exercise · reveal the verification check
Try it

Write a three-stage migration plan for a live table.

Check your result

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.

Why it matters

Storage choices must match concurrency, hosting and recovery targets.

In practice

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
Try it

Restore a representative snapshot and run integrity checks.

Check your result

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.

Why it matters

Search quality comes from measured relevance rather than fashionable infrastructure.

In practice

Build headline search using text indexes and test semantic retrieval only on deliberately ambiguous queries.

PostgreSQL
SELECT title FROM events
WHERE search_vector @@ plainto_tsquery('english','jazz festival');
Hands-on exercise · reveal the verification check
Try it

Label 20 test queries and compare retrieval strategies.

Check your result

Show source attribution and measured relevance.