SteelReed

Search

Search posts, questions…

4. Database & SQL

The data modeling process: access patterns, table types, foreign keys and table templates

Design a schema from its queries, not from boxes on a diagram: four kinds of tables, when to denormalize, whether to keep foreign keys (with parent-row locking measured on PostgreSQL 16 and MySQL 8.4), where the reference column goes, and a table template with technical columns.

18 Nov 20268 min readSenior

–

1. The problem

A multi-author blog with a 3NF schema. The feed "20 latest posts by authors in Singapore" takes 63 ms against a target of p95 < 50 ms at 300 req/s. No index serves it fully, because it filters on author and sorts on post.

2. Key idea

The schema is the hardest thing to change. Like building a warehouse: know what gets picked most before placing the shelves.

The process: (1) list the queries and writes with frequency and target latency; (2) group fields into tables, pick keys; (3) review the normalisation.

Table kind Example Traits
Entity: identity and lifecycle author, post, booking status is a state machine; full technical columns
Relation: N–M link post_tag (post_id, tag_id) composite primary key, just created_at
Support: secondary 1–N data post_revision foreign key to the parent entity
Config: rarely changing catalogue country, currency read-heavy, cached in the app, natural keys

2.1 Normalise or denormalise? Keep the FK or drop it?

Decision Use when Don't use when
Normalise (default) filtering and sorting on the same table, frequently changing source data a hot query filters on table A and sorts on table B
Redundant column (post.author_country) a measured hot query; rarely changing source; sync and reconciliation in place "for speed" without measuring
Keep the FK (default) same database, same service; remember to index the FK column different shards or services, using gh-ost

The real cost of an FK is locking the parent row: InnoDB holds an S lock on the parent record until the child-inserting transaction ends, so every UPDATE on the parent waits; PostgreSQL only blocks deletes or key changes. Dropping the FK and checking with SELECT then INSERT lets races create orphan rows.

Update counters atomically: SET comment_count = comment_count + 1.

3. Worked example: a table template for entities

SQL
CREATE TABLE app_user (
  -- business
  user_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      text        NOT NULL UNIQUE,
  birth_date date,                                  -- don't store age: it changes every year
  status     text        NOT NULL DEFAULT 'ACTIVE'
             CHECK (status IN ('ACTIVE', 'LOCKED', 'CLOSED')),
  data       jsonb       NOT NULL DEFAULT '{}',     -- rarely queried extra attributes
  -- technical
  version    int         NOT NULL DEFAULT 0,        -- optimistic locking
  created_at timestamptz NOT NULL DEFAULT now(),    -- sorting, keyset paging, partitioning
  created_by text        NOT NULL,                  -- user, admin, service, job
  updated_at timestamptz NOT NULL DEFAULT now(),    -- incremental sync to other systems
  updated_by text        NOT NULL
);
-- Append-only tables (ledgers, event logs): drop updated_*, version; a trigger blocks UPDATE/DELETE

Each column has one job; drop the ones you don't need. For 1–1 relations, the entity created later holds the reference to the one created earlier, with UNIQUE.

PostgreSQL measurements and Spring Data auditing

Q1 over 100,000 authors and 2 million posts (PostgreSQL 16):

Approach Country Buffers read Time
JOIN, filter on author VN (60% of authors) read 32 posts 0.2 ms
JOIN, filter on author SG (0.1%) 125,000 63 ms
post.author_country + index (author_country, created_at) SG 23 0.074 ms

PostgreSQL walks the post (created_at) index backwards and checks each author; for SG it reads ~41,000 posts to collect 20 rows. Latency depends on the parameter value.

  • Spring Data auditing: @CreatedDate and @LastModifiedDate need @EntityListeners(AuditingEntityListener.class) and @EnableJpaAuditing; @CreatedBy also needs an AuditorAware<T> bean. Miss one and the column is silently null; hand-written @Modifying updates skip auditing too.
  • ON DELETE CASCADE can drag millions of rows into one transaction; for big data use soft deletes or batched deletes.
  • NoSQL also starts from access patterns, it just groups data by how it's read from the outset.

4. Working with AI

Delegate to AI: DDL, Flyway migrations, updated_at triggers, reconciliation jobs.

Check yourself:

  • There's a query list with frequency and p95 before any tables.
  • Every redundant column has a measured query, one sync mechanism and a reconciliation job.
  • FKs are indexed; dropped FKs have a reason (different shards, gh-ost, measured lock contention).

5. Exercises

Exercise 1: Read a parent-row lock incident

MySQL 8.4. A big merchant receives 2,000 orders/minute; each inserts an order (FK to merchant) in a ~300 ms transaction. A job updating merchant.last_order_at keeps failing with error 1205 (lock wait timeout), with occasional deadlocks. AI suggests "raise innodb_lock_wait_timeout to 120". Diagnose and propose.

Solution to Exercise 1
  • Diagnosis: InnoDB holds S,REC_NOT_GAP on the merchant row until each order-inserting transaction ends. There's always an uncommitted order, so UPDATE merchant never gets its X lock. A longer timeout just makes the job hang longer.
  • Now: shorten the ordering transaction (move I/O out); move last_order_at to a separate merchant_stats table that isn't the FK's parent row.
  • Consider: if contention is still measurable after the split, drop the order → merchant FK and add an orphan-finding job. On PostgreSQL a non-key UPDATE runs immediately, so this doesn't happen.

Exercise 2: Comment counter: trigger or same transaction?

AI added an AFTER INSERT ON comment trigger doing post.comment_count = comment_count + 1, noting "perfectly consistent". A hot post gets 200 comments/second. What's the problem? When would you choose differently?

Solution to Exercise 2
  • It's consistent, but every comment insert competes for the hot post row's lock: 200 comments/second queue on one row. The trigger is also hidden logic, hard to debug, and misses soft deletes without an AFTER UPDATE.
  • Few hot posts: doing it in the same transaction (SET comment_count = comment_count + 1) is clearer than a trigger.
  • Hot posts: asynchronous events (outbox) batched every few seconds, accepting a few seconds of lag; or split the counter into N rows summed on read. Always reconcile against count(*).

Summary

  • The query list comes before the tables.
  • Four kinds of table: entity, relation, support, config.
  • Normalise by default; denormalise where measured, with sync and reconciliation.
  • Keep FKs by default; remember InnoDB's S lock on the parent row.
  • Entities get technical columns; append-only tables have no updated_*.

Next: Part 2: JSON columns, online DDL, data types and views.

Practice interview questions on this topic

All Data Modeling & Scaling questions →

Loading comments…