Chapter 3 of 8Database design

Database Design

Seven tables hold the whole MVP. We design them together: keys, relationships, constraints, the indexes that keep the feed fast, and the trade-offs behind each choice.

Contents · Chapter 3 of 8

What you will learn

  • Why a relational database fits a social network
  • Tables, columns, primary keys, foreign keys and the three kinds of relationship
  • All seven Chirp tables, column by column, with the reasons behind each choice
  • What an index is, which ones the feed needs, and how to read EXPLAIN
  • Why "load more" uses a cursor instead of page numbers
  • How to create the schema with Docker, psql and Flyway

Why it matters

Code is easy to change. Data is not: once real people have written posts, every change to a table has to move the existing rows along. A good schema also does part of your job for you. It can refuse a duplicate like or a post longer than 280 characters even when the application has a bug. Time spent here pays off in every later chapter.

Why a relational database?

A relational database such as PostgreSQL stores data in tables. A table looks like a spreadsheet: each row is one thing (one user, one post) and each column is one fact about it (its username, its text). Unlike a spreadsheet, every column has a fixed type (number, text up to 280 characters, timestamp) and the database refuses values that don't fit.

Look back at the feature table from chapter 1. Almost every feature is a relationship between two things: a user writes a post, a user follows a user, a user likes a post, a comment belongs to a post. Relational databases were designed for exactly this kind of data. You store each thing once, connect things by their ids, and ask questions across the connections with joins: "posts written by people Bob follows".

Analogy: a library card catalogue

A library doesn't write the author's full biography inside every book. It keeps one card per author, and each book card just says "author: card 17". That is a foreign key. If the author changes their name, one card changes and every book is still correct. Storing each fact in exactly one place is called normalisation, and it is the main idea of this chapter.

The rule of thumb we follow: one kind of thing per table. Users, posts, comments and notifications are things, so each gets a table. Following, liking and reposting are connections between things, and each of those gets a small table of its own too. We will see why that is better than a list stored inside a row.

Keys and relationships

Primary keys: a name tag for every row

A primary key is a column (or several) whose value is different for every row and never empty. It is how the rest of the system points at a row: "post 42". We use BIGSERIAL: a 64-bit integer that PostgreSQL fills in for us from a counter (a sequence), 1, 2, 3 and so on.

Counting upwards has a bonus we will use all the time. A post created later always gets a bigger id, so "newest first" is simply "biggest id first", and "the next page of older posts" is "ids smaller than the last one I saw". That makes fast pagination easy (more on that below).

In production

One database counter only works while one database hands out the ids. Large systems that write to many databases at once use ids that are generated anywhere but still roughly increase with time. Twitter published such a scheme, called Snowflake: a timestamp, a machine number and a counter packed into 64 bits. Chapter 7 comes back to this. For our MVP, BIGSERIAL is the simple, correct choice.

Foreign keys: pointing at another row

A foreign key is a column that holds the primary key of a row in another table. posts.author_id holds a users.id. Declaring it with REFERENCES users (id) makes PostgreSQL check it: you can't save a post whose author doesn't exist, and you decide what happens to the posts when the user is deleted.

The three kinds of relationship

KindExample in ChirpHow it is stored
One-to-manyOne user writes many posts; one post has many commentsA foreign key on the "many" side: posts.author_id, comments.post_id
Many-to-manyUsers follow many users and are followed by many; users like many posts and a post is liked by many usersA join table with two foreign keys: follows, likes, reposts
One-to-one(not used in Chirp) a user and their private settingsA foreign key that is also unique, or the same primary key in both tables

A join table is the database version of a list of pairs. "Bob follows Alice" is one row (follower_id = 2, followee_id = 1). Bob following 300 people is 300 small rows, and "who follows Alice?" is just "every row whose followee_id is 1".

The whole schema at a glance

This is an entity-relationship (ER) diagram of every table in the MVP. Each box is a table, each line is a foreign key, and the arrow points at the table being referenced. Click a table to highlight its relationships and read why it looks the way it does. PK marks the primary key, FK a foreign key.

users
One row per account. Everything else points here, so it is the centre of the diagram. username and email are UNIQUE; the password is stored only as a BCrypt hash.
posts
One row per post, pointing at its author. It also keeps three counters (likes, comments, reposts) so a page of 20 posts can be shown without counting rows in three other tables.
follows
A join table between users and users: one row means "follower follows followee". Both columns point at users. The pair is the primary key, so nobody can follow the same person twice.
likes
A join table between users and posts. The primary key (user_id, post_id) means one like per person per post, enforced by the database.
reposts
Exactly the same shape as likes: who reposted which post, once each.
comments
Replies. Unlike a like, a person can comment many times on the same post, so a comment needs its own id instead of a (user, post) key. It points at both the post and its author.
notifications
"actor did type to recipient", e.g. Bob (actor) liked a post of Alice (recipient). Two foreign keys to users, and an optional one to posts (a follow has no post).
Chirp's MVP schema. Seven tables: four "things" (users, posts, comments, notifications) and three join tables (follows, likes, reposts).

