AlgoViz

Design a news feed like Facebook's

hard 50 min

Show each person the best recent posts from everyone they follow, in a fifth of a second.

Grow the design

Start with the smallest system that works. Change it only when something breaks.

Version by version

From one query to the full system

Seven versions

Version 1: One service, one database

Forced by: The features: post, and read what your friends posted.

Our systemUsersOne servicePostgreSQL
What changes
Posts and follows are two tables. A feed is a join: posts whose author I follow, newest first, limit 20. Add a standby, because posts must not be lost.
What it costs
Almost nothing. One thing to run.
What breaks next
Every read gathers from 500 accounts. At 231,000 reads a second that is 116 million small reads. At a few hundred reads a second, stop here.

Say: Let me get a correct feed first, then see which number it cannot meet.

Architecture

High-level design

The whole system

People reach a CDN for photos and video, and a gateway for everything else. Reads go to the feed service, which holds recent posts of big accounts in memory, reads ready feeds from Redis, asks the ranking service and reads posts from a post cache in front of Cassandra. Writes go to the post service, Cassandra and Kafka; fan-out workers ask the follow graph and write into Redis; a hint service tells connected people that new posts exist. Photos are stored in S3.
Blue is reading, pink is writing, orange happens later.

Four layers

  1. 1

    Edge

    A CDN serves photos, video and scripts. The nearest region is chosen by DNS. Personal feed replies are never cached there.

  2. 2

    Gateway

    Sign-in checks with cached keys, rate limits, routing to feed or post services. Any instance can serve any user.

  3. 3

    Services

    Feed (gather, merge, filter, assemble), ranking (score), post (validate, store), graph (follows and blocks), hint (open streams). The first three keep no user state.

  4. 4

    Data

    Redis for ready feeds, a post cache, Cassandra for posts and edges, PostgreSQL for accounts, Kafka for events, S3 for media.

Flows

The three flows

Flow 1: open the feed

Later pages use the stored order and go straight to filter and hydrate.

Flow 2: create a post

The position is committed after the writes, so a crash repeats work instead of losing it.

Flow 3: a hint

Step through each flow, the fan-out decision, the ranking passes and the failures in Visualize.