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.

API and data

The contract first, then the data that serves it.

Entities

Name the things first

User, Follow (who follows whom, and since when), Post (author, text, media, audience, status), Reaction, and Feed session (one ranked visit). The viewer and author come from the sign-in token, never from the request body. More on that in API authentication.

HTTP
GET /v1/feed?limit=20GET /v1/feed?cursor=eyJzIjoi...&limit=20→ 200 { "posts": [ { "id": "8841", "author": { "id": "u456", "name": "Asha" },          "text": "Hello world!", "media": [ { "type": "image", "url": "..." } ],          "reactions": { "like": 42, "love": 10 }, "comment_count": 5,          "created_at": "2026-01-15T10:30:00Z" } ],        "next_cursor": "eyJzIjoi...", "has_more": true }POST /v1/media/upload-url{ "content_type": "image/jpeg", "size": 2048000 }→ 200 { "upload_url": "...", "media_id": "m_abc", "expires_in": 900 }POST /v1/posts                 Idempotency-Key: <client uuid>{ "text": "Hello world!", "media_ids": ["m_abc"], "audience": "friends" }→ 201 { "id": "8841" }         or 202 while media is still processingPOST   /v1/posts/{id}/reactions   { "kind": "like" }DELETE /v1/posts/{id}          → 204GET    /v1/posts/{id}          → 200, 403 or 404GET    /v1/feed/stream         (server-sent events)event: new_postsdata: { "count": 5 }
Read a feed, create a post, react, delete, listen for hints.

Status codes

CodeMeaning here
200 OKRead worked
201 CreatedPost stored
202 AcceptedMedia still processing; published when ready
400 Bad RequestBad field, or a cursor that has expired: start again
401 UnauthorizedNot signed in
403 ForbiddenSigned in, not allowed
404 Not FoundDeleted, or hidden from this viewer
429 Too Many RequestsOver a limit, with Retry-After
500 and 503Our fault, with an incident ID

API decisions

  1. Interviewer

    Why a cursor, and what is in it?

  2. You

    New posts push everything down, so offsets repeat posts. The cursor is opaque and signed. It holds a feed session and a position.

    • The first request ranks once and stores 100 post IDs for ten minutes.
    • Later pages read the next 20 IDs of that stored order.
    • When it expires, the reply says so and the client starts a new visit.
    • Filters still run on every page, so a deleted post never returns.
  3. Interviewer

    Posts with photos?

  4. You

    The client uploads straight to object storage with a short-lived signed address, then creates the post with media IDs. We check the media belongs to the author and is ready. See file upload APIs.

  5. Interviewer

    How do you version this, and limit it?

  6. You

    Path versions, additive changes, at least six months of warning before removal, and 410 Gone afterwards. Clients can name features they understand. Limits are sliding windows by user:

    • Feed reads 100 a minute; background refresh 1 a minute.
    • Posts 10 an hour, comments 30 a minute, reactions 60 a minute, uploads by size.
    • 429 with Retry-After; the app keeps showing its saved page.
    • Very regular request patterns are flagged for review.
  7. Interviewer

    REST or GraphQL?

  8. You

    Either. A feed page is many shapes of post, so a query language saves fields and round trips on mobile. I would keep the same services behind it. See REST, GraphQL and gRPC.

Database

Data model

What is stored

The follow edge is stored twice, once for each question: whom do I follow, and who follows me.

Why each store

DataStoreWhyAlternatives
PostsCassandra, or any partitioned storeLookups by post ID, appends by author, 2.2 PBSharded MySQL
Follow edgesPartitioned tables plus a cacheOnly one step is needed: my follows, my followersGraph database for friends of friends
Ready feedsRedis sorted setsInsert by time, read the top, no duplicatesPacked lists in Memcached
Post cacheRedis or Memcached14M lookups a second at peakMore replicas of the store
Accounts, sign-inPostgreSQLTransactions, not on the hot pathMySQL
EventsKafkaKeeps events, replays after a faultPulsar, Kinesis
MediaS3 and a CDNLarge, written once, read oftenAny object store
MeasurementsA column storeAppend, then aggregateCassandra with batch jobs
SQL
CREATE TABLE posts (  post_id   bigint PRIMARY KEY,  author_id bigint,  kind      text,          -- text, photo, video, link  body      text,  media     list<text>,  audience  text,          -- public, friends, custom, only_me  list_id   bigint,        -- for custom audiences  place     text,  feeling   text,  tagged    set<bigint>,  status    text,          -- active, restricted, review, removed, deleted  edited_at timestamp);CREATE TABLE author_posts (  author_id bigint,  month     text,          -- keeps one partition small  post_id   bigint,  PRIMARY KEY ((author_id, month), post_id)) WITH CLUSTERING ORDER BY (post_id DESC);CREATE TABLE followers (  target_id bigint,  bucket    int,           -- 0..n, so 100M followers are not one row group  user_id   bigint,  PRIMARY KEY ((target_id, bucket), user_id));
Cassandra tables. Post IDs contain the creation time, so clustering by ID is clustering by time.
Text
ZADD feed:u123 1768473000000 8841ZREMRANGEBYRANK feed:u123 0 -501      keep the newest 500EXPIRE feed:u123 604800               cold after 7 daysZREVRANGE feed:u123 0 499             candidates, newest first
A ready feed in Redis. The score is the post's time in milliseconds, not a rank, because ranks go out of date.

Consistency

  1. Interviewer

    How do you make sure a stored post is always delivered?

  2. You

    Writing to the store and then to Kafka is two steps, and a crash between them loses the delivery. I publish from the store's change stream, or an outbox table, so the event exists if the post does. See change data capture. Workers may repeat a task, and adding the same ID twice changes nothing.

  3. Interviewer

    Do you need a graph database?

  4. You

    Not for the feed: it asks one-step questions. "People you may know" asks for friends of friends, 500 × 500 = 250,000 edges for one person, and that can be a separate offline job or a graph store. See the connection graph problem.