The tables, one by one

All seven tables live in one SQL file, V1__create_schema.sql. We go through it table by table; the complete file follows at the end of the section. Read the comments in the SQL too: they are part of the explanation.

users

CREATE TABLE users (
    id            BIGSERIAL    PRIMARY KEY,
    username      VARCHAR(30)  NOT NULL UNIQUE,
    email         VARCHAR(254) NOT NULL UNIQUE,
    password_hash VARCHAR(100) NOT NULL,
    display_name  VARCHAR(50)  NOT NULL,
    bio           VARCHAR(160) NOT NULL DEFAULT '',
    created_at    TIMESTAMPTZ  NOT NULL DEFAULT now(),
    -- usernames are stored in lower case: letters, digits and underscores only
    CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,30}$')
);
  • username VARCHAR(30) NOT NULL UNIQUE: UNIQUE makes PostgreSQL refuse a second "alice". It also creates an index, so finding a user by name is fast.
  • Lower-case usernames. To users, "Alice" and "alice" are the same name. The backend lower-cases names before saving (chapter 4), and the CHECK constraint with a regular expression guarantees that only a-z, digits and _, 3 to 30 characters, ever reach the table. If a bug skips the lower-casing, the database still says no.
  • password_hash, not password. A BCrypt hash is 60 characters; VARCHAR(100) leaves room to switch algorithms later. Naming the column password_hash makes it obvious nobody should ever put a real password there.
  • display_name is the name people see ("Alice Chen"); username is the unique handle (@alice). bio defaults to an empty string, so code never has to handle "no bio" separately.
  • TIMESTAMPTZ ("timestamp with time zone") stores an exact moment. PostgreSQL saves it in UTC and converts for display, so users in different countries agree on when something happened. Always prefer it to TIMESTAMP (no zone) or a text column.

posts

CREATE TABLE posts (
    id            BIGSERIAL    PRIMARY KEY,
    author_id     BIGINT       NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    content       VARCHAR(280) NOT NULL,
    image_url     VARCHAR(500),
    like_count    INTEGER      NOT NULL DEFAULT 0,
    comment_count INTEGER      NOT NULL DEFAULT 0,
    repost_count  INTEGER      NOT NULL DEFAULT 0,
    created_at    TIMESTAMPTZ  NOT NULL DEFAULT now()
);
-- "Newest posts by this author" (profile pages and the home feed).
CREATE INDEX posts_author_id_id_idx ON posts (author_id, id DESC);
  • VARCHAR(280) is our product rule written into the schema. PostgreSQL counts characters, not bytes, so an emoji counts as one character here. The backend checks the length too, to give a friendly error message; the database is the last line of defence.
  • image_url can be empty (no NOT NULL), because most posts have no picture. We add it now and fill it in chapter 6, so we don't need a schema change for image uploads.
  • ON DELETE CASCADE on author_id: when a user is deleted, their posts are deleted too, and so (through the other tables' cascades) are the likes, reposts, comments and notifications on those posts.

Should a post store its like count?

like_count breaks the "store each fact once" rule: the true number of likes is already in the likes table, and SELECT count(*) FROM likes WHERE post_id = 42 would give it. Storing a copy is called denormalisation. Here is the honest trade-off:

Store the count on the post

A page of 20 posts is one read of 20 rows. The count is ready to show.

Cost: every like must also update the post, in the same transaction, or the two can disagree.

Count every time

Always correct, nothing to keep in sync.

Cost: three extra counting queries (likes, comments, reposts) for every page, on the busiest screen in the app, and a popular post means counting many rows.

The feed is read far more often than posts are liked, so we keep counters on posts, and the backend changes them in one atomic statement, UPDATE posts SET like_count = like_count + 1 WHERE id = ?, inside the same transaction that inserts the like. The database does the addition itself, so two likes arriving at the same moment both count (the race from chapter 1). For profile counts (followers, following) we do the opposite and count with count(*): a profile shows one user at a time and the index makes the count cheap. Chapter 6 caches those counts in Redis instead.

follows

CREATE TABLE follows (
    follower_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    followee_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (follower_id, followee_id),
    CONSTRAINT follows_not_self CHECK (follower_id <> followee_id)
);
-- The primary key answers "who does X follow?"; this index answers "who follows X?".
CREATE INDEX follows_followee_id_idx ON follows (followee_id);
  • The primary key is the pair (follower_id, followee_id) (a composite key). There is no separate id, because nothing ever needs to point at "follow number 7". The pair being unique means following twice is impossible, which lets the backend write INSERT … ON CONFLICT DO NOTHING: "follow" can be pressed twice safely. That property is called idempotency.
  • CHECK (follower_id <> followee_id): you can't follow yourself. A one-line rule that keeps silly rows out forever.
  • The extra index on followee_id. The primary key's index is sorted by follower_id first, so it answers "who does Bob follow?" quickly. It can't help with "who follows Alice?", which we need for follower counts and, in chapter 6, for pushing a new post to every follower. A second index sorted by followee_id answers that. The indexes section explains why the column order matters.

likes and reposts

CREATE TABLE likes (
    user_id    BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    post_id    BIGINT      NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, post_id)
);
CREATE INDEX likes_post_id_idx ON likes (post_id);

