Sub topic 10
Freshness, Consistency and Failure Handling
This chapter assumes you know the fan-out models from earlier chapters, basic caching, and message queues. It covers how fresh a feed must be, which consistency guarantees users notice, and what to do when parts of the pipeline fail.
What "fresh" means for a feed
Freshness is the delay between a user publishing a post and that post appearing in a follower's feed. A feed does not need to be perfectly current. A delay of a few seconds is invisible to most readers. Stating a target keeps the design honest, for example: "99% of posts appear in followers' feeds within 5 seconds."
Fan-out on write is asynchronous. The author's request returns once the post is stored. A queue then delivers the post reference to follower timelines. Freshness is therefore the queue delay plus the time to write to every follower's timeline.
Consistency users actually notice
Feeds are usually eventually consistent. Different followers may see a new post at slightly different times, and that is acceptable. A few guarantees matter more than global agreement:
- Read your own writes. An author who posts and then reloads must see the post. If fan-out has not finished, the reader can merge the author's own recent posts into the response at read time.
- Monotonic reads. A user should not see a post, refresh, and see it vanish. This can happen when two cache replicas are at different positions. Pinning a user's session to one replica, or passing a version in the cursor, avoids it.
- No duplicates and stable order. Retries can deliver the same post twice. Keying each entry by
(timestamp, post_id)makes inserts idempotent, meaning repeating one has no further effect.
The last point matters because queues usually give at-least-once delivery. A worker may crash after writing but before acknowledging, and the job is then retried. The write must tolerate that.
def add_to_timeline(feed, entry, limit=800):
"""Idempotent insert: a retried job leaves the feed unchanged."""
if entry in feed:
return
feed.append(entry)
feed.sort(reverse=True)
del feed[limit:]
feed = [(105, "p5"), (101, "p1")]
add_to_timeline(feed, (103, "p3"))
add_to_timeline(feed, (103, "p3")) # retry: no duplicate
print(feed) # [(105, 'p5'), (103, 'p3'), (101, 'p1')]In a real timeline store, a sorted set keyed by post ID gives the same property without the linear membership check.
Failure modes and mitigations
| Failure | Symptom | Mitigation |
|---|---|---|
| Fan-out worker crashes | Some followers miss a post | Acknowledge the job only after the write. Retry with backoff. |
| Queue backlog after a celebrity post | Freshness degrades for everyone | Use separate queues by priority. Scale workers on queue age, not queue depth. |
| Timeline cache node lost | Empty or missing feeds | Rebuild on demand from the follow graph and post store (fan-out on read). |
| Post store slow or down | Feed has gaps or errors | Serve the cached timeline of IDs. Hide posts that cannot be loaded. |
| Poison message | A job fails every retry | Move it to a dead-letter queue after a fixed number of attempts and alert. |
Rebuilding a lost timeline
The timeline cache holds derived data. The post store and follow graph are the source of truth. If a cache entry is missing, the read path can build it with a fan-out-on-read query, write the result back, and serve it. This is slower, so protect the post store from a rush of rebuilds after a cache node failure. Two common tools are request coalescing, where concurrent rebuilds for one user share a single query, and a rate limit on rebuilds.
Degrading gracefully
When a dependency is unhealthy, serve something rather than an error:
- If ranking is down, return the feed in reverse-chronological order.
- If the celebrity pull is slow, return the pushed timeline and skip it, with a short timeout.
- If the whole feed service is down, show a stale cached page, marked as possibly out of date.
Each fallback trades quality for availability. Set a timeout on every call and decide in advance what each timeout falls back to.
Detecting problems
Measure freshness directly. Record the time a post is published and the time it lands in a timeline, then track the 50th and 99th percentile of the difference. Also monitor queue age, dead-letter queue size, cache hit rate, and the share of requests that used a fallback. A rising fallback rate is an early warning.
Exercises
Exercise
A worker writes a post into a follower's timeline and then crashes before acknowledging the queue message. The message is redelivered. What property of the timeline insert keeps the feed correct, and how can you get it?
Show answer
The insert must be idempotent. Key each timeline entry by (timestamp, post_id), or store it in a sorted set keyed by post ID, so inserting the same entry twice leaves one copy.
Exercise
After a cache node fails, millions of users have empty timelines and the post store is overloaded by rebuilds. Name two measures that reduce the load.
Show answer
Request coalescing, so concurrent rebuilds for the same user share one query, and rate limiting rebuilds. Rebuilding only the most recent page, or serving a degraded feed while the cache warms, also works.