Design a Query-Driven Feed Ranking System with Ad Insertion
System DesignModel answerLast updated
Design a low-latency pipeline that blends organic search results with sponsored content, balancing user engagement and revenue at 50k QPS.
Query-Driven Feed Ranking with Sponsored Content
You are designing the backend ranking pipeline for a high-traffic mobile platform where users type queries and receive a blended feed of organic results (creators, videos, places) and paid advertisements. Your job is to architect the system end-to-end.
Scale and Constraints
- Traffic: 50,000 queries per second at peak
- Organic inventory: billions of documents; roughly 500M frequently updated items
- Ad inventory: ~10M active creatives across ~1M campaigns
- Latency: p99 server-side response under 200ms
- Each response: ~20 ranked items per page, mixing organic and sponsored content
What You Need to Design
1. Pipeline Architecture Lay out the stages from raw query to final response. How do you structure retrieval, scoring, and blending? How do the organic and ad funnels relate to each other?
2. Multi-Objective Modeling Users care about relevance and engagement. The platform cares about revenue. How do you represent both in a model, what signals and features matter, and how do you handle the tension between them?
3. Auction and Pacing Mechanics Advertisers bid for placement. Campaigns have daily budgets. How do you score ads, run the auction, and prevent a campaign from blowing its budget in the first hour?
4. Mixing and Ad Load Once you have a ranked list of organic items and a ranked list of ads, how do you decide which slots get ads? What constraints protect the user experience?
5. Latency and Throughput Walk through your strategies for hitting the 200ms budget. Where does compute go and how do you stay under the limit at 50k QPS?
Treat this as a real design conversation: call out assumptions, discuss trade-offs, and flag where you'd run experiments rather than hard-code values.
Hints
Hint 1
Break the pipeline into two parallel funnels — organic and ads — that both start at query time, then merge at a late mixing stage. Each funnel should progressively shrink its candidate set by ~10x per stage so expensive models only score a small pool.
Hint 2
Ad ranking is not just about bid size. Think about what 'effective CPM' means across different campaign types (CPC vs. oCPM), and why predicted click and conversion probabilities need to be well-calibrated — not just accurate — since they directly determine prices.
Hint 3
Hard constraints in the mixer (no ad in slot 1 for navigational queries, minimum spacing between ads, per-session fatigue caps) are your safety net. They protect user experience even when the revenue-engagement trade-off weight λ is tuned aggressively.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Step 1: Pin Down Assumptions and Latency Budget
Before drawing boxes, state what you're building. The pipeline handles typed queries returning a vertical list of mixed content. At 50k QPS and 200ms p99, the math is tight. A reasonable time allocation:
| Stage | Budget |
|---|---|
| Query understanding | ~15ms |
| Parallel retrieval (organic + ads) | ~40ms |
| Ranking (light + heavy models) | ~60ms |
| Auction and blending | ~15ms |
| Network, serialization, slack | ~70ms |
The core constraint is that you cannot run heavy models over thousands of candidates. Every stage's job is to reduce the pool so the next stage can afford to spend more per item.
Step 2: Pipeline Architecture
Run two funnels in parallel from the moment the query arrives.
Organic funnel:
- Retrieval (~5,000 candidates): run lexical (BM25 inverted index) and semantic (two-tower ANN) retrieval in parallel and union results. Navigational queries like creator names favor lexical; open-ended queries favor the semantic path.
- Light ranker (~500 candidates): small GBDT or shallow MLP on cached features. Cheap pruning only.
- Heavy ranker (~50 candidates): multi-task deep model (DCN or MMoE architecture) on GPU or highly optimized CPU.
Ads funnel:
- Targeting filter + retrieval (~2,000 candidates): hard filters first (geo, age, brand safety, budget remaining), then keyword match plus a separate two-tower ANN tuned for ad relevance.
- Light pCTR scorer (~200 candidates): fast model to prune low-relevance ads.
- Heavy pCTR/pCVR scorer (~30 candidates): full prediction for auction input.
After both funnels complete, the auction runs on the ad pool, then the mixer interleaves results.
Step 3: Multi-Objective Modeling
Organic scoring. A multi-task model produces several predictions that combine into a single value:
V_org = w1·P(click) + w2·E[watch_time] + w3·P(follow) − w4·P(hide)
The weights aren't guesses — they're calibrated against long-term holdout experiments, because short-term click optimization often trades away retention.
Ad scoring. The model predicts pCTR and, for conversion-optimized campaigns, pCVR. Calibration matters far more here than in the organic path, because these probabilities set prices. A model with high AUC but poor calibration will systematically over- or undercharge advertisers. Use Platt scaling or isotonic regression per segment and track calibration as a first-class metric separate from AUC.
Essential features:
- Query: tokens, embedding, intent class (navigational vs. exploratory), query popularity tier
- User: embedding, recent engagement history, ad fatigue counters (ads seen in last hour, historical ad CTR)
- Item/ad: embedding, historical CTR at 1h/1d/7d windows, freshness, creator or advertiser quality score
- Cross features: query–item semantic similarity, user–advertiser past interaction
- Context: slot position, time of day, device type, network quality
A common mistake is ignoring position bias. Train with position as a feature and fix it to a neutral value at serving time — otherwise the model learns that high-position items are good, and the ranking becomes self-reinforcing.
Step 4: Auction and Pacing
Effective CPM. Normalize all bids to a common currency:
- CPC campaign:
eCPM = bid × pCTR × 1000 - oCPM/target-CPA campaign:
eCPM = target_CPA × pCTR × pCVR × 1000
Add a relevance quality term so high bids can't win with irrelevant ads:
AdScore = α_c · eCPM + β · Q(ad, query, user)
Pacing (α_c). Without pacing, popular time slots drain budgets before most users are even awake. A PID controller per campaign compares actual spend to a target spend curve (shaped by forecasted traffic, not a flat line). Every few seconds it adjusts α_c ∈ [0, 1]. Overspending lowers α_c, effectively shading the bid. Underspending raises it. Pacing state lives in a local cache refreshed every 1–5 seconds — small overspend from staleness is absorbed by a safety margin in budget caps.
Auction mechanics. Run a generalized second-price auction over the ranked ad pool. The winner pays the minimum eCPM needed to hold its rank, divided back through pCTR to get a per-click charge. Apply a per-query reserve price and drop any ad below a minimum relevance threshold regardless of bid. This prevents advertisers from gaming placement purely through high bids on irrelevant queries.
Step 5: Mixing Organic and Ads
Avoid hard-coded rules like "every 4th slot is an ad." Instead, treat slot assignment as a utility maximization problem in a shared currency:
U(item at slot k) = position_weight_k · (V_engagement + λ · Revenue − γ · UserCost)
Revenueis 0 for organic, expected charge for adsUserCostcaptures predicted negative impact: increased hide rate, session shorteningλis the exchange rate between revenue and engagement — set by offline calibration and long-term experiments, not intuition
Greedy allocation: walk slots top-down, inserting the best remaining ad only when its utility exceeds the organic item it would displace.
Hard constraints that override the optimization:
- No ad in slot 1 for navigational queries (a user searching a friend's name expects that friend)
- Minimum gap between ads (e.g., 4 items)
- Maximum ad load per page and per session
- No ads on sensitive query classes
- Per-user fatigue caps (e.g., no more than N ad impressions per hour)
These constraints are non-negotiable guardrails. They exist precisely because λ will be mis-tuned at some point — they prevent a bad experiment from causing a bad user experience at scale.
Step 6: Hitting the Latency Target
- ANN indexes (HNSW or IVF-PQ) sharded across nodes, fully in memory. The ad index is ~10M items × ~1KB ≈ 10GB, feasible in RAM.
- Feature serving: online feature store (Redis-style) co-located with ranking nodes. Pre-compute and cache user embeddings; refresh on new events, not on every query.
- Model optimization: quantize heavy rankers to INT8. Batch queries across concurrent requests to amortize GPU overhead.
- Caching: cache retrieval results for popular queries with TTLs short enough to stay fresh (seconds for trending content). Do not cache personalized rankings.
- Async logging: impression and click events go to a message queue (Kafka). Billing, pacing updates, and training label generation are all downstream consumers — none of this is in the critical path.
A common failure mode is adding a synchronous call to the pacing service on every query. Keep pacing state in a local cache and push updates from a background process; the critical path reads, it does not write.
Common Mistakes to Avoid
- Conflating AUC with calibration for ad models — calibration is what drives correct pricing.
- Flat pacing curves — campaigns front-load if the target is uniform, since early traffic is lighter.
- No relevance floor in the auction — bid-only ranking degrades user experience and eventually advertiser ROI.
- Hard-coded ad load rules — they're brittle. A utility-based mixer with hard safety constraints is more robust to traffic pattern changes.
- Synchronous pacing or billing in the ranking path — this is a latency killer.