reposts has exactly the same shape (see the full file below). Same ideas as follows: the pair (user_id, post_id) is the key, so one like per person per post; the primary key index answers "which posts did Bob like?", and likes_post_id_idx answers "who liked post 42?" and makes deleting a post's likes fast. We keep the time of the like because "liked 5 minutes ago" lists and future features (most-liked this week) need it.

comments

CREATE TABLE comments (
    id         BIGSERIAL    PRIMARY KEY,
    post_id    BIGINT       NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
    author_id  BIGINT       NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    content    VARCHAR(280) NOT NULL,
    created_at TIMESTAMPTZ  NOT NULL DEFAULT now()
);
CREATE INDEX comments_post_id_id_idx ON comments (post_id, id);

A person may reply to the same post many times, so (author, post) can't be the key; each comment gets its own BIGSERIAL id. The index (post_id, id) is shaped for the only question we ask: "comments of post 42, oldest first". The database jumps to post 42 in the index and reads the comments already in order.

Why not a parent_comment_id for threaded replies?

Real threads (replies to replies) need a self-referencing foreign key, parent_id BIGINT REFERENCES comments (id), and queries that walk a tree (PostgreSQL can do that with WITH RECURSIVE). That is a nice extension, but one level of replies is enough for the core loop, so the MVP keeps it flat.

notifications

CREATE TABLE notifications (
    id           BIGSERIAL   PRIMARY KEY,
    recipient_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    actor_id     BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    type         VARCHAR(20) NOT NULL,
    post_id      BIGINT      REFERENCES posts (id) ON DELETE CASCADE,
    is_read      BOOLEAN     NOT NULL DEFAULT false,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT notifications_type_check CHECK (type IN ('LIKE', 'COMMENT', 'FOLLOW', 'REPOST'))
);
CREATE INDEX notifications_recipient_id_id_idx ON notifications (recipient_id, id DESC);
  • Two foreign keys to users: the recipient (who sees it) and the actor (who did it). A table may reference the same table several times, each with its own meaning.
  • post_id may be empty: "Bob followed you" is not about a post.
  • type with a CHECK: only the four values the app understands can be stored. PostgreSQL also has ENUM types; a VARCHAR plus CHECK is easier to extend (a new value is one changed constraint) and maps simply to a Java enum.
  • is_read powers the unread badge. The index (recipient_id, id DESC) serves "my 30 newest notifications".

The complete migration

Here is the whole file. In chapter 4 it goes into the backend project at exactly this path, and Flyway runs it automatically the first time the application starts.

-- V1: the whole MVP schema. Flyway runs this file once, in order, and records it in flyway_schema_history.

CREATE TABLE users (
    id            BIGSERIAL    PRIMARY KEY,
    username      VARCHAR(30)  NOT NULL UNIQUE,
    email         VARCHAR(254) NOT NULL UNIQUE,
    password_hash VARCHAR(100) NOT NULL,
    display_name  VARCHAR(50)  NOT NULL,
    bio           VARCHAR(160) NOT NULL DEFAULT '',
    created_at    TIMESTAMPTZ  NOT NULL DEFAULT now(),
    -- usernames are stored in lower case: letters, digits and underscores only
    CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,30}$')
);

