Sub topic 10
Freshness, consistency and failure handling
The earlier chapters built a feed that is fast to read: posts are pushed into bounded per-user timelines, high-follower accounts are pulled at read time, and the client pages through results with a cursor. This chapter covers what happens when that pipeline is slow, out of order or partly broken.
It assumes you know the following:
- The fan-out on write and hybrid designs from the earlier chapters.
- How a message queue delivers messages "at least once".
- How a cache differs from the database that backs it.
- Short Python snippets.
What "fresh" means for a feed
Freshness is the delay between a post being accepted and that post appearing in a follower's feed. A feed is not a bank ledger. Users tolerate a few seconds of delay, but they notice a post that never arrives or a feed that rearranges itself.
State freshness as a service level objective (SLO), a measurable target. For example:
- 99% of posts from accounts below the celebrity threshold appear in all follower feeds within 5 seconds.
- 99.9% appear within 60 seconds.
- A user always sees their own post immediately.
Each target puts a different part of the system under pressure. The 5-second target limits queue lag and worker throughput. The 60-second target decides how long you can tolerate retries. The last target does not depend on the fan-out pipeline at all, as the next sections show.
Freshness is a trade-off against cost. You can improve it by adding workers, shortening batches and skipping the dedupe checks. Each of those raises cost or risk elsewhere.
Where the delay comes from
A post passes through several asynchronous stages after the write returns to the author.
- The post is stored in the posts table. This is the source of truth.
- A "post created" event goes onto a queue.
- Fan-out workers read the event, look up the followers and write into their timelines.
- The feed cache updates, and replicas of the cache or database catch up.
- The follower's next read picks up the new entry.
The author receives the response at the "201 Created" step, before any follower has the post. This ordering is what makes the system eventually consistent. Followers' timelines converge on the correct state, but at any instant different followers see different states.
The usual causes of lag are:
- Queue backlog. A burst of posts, or one very large fan-out, fills the queue faster than workers drain it.
- Hot partitions. If events are partitioned by author, one busy author occupies one worker while others sit idle.
- Slow dependencies. Looking up a follower list from an overloaded graph store delays every event.
- Replica lag. Reading from a replica that is seconds behind hides data the primary already has.
Monitor lag directly. Track the age of the oldest unprocessed message, and track end-to-end delivery time by comparing a post's creation timestamp with the time its entry lands in a timeline. Queue depth alone misleads, because a deep queue of cheap events can drain faster than a shallow one with large fan-outs.
Consistency guarantees worth providing
You cannot give strict consistency across the fan-out pipeline without paying heavily, since it would mean updating millions of timelines inside the write request. You can give a small set of weaker guarantees that match what users notice.
| Guarantee | What it means for a user | Typical mechanism |
|---|---|---|
| Read your own writes | After posting, I see my post at once | Merge the author's recent posts into their own read |
| Monotonic reads | A refresh never makes a post I saw disappear | Stick to one replica per session, or send a version in the cursor |
| Stable pagination | Page 2 does not repeat or skip items from page 1 | Keyset cursor on (created_at, post_id) |
| Per-author ordering | Posts from one author keep their order | Order by timestamp and ID, not by arrival time |
| Eventual delivery | Every post eventually reaches every follower | Retries, idempotent writes, dead-letter queue |
Global ordering across authors is not on the list. Two followers may see posts from different authors appear in a different sequence for a few seconds. Sorting by (created_at, post_id) on read makes the final order identical for everyone once both entries have arrived.
Read your own writes
An author who posts and then refreshes expects to see the post. The fan-out might not have reached the author's own timeline yet, particularly if the author follows themselves only implicitly. The fix is to take the author's recent posts straight from the posts table, or from a small per-user cache, and merge them into the result at read time.
import heapq
from itertools import islice
def read_own_feed(precomputed, own_recent, limit=20):
"""Merge the pushed timeline with the user's own recent posts.
Both inputs are lists of (timestamp, post_id) sorted newest first.
The same post can appear in both lists once fan-out catches up,
so drop duplicates by post_id.
"""
seen = set()
merged = heapq.merge(precomputed, own_recent, reverse=True)
unique = (
item for item in merged
if item[1] not in seen and not seen.add(item[1])
)
return list(islice(unique, limit))
timeline = [(105, "p5"), (101, "p1")]
mine = [(106, "p6"), (101, "p1")]
print(read_own_feed(timeline, mine, limit=3))
# [(106, 'p6'), (105, 'p5'), (101, 'p1')]The same deduplication matters in the hybrid design. A post from a high-follower account can arrive through both the push path and the pull path during a threshold change, so the merge step should always drop duplicates.
Monotonic reads and stable cursors
Suppose a user's first request hits a cache replica that has the newest post, and the second hits a replica that does not. The post vanishes on refresh. Two mitigations work in practice:
- Route a session to the same replica for a short window.
- Put the newest timestamp the client has seen into the cursor. The server then knows to wait briefly, or to merge from the primary, if its replica is older than that.
Keyset pagination already protects against the other common problem. Because the cursor is a position in the sort order and not a row count, new posts arriving at the top do not shift later pages.
Failure handling in the fan-out pipeline
Distributed queues usually deliver at least once. A worker may process a message, crash before acknowledging it, and see the same message again. The pipeline must therefore be safe under repetition.
Make timeline writes idempotent
An operation is idempotent if doing it twice leaves the same result as doing it once. Inserting (timestamp, post_id) into a timeline is naturally idempotent if the store treats the entry as a set member. A Redis sorted set keyed by post ID behaves this way. A plain list does not, so the code must check for the entry first.
from collections import defaultdict
FEED_LIMIT = 800
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)], newest first
def add_to_feed(user_id, timestamp, post_id):
"""Idempotent insert: repeated delivery does not create duplicates."""
feed = feeds[user_id]
if any(pid == post_id for _, pid in feed):
return False
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:]
return True
print(add_to_feed("u1", 100, "p1")) # True
print(add_to_feed("u1", 100, "p1")) # False, redelivery is harmless
print(feeds["u1"]) # [(100, 'p1')]A linear scan is acceptable at 800 entries in an example. A production store uses a sorted set or a unique key so that the check and the insert happen in one atomic step.
Retry, back off and dead-letter
Failures divide into transient ones (a timeout, a briefly overloaded shard) and permanent ones (a malformed event, a deleted author). Retry the first kind with exponential backoff. Move the second kind to a dead-letter queue, a holding area for messages that need a human or a separate repair job. Without a cap on attempts, one bad message blocks a partition forever.
class TransientError(Exception):
pass
def process_with_retry(handler, message, dead_letters, max_attempts=3):
"""Run handler(message). Retry transient errors, dead-letter the rest."""
for attempt in range(1, max_attempts + 1):
try:
handler(message)
return True
except TransientError:
# A real worker would sleep min(cap, base * 2**attempt) plus jitter.
continue
except Exception as exc:
dead_letters.append((message, repr(exc)))
return False
dead_letters.append((message, "max attempts exceeded"))
return False
calls = {"n": 0}
def flaky(message):
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("timeout")
dead = []
print(process_with_retry(flaky, {"post_id": "p1"}, dead)) # True
print(process_with_retry(lambda m: 1 / 0, {"post_id": "p2"}, dead)) # False
print(dead) # [({'post_id': 'p2'}, "ZeroDivisionError('division by zero')")]Add jitter, a random offset, to the backoff delay. Without it, thousands of workers that failed together retry together and overload the dependency again.
Split large fan-outs into chunks
One event for an account with 200,000 followers should not be one unit of work. A crash at follower 150,000 would force a repeat of everything. Break the follower list into chunks of, say, 1,000 and enqueue one message per chunk. A failure then costs one chunk, and because inserts are idempotent, redoing a chunk is safe. Chunking also spreads the work across workers and reduces the lag caused by a single large author.
Recover from cache loss
A feed cache is a copy, not the source of truth. When a node dies or evicts a timeline, the feed for those users is empty or stale. Handle it as follows:
- Detect the miss. A missing key differs from an empty feed, so store a marker or check the key's existence.
- Rebuild the timeline with a pull. Fetch recent posts from the accounts the user follows, merge them and write the result back.
- Limit concurrent rebuilds. After a large cache failure, every user returns at once, and the rebuild load can take down the posts store. Use a lock or a request-coalescing layer so each user is rebuilt once, and cap the total rate.
Degrade instead of failing
When a dependency is down, return something useful.
- If the ranking service is unavailable, return the candidate list in chronological order.
- If the pull path for high-follower accounts times out, return the pushed timeline alone and let the client retry.
- If the cache is cold and rebuilds are saturated, return the most recent page only and fill in the rest later.
Set a timeout on each dependency that is shorter than the overall request budget, so one slow call cannot consume the whole budget.
Summary of failure modes
| Failure | User-visible effect | Mitigation |
|---|---|---|
| Queue backlog | Posts appear late | Autoscale workers, alert on oldest-message age, prioritize small fan-outs |
| Worker crash mid-fan-out | Some followers miss the post | Chunked work, at-least-once delivery, idempotent inserts |
| Duplicate delivery | Same post twice | Deduplicate by post_id on write and on read |
| Poison message | A partition stops moving | Attempt cap, dead-letter queue |
| Replica lag | Posts vanish on refresh | Session stickiness, timestamp in cursor |
| Cache node loss | Empty or short feeds | Rebuild by pull, rate-limited |
| Ranking outage | Unranked feed | Fall back to chronological order |
Repairing divergence
Even with retries, a timeline can end up missing a post, for example if a dead-lettered message was never replayed. Run a periodic reconciliation job for a sample of users. It compares their cached timeline with one rebuilt from the posts table and the follow graph, then records the difference. The mismatch rate is a useful health metric. A nonzero rate is normal. A rising rate means a bug or a pipeline gap. The job should repair entries it finds missing, and it should never delete entries without checking the deletion rules in the next chapter.
Decision criteria
- Choose a tighter freshness SLO only if users or the business notice the difference. Going from 60 seconds to 5 seconds can double worker cost.
- Prefer a weaker guarantee that you can verify to a strong one that you cannot. Read-your-writes and stable cursors are cheap and visible. Global ordering is expensive and mostly invisible.
- Put correctness in the data (idempotent writes, unique keys) and not only in the process (careful ordering of steps). Processes fail in ways that data constraints do not.
Exercise
A worker fans out a post to 50,000 followers as a single task. It crashes after writing 30,000 timelines, and the queue redelivers the message. Describe two properties your design needs so that the retry leaves every follower with exactly one copy of the post, and say how splitting the task helps.
Show answer
First, the timeline insert must be idempotent, for example by using a sorted set or unique key on post_id, so the 30,000 followers who already have the post do not get a second copy. Second, delivery must be at least once, so the message is redelivered and the remaining 20,000 followers are eventually reached. Splitting the task into chunks (for example 50 chunks of 1,000) means a crash only repeats the chunk in progress and spreads the work across workers, which also reduces lag.
Exercise
A user posts, refreshes, and does not see the post. A second refresh shows it. Name two possible causes and one fix for each.
Show answer
Cause one: fan-out has not reached the author's timeline yet because of queue lag. Fix: merge the author's own recent posts into their read, which gives read-your-own-writes. Cause two: the first refresh hit a cache or database replica that was behind the primary. Fix: stick the session to one replica, or include the newest seen timestamp in the cursor so the server reads from an up-to-date source when its replica is older.