Ch.34: Twitter System Design: Delete From Every Timeline
Outline
- 0:00 Alice deletes it. Bob still sees it
- 0:49 Define invisible before designing it
- 1:56 The system has two paths
- 3:27 Candidates are hints, not truth
- 4:40 A normal read crosses the fence
- 5:44 Delete commits one small piece of truth
- 6:47 Why the outbox belongs in the transaction
- 7:33 A replay and a stale body arrive
- 8:02 The authority check wins
- 8:32 Half the authority batch times out
- 9:38 Old cursors do not preserve old permission
- 10:38 Decide how uncertainty fails
- 11:55 Know when it becomes a leak
- 12:51 Walk Alice's delete through the whole map
- 13:46 The interview answer
Transcript
0:00 Alice deletes her post. 1 second later, Bob refreshes Home. The old timeline still shows it, though it vanished from her profile. How did it survive? The feed still holds its ID, and Bob may resume an old page. Neither knows the post died. Deletion lost a race against its own copies. That is the privacy failure we have to stop. Here's the whole system. The delete API commits a permanent deleted-state record and a cleanup record together. Every candidate ID has to pass a current-state check before it reaches Bob's page. An independent auditor can quarantine a leaking region.
0:36 Imagine one route: write truth, fence reads, verify leaks. We'll unpack each path, then return to this same map for the final race. This shows Bob's safety path even when every old copy arrives. First, define the functional requirements. Alice can retry her delete safely. On his next request, Home, search, her profile and repost references must all suppress the post, even if a cached page hands them its old ID. That matches X's official deletion help, which names the author's account, follower timelines, search and reposts.
1:09 The links are in the description. Now the non-functional requirements: how quickly must Bob's next refresh finish, and what happens if current state cannot be proven? Start the clock at commit. We need three deadlines. Timeline reads: 99% within 250 milliseconds. In-flight authority proof: usable for 500 milliseconds after the server acquires it. Visibility: by 1 second, every response has fresh authority or hides Alice. We measure safety when the server sends the response because we cannot recall bytes already sent. Physical cleanup may take minutes.
1:42 Okay, three clocks, not 1: read latency, proof lifetime and visibility deadline. So “gone” is a read guarantee before it is a storage fact. What if the primary database cannot prove the latest state? The wrong boundary is waiting for every copy. When authority is unproven, we omit the item. A product manager might still say, “Do not return success until every copy disappears.” Yeah, I get why they want that. It sounds like the only honest definition of deleted. But it puts every cache and index on Alice's critical path.
2:15 The design has to make Bob safe quickly without doing that. The result is simple: protect Bob on the read and let cleanup trail behind. With that contract set, focus on Bob's read path. Home gives his feed service ranked IDs. It batches those candidates through the authority fence, drops the dead ID, then builds the page from the survivors. Profile, search and repost use that same guard. Twitter's historic public Home Mixer README separates candidate generation from filters, including visibility filters.
2:44 This delete path is our interview design, not a claim about X's private system. Alice's change path stays separate. Her delete call writes the source-of-truth row and a durable cleanup record in the same transaction. Workers later remove stale references from timelines, search, reposts, notifications and caches. So the read path is the bouncer, and cleanup is the closing crew. One decides what Bob may see; the other cleans up the mess afterward? Oh, I like that split: correctness now, hygiene later.
3:14 Suppose the cleanup path stalls for 10 minutes. Alice's old ID can still sit there, you know, wasting space in caches without reaching Bob. It is a storage cost, not a visibility risk. That split leads to one enforceable rule. A post keeps its ID, author, state, version and deleted timestamp. Delete writes a durable tombstone: a record that the post existed and is now unavailable. Why keep a tombstone instead of removing the row? Because late events and old caches need an authoritative answer. If absence could mean either deleted or temporarily missing, a retrying worker might rebuild the post from stale data.
3:54 Ah, every late arrival learns from the tombstone that the identity is dead, so what does a timeline entry hold? Only a viewer, a stable sort position called the rank key, the post ID and the author ID. It is a derived candidate. For Alice's delete, the answer is always deny. Other live-post rules still come from current policy: follower-only for protected posts, targeted denial for blocks or moderation, and Home filtering for Bob's mute. Whether her ID sits in 10 feeds or 10 million, each read recomputes those rules against current authority rather than trusting the timeline copy.
4:32 Right. Ranking is stored, permission is recomputed. The tombstone is not just cleanup metadata; the read must consult it within budget. Now that candidate-only model meets a normal read. For example, Bob asks for 20 posts, and the timeline returns at most 60 ranked IDs because filtering may remove some. How do we bound the work? Three bounds. The cap limits records, batching limits, Network trips, and the deadline limits latency. Group those IDs by authority shard, each one a partition of the authoritative database, and read each group under that deadline.
5:07 If a shard proves Alice is deleted, her candidate is gone. If it cannot prove a current answer in time, her candidate is unknown and suppressed. We will make that freshness proof concrete when a region falls behind. Only survivors reach the page builder. It keeps their existing order and fills 20 slots if possible. Filtering may scan more candidates, but it does not rerank them around Alice's delete. So the normal read is bounded work, but does Alice's delete still have to touch every precomputed feed?
5:36 No. Delete touches one authoritative row; follower count changes only how much cleanup remains. The result is one bounded delete and variable cleanup. Now take an example: Alice calls the delete-post endpoint. We authenticate her, verify authorship, and lock or conditionally update the current post version. Yes. In one replicated database transaction we write the tombstone and its cleanup intent, containing the new version, change type, post identity and author. We acknowledge only after a majority commits it.
6:05 Hold on. Success comes before we remove the ID from every follower timeline? Yes, because the tombstone plus a fresh authority check make reads safe within our 1-second visibility bound. Synchronous global cleanup would couple Alice's latency to her follower count, every cache, and every derived index being healthy at once. Oh, that would be a production nightmare: one unreachable search shard could prevent a celebrity from deleting anything. Deletion just became a company-wide health check. Yeah. That dependency shape is the problem.
6:37 Durable authority plus durable cleanup intent removes the coupling. The remaining crash window is event delivery after commit. That sets up the outbox. That success boundary raises one familiar crash question: could we commit the tombstone, then publish cleanup separately? No. If the database commits and the publisher crashes, cleanup may never hear about it. If cleanup publishes first but the database commit fails, workers remove derived copies of a post that was never deleted. So either ordering creates a different lie.
7:07 Those two records need one receipt: one database commit produces both or neither. That's exactly it. Atomicity first. So how does cleanup leave the database? That is the transactional outbox: the cleanup record commits beside the tombstone, and a dispatcher publishes it afterward. The dispatcher may retry revision nine, but consumers keep the highest revision and ignore a late eight. Retries become harmless instead of reversible. Okay, let's make the retry ugly. Bob's node misses the invalidation, the signal that should discard the stale version-8 body, while search repair replays revision eight.
7:43 Can either stale copy escape? My first instinct is yes. The cache already has the bytes, and search can put Alice's ID back into Bob's candidates. Yes, but they can only nominate Alice; neither can authorize her. That leaves one decisive test: assemble the page with both stale copies present. That assembly test leads to Bob's live request. Imagine the refresh: the cache has the body and authority says it is dead. Which one wins at page assembly? It discards body eight. Search's late revision eight is also rejected because the consumer already knows nine. If authority stays silent, the builder suppresses Alice.
8:19 A missed invalidation cannot bypass current truth. Okay, that is the distinction: the bytes survived; permission did not. Next, make the authority path itself partial: one shard answers while another goes dark. That partial-shard failure raises the page-level question: do we throw away Bob's whole page? Take a concrete case. Bob's 60 candidates need current state from two authority shards. One shard returns 30 records; the other times out. My first thought is to retry the whole page. Honestly, many of us would reach for that under pressure, but it turns one slow shard into a total outage.
8:54 Instead, evaluate each candidate whose current state we established and suppress the 30 unknowns. Oh, right. I think I treated the shard timeout as a page-level error. The axis is uncertainty's blast radius: per-request failure drops all 60 candidates; per-item failure hides only the 30 without proof. Bob gets a shorter page, and another authority replica can retry those unresolved records. Exactly. It is the difference between one breaker blacking out the whole building and a room-level breaker isolating the 30 records we cannot prove.
9:29 That asymmetry matters because a short page looks degraded while a leaked post can look correct until it becomes a real incident. Right. The same fail-closed rule has to survive pagination. Can yesterday's cursor carry yesterday's permission forward? Next, take Bob's first page, created before Alice's deletion. His cursor resumes after rank key 100. If it preserved the old visibility decision, deleted content could reappear on page two. Not in this design. The cursor preserves rank position, never permission.
10:00 We fetch the next candidate IDs, then obtain new authority evidence for the page. Wait, if filters remove most candidates, Bob may get only seven posts. Do we, I mean, keep scanning forever to fill 20? No. Fetch one extra bounded batch, then stop. An undersized page beats an unbounded scan. The cursor says where to resume; it never stores post bodies or permission decisions, so each returned item crosses today's fence. Seven safe posts beat 20 with a ghost. So now the missing proof is regional: what makes that authority evidence current when the replica is behind?
10:37 That cursor rule leads to one concrete regional state. Imagine Bob asks West for Alice's current state. Alice's delete is revision nine, and a majority has already committed it. West's replica has applied only through eight. Okay. So what must happen before West can safely answer Bob? West cannot decide from replica eight. It can wait for nine or route to a caught-up leader. If no majority can prove current state, it hides Alice. The marker confirming revision nine is durable is the majority-commit watermark.
11:11 West can reuse it across many reads, so we don't call the leader for every post. And Bob's request treats that confirmed nine as its read fence? Exactly. West must cross that fence before its answer can authorize Alice. If it cannot reach nine within the request budget, it routes to a caught-up source or omits Alice and keeps only proven items. Right. What about an in-flight request holding earlier proof? Yeah, that's the uncomfortable edge. That proof gets only the lifetime we set at the start.
11:42 When it expires, the request rechecks current state or suppresses Alice. During a partition, Bob's page becomes slower, shorter or unavailable rather than stale. The network may fail; privacy does not. That proof deadline opens the detection question. Suppose one broken server leaks cached body eight beyond the cutoff. How do we catch it without trusting that server's own logs? An outside auditor asks every region for Alice's deleted post as Bob and records the reply. Alice's delete already produced an immutable receipt: post 42, commit nine, cutoff time.
12:18 That receipt is copied to an audit log serving code cannot edit. Oh, man. None of us would let the broken server grade its own homework. If a region sends body eight after the receipt's cutoff, the probe has caught a real leak. Then the deployment has violated the contract. Does it lose traffic immediately? It does. The traffic controller removes it until it passes the stale-body probe again. One bad reply loses traffic, and the path must prove safety before returning. That gives the race both a guard and an alarm.
12:50 Now use the full map for one final race: every cleanup worker is frozen, Bob resumes a cursor issued before the delete, and his cache still holds revision-8 bytes. Alice's post API writes tombstone version 9 and its outbox record, then responds. Bob refreshes. The cursor and timeline nominate Alice's ID, and the cached body arrives. His regional replica obtains majority-backed fence nine, incorporates it, loads the current tombstone, then rejects body eight before page assembly. If that leader or majority is unreachable, Alice's candidate is hidden instead.
13:25 After the deadline, the audit receipt lets outside probes test every region for the same deny even while cleanup remains frozen. I love that: every stale copy showed up, yet none carried permission into this request. The result is one invariant for the interview answer: old copies may nominate, but current truth alone controls Bob's response. Let's hear it. If the interviewer cuts us off, what is the answer? Do not promise a global rewrite. Commit an authoritative tombstone and cleanup intent together. Before each response, batch IDs by shard and get a majority-backed read fence; serve only after the replica crosses it.
14:03 If fresh authority proof is unavailable or expired, hide the item. Okay, my one-line version: stale candidates are tolerable; stale permission is not? Exactly. Write-side delete receipts let independent probes verify each region once its deadline passes. Right. That closes both the safety and detection loops. Thanks for listening to Learning Podcasts.