CREATE TABLE posts (
    id            BIGSERIAL    PRIMARY KEY,
    author_id     BIGINT       NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    content       VARCHAR(280) NOT NULL,
    image_url     VARCHAR(500),
    like_count    INTEGER      NOT NULL DEFAULT 0,
    comment_count INTEGER      NOT NULL DEFAULT 0,
    repost_count  INTEGER      NOT NULL DEFAULT 0,
    created_at    TIMESTAMPTZ  NOT NULL DEFAULT now()
);
-- "Newest posts by this author" (profile pages and the home feed).
CREATE INDEX posts_author_id_id_idx ON posts (author_id, id DESC);

CREATE TABLE follows (
    follower_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    followee_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (follower_id, followee_id),
    CONSTRAINT follows_not_self CHECK (follower_id <> followee_id)
);
-- The primary key answers "who does X follow?"; this index answers "who follows X?".
CREATE INDEX follows_followee_id_idx ON follows (followee_id);

CREATE TABLE likes (
    user_id    BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    post_id    BIGINT      NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, post_id)
);
CREATE INDEX likes_post_id_idx ON likes (post_id);

CREATE TABLE reposts (
    user_id    BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    post_id    BIGINT      NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, post_id)
);
CREATE INDEX reposts_post_id_idx ON reposts (post_id);

CREATE TABLE comments (
    id         BIGSERIAL    PRIMARY KEY,
    post_id    BIGINT       NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
    author_id  BIGINT       NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    content    VARCHAR(280) NOT NULL,
    created_at TIMESTAMPTZ  NOT NULL DEFAULT now()
);
CREATE INDEX comments_post_id_id_idx ON comments (post_id, id);

CREATE TABLE notifications (
    id           BIGSERIAL   PRIMARY KEY,
    recipient_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    actor_id     BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    type         VARCHAR(20) NOT NULL,
    post_id      BIGINT      REFERENCES posts (id) ON DELETE CASCADE,
    is_read      BOOLEAN     NOT NULL DEFAULT false,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT notifications_type_check CHECK (type IN ('LIKE', 'COMMENT', 'FOLLOW', 'REPOST'))
);
CREATE INDEX notifications_recipient_id_id_idx ON notifications (recipient_id, id DESC);

Let the database protect your data

Every constraint above is a rule PostgreSQL enforces even if the application has a bug. Here is what happens when we break them on purpose. These statements were run against the schema above, with three users (alice = 1, bob = 2, carol = 3) and a few posts already inserted:

INSERT INTO users (username, email, password_hash, display_name) VALUES ('Alice!','a2@example.com','x','A');
INSERT INTO follows (follower_id, followee_id) VALUES (2,2);
INSERT INTO likes (user_id, post_id) VALUES (2,1);
INSERT INTO likes (user_id, post_id) VALUES (2,1);
INSERT INTO likes (user_id, post_id) VALUES (2,1) ON CONFLICT DO NOTHING;
INSERT INTO likes (user_id, post_id) VALUES (2,999);
ERROR:  new row for relation "users" violates check constraint "users_username_format"
DETAIL:  Failing row contains (4, Alice!, a2@example.com, x, A, , 2026-11-05 17:10:59.183835+00).
ERROR:  new row for relation "follows" violates check constraint "follows_not_self"
DETAIL:  Failing row contains (2, 2, 2026-11-05 17:10:59.184134+00).
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "likes_pkey"
DETAIL:  Key (user_id, post_id)=(2, 1) already exists.
INSERT 0 0
ERROR:  insert or update on table "likes" violates foreign key constraint "likes_post_id_fkey"
DETAIL:  Key (post_id)=(999) is not present in table "posts".

Read the results line by line: the badly formatted username and the self-follow are refused by CHECKs; the first like works (INSERT 0 1 means one row inserted); the second like hits the primary key; with ON CONFLICT DO NOTHING the same insert quietly does nothing (INSERT 0 0), which is how Chirp makes "like" safe to press twice; and a like on a post that doesn't exist breaks the foreign key.

Now the cascade. Deleting Alice removes her posts, and the like on her post goes with them:

DELETE FROM users WHERE username = 'alice';
SELECT count(*) AS posts_left FROM posts;
SELECT count(*) AS likes_left FROM likes;
DELETE 1
 posts_left
------------
          2
(1 row)

 likes_left
------------
          0
(1 row)

Cascades are powerful: choose them on purpose

One DELETE of a user can remove thousands of rows in other tables. That is what we want for a social app (an account deletion should take its content with it), but for data you must keep, such as payments or audit logs, use the default (NO ACTION, which refuses the delete) or ON DELETE SET NULL. Many products also "soft delete" accounts with a deleted_at column and clean up later.

Indexes: how the database finds rows fast

