Sub topic 3
Narrowing millions of posts to a candidate pool
This chapter assumes you know that a ranked feed orders posts by a predicted score instead of by time. It also assumes you can read short Python functions and sets. Here we cover the first stage of the pipeline, candidate generation. This stage decides which posts get scored at all. The next chapters cover what the ranker does with them.
Why scoring everything is not an option
A large platform may hold billions of posts, and tens of thousands of new ones arrive every minute. A feed request has to return in a few hundred milliseconds, and the ranking model is expensive to run. A model that predicts several reactions for one post, using hundreds of features, might take a fraction of a millisecond per post even when batched on fast hardware. Multiply that by millions of posts per user, for millions of users, and the cost becomes impossible.
The standard answer is a funnel. Early stages are cheap and broad. Later stages are expensive and narrow.
| Stage | Typical input size | Cost per post | Goal |
|---|---|---|---|
| Candidate generation (retrieval) | Millions to billions | Very low | Do not miss good posts |
| Light ranking (optional) | Thousands | Low | Trim the pool further |
| Heavy ranking | Hundreds to a few thousand | High | Predict reactions precisely |
| Re-ranking | Tens to hundreds | Low, but rule-heavy | Enforce variety and policy |
The sizes are illustrative. Real systems vary and rarely publish exact numbers.
What the stage is optimizing
Candidate generation is judged mainly on recall. Recall here means the share of posts the user would have valued that made it into the pool. A post that never enters the pool cannot be shown, however good the ranker is. Precision, meaning how many pool members are good, matters less at this stage, because the ranker will sort them out.
This creates a different trade-off from the ranking stage. The pool must be large enough to contain the good posts and small enough to score within the latency budget. Growing the pool from 500 to 2000 posts may raise recall slightly and quadruple scoring cost. Teams usually pick the pool size by measuring this curve, not by intuition.
Where candidates come from
A feed rarely uses one source. Each source is a separate retrieval method with its own strengths, and the pool is their union.
In-network sources
In-network candidates come from accounts, pages, or groups the user has chosen to follow. The lookup is simple: take the follow list, fetch each account's recent posts, and apply a time window such as the last 48 hours. It is cheap and predictable, and it matches what users expect to see.
There are two ways to build this. With fan-out on write (push), each new post is copied into the inbox of every follower when it is published. Reading a feed is then a quick lookup. With fan-out on read (pull), nothing is copied. At request time the system queries each followed account's recent posts. Push makes reads fast but costs a lot when an account has millions of followers. Pull avoids that cost but makes each read slower. Many systems use push for ordinary accounts and pull for very large ones, then merge the results.
Out-of-network sources
Out-of-network candidates come from accounts the user does not follow. They are what lets a feed introduce new things. Common methods:
- Embedding similarity. A model turns users and posts into vectors, which are lists of numbers where nearby vectors mean similar content or taste. Retrieval finds posts whose vectors are close to the user's vector. At scale this uses approximate nearest neighbor search, which returns very close matches without comparing against every post.
- Collaborative signals. Posts that people similar to you reacted to, or posts your connections engaged with.
- Trending or popular posts. Items with a high recent engagement rate, often filtered by region or topic.
- Topic and location sources. Posts about topics you engaged with, or from your area.
Each source has a weakness, so combining them covers more ground.
| Source | Strength | Typical weakness |
|---|---|---|
| Followed accounts | Matches stated choices | Misses new interests |
| Embedding similarity | Finds relevant strangers | Needs enough history for the user |
| Trending | Works for any user | Generic, favors already-popular posts |
| Collaborative | Surfaces non-obvious matches | Reflects the crowd's taste |
A small working example
The code below builds a pool from three sources. Each source returns a short, ordered list. A merge step then removes duplicates, drops posts the user has already seen, drops blocked authors, and caps the total. The embeddings are two numbers each so you can check the arithmetic by hand.
from dataclasses import dataclass
@dataclass(frozen=True)
class Post:
id: str
author: str
age_hours: float
embedding: tuple[float, float]
recent_likes: int
@dataclass(frozen=True)
class Candidate:
post: Post
source: str
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def in_network(posts, follows, max_age_hours=48, limit=3):
fresh = [p for p in posts
if p.author in follows and p.age_hours <= max_age_hours]
fresh.sort(key=lambda p: p.age_hours) # newest first
return [Candidate(p, "in_network") for p in fresh[:limit]]
def by_embedding(posts, follows, user_vec, limit=3):
pool = [p for p in posts if p.author not in follows]
pool.sort(key=lambda p: dot(p.embedding, user_vec), reverse=True)
return [Candidate(p, "embedding") for p in pool[:limit]]
def trending(posts, follows, limit=2):
pool = [p for p in posts if p.author not in follows]
pool.sort(key=lambda p: p.recent_likes, reverse=True)
return [Candidate(p, "trending") for p in pool[:limit]]
def merge(source_lists, seen, blocked, max_total=10):
pool, taken = [], set()
for candidates in source_lists:
for c in candidates:
if c.post.id in taken or c.post.id in seen:
continue
if c.post.author in blocked:
continue
taken.add(c.post.id)
pool.append(c)
return pool[:max_total]
posts = [
Post("p1", "ana", 2, (0.9, 0.1), 10),
Post("p2", "ben", 30, (0.2, 0.8), 5),
Post("p3", "cy", 5, (0.8, 0.3), 50),
Post("p4", "dee", 60, (0.1, 0.9), 2),
Post("p5", "eli", 1, (0.7, 0.6), 400),
Post("p6", "fay", 3, (0.6, 0.5), 100),
Post("p7", "gus", 4, (0.95, 0.0), 8),
]
follows = {"ana", "ben", "dee"}
seen = {"p7"}
blocked = {"fay"}
user_vec = (1.0, 0.0)
pool = merge(
[
in_network(posts, follows),
by_embedding(posts, follows, user_vec),
trending(posts, follows),
],
seen,
blocked,
)
for c in pool:
print(c.post.id, c.source)Running it prints:
p1 in_network
p2 in_network
p3 embedding
p5 embeddingTrace what happened to the other posts:
p4is from a followed author but is 60 hours old, so the 48-hour window excludes it.p7is the closest embedding match, but the user has already seen it, somergedrops it.p6appears in the trending list, but its author is blocked, somergedrops it.p5appears twice, from embedding and from trending. The first source to supply it keeps the credit, and the duplicate is skipped.
Edge cases and common errors
Eligibility filtering belongs here too. Removing seen posts, blocked authors, deleted posts, and posts the user is not allowed to view is cheaper before scoring than after. Integrity and quality filtering is a separate, richer topic covered later. At this stage the filters are mostly hard yes/no checks.
Window cutoffs create cliffs. A fixed cutoff such as 48 hours drops a post at hour 48.01 and keeps one at 47.99. For users who open the app once a week, a short window empties the in-network source entirely. Some systems widen the window when the user has been away.
Thin sources starve silently. If a user follows few accounts, the in-network source returns almost nothing, and the pool is dominated by whatever the other sources supply. Monitor how many candidates each source contributes per request, not just the total pool size.
Retrieval bias persists downstream. The ranker only sees what retrieval hands it. If the embedding source rarely retrieves posts from small or new accounts, the ranker will never get a chance to rate them well. This is one reason later chapters cover cold start and exploration.
Stale or inconsistent indexes. Retrieval indexes are updated asynchronously. A post may be deleted or restricted while still in an index, so a final eligibility check close to serving time is a common safeguard.
Latency adds up. Sources typically run in parallel, and the slowest one sets the delay. A common design gives each source a timeout and serves the feed without a source that misses it. The cost is a feed that changes quality from one request to the next.
Key takeaways
- The funnel exists because ranking models are too costly to run on every post.
- Candidate generation is judged on recall, and the ranker later handles precision.
- Several sources run in parallel: followed accounts, embedding similarity, trending posts, and others. Each covers the others' blind spots.
- Merging means deduplicating, applying eligibility rules, and capping the size, and those choices affect what the ranker can ever show.
Exercise
In the example, change max_age_hours in the in_network call from 48 to 72, then explain which post joins the pool and what its source label would be. Then state one reason a platform might not simply use a very large window.
Show answer
With a 72-hour window, p4 (author dee, 60 hours old) passes the age check, because dee is followed. The in-network list becomes p1, p2, p4 (sorted newest first, so ages 2, 30, 60), and p4 joins the pool with the source label in_network, after p2. A very large window grows the pool with older posts that the ranker must score, which raises cost and latency, and most old posts rank low anyway because of freshness decay. It also gives the user stale content when the retrieval cap fills with old items.
Exercise
A user follows only three accounts, and all three are inactive this week. Name two sources from this chapter that would still fill the pool, and describe one risk of relying on them.
Show answer
The embedding similarity source and the trending source would still fill the pool, since neither depends on the follow list. A risk is that the pool becomes generic or dominated by already-popular posts, because trending favors posts with existing engagement. Embedding retrieval can also be weak for a user with little history. The feed may then feel unrelated to the user's choices.