Design a News Feed: The Ask
A news feed is a list of recent posts from the accounts a user follows, shown newest first. This lesson clarifies the ask before any design begins.
A small follow graph
The follow graph stores who follows whom. The printout lists each user and the accounts that user follows.
follows = {
"ana": ["cy"],
"ben": ["ana"],
"cy": ["ana", "ben"],
}
for user in sorted(follows):
print(user, "follows", ", ".join(follows[user]))Posts in time order
Each post carries the time it was posted. Sorting by time puts the newest post first.
posts = [
(5, "ana: morning run"),
(9, "ana: new photo"),
(7, "ben: hello all"),
]
for when, text in sorted(posts, reverse=True):
print(when, text)Posting stores one post
A new post is stored once, under its author. The printout shows the stored counts after one post is added.
posts = {"ana": ["ana: morning run"], "ben": [], "cy": []}
posts["ben"].append("ben: hello all")
for author in sorted(posts):
print(author, "stored posts:", len(posts[author]))Example
follows = {"ana": ["cy"], "ben": ["ana"], "cy": ["ana", "ben"]}
posts = [
(5, "ana", "ana: morning run"),
(9, "ana", "ana: new photo"),
(7, "ben", "ben: hello all"),
(6, "cy", "cy: my own post"),
]
feed = [p for p in posts if p[1] in follows["cy"]]
feed.sort(reverse=True)
for when, author, text in feed:
print(text)
print("cy feed has", len(feed), "posts")Key points
- News feed: a list of recent posts from followed accounts, shown newest first.
- Post: a short message a user publishes for followers to see.
- Follow: a link from one user to an account whose posts they want in their feed.
- Fan-out: posting fans a post out to followers' feeds.
- Clarify: this step fixes the job of the system before design starts.
- Scope: posting, following and viewing the home feed are in the design.
- Freshness: a new post should reach followers' feeds quickly.
In this example, the feed for cy gathers posts from the accounts cy follows and sorts them newest first. Cy's own post stays out, because cy does not follow cy.
Note
search, messaging and profiles sit outside this design.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a news feed show a user?