Without an index, the only way to find "posts by Alice" is to read every row of posts and keep the matching ones. With 300,000 posts that is 300,000 rows to look at, for every profile page view.

Analogy: the index at the back of a book

To find every page that mentions "PostgreSQL" you don't read the book; you look up "PostgreSQL" in the index, which is sorted alphabetically, and it lists the pages. A database index is the same: a separate, sorted structure (a B-tree) that maps column values to the rows that contain them. Because it is sorted, the database can jump straight to "author 46" instead of scanning.

Indexes are not free. Each one takes disk space and must be updated on every INSERT, UPDATE and DELETE, so we add one for each important query, not one per column. PostgreSQL creates an index automatically for every primary key and UNIQUE constraint. The others we create ourselves:

IndexServes the questionUsed by
posts_author_id_id_idx (author_id, id DESC)Newest posts by one authorProfile pages, the home feed
follows_pkey (follower_id, followee_id)Who does X follow?The home feed
follows_followee_id_idx (followee_id)Who follows X?Follower counts, pushing posts to followers (ch. 6)
likes_pkey (user_id, post_id)Which of these posts did X like?The ♥ state on every post
likes_post_id_idx, reposts_post_id_idxLikes/reposts of one postDeleting a post (the cascade must find them)
comments_post_id_id_idx (post_id, id)Comments of a post, oldest firstThe post page
notifications_recipient_id_id_idx (recipient_id, id DESC)My newest notificationsThe notifications page

Why the column order in an index matters

A composite index is sorted by its first column, then by the second within each first value, like a phone book sorted by surname, then first name. (author_id, id DESC) keeps each author's posts together, newest first. So "author 46, newest 20" is: jump to author 46, read 20 entries, stop. An index on (id, author_id) would be useless for that question, just as a phone book sorted by first name can't find all the "Smiths". This is also why follows needs two indexes: one starts with follower_id, the other with followee_id.

Seeing it work: EXPLAIN

EXPLAIN in front of a query asks PostgreSQL how it plans to run it, without running it; EXPLAIN ANALYZE runs it and reports the real time. To get realistic plans we filled a test database with 5,004 users, 250,002 follows and 300,006 posts, then asked for the newest 20 posts of one user (id 46):

EXPLAIN SELECT id, content FROM posts
WHERE author_id = 46 AND id < 9223372036854775807
ORDER BY id DESC LIMIT 20;
                                          QUERY PLAN
----------------------------------------------------------------------------------------------
 Limit  (cost=0.42..82.15 rows=20 width=19)
   ->  Index Scan using posts_author_id_id_idx on posts  (cost=0.42..245.62 rows=60 width=19)
         Index Cond: ((author_id = 46) AND (id < '9223372036854775807'::bigint))
(3 rows)

Index Scan using posts_author_id_id_idx: the database jumps to author 46 in our index and reads entries in order. Index Cond shows both conditions are answered by the index itself. Limit stops after 20 rows.

                                         QUERY PLAN
---------------------------------------------------------------------------------------------
 Limit  (cost=0.42..4036.13 rows=20 width=19)
   ->  Index Scan Backward using posts_pkey on posts  (cost=0.42..12107.54 rows=60 width=19)
         Index Cond: (id < '9223372036854775807'::bigint)
         Filter: (author_id = 46)
(4 rows)

We dropped posts_author_id_id_idx and asked again. PostgreSQL now walks the primary key backwards (newest post first) and throws away every row that isn't by author 46 (Filter), until it has found 20. This author has only about 60 posts among 300,006, so it reads a large part of the table to collect 20 of them. The estimated cost jumps from 82 to 4,036.

with the index:     Execution Time: 0.259 ms   0.165 ms   0.198 ms
without the index:  Execution Time: 7.760 ms   6.462 ms   7.308 ms

Measured on one laptop while writing this chapter, with the data described above; your numbers will differ. The difference grows with the table: without the index the work depends on how many posts exist; with it, on how many you ask for.

How to read an EXPLAIN plan

  • Read it from the most indented line outwards: inner steps feed rows to the outer ones.
  • Seq Scan reads the whole table. Index Scan uses an index then fetches rows. Index Only Scan finds everything it needs in the index alone (the cheapest).
  • cost=start..total is PostgreSQL's estimate in arbitrary units, useful for comparing plans, not as milliseconds. rows is how many rows it expects.
  • Index Cond is answered by the index; Filter means rows were read and then thrown away. A big Filter on a hot query is a sign that an index is missing.

The home feed plan

The same database, asked for user 46's home feed with the query from the next section:

                                            QUERY PLAN
