Sub topic 2
Modeling users, posts and follow edges
This chapter assumes you know basic SQL, how a key-value store works, and how to read short Python snippets. It defines the three entities every feed design builds on, and shows the access patterns that decide how you store them.
Start from the queries
A data model for a feed should follow from the questions the system must answer fast. There are four:
- Given a user, who do they follow?
- Given an author, who follows them (needed to push posts to followers)?
- Given an author, what are their recent posts?
- Given a list of post ids, what are the post bodies and authors?
Both fan-out strategies in the next chapters are built from these four lookups. Fan-out on read leans on queries 1 and 3. Fan-out on write leans on queries 2 and 4.
The three core entities
| Entity | Key fields | Notes |
|---|---|---|
| User | `user_id`, `handle`, `is_private`, `follower_count` | Small, read often, changes rarely. |
| Post | `post_id`, `author_id`, `created_at`, `body`, `deleted_at` | Append-heavy. Rarely edited. |
| Follow edge | `follower_id`, `followee_id`, `created_at` | Directed. A follows B does not mean B follows A. |
A few choices matter here:
- Post ids should be roughly time-ordered. Snowflake-style 64-bit ids (timestamp bits, then a machine id, then a sequence number) sort by creation time and can be generated on many machines without coordination. Time-ordered ids also make
(created_at, post_id)a unique, total sort key, which the pagination chapter relies on. - Soft-delete posts with a
deleted_atcolumn. Copies of the post id already sit in many timelines, so you need a flag readers can check. Edge cases are covered in a later chapter. - Keep
follower_counton the user row. Counting edges on demand is expensive. The count is also what a hybrid design uses to decide whether an author counts as high-follower.
Storing the follow graph in both directions
The follow graph is queried from two sides, so store it twice. One table answers "who does A follow?" and the other answers "who follows B?".
CREATE TABLE users (
user_id BIGINT PRIMARY KEY,
handle TEXT NOT NULL UNIQUE,
is_private BOOLEAN NOT NULL DEFAULT FALSE,
follower_count BIGINT NOT NULL DEFAULT 0
);
CREATE TABLE posts (
post_id BIGINT PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES users (user_id),
created_at TIMESTAMP NOT NULL,
body TEXT NOT NULL,
deleted_at TIMESTAMP
);
-- Query 3: recent posts by an author, newest first.
CREATE INDEX posts_by_author ON posts (author_id, created_at DESC, post_id DESC);
-- Query 1: who does this user follow?
CREATE TABLE following (
follower_id BIGINT NOT NULL,
followee_id BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (follower_id, followee_id)
);
-- Query 2: who follows this author?
CREATE TABLE followers (
followee_id BIGINT NOT NULL,
follower_id BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (followee_id, follower_id)
);Both tables hold the same edges with the key order swapped. The primary key of each table makes its main lookup a single index range scan. A follow or unfollow must write to both tables and adjust follower_count. If those writes are not in one transaction, or are on different shards, the two copies can drift apart, so plan for repair jobs that compare them.
The posts_by_author index lets query 3 read the newest rows for one author without sorting.
Relational store or key-value store?
The same model can live in either kind of store. The choice depends on scale and on the queries you need.
- Relational database. Foreign keys, transactions and ad hoc queries come for free. It works well for the first tens of millions of users. Beyond a single machine you must shard it yourself.
- Key-value or wide-column store. Each edge becomes a row keyed by
(user_id, other_id). This scales out horizontally and suits the follow graph, which is only ever read by prefix. You lose joins and multi-row transactions.
A common split is relational storage for users, key-value storage for edges and timelines, and an object store or blob service for media. Only a media URL is kept in the post row.
Reading the model in code
The next snippet shows the follow graph in memory. It has the same two-sided shape as the tables above.
from collections import defaultdict
following = defaultdict(set) # follower_id -> set of followee ids
followers = defaultdict(set) # followee_id -> set of follower ids
def follow(follower_id, followee_id):
if follower_id == followee_id:
raise ValueError("cannot follow yourself")
following[follower_id].add(followee_id)
followers[followee_id].add(follower_id)
def unfollow(follower_id, followee_id):
following[follower_id].discard(followee_id)
followers[followee_id].discard(follower_id)
follow(1, 2)
follow(3, 2)
print(sorted(followers[2])) # [1, 3]
print(sorted(following[1])) # [2]Using sets makes repeat follows harmless. Following twice leaves one edge, which matches the composite primary key in SQL.
Common errors
- Storing only one direction. Fan-out on write then has to scan the whole
followingtable to find an author's followers. - Auto-increment ids on a sharded database. Ids collide or lose time order. Use time-ordered generated ids.
- Copying post bodies into timelines. Timelines should hold only references. Bodies are fetched by id so that edits and deletes take effect in one place.
- Ignoring skew. Most users have tens of followers. A few have millions. A model that treats them the same will fail on the few, and the hybrid chapter addresses this.
How the pieces connect
Exercise
A user unfollows an author. Which tables and counters must change, and what goes wrong if only the following table is updated?
Show answer
Delete the edge from both following and followers, and decrement the author's follower_count. If only following changes, the followers table still lists the user, so the author's future posts are still pushed into that user's timeline and the follower count stays too high.
Exercise
Why is (created_at, post_id) a better sort key for posts than created_at alone?
Show answer
Two posts can have the same timestamp. Adding the unique post_id makes the order total and deterministic, so a cursor pointing at one post never skips or repeats another post with the same timestamp.