Timeline caches, celebrities and pagination
Build the timeline cache of a hybrid feed in Valkey: post ids instead of posts, measured memory, writes that are safe to retry, a read path that merges big accounts under one cursor, offset paging failing while cursor paging holds, rebuilds that do not lose posts, and a test of every page against the database.
Contentsand lesson path
On this page
- The problem
- Set-up and the source of truth
- Step 1: lay out the keys
- Step 2: store ids, not posts, and size the memory
- Step 3: fan-out that is safe to repeat
- Step 4: read a page, merging the big accounts
- Step 5: pages that hold still while posts arrive
- Step 6: rebuild a lost timeline without losing posts
- Step 7: test the read path against the database
- Check your understanding
- Apply it
- Review prompt
Lessons of News Feed Design
- Scoping the feed and estimating fan-out Worked example · 20 min
- Push, pull and hybrid timelines Concept · 25 min
- Timeline caches, celebrities and pagination Worked example · 25 min
- Ranking, media and graceful degradation Concept · 20 min
- Feed design check Knowledge check · 6 questions
What you will learn
- Design timeline storage and caching, including the celebrity problem and cursor pagination.
Prerequisites: Caching Strategies
01. The problem
Lesson 2 chose a hybrid: posts from ordinary accounts are pushed into followers' timelines, and posts from accounts with 10,000+ followers are pulled at read time. Now design the storage, with these constraints:
- Pages are served in under 300 ms at p99, so reads touch few keys.
- The fan-out queue can deliver a task twice, so writes must be safe to repeat.
- Any cache can be lost; rebuilt from the database, a list must not miss posts.
- Posts arrive while people scroll, and pages must neither repeat nor skip posts.
The cache is Valkey, an open-source fork of Redis (these commands also exist in Redis 6.2+); SQLite plays the posts database. Pages hold 5 posts.
02. Set-up and the source of truth
You need Docker (or a Valkey 9.0 binary), Python 3.12 and the redis client. The official image turns protected mode off and has no password, so publish the port on 127.0.0.1 only. The scripts call FLUSHDB: use a throwaway server, and set VALKEY_URL if it is not on localhost:6379. seed.py creates feed.db: 3,000 users, two big accounts (2 and 3), 50 readers, 20,000 posts. Post ids are Snowflake-style, as in the Snowflake lab, so a larger id is a newer post.
"""Create feed.db, the durable store of the worked example (SQLite, seeded data)."""
import random
import sqlite3
EPOCH_MS = 1_767_225_600_000 # 2026-01-01 00:00 UTC, the zero of our post-id clock
rng = random.Random(3)
db = sqlite3.connect("feed.db")
db.executescript("""
DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS follows; DROP TABLE IF EXISTS posts;
CREATE TABLE users (user_id INTEGER PRIMARY KEY, followers INTEGER NOT NULL);
CREATE TABLE follows (follower_id INTEGER, followee_id INTEGER,
PRIMARY KEY (follower_id, followee_id));
CREATE TABLE posts (post_id INTEGER PRIMARY KEY, author_id INTEGER, body TEXT);
CREATE INDEX posts_by_author ON posts (author_id, post_id);
""")
# Accounts 2 and 3 are big: their follower counts stand for the whole network.
users = [(1, 120), (2, 250_000), (3, 40_000)]
users += [(u, rng.randint(5, 3_000)) for u in range(4, 3_001)]
db.executemany("INSERT INTO users VALUES (?, ?)", users)
# 50 readers (user 1 and users 4 to 52) each follow both big accounts and 148
# small ones.
for u in [1, *range(4, 53)]:
followees = [2, 3, *rng.sample(range(4, 3_001), 148)]
db.executemany("INSERT OR IGNORE INTO follows VALUES (?, ?)",
[(u, a) for a in followees if a != u])
# 20,000 posts over about 14 hours. A post id is (ms since EPOCH_MS) << 22, as
# in a Snowflake-style generator, so a larger id means a newer post.
ms = 300 * 86_400_000
for n in range(20_000):
ms += rng.randint(1, 5_000)
author = rng.choices([2, 3, rng.randint(4, 3_000)], weights=[2, 1, 97])[0]
db.execute("INSERT INTO posts VALUES (?, ?, ?)", (ms << 22, author, f"post {n}"))
db.commit()
for table in ("users", "follows", "posts"):
print(table, db.execute(f"SELECT count(*) FROM {table}").fetchone()[0])docker run -d --name feed-valkey -p 127.0.0.1:6379:6379 valkey/valkey:9.0.8
python3.12 -m venv .venv && . .venv/bin/activate
pip install redis==8.2.0
python3 seed.pyusers 3000
follows 7496
posts 2000003. Step 1: lay out the keys
tl:{user} is a timeline: the newest 500 post ids pushed to one user. outbox:{author} holds the newest 500 ids of one big account, read by all its followers. post:{id} caches one post body. Timelines and outboxes are both lists of ids, so they share two rules: writers add only to lists that exist, and a missing list is rebuilt from the database when a reader needs it.
Each list is a sorted set, unique members kept in order. Every member gets score 0, so Valkey orders them by their bytes, and zero-padding ids to 19 digits makes byte order equal time order. Why not use the id as the score? Scores are 64-bit floating-point numbers, exact for whole numbers only up to 2^53, and these ids are around 10^17; the end of step 7 shows two ids collapsing into one score. Save the library as feedlib.py.
"""Timeline cache for the worked example: Valkey for timelines, SQLite as the
source of truth. Python 3.12, redis-py 8.2, Valkey 9.0 (Redis 6.2+ also works)."""
import json
import os
import sqlite3
import redis
CAP = 500 # newest post ids kept in each timeline and each outbox
BIG = 10_000 # accounts with this many followers are pulled at read time
TL_TTL = 86_400 # a timeline unread for a day expires and is rebuilt on return
r = redis.Redis.from_url(os.environ.get("VALKEY_URL", "redis://localhost:6379/0"),
decode_responses=True)
db = sqlite3.connect("feed.db")
def pid(post_id: int) -> str:
"""Zero-pad to 19 digits so that byte order equals numeric order."""
return f"{post_id:019d}"
# All members get score 0, so the set is ordered by member bytes, oldest first.
# Writers add only to lists that exist; a missing list is rebuilt on read.
ADD_IF_PRESENT = r.register_script("""
if redis.call('EXISTS', KEYS[1]) == 0 then return -1 end
redis.call('ZADD', KEYS[1], 0, ARGV[1])
redis.call('ZREMRANGEBYRANK', KEYS[1], 0, -(tonumber(ARGV[2]) + 1))
return redis.call('ZCARD', KEYS[1])
""")
def followers_of(author: int) -> list[int]:
sql = "SELECT follower_id FROM follows WHERE followee_id = ? ORDER BY 1"
return [row[0] for row in db.execute(sql, (author,))]
def big_followees(uid: int) -> list[int]:
sql = ("SELECT f.followee_id FROM follows f JOIN users u ON u.user_id = "
"f.followee_id WHERE f.follower_id = ? AND u.followers >= ? ORDER BY 1")
return [row[0] for row in db.execute(sql, (uid, BIG))]
def publish(author: int, text: str) -> int:
"""Store a post, then push its id to followers or to the author's outbox."""
post_id = db.execute("SELECT max(post_id) FROM posts").fetchone()[0] + (1 << 22)
db.execute("INSERT INTO posts VALUES (?, ?, ?)", (post_id, author, text))
db.commit()
if db.execute("SELECT followers FROM users WHERE user_id = ?",
(author,)).fetchone()[0] >= BIG: # pulled by readers
ADD_IF_PRESENT(keys=[f"outbox:{author}"], args=[pid(post_id), CAP])
else:
pipe = r.pipeline(transaction=False)
for f in followers_of(author):
ADD_IF_PRESENT(keys=[f"tl:{f}"], args=[pid(post_id), CAP], client=pipe)
pipe.execute()
return post_id
PUSHED = """SELECT p.post_id FROM follows f
JOIN users u ON u.user_id = f.followee_id AND u.followers < ?
JOIN posts p ON p.author_id = f.followee_id
WHERE f.follower_id = ? AND p.post_id > ? ORDER BY p.post_id DESC LIMIT ?"""
BY_AUTHOR = """SELECT post_id FROM posts
WHERE author_id = ? AND post_id > ? ORDER BY post_id DESC LIMIT ?"""
def write_ids(key: str, ids: list[int]) -> None:
if ids:
pipe = r.pipeline() # MULTI/EXEC: add and trim together
pipe.zadd(key, {pid(i): 0 for i in ids})
pipe.zremrangebyrank(key, 0, -(CAP + 1))
pipe.execute()
def fill(key: str, query: str, args: tuple, between=None, catch_up=True) -> None:
"""Load a lost list from the database, then catch up on posts committed since."""
ids = [row[0] for row in db.execute(query, (*args, 0, CAP))]
if between:
between() # demo hook: something happens between the read and the write
write_ids(key, ids)
if catch_up: # posts committed after our read whose fan-out found no key
newest = max(ids, default=0)
write_ids(key, [row[0] for row in db.execute(query, (*args, newest, CAP))])
def rebuild(uid: int, between=None, catch_up: bool = True) -> None:
"""Recompute a lost timeline (pushed authors only)."""
fill(f"tl:{uid}", PUSHED, (BIG, uid), between, catch_up)
def load_outbox(author: int) -> None:
"""Recompute a lost outbox: the newest posts of one big account."""
fill(f"outbox:{author}", BY_AUTHOR, (author,))
def hydrate(ids: list[str]) -> list[tuple[str, dict]]:
"""Turn ids into posts: post cache first, database on a miss."""
page = []
for i, cached in zip(ids, r.mget([f"post:{i}" for i in ids]) if ids else []):
if cached is None:
row = db.execute("SELECT author_id, body FROM posts WHERE post_id = ?",
(int(i),)).fetchone()
if row is None:
continue # deleted since it was pushed: drop the id
cached = json.dumps({"author": row[0], "text": row[1]})
r.set(f"post:{i}", cached, ex=86_400)
page.append((i, json.loads(cached)))
return page
OLDER = """SELECT p.post_id FROM follows f JOIN posts p ON p.author_id = f.followee_id
WHERE f.follower_id = ? AND p.post_id < ? ORDER BY p.post_id DESC LIMIT ?"""
def read_page(uid: int, cursor: str | None = None, n: int = 5):
"""One page of the home feed, strictly older than the cursor (a post id).
Returns (posts, next cursor, where the ids came from)."""
big = big_followees(uid)
if not r.exists(f"tl:{uid}"):
rebuild(uid)
r.expire(f"tl:{uid}", TL_TTL) # reading keeps the timeline alive
for a in big: # a lost outbox is rebuilt like a lost timeline
if not r.exists(f"outbox:{a}"):
load_outbox(a)
top = f"({cursor}" if cursor else "+"
ids, past_window = [], False
for key in [f"tl:{uid}"] + [f"outbox:{a}" for a in big]: # one cursor for all
got = r.zrange(key, top, "-", desc=True, bylex=True, offset=0, num=n)
past_window |= len(got) < n and r.zcard(key) >= CAP # older ids trimmed
ids += got
if past_window: # a full list ran out below the cursor: ask the database
below = int(cursor) if cursor else 2**63 - 1
page = [pid(row[0]) for row in db.execute(OLDER, (uid, below, n))]
return hydrate(page), (page[-1] if page else None), "database"
page = sorted(set(ids), reverse=True)[:n]
return hydrate(page), (page[-1] if page else None), "cache"04. Step 2: store ids, not posts, and size the memory
"""Step 2: memory for one full timeline, post ids versus whole posts."""
import json
from feedlib import CAP, pid, r
post = {"author": 48_211_937, "text": "x" * 200, "likes": 1_520, "replies": 37,
"media": "https://media.example.com/p/9f3c2a7b41d8e6f0.jpg",
"created_at": "2026-11-27T10:15:00Z"}
body = json.dumps(post)
ids = [pid((i + 1) << 22) for i in range(CAP)]
r.delete("demo:ids", "demo:id-list", "demo:posts")
r.zadd("demo:ids", {i: 0 for i in ids}) # sorted set of ids (this lesson)
r.rpush("demo:id-list", *ids) # plain list of ids, read by position only
r.rpush("demo:posts", *[body] * CAP) # list of whole posts
for key in ("demo:ids", "demo:id-list", "demo:posts"):
used = r.memory_usage(key, samples=0) # samples=0: measure every element
print(f"{key:<13}{r.object('encoding', key):<10}{used:>8,} bytes"
f" {used / CAP:>4.0f} per entry")
print(f"one post as JSON: {len(body)} bytes")python3 step2_memory.pydemo:ids skiplist 44,224 bytes 88 per entry
demo:id-list quicklist 10,904 bytes 22 per entry
demo:posts quicklist 187,360 bytes 375 per entry
one post as JSON: 361 bytesA full timeline of ids costs about 44 KB, roughly 89 bytes per id including Valkey's bookkeeping. Whole posts cost 187 KB for a modest 361-byte post, and every follower would hold a copy, so an edit or a new like count would rewrite thousands of copies. With ids, a delete removes one key, post:{id}, and the next page drops the id.
Size the tier from what is kept, not from traffic: timelines kept × bytes per timeline, plus replicas and growth. read_page renews a one-day expiry on each read, so a timeline lives while its owner reads and is rebuilt on return (step 6); a maxmemory limit with the allkeys-lru policy is a backstop. Assuming one live timeline per daily active user, lesson 1's 800,000 give at most 35 GB, or 70 GB with a replica. A plain list needs only 22 bytes per id but is read by position, and step 5 shows what that does to paging; the sorted set's extra bytes buy reads that seek by value.
05. Step 3: fan-out that is safe to repeat
"""Step 3: fan-out that is safe to repeat and safe when a timeline is missing."""
from feedlib import ADD_IF_PRESENT, CAP, db, followers_of, pid, r, rebuild
r.flushdb()
author = db.execute("SELECT followee_id FROM follows WHERE followee_id > 3 "
"GROUP BY 1 ORDER BY count(*) DESC, 1 LIMIT 1").fetchone()[0]
fans = followers_of(author)
print(f"author {author}, followers in the demo: {fans}")
for f in fans:
rebuild(f)
new_id = pid(db.execute("SELECT max(post_id) FROM posts").fetchone()[0] + (1 << 22))
key = f"tl:{fans[0]}"
print(f"{key} holds {r.zcard(key)} ids, oldest {r.zrange(key, 0, 0)[0]}")
for attempt in (1, 2): # a queue may deliver the same fan-out task twice
size = ADD_IF_PRESENT(keys=[key], args=[new_id, CAP])
print(f"attempt {attempt}: size {size}, oldest {r.zrange(key, 0, 0)[0]}")
lost = f"tl:{fans[1]}"
r.delete(lost) # the timeline is gone: evicted, or its cache node was replaced
r.zadd(lost, {new_id: 0}) # a plain ZADD recreates the key with one id
print(f"plain ZADD on a missing timeline: {lost} now holds {r.zcard(lost)} id")
r.delete(lost)
print(f"ADD_IF_PRESENT on a missing timeline: returns "
f"{ADD_IF_PRESENT(keys=[lost], args=[new_id, CAP])}, key exists: "
f"{r.exists(lost)}")python3 step3_fanout.pyauthor 110, followers in the demo: [5, 10, 16, 20, 24, 26, 27, 30, 41]
tl:5 holds 500 ids, oldest 0108816661380857856
attempt 1: size 500, oldest 0108817535784189952
attempt 2: size 500, oldest 0108817535784189952
plain ZADD on a missing timeline: tl:10 now holds 1 id
ADD_IF_PRESENT on a missing timeline: returns -1, key exists: 0The first attempt adds the new id and trims the oldest; the timeline stays at 500. The second, a duplicate delivery, changes nothing: the member is already there. The insert is safe under at-least-once delivery.
The last two lines show why writers use a script. On a missing list, a plain ZADD creates a key holding one id, which readers would take as complete. ADD_IF_PRESENT adds only if the key exists, and Valkey runs a script atomically, so nothing runs between the check and the add. It names its one key in KEYS, as Valkey requires for scripts that must work on a cluster. publish uses it for timelines and outboxes alike.
06. Step 4: read a page, merging the big accounts
"""Step 4: read two pages for user 1, merging the two big accounts at read time."""
from feedlib import big_followees, r, read_page
r.flushdb() # empty cache: read_page rebuilds the timeline and both outboxes
print("big accounts user 1 follows:", big_followees(1))
cursor = None
for number in (1, 2):
posts, cursor, source = read_page(1, cursor)
print(f"page {number} ({source}):")
for post_id, post in posts:
print(f" {post_id} author {post['author']:>4} {post['text']}")
print(f" next cursor: {cursor}")python3 step4_read.pybig accounts user 1 follows: [2, 3]
page 1 (cache):
0108926229058420736 author 2801 post 19970
0108925847720689664 author 2 post 19936
0108925738299686912 author 2601 post 19928
0108925448246788096 author 2034 post 19902
0108925395834765312 author 731 post 19899
next cursor: 0108925395834765312
page 2 (cache):
0108925377874755584 author 870 post 19897
0108925348690788352 author 2 post 19894
0108925105404379136 author 731 post 19872
0108925099138088960 author 3 post 19871
0108924986227425280 author 1906 post 19864
next cursor: 0108924986227425280read_page first rebuilds missing sources, here the timeline and both outboxes. It then reads all three with the same cursor, the last id the reader has seen. Each returns up to 5 ids below it; the 5 newest of the union put posts by accounts 2 and 3 in place, and page 2 continues where page 1 stopped. The page is then hydrated: one MGET fetches cached bodies, and a miss reads the database and fills the post cache.
Each followed big account adds one read per feed open, the merge cost lesson 2 measured. All followers read the same outbox, a hot key: read it from replicas or keep a copy in application memory for a second or two, as in surviving stampedes and hot keys.
07. Step 5: pages that hold still while posts arrive
"""Step 5: offset paging versus cursor paging while new posts arrive."""
from feedlib import CAP, db, publish, r, read_page, rebuild
r.flushdb()
rebuild(1)
key = "tl:1"
page1 = r.zrange(key, 0, 4, desc=True) # ranks 0-4: "offset 0, limit 5"
small = [row[0] for row in db.execute(
"SELECT followee_id FROM follows WHERE follower_id = 1 AND followee_id > 3 "
"ORDER BY 1 LIMIT 3")]
for a in small:
publish(a, "posted while user 1 was reading page 1")
by_offset = r.zrange(key, 5, 9, desc=True) # "offset 5, limit 5"
by_cursor = r.zrange(key, f"({page1[-1]}", "-", desc=True, bylex=True,
offset=0, num=5)
def show(label: str, page: list[str]) -> None:
"""Print the last 7 digits of each id, and how many ids page 1 already had."""
repeats = "" if page is page1 else f" repeats {len(set(page1) & set(page))}"
print(f"{label:<17}{' '.join(i[-7:] for i in page)}{repeats}")
show("page 1", page1)
show("page 2 by offset", by_offset)
show("page 2 by cursor", by_cursor)
oldest = r.zrange(key, 0, 0)[0] # the last id the cache window holds
posts, cursor, source = read_page(1, oldest)
print(f"next page after the {CAP}-id window, from the {source}:")
show("", [p[0] for p in posts])python3 step5_paging.pypage 1 8420736 9686912 6788096 4765312 4755584
page 2 by offset 6788096 4765312 4755584 4379136 7425280 repeats 3
page 2 by cursor 4379136 7425280 5971712 2743680 8904960 repeats 0
next page after the 500-id window, from the database:
0232064 7022464 6210688 6069248 2644480 repeats 0Offset paging asks for "positions 5 to 9". Three posts arrived during page 1, older posts moved down three places, and page 2 repeats three; a deletion would skip one instead. Cursor paging asks for "the 5 newest posts older than this id", unchanged by posts arriving above it. In SQL, offset also slows deep pages: PostgreSQL's documentation notes that rows skipped by OFFSET are still computed. Cursor basics are in errors, pagination and filtering.
The last line is the window boundary. A full list with nothing left below the cursor has had its older ids trimmed, so read_page serves the page from the database with the same cursor: a slower page, not a gap.
08. Step 6: rebuild a lost timeline without losing posts
Lists go missing through eviction, expiry or a replaced cache node. A rebuild (fill in feedlib.py) reads the newest posts from the database and writes them. Predict first: a post is committed and fanned out between the rebuild's read and its write. Is it in the rebuilt timeline?
"""Step 6: rebuilding a lost timeline while new posts keep arriving."""
from feedlib import db, pid, publish, r, read_page, rebuild
r.flushdb()
author = db.execute("SELECT min(followee_id) FROM follows "
"WHERE follower_id = 1 AND followee_id > 3").fetchone()[0]
def post_lands():
"""A post is committed and fanned out while the rebuild is in progress."""
post_id = publish(author, "posted during the rebuild")
print(f" post {post_id} by {author} lands; tl:1 exists: {bool(r.exists('tl:1'))}")
for catch_up in (False, True):
r.delete("tl:1")
print(f"rebuild with catch_up={catch_up}")
rebuild(1, between=post_lands, catch_up=catch_up)
newest = db.execute("SELECT max(post_id) FROM posts").fetchone()[0]
print(f" timeline size {r.zcard('tl:1')}, has the new post: "
f"{r.zscore('tl:1', pid(newest)) is not None}")
r.delete("tl:1") # lost again: the next read rebuilds it before serving
posts, cursor, source = read_page(1)
print(f"read after loss: {len(posts)} posts from the {source},"
f" timeline size {r.zcard('tl:1')}")python3 step6_lost.pyrebuild with catch_up=False
post 108926586140491776 by 14 lands; tl:1 exists: False
timeline size 500, has the new post: False
rebuild with catch_up=True
post 108926586144686080 by 14 lands; tl:1 exists: False
timeline size 500, has the new post: True
read after loss: 5 posts from the cache, timeline size 500Without a catch-up, no. The fan-out ran while tl:1 did not exist, so ADD_IF_PRESENT skipped it, and the rebuild wrote a list read before the post was committed. The fix: after writing, read again for posts newer than the newest id found, and add them; a post committed after that read is fanned out to a list that now exists. This assumes the second read sees every committed post (read the primary, not a lagging replica) and that ids grow with commit order; with many writers they only roughly do, so read back a few seconds of margin.
Losing a cache node rebuilds thousands of lists at once: rebuild only on read, one request per list (single-flight), cap concurrent rebuilds, and replicate cache nodes. The demo leaves these out, and its timeline rebuild is one SQL join where a large system would merge each followed account's newest posts.
09. Step 7: test the read path against the database
Each rule closes one way to lose posts, so test them together against the source of truth. step7_check.py scrolls user 1's feed and compares it with the database in three cases: an empty cache, a big account posting into an empty cache, and a big account posting 600 times, more than its outbox holds. It ran for about two and a half minutes on our machine.
"""Step 7: scroll user 1's feed and compare every page with the database."""
from collections import Counter
from feedlib import db, pid, publish, r, read_page
FEED = """SELECT p.post_id FROM follows f JOIN posts p ON p.author_id = f.followee_id
WHERE f.follower_id = ? ORDER BY p.post_id DESC"""
def scroll(label: str, pages: int) -> None:
"""Read pages with cursors; compare with the true newest-first feed."""
truth = [pid(row[0]) for row in db.execute(FEED, (1,))]
served, sources, cursor = [], Counter(), None
for _ in range(pages):
posts, cursor, source = read_page(1, cursor)
served += [post_id for post_id, _ in posts]
sources[source] += 1
missing = len(set(truth[:len(served)]) - set(served))
in_order = served == truth[:len(served)]
print(f"{label:<24}served {len(served):>3} missing {missing:>3} in order: "
f"{in_order!s:<5} pages cache/db {sources['cache']}/{sources['database']}")
r.flushdb() # A: a replaced cache node; nothing is loaded by hand
scroll("A. empty cache", 20)
r.flushdb() # B: a big account posts before anyone reads
publish(2, "posted into an empty cache")
scroll("B. big post first", 20)
for i in range(600): # C: more posts than the 500-id outbox window holds
publish(2, f"busy post {i}")
scroll("C. 600 posts, account 2", 140)python3 step7_check.pyA. empty cache served 100 missing 0 in order: True pages cache/db 20/0
B. big post first served 100 missing 0 in order: True pages cache/db 20/0
C. 600 posts, account 2 served 700 missing 0 in order: True pages cache/db 100/40Every post is served, in order. A feedlib.py that loaded outboxes only by hand, wrote them with a plain ZADD and checked only the timeline's window failed the same check in our run: 39 of the first 100 posts missing in cases A and B, 140 of 700 in case C, every page claiming to come from the cache. In case C the busy account's 500 ids cover less time than the timeline, so after 100 pages its older posts exist only in the database. Serving the whole page from there is a correct simplification; a faster read would fetch only that author's older posts.
docker exec -it feed-valkey valkey-cli
127.0.0.1:6379> DEL prec
(integer) 0
127.0.0.1:6379> ZADD prec 108926586140491777 a 108926586140491778 b
(integer) 2
127.0.0.1:6379> ZRANGE prec 0 -1 WITHSCORES
1) "a"
2) "108926586140491776"
3) "b"
4) "108926586140491776"10. Check your understanding
11. Apply it
Add a storage section to your design doc, then change the code:
- Add a sentinel member so that a user who follows nobody is not rebuilt on every read; reads ignore it and trimming keeps it.
- Make rebuilds single-flight with a short lock (
SET key value NX PX 5000). - Make the database fallback read only the exhausted author's older posts and merge them, keeping
step7_check.pypassing. - Redo the memory estimate for your product, with one replica.
12. Review prompt
Without looking back, explain in your own words:
- Why a timeline holds post ids, and how you estimate its memory.
- What makes the fan-out insert safe to repeat, and why writers must not create missing lists.
- Why offset paging repeats posts, how one cursor covers every source, and what happens when a full list runs out below the cursor.
- How a post can be lost during a rebuild, and how the catch-up read prevents it.
References
- Valkey documentation: Sorted sets
- Valkey documentation: ZRANGE (BYLEX, REV, LIMIT)
- Valkey documentation: ZADD
- Valkey documentation: Scripting with Lua
- Valkey documentation: MEMORY USAGE
- Valkey documentation: Key eviction (maxmemory policies)
- PostgreSQL documentation: LIMIT and OFFSET
- MDN: Number.MAX_SAFE_INTEGER
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.