---------------------------------------------------------------------------------------------------
 Limit  (cost=95.59..97.31 rows=20 width=8)
   ->  Index Scan Backward using posts_pkey on posts p  (cost=95.59..12952.73 rows=150033 width=8)
         Index Cond: (id < '9223372036854775807'::bigint)
         Filter: ((author_id = 46) OR (ANY (author_id = (hashed SubPlan 1).col1)))
         SubPlan 1
           ->  Index Only Scan using follows_pkey on follows f  (cost=0.42..95.05 rows=50 width=8)
                 Index Cond: (follower_id = 46)
(7 rows)

First, the inner step (SubPlan 1) reads the 50 people user 46 follows straight from the follows primary key index (an Index Only Scan). PostgreSQL puts them in an in-memory hash set. Then it walks all posts newest first and keeps each one whose author is in that set, stopping at 20. Here every user follows 50 people who post often, so 20 matches come quickly. If the people you follow rarely post, the walk gets long. That weakness of "build the feed when it is read" is one reason chapter 6 builds feeds in advance.

Try it: build Bob's home feed by hand

Below is a tiny copy of our database: four users, a few follows and seven posts. Step through what the feed query does for Bob (user 2), with a page size of 3. Change who Bob follows and run it again: the result changes with the follows rows.

Mini database: the home feed queryInteractive
Bob follows:

follows

follower_idfollowee_id

users

idusername

posts

idauthor_idcontent

The real queries the app will run

A schema is only good if it answers the app's questions quickly. Here are the three most important ones, taken from the backend code you will write in chapter 4.

1. The home feed

/** The home feed: ids of my posts and posts by people I follow, newest first. */
@Query(value = """
        SELECT p.id FROM posts p
        WHERE p.id < :cursor
          AND (p.author_id = :userId
               OR p.author_id IN (SELECT f.followee_id FROM follows f WHERE f.follower_id = :userId))
        ORDER BY p.id DESC
        LIMIT :limit
        """, nativeQuery = true)
List<Long> findFeedIds(long userId, long cursor, int limit);
  1. SELECT p.id FROM posts p: we fetch only ids here; a second query loads the full posts and their authors. Keeping the "which posts?" step small makes it fast and lets chapter 6 replace it with Redis without touching the rest.
  2. p.id < :cursor: only posts older than the last one on screen. For the first page the backend passes the largest possible number.
  3. p.author_id = :userId OR p.author_id IN (SELECT f.followee_id …): my own posts, or posts by anyone in the list of people I follow. The inner SELECT is a subquery, answered from the follows primary key.
  4. ORDER BY p.id DESC LIMIT :limit: newest first, one page only.

The :userId placeholders are not string concatenation

Values are sent to PostgreSQL separately from the SQL text (a prepared statement), so a username like '; DROP TABLE users; -- is just a strange name, never code. Never build SQL by gluing user input into a string.

2. "Which of these posts did I like?"

Every post on screen shows a filled ♥ if you liked it. Asking once per post would mean 20 queries per page (the "N+1 queries" problem). Instead we ask once for the whole page:

