Sub topic 2
Modeling users, posts and follow edges
This chapter defines the three core entities of a news feed: users, posts and follow edges. Every later choice rests on them: fan-out on read, fan-out on write, the hybrid approach, pagination and the feed cache. A weak model here makes each of those harder.
You should already know basic SQL (primary keys, secondary indexes, joins), how a key-value store behaves, and how to read short Python snippets. The chapter on requirements and load estimates comes before this one. Its numbers appear here only as examples.
What the model must support
A data model is only good relative to the queries it has to answer. A feed needs these access patterns:
| Access pattern | Used by | Frequency |
|---|---|---|
| Latest posts by one author | Fan-out on read, hybrid pull path, profile page | Very high |
| All followees of a user | Fan-out on read | Very high |
| All followers of an author | Fan-out on write | One per post written |
| Does A follow B? | Privacy checks, follow button | High |
| Fetch posts by a list of IDs | Hydrating a cached timeline | Very high |
| Follower count of an author | Choosing push or pull in the hybrid design | Every write |
Two of these queries run in opposite directions over the same edges. "Who does A follow?" and "who follows B?" both scan the follow graph. The model has to answer both quickly.
The relational baseline
Start with a relational schema, because it is the clearest way to state the constraints. Later sections discuss when parts of it move to other stores.
CREATE TABLE users (
user_id BIGINT PRIMARY KEY,
handle TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
is_private BOOLEAN NOT NULL DEFAULT false,
follower_count BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE posts (
post_id BIGINT PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES users (user_id),
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
deleted_at TIMESTAMPTZ
);
-- Serves "latest posts by author" and keyset pagination.
CREATE INDEX posts_author_created_idx
ON posts (author_id, created_at DESC, post_id DESC);
CREATE TABLE follows (
follower_id BIGINT NOT NULL REFERENCES users (user_id),
followee_id BIGINT NOT NULL REFERENCES users (user_id),
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'pending')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (follower_id, followee_id),
CHECK (follower_id <> followee_id)
);
-- Reverse direction: "who follows X?"
CREATE INDEX follows_followee_idx
ON follows (followee_id, follower_id);
CREATE TABLE blocks (
blocker_id BIGINT NOT NULL REFERENCES users (user_id),
blocked_id BIGINT NOT NULL REFERENCES users (user_id),
PRIMARY KEY (blocker_id, blocked_id)
);The sections below explain the choices that matter.
Users
The users table is small and read-heavy. Three decisions deserve attention.
- Numeric primary key.
user_idis a 64-bit integer, not the handle. Handles can change, and an integer key makes every join, cache key and shard key cheaper. - Privacy flag.
is_privatedecides whether a follow takes effect immediately or waits for approval. The feed pipeline checks it, so it belongs on the user record. - Denormalized follower count.
follower_countis a counter kept next to the user. The hybrid design (a later chapter) asks "does this author have more than N followers?" on every write. RunningCOUNT(*)over the follow edges each time would be far too slow.
Keep the counter approximate and update it asynchronously. A count that is off by a few for a minute does not hurt the feed, because the hybrid threshold is a coarse decision. An exact count would force a hot write on the user row each time someone follows a popular account.
Posts
A post is immutable in the way that matters most to the feed: its post_id and created_at never change. Text edits are possible, but they must not move the post in anyone's timeline.
The feed pipeline stores and moves references, not bodies. A timeline entry is (timestamp, post_id). The reader fetches bodies in a second step, which is called hydration. That has three consequences:
- Edits and deletions take effect without rewriting millions of timelines.
- Timeline entries stay small, so more of them fit in memory.
- The posts table must support fast lookup by
post_id, which the primary key already does.
Choosing post IDs
Post IDs have a second job: they break ties. Two posts can share a created_at value, and pagination needs a strict total order. Pairing the timestamp with the ID gives you one.
A better approach is to make the ID itself time-sortable. A Snowflake-style ID packs a millisecond timestamp, a worker number and a per-millisecond sequence into 64 bits. Sorting by ID then approximates sorting by time, and IDs can be generated on many machines without coordination.
import threading
import time
EPOCH_MS = 1_700_000_000_000 # custom epoch, in milliseconds
WORKER_BITS = 10
SEQUENCE_BITS = 12
MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1
class IdGenerator:
"""64-bit time-sortable IDs: 41 bits time | 10 bits worker | 12 bits sequence."""
def __init__(self, worker_id):
if not 0 <= worker_id < (1 << WORKER_BITS):
raise ValueError("worker_id out of range")
self.worker_id = worker_id
self.last_ms = -1
self.sequence = 0
self.lock = threading.Lock()
@staticmethod
def _now_ms():
return int(time.time() * 1000)
def next_id(self):
with self.lock:
now = max(self._now_ms(), self.last_ms) # never go backwards
if now == self.last_ms:
self.sequence = (self.sequence + 1) & MAX_SEQUENCE
if self.sequence == 0: # sequence exhausted: wait for next ms
while now <= self.last_ms:
now = self._now_ms()
else:
self.sequence = 0
self.last_ms = now
return ((now - EPOCH_MS) << (WORKER_BITS + SEQUENCE_BITS)) \
| (self.worker_id << SEQUENCE_BITS) | self.sequence
gen = IdGenerator(worker_id=7)
ids = [gen.next_id() for _ in range(5)]
assert ids == sorted(ids) and len(set(ids)) == 5
print(ids)IDs from different workers are only roughly ordered by time, because machine clocks differ by a few milliseconds. That is acceptable for a feed. Strict ordering across workers would need coordination, which costs more than it gains.
The follow graph
The follow relationship is a directed graph. An edge from A to B means "A follows B". It is not symmetric. A can follow B without B following A. Friend systems with mutual approval are a different model, and you can build them from two directed edges.
One edge, two directions
The follows table has a composite primary key (follower_id, followee_id). That key serves the forward query ("whom does A follow?") as an index range scan and prevents duplicate edges. The second index on (followee_id, follower_id) serves the reverse query ("who follows B?").
| Query | Index used | Needed by |
|---|---|---|
| Followees of A | Primary key prefix `follower_id` | Fan-out on read |
| Followers of B | `follows_followee_idx` prefix `followee_id` | Fan-out on write |
| Does A follow B? | Primary key, full match | Privacy and follow button |
Both directions cost write amplification: each follow touches the table and both indexes. At large scale, teams often store the two directions as separate datasets in a key-value store, each keyed by one user. This is called an adjacency list. It makes sharding simple, because each list lives on one node. The price is that the two copies can disagree after a partial failure, so you need a repair job or a single transactional write path.
Sizing the graph
An example estimate: 100 million users who follow 150 accounts on average give 15 billion edges. At about 40 bytes per edge including index overhead, one direction takes roughly 600 GB. Two directions take about 1.2 TB. That is too big for one comfortable relational node, but it is easy to shard by user ID. The post table grows more slowly. At 20 million posts per day and 300 bytes per post, expect about 6 GB per day, or about 2.2 TB per year.
The average hides the skew. A few accounts have tens of millions of followers, and their follower lists are huge. Reading such a list in full to fan out one post is the exact problem the hybrid chapter solves. For now, make sure the follower list can be read in pages, not as a single result.
from collections import defaultdict
followees = defaultdict(set) # user -> accounts they follow
followers = defaultdict(set) # account -> users who follow it
def follow(follower_id, followee_id):
if follower_id == followee_id:
raise ValueError("cannot follow yourself")
if followee_id in followees[follower_id]:
return False # idempotent: a repeated request changes nothing
followees[follower_id].add(followee_id)
followers[followee_id].add(follower_id)
return True
def unfollow(follower_id, followee_id):
followees[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(followees[1])) # [2]The follow function returns False for a repeated request. That matters because clients retry, and a retry must not double-count follower_count or write a duplicate edge.
Pending follows and private accounts
For a private account, a follow request creates an edge with status = 'pending'. Only active edges count as follows. Every query that expands followers or followees must filter on status. A forgotten filter leaks private posts to people who were never approved, which is a privacy bug and not just a data bug.
Blocks and mutes
Blocks are a separate table, not a status on follows. A block applies in both directions of visibility: the blocked user cannot see the blocker's posts, and the blocker does not see theirs. It also removes any follow edge between the two. Keeping blocks separate gives you a small table that every read path can check cheaply, and the follow graph stays a pure record of intent.
Muting is lighter. A mute hides an author from the muter's feed without any visible change to the author. You can model it as another table with the same shape as blocks, or as a column on follows. The feed treats both as filters applied when the timeline is read. The edge-cases chapter returns to when filtering happens.
Where each piece lives
One database does not have to hold everything. A common split:
| Data | Typical store | Reason |
|---|---|---|
| Users, handles | Relational database | Strong uniqueness, low volume |
| Posts | Sharded relational or wide-column store | Large, append-mostly, lookup by ID |
| Follow edges | Sharded adjacency lists or relational table | Two-direction lookups at high volume |
| Timelines | In-memory key-value store | Bounded lists, very fast reads (later chapter) |
| Counters | Cache with asynchronous write-back | Hot, tolerant of small errors |
Timelines are derived data. You can rebuild them from posts and follow edges, so the first three rows are the source of truth. Treat everything else as a cache that you may lose.
Common errors
- Missing reverse index. Without an index on
followee_id, fan-out on write scans the whole table for every post. This works in a test and fails at scale. - Putting the whole post in the timeline. Copying bodies into every follower's timeline multiplies storage by the follower count and makes edits and deletes unmanageable.
- Sorting by
created_atalone. Ties make pagination skip or repeat posts. Always addpost_idas a tiebreaker. - Hard deletes. Removing a post row breaks timeline references that still point to it. A
deleted_atcolumn lets the reader skip the entry cleanly. Cleanup can follow later. - Using
COUNT(*)for follower counts on every request instead of a maintained counter. - Ignoring edge status. Treating
pendingedges as active exposes private content. - Unbounded follower reads. Loading all of a popular author's followers into memory at once will exhaust a worker.
How this model feeds the next chapters
The model makes each strategy cheap or expensive in a specific way:
- Fan-out on read uses
followsforward, then theposts_author_created_idxindex once per followee, then merges the results. It writes nothing extra but reads a lot. - Fan-out on write uses
followsin reverse once per post, then writes a small reference into each follower's timeline. Posting is expensive, and reading is a single lookup. - The hybrid approach uses
follower_countto decide which of the two paths an author takes. - Pagination uses
(created_at, post_id)as its cursor, which is why the composite index on posts has that shape.
Exercise
A user with 40 million followers posts once. Using the schema in this chapter, which index does a fan-out-on-write job use to find the recipients, and what two precautions should the job take when reading from it?
Show answer
It uses followsfolloweeidx on (followeeid, followerid), which returns all followers of the author as an ordered range scan. The job should read the followers in pages (for example by keyset on follower_id) instead of loading all 40 million at once, and it should only include rows with status = 'active' so pending requests to a private account do not receive the post. It should also skip any follower with a block in either direction.
Exercise
Why does the follow function in this chapter return False when the edge already exists, and what could go wrong if it did not?
Show answer
It makes the operation idempotent. Clients and queues retry requests, so the same follow can arrive twice. Without the check, a retry could insert a duplicate edge, or increment follower_count a second time, which leaves the counter inflated and can push an account over the celebrity threshold too early.