Sub topic 11
Handling deletes, unfollows, blocks and privacy
This chapter assumes you have read the earlier chapters on the data model, fan-out on write, hybrid fan-out, cursor pagination and the feed cache. You should know that a timeline stores (timestamp, post_id) references rather than full posts. You should also be comfortable reading short Python snippets.
The feed is built from copies. Fan-out on write places a post reference into thousands of timelines, and caches hold those references for hours or days. When something changes (a post is deleted, a user unfollows someone, an account goes private), every copy becomes potentially wrong. This chapter covers how to keep those copies from showing content a viewer should no longer see.
Why these cases are hard
A feed optimizes reads by precomputing answers. Precomputed answers go stale. Deletes, unfollows, blocks and privacy changes are the cases where stale means harmful, not just slightly out of date. A late-arriving new post is a freshness problem. A deleted photo that still appears in a former friend's feed is a privacy incident.
Two principles keep the design manageable:
- Treat the timeline as a hint, not as authority. The timeline says which posts are candidates. The authoritative state (does the post exist, may this viewer see it) is checked again when the page is served.
- Separate correctness from cleanup. Read-time checks guarantee that nothing wrong is shown. Background cleanup reclaims space and keeps pages full. If cleanup is late, the system is wasteful but still correct.
Deleting posts
Tombstones instead of immediate removal
Deleting a post from the posts table and then hunting down every timeline entry is slow and racy. A common approach is to mark the post as deleted first. The record is a tombstone: a row that stays in place but has deleted = true (and often a deleted_at time). The tombstone is the single source of truth. Every reader checks it.
The delete flow looks like this:
- Set the tombstone on the post row, in the same transaction as the user's request.
- Invalidate any cached copy of the post object (the post body cache, not the timelines).
- Publish a
PostDeletedevent to a queue. - Workers consume the event and remove the reference from timelines, search indexes, notification lists and any other derived store.
- After a retention period, a separate job physically deletes the row and its media.
Step 4 is optional for correctness. If it fails or lags, the read-time check in the next section still hides the post.
The fan-out race
A delete can race with its own fan-out. Suppose a user posts and deletes within a second. The fan-out worker for PostCreated may still be running when the PostDeleted cleanup runs. The cleanup removes the reference from the timelines it finds, and then the slower fan-out inserts the reference into the rest.
Mitigations:
- Fan-out workers re-read the post's state just before writing, and skip the write if it is tombstoned. This narrows the window but does not close it.
- Read-time filtering closes it completely, because a stale reference to a tombstoned post is dropped at serve time.
- Run the cleanup for a deleted post a second time after a delay, to catch references inserted by late fan-out.
Timeline entries for deleted posts
Because timelines store only the post ID, a lazily cleaned timeline contains dead references. These show up at read time as missing or tombstoned posts. The reader skips them. They disappear on their own when the bounded timeline trims old entries, so for a feed limited to a few hundred items the cleanup work is often small.
Unfollows
When user A unfollows user B, A's timeline still contains B's posts. There are two ways to handle it.
Eager removal. Scan A's timeline and delete entries by B. This needs a way to map each post_id to its author, because the timeline stores only (timestamp, post_id).
def remove_author_from_feed(feeds, post_author, user_id, author_id):
"""Drop every entry written by author_id from user_id's timeline.
feeds: user_id -> [(timestamp, post_id)]
post_author: post_id -> author_id
"""
feeds[user_id] = [
(ts, pid)
for ts, pid in feeds[user_id]
if post_author.get(pid) != author_id
]
feeds = {"ann": [(105, "p5"), (104, "p4"), (101, "p1")]}
post_author = {"p5": "bob", "p4": "carol", "p1": "bob"}
remove_author_from_feed(feeds, post_author, "ann", "bob")
print(feeds["ann"]) # [(104, 'p4')]Lazy filtering. Leave the timeline alone and check at read time whether the viewer still follows the author. The follow edge is the authority.
Eager removal is cheap here because the scan is bounded by the timeline length. Even so, do not rely on it alone. The unfollow request returns before the cleanup finishes, and a user who unfollows and immediately reloads should not see the old posts. Run both: filter at read time and clean up in the background.
The reverse case matters too. When A follows B, the timeline has no backfill of B's older posts. Many systems enqueue a small backfill job that pulls B's last N posts into A's timeline. That is a freshness feature, not a safety one, so it can be best-effort.
For the hybrid design, remember that posts from high-follower accounts are not pushed. They are merged in at read time from a list of followed celebrity accounts. An unfollow of a celebrity only needs the follow edge updated, and the next read respects it with no timeline cleanup.
Blocks
A block is stronger than an unfollow. If A blocks B:
- A must not see B's posts, replies, reposts of B's content, or mentions of B.
- B must not see A's posts either. Blocks are usually enforced in both directions for content visibility.
- Any follow edge between the two is removed, in both directions.
- B should not be able to detect the block through the feed beyond what the product allows.
Because a block is a safety feature, eager cleanup alone is not acceptable. The read-time check must consult the block list. Store blocks as a set per user, and check both directions: (viewer, author) and (author, viewer).
Indirect exposure is the usual gap. B might repost a post by C, and A follows C, not B. If A has blocked B, the repost entry must still be hidden, since it carries B's activity. Likewise a reply thread can contain B's comment under a post A is allowed to see. Check the actor of each feed item, not only the original author.
Privacy changes
Privacy settings add a visibility field to each post or account. Typical values are public, followers only, and private account with approved followers.
Visibility can change after fan-out:
- Public to private. Posts already pushed into the timelines of non-approved followers must disappear. Pushing was fine under the old rules.
- Follow request approved or revoked. The set of people allowed to see an account's posts changes. Approval should trigger a backfill. Revocation should trigger the same cleanup as an unfollow.
- Per-post audience. If a post is limited to a list of people, fan-out should only target that list, and the reader should still verify membership.
The rule is the same as for blocks: the timeline never grants access. Access is decided from current data at read time. A user who is not allowed to see a post should not receive its content, its author's name, its media URLs or even its existence.
Media is easy to overlook. Signed URLs for images and video should be short-lived and issued only after the visibility check. If the media is on a CDN with a permanent public URL, deleting or hiding the post does not hide the file.
The read-time filter pipeline
All of the cases above converge on one step in the read path. After the candidate references are taken from the timeline and the celebrity merge, the server hydrates them (loads the post objects) and runs checks before building the page.
The code below implements the pipeline. It scans candidates until the page is full or a scan limit is hit, and it returns a cursor that points at the last candidate scanned, whether or not that candidate was shown.
from dataclasses import dataclass
@dataclass(frozen=True)
class Post:
post_id: str
author_id: str
created_at: int
deleted: bool = False
def is_visible(viewer_id, post, following, blocked_pairs, private_authors):
if post is None or post.deleted:
return False
author = post.author_id
if (viewer_id, author) in blocked_pairs or (author, viewer_id) in blocked_pairs:
return False
if (
author in private_authors
and author != viewer_id
and author not in following.get(viewer_id, set())
):
return False
return True
def read_page(viewer_id, timeline, posts, following, blocked_pairs,
private_authors, limit=20, max_scan=200):
"""timeline: [(timestamp, post_id)] newest first.
Returns (visible posts, next cursor or None)."""
page = []
scanned = 0
cursor = None
for ts, post_id in timeline:
if scanned >= max_scan:
break
scanned += 1
cursor = (ts, post_id)
post = posts.get(post_id)
if is_visible(viewer_id, post, following, blocked_pairs, private_authors):
page.append(post)
if len(page) == limit:
break
next_cursor = cursor if scanned < len(timeline) else None
return page, next_cursor
timeline = [(105, "p5"), (104, "p4"), (103, "p3"), (102, "p2"), (101, "p1")]
posts = {
"p5": Post("p5", "bob", 105, deleted=True),
"p4": Post("p4", "carol", 104),
"p3": Post("p3", "dave", 103),
"p2": Post("p2", "erin", 102),
"p1": Post("p1", "erin", 101),
}
following = {"ann": {"bob", "carol", "erin"}}
blocked_pairs = {("ann", "carol")}
private_authors = {"dave"}
page, cursor = read_page("ann", timeline, posts, following,
blocked_pairs, private_authors, limit=1)
print([p.post_id for p in page], cursor) # ['p2'] (102, 'p2')Three details in this code matter in practice.
- The cursor advances past filtered items. If the cursor only moved past visible posts, the next request would rescan the same hidden entries. Using the last scanned entry keeps keyset pagination stable and fast.
- The scan is capped. A viewer who blocked a prolific account could otherwise trigger an unbounded scan. With the cap, the server returns a short page and a cursor, and the client asks again.
- Pages can be short. Clients must not treat a page smaller than the limit as the end of the feed. Only a missing cursor means the end.
Choosing between eager and lazy handling
| Event | Read-time check | Background cleanup | Notes |
|---|---|---|---|
| Post deleted | Tombstone lookup | Remove from timelines, search, notifications | Run cleanup twice to cover fan-out races |
| Unfollow | Follow edge lookup | Remove author's entries from timeline | Hybrid celebrity posts need no cleanup |
| Block | Block set, both directions | Remove follow edges and the other user's entries | Also check reposts and replies |
| Account becomes private | Visibility and approved-follower check | Remove entries from non-approved timelines | Revoke media URLs |
| Follow approved | None | Backfill recent posts | Best effort |
The read-time check is mandatory for the first four rows. The cleanup is an optimization that keeps pages full and storage small.
Failure modes
- Hydration cache holds a deleted post. If post objects are cached separately from timelines, a delete must invalidate that cache. Otherwise the tombstone is never seen. Prefer deleting the cache entry over updating it, and keep a short TTL as a backstop.
- Replica lag. The feed reads from a replica that has not yet received the tombstone or the block. For safety-relevant checks, read from the primary or use a store with read-your-writes for the acting user. At minimum, apply a client-side hide for the user's own delete, block or unfollow so they see the effect at once.
- Event loss. If the
PostDeletedmessage is dropped, cleanup never runs. Because correctness comes from read-time checks, the cost is wasted space. A periodic reconciliation job that scans recent tombstones catches the gap. - Fan-out amplification. Deleting a post from a user with a million followers means a million timeline edits. With lazy filtering you can skip most of them and let trimming do the work.
- Derived stores. Search indexes, notification inboxes, email digests and recommendation candidate sets also contain references. Each needs the same check. A feed that is correct while search leaks the deleted post is still a defect.
- Hard deletion requirements. Privacy law and platform policy may require that deleted content actually be erased, including from backups after a delay. Plan the physical delete job and document the retention window.
Summary of the design
- Timelines are candidate lists, and authoritative stores decide visibility.
- Deletes use tombstones, then asynchronous cleanup, then physical removal.
- Unfollows are filtered at read time and cleaned up in the background.
- Blocks are enforced in both directions and also apply to reposts and replies.
- Privacy changes revoke access at read time and for media URLs.
- Cursors move past hidden items, and clients treat a missing cursor as the only end of feed.
Exercise
A user with 2 million followers deletes a post one second after publishing it. Name two reasons a follower might still see the post if you rely only on a background cleanup job, and describe the read-time check that prevents it.
Show answer
First, the fan-out worker for the original PostCreated event may still be running and can insert the reference after the cleanup has already passed that follower's timeline. Second, the cleanup event can be delayed or lost, and the post object may still be in a hydration cache. The read-time check loads the post (or its tombstone state) when the page is built and drops any item that is missing or marked deleted. The post cache entry is invalidated on delete so the tombstone is visible.
Exercise
User A blocks user B. B had reposted a post by C, and A follows C. Which check hides the repost, and why is checking only the original author not enough?
Show answer
The filter must check the actor of each feed item, which is B for the repost, against the block set in both directions. Checking only the original author C passes, because A follows C and has not blocked C, so the repost would appear and expose B's activity to A.
Exercise
Your read_page function returns 12 posts when the limit is 20, and a next cursor. A client developer says this means the feed has ended. What is wrong with that conclusion, and what should the client do?
Show answer
Hidden items (deleted posts, blocked authors, private accounts) are dropped after the candidates are scanned, or the scan cap was reached, so the page can be short even though more candidates exist. The cursor points at the last scanned candidate. The client should treat only a missing cursor as the end of the feed and request the next page with the returned cursor.