/** Which of these posts has the user liked? One query for a whole page of posts. */
public Set<Long> findLikedPostIds(long userId, Collection<Long> postIds) {
    if (postIds.isEmpty()) return Set.of();
    return new HashSet<>(jdbc.sql("SELECT post_id FROM likes WHERE user_id = :userId AND post_id IN (:postIds)")
            .param("userId", userId)
            .param("postIds", postIds)
            .query(Long.class)
            .list());

post_id IN (:postIds) receives the 20 ids of the page. Because the primary key of likes starts with user_id, PostgreSQL jumps to "my likes" in the index and checks the 20 ids there.

3. Follower and following counts

public long countFollowers(long userId) {
    return jdbc.sql("SELECT count(*) FROM follows WHERE followee_id = ?").param(userId).query(Long.class).single();
}
public long countFollowing(long userId) {
    return jdbc.sql("SELECT count(*) FROM follows WHERE follower_id = ?").param(userId).query(Long.class).single();
}

The first count uses follows_followee_id_idx, the second the primary key. Without the extra index, counting someone's followers would scan the whole follows table.

Pagination: why "load more" uses a cursor

A feed can't send every post at once, so we send pages of 20. There are two ways to ask for "the next page":

Offset: "skip 40, give me 20"

SELECT * FROM posts
ORDER BY id DESC
LIMIT 20 OFFSET 40;

To skip 40 rows the database still has to find them and throw them away. Page 500 means walking past 10,000 rows first, so deep pages get slower and slower.

Cursor (keyset): "older than post 4,812"

SELECT * FROM posts
WHERE id < 4812
ORDER BY id DESC
LIMIT 20;

The index jumps straight to 4,812 and reads 20 entries. Page 500 costs the same as page 1.

Speed is only half the story. Suppose you have read the first 20 posts and, while you scroll, 3 new posts arrive at the top. With offsets, "skip 20" now skips the 3 new posts plus 17 old ones, so 3 posts you already saw appear again on page 2. Delete a post instead and one you never saw is skipped. A cursor says "older than the last post I saw", so new or deleted posts at the top can't shift the pages.

That is why the feed and profile pages use cursors (the API returns nextCursor). Comments use classic page numbers in chapter 4 on purpose, so you see both: page numbers are still the right choice when people want "page 3 of 7" and the list doesn't change much while they read.

Create the database

You don't need to install PostgreSQL. Docker runs it in a container. In the chirp folder from chapter 1, create compose.yaml:

# Development services. Start them with:  docker compose up -d
services:
  postgres:
    image: postgres:18-alpine
    environment:
      POSTGRES_DB: chirp
      POSTGRES_USER: chirp
      POSTGRES_PASSWORD: chirp
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql

volumes:
  pgdata:

The volumes entry keeps the data in a named Docker volume, so it survives restarts of the container. PostgreSQL 18 images store their data under /var/lib/postgresql, which is why the volume is mounted there. Start it:

docker compose up -d

The tables are created by Flyway when the Spring Boot app starts in chapter 4: it finds V1__create_schema.sql, runs it once, and records that in a table called flyway_schema_history. You can also paste the SQL into psql now to explore. Open a psql shell inside the container and list the tables:

docker compose exec postgres psql -U chirp -d chirp
\dt
             List of tables
 Schema |     Name      | Type  | Owner
--------+---------------+-------+-------
 public | comments      | table | chirp
 public | follows       | table | chirp
 public | likes         | table | chirp
 public | notifications | table | chirp
 public | posts         | table | chirp
 public | reposts       | table | chirp
 public | users         | table | chirp
(7 rows)

(After chapter 4 you will also see flyway_schema_history in this list.) \d posts describes one table, including its indexes and every foreign key that points at it:

                                        Table "public.posts"
    Column     |           Type           | Collation | Nullable |              Default
---------------+--------------------------+-----------+----------+-----------------------------------
 id            | bigint                   |           | not null | nextval('posts_id_seq'::regclass)
 author_id     | bigint                   |           | not null |
 content       | character varying(280)   |           | not null |
 image_url     | character varying(500)   |           |          |
 like_count    | integer                  |           | not null | 0
 comment_count | integer                  |           | not null | 0
 repost_count  | integer                  |           | not null | 0
 created_at    | timestamp with time zone |           | not null | now()
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)
    "posts_author_id_id_idx" btree (author_id, id DESC)
Foreign-key constraints:
    "posts_author_id_fkey" FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE CASCADE
Referenced by:
    TABLE "comments" CONSTRAINT "comments_post_id_fkey" FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE
    TABLE "likes" CONSTRAINT "likes_post_id_fkey" FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE
    TABLE "notifications" CONSTRAINT "notifications_post_id_fkey" FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE
    TABLE "reposts" CONSTRAINT "reposts_post_id_fkey" FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE

Notice that BIGSERIAL became bigint with a default of nextval('posts_id_seq'): it is shorthand for "a bigint filled from a sequence". Leave psql with \q.

Migrations: changing the schema safely

A migration is a numbered SQL file that moves the schema one step forward. Flyway runs every file whose version it hasn't seen yet, in order, and remembers a checksum of each one. Two rules follow:

  • Never edit a migration that has already run anywhere that matters. Flyway would notice the checksum changed and refuse to start, and other databases would never get your edit.
  • Every change is a new file. In chapter 6 we add search indexes in V2__search_indexes.sql while V1 stays exactly as it is.

That is also why application.yml in chapter 4 sets Hibernate to ddl-auto: validate: Flyway owns the schema, and Hibernate only checks that the Java classes match it.

Common mistakes

Storing lists in one column ("1,4,9" of followed ids)

It looks simple, but the database can't index inside the text, can't check that the ids exist, and "who follows user 4?" needs a scan of every user plus text parsing. Two people following at the same moment can also overwrite each other's change.

Fix: a join table with one row per pair, like follows.

No unique key on likes

With an extra id and no UNIQUE (user_id, post_id), a double-click or a retried request stores two likes, and counts drift away from reality.

Fix: make the pair the primary key and insert with ON CONFLICT DO NOTHING.

Forgetting the index for the "other direction"

A composite primary key only helps queries that start with its first column. "Who follows Alice?" on follows (follower_id, followee_id) alone becomes a full table scan.

Fix: add an index for each direction you query (follows_followee_id_idx), and check with EXPLAIN.

Times as text, numbers or TIMESTAMP without a time zone

Text sorts wrongly ("10:00" before "9:00"), numbers hide the unit, and a plain TIMESTAMP means different moments on servers in different time zones.

Fix: TIMESTAMPTZ everywhere, defaulting to now().

Updating counters in application code

"Read like_count, add one in Java, save it" loses likes under concurrent requests.

Fix: UPDATE posts SET like_count = like_count + 1, in the same transaction as the insert into likes.

Editing a migration that already ran

Flyway refuses to start because the file's checksum no longer matches, and teammates' databases never get the change.

Fix: leave old migrations alone and add V2__…sql. On your own throwaway database you can instead drop it and start fresh (docker compose down -v deletes the volume).

Cascades you didn't intend

ON DELETE CASCADE copied onto every foreign key can wipe data you meant to keep when a single parent row is deleted.

Fix: decide per relationship: cascade for content that has no meaning without its parent (likes of a post), refuse or SET NULL for records you must keep.

Key takeaways

  • One kind of thing per table; connections between things (follows, likes, reposts) get join tables.
  • Primary keys identify rows; foreign keys connect them and are checked by the database.
  • Increasing BIGSERIAL ids give us "newest first" and cursor pagination for free.
  • Constraints (UNIQUE, CHECK, composite keys) enforce product rules even when the code has a bug.
  • Indexes are sorted copies of columns; create one per important query, mind the column order, and confirm with EXPLAIN.
  • Denormalised counters make the feed cheap, as long as they change atomically with the rows they count.
  • Schema changes are new migration files; applied migrations never change.

Check your understanding

Why is the primary key of likes the pair (user_id, post_id) rather than a separate id column?

  1. Composite keys use less disk space
  2. It makes a second like by the same person on the same post impossible
  3. Foreign keys only work with composite keys
The primary key must be unique, so the same (user, post) pair can't be stored twice. That is the database enforcing "one like per person per post", and it lets the backend use ON CONFLICT DO NOTHING to make liking idempotent.

The follows table has the primary key (follower_id, followee_id). Which question needs the extra index follows_followee_id_idx?

  1. Who does Bob follow?
  2. Does Bob follow Alice?
  3. Who follows Alice?
The primary key is sorted by follower_id first, so it answers questions that start from the follower (1 and 2). "Who follows Alice?" starts from the followee, so it needs an index sorted by followee_id.

An EXPLAIN plan shows Filter: (author_id = 46) under a scan of a large table. What does that suggest?

  1. Rows are read and then thrown away, so an index on author_id may be missing
  2. The query is using the best possible index
  3. The table has no primary key
Filter means the condition was checked row by row after reading. When the condition is selective and the query is frequent, an index (here posts_author_id_id_idx) lets PostgreSQL find the rows directly, which shows up as Index Cond instead.

You have read the first page of your feed (20 posts) and 5 new posts arrive. You press "load more". With OFFSET 20, what happens?

  1. You get exactly the next 20 older posts
  2. 5 posts you already saw appear again
  3. The 5 new posts appear on page 2
The 5 new posts push everything down by 5, so "skip 20" now skips the 5 new ones and only 15 of the ones you saw; the last 5 you saw come back. A cursor ("older than the last id I saw") doesn't have this problem.

Exercise: let users block each other

Users want to block someone so that person's posts never appear in their feed. Design a blocks table: columns, types, primary key, constraints, indexes and delete behaviour. Then write how the home feed query would change.

Show a sample answer
CREATE TABLE blocks (
    blocker_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    blocked_id BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (blocker_id, blocked_id),
    CONSTRAINT blocks_not_self CHECK (blocker_id <> blocked_id)
);
-- "Who has blocked me?" (to hide my posts from them, or theirs from me)
CREATE INDEX blocks_blocked_id_idx ON blocks (blocked_id);

It has the same shape as follows: a pair as the key (no double blocks), no self-block, and an index for the reverse direction. In the feed query, add AND p.author_id NOT IN (SELECT b.blocked_id FROM blocks b WHERE b.blocker_id = :userId). Usually blocking also removes the follow in both directions, which the backend would do in the same transaction.

Finished this chapter? Tick it off. Progress is saved in this browser only.