Building a Real-Time Ad Recommendation Engine
Machine LearningModel answerLast updated
Design a machine learning system that delivers personalized advertisements to users at scale, covering infrastructure, modeling, and evaluation.
You're building an advertisement recommendation engine for a large social platform. The system must deliver relevant ads to hundreds of millions of users with strict latency requirements while balancing platform revenue, advertiser return on investment, and user satisfaction.
Your task is to design the complete machine learning system from end to end. Address the following:
- System architecture: How would you structure the pipeline from candidate selection through final ad delivery?
- Machine learning components: What models would you use at each stage, and how would you train them?
- Feature design: What signals would you incorporate, and how would you make them available at inference time?
- Evaluation strategy: What metrics matter offline and online? How would you run experiments?
- Cold-start problem: How would you handle new users with no history and newly launched ad campaigns?
- Practical challenges: Address issues like delayed conversions, position bias, and budget pacing.
Discuss trade-offs, quantify where possible, and explain how you'd validate that the system works correctly.
Hints
Hint 1
Break the problem into stages with different speed/accuracy trade-offs—you can't score millions of ads in real-time
Hint 2
Remember that ad systems involve auctions and pricing, not just ranking—predictions must be calibrated, not just well-ordered
Hint 3
Training data comes from your own serving decisions, creating feedback loops and biases that need explicit handling
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Building a Real-Time Ad Recommendation Engine
Understanding the Problem
This question tests your ability to translate business requirements into a production ML system. Success means generating revenue while maintaining user experience and advertiser satisfaction—a multi-stakeholder optimization problem with real-time constraints.
1. Scoping and Requirements
Start by establishing concrete numbers:
Scale assumptions:
- 400M daily active users
- 15 ad opportunities per user daily = 6B requests/day
- ~70k queries per second average, ~200k at peak
- 8M active advertisements from 800k advertisers
Performance targets:
- p99 latency: 80ms (within a 250ms feed load budget)
- Model refresh: hourly for rapid iteration
- New campaign activation: under 5 minutes
Objectives:
- Maximize platform revenue per user
- Deliver advertiser performance (conversions within cost targets)
- Maintain user engagement (minimize ad-driven churn)
2. Multi-Stage Architecture
A single model cannot evaluate millions of ads in 80ms. Use a funnel approach:
| Stage | Candidates | Method | Time |
|---|---|---|---|
| Filtering | 8M → 50k | Index lookup (targeting, budgets, frequency caps) | 5ms |
| Retrieval | 50k → 1k | Embedding similarity (ANN search) | 20ms |
| Coarse ranking | 1k → 150 | Lightweight model (boosted trees) | 15ms |
| Fine ranking | 150 → scored | Deep neural network (multi-objective) | 25ms |
| Auction & diversification | Final selection | Business logic | 10ms |
Why this funnel? Early stages use cheap operations (index lookups, dot products) to eliminate poor candidates. Expensive deep models only see pre-filtered sets.
3. Modeling Approach
Retrieval Stage
Use a two-tower architecture:
- User tower: encodes demographics, interests, recent activity
- Ad tower: encodes advertiser, category, creative content
- Training objective: maximize dot product for engaged ads, minimize for ignored ones
Use approximate nearest neighbor search (HNSW or FAISS) to find top-k ads by embedding similarity. Refresh ad embeddings every 15 minutes as new campaigns launch.
Ranking Model
Deploy a multi-task neural network predicting:
- p(click): probability user clicks the ad
- p(conversion|click): probability of conversion given click
- p(negative): probability user hides/reports the ad
Architecture choice: Use a shared bottom layer (handles ID embeddings and cross features) with task-specific towers. Something like Multi-gate Mixture-of-Experts (MMoE) works well when tasks have different data distributions.
Critical detail for conversions: Train on all impressions, not just clicks. Predict p(click AND convert) directly, then derive p(convert|click) = p(click AND convert) / p(click). Training only on clicks creates severe selection bias.
Scoring Function
Rank ads by expected value:
score = bid × p(click) × p(convert) × value_weight - penalty × p(negative)
For auction pricing, use a generalized second-price mechanism where winners pay just enough to beat the next-highest bidder.
Why calibration matters: Advertisers set budgets based on your predictions. If you predict 5% click rate but deliver 3%, they'll leave. Apply calibration (isotonic regression or temperature scaling) per advertiser segment and monitor prediction/actual ratios continuously.
4. Feature Engineering
User features:
- Static: age, location, device type, platform
- Behavioral: categories of recent engagement, average session length
- Sequential: last 30 interactions encoded via transformer or attention layer
- Aggregate statistics: CTR on lifestyle vs. tech ads (7-day and 30-day windows)
Ad features:
- Campaign metadata: advertiser ID, category, budget tier
- Creative characteristics: image embeddings (from pre-trained vision model), text embeddings, aspect ratio
- Performance history: smoothed CTR using empirical Bayes (important for new ads with little data)
- Landing page signals: load time, mobile optimization score
Cross features:
- Has this user seen this advertiser before?
- Similarity between user interests and ad category
- Time since last ad from this vertical
Contextual:
- Time of day, day of week
- Session depth (first scroll vs. 20 minutes in)
- Network connection quality
Real-time counters (via streaming):
- Impressions of this ad to this user today (fatigue tracking)
- Clicks on this category in the last hour
- Budget spend rate for pacing decisions
Implementation: Use a feature store with offline (Hive/BigQuery) and online (Redis/DynamoDB) layers. Define features once; the system materializes them for both training (point-in-time correct) and serving (low latency).
5. Handling Difficult Challenges
Cold Start
New users:
- Start with demographic-based targeting (age, location)
- Use a "generic user" embedding initially
- Apply Thompson sampling: explore different ad categories aggressively in first session
- Update quickly—after 5-10 interactions, personalized signals emerge
New ads:
- Use advertiser's historical performance as prior
- Extract creative features (image/text embeddings) immediately
- Route to exploration traffic (2% of requests see randomly sampled ads)
- Apply optimistic estimates (upper confidence bound) to give new campaigns a chance
Delayed Conversions
Conversions arrive hours or days after the click. Three strategies:
- Immediate labels: Train click prediction on fresh data
- Delayed feedback model: Use survival analysis techniques or treat conversion as a time-to-event problem
- Importance weighting: Upweight recent negatives less, as they might still convert
Never mark a click as "negative conversion" immediately—wait for the attribution window (typically 7 days).
Position Bias
Ads at the top get more clicks regardless of relevance.
Training: Include position as an input feature Serving: Fix position to a neutral value (e.g., position 3) or use a separate position tower that you can zero out
Also collect data where positions are randomized to measure true relevance.
Feedback Loops
Your model creates its own training data—if it never shows certain ads, it never learns they might work.
Solution:
- Reserve 1-2% of traffic for exploration (random or Thompson sampling)
- Use inverse propensity scoring to reweight training examples
- Train partly on exploration data where selection is unbiased
Budget Pacing
Advertisers set daily budgets. Spend it all by 8am and you waste inventory; run out at 11pm and you underdeliver.
Implement a pacing controller:
- Track spend rate vs. time
- Adjust effective bid (bid shading) or throttle delivery probability
- Use PID control loop for smooth spending
6. Evaluation Strategy
Offline Metrics
- Log loss (cross-entropy): Primary metric, measured relative to baseline
- AUC-ROC: Ranking quality
- Calibration: Predicted probability / actual rate, sliced by segment
- Recall@k: For retrieval stage, what fraction of eventually-clicked ads appear in top-k?
Use replay evaluation on logged data: what would this new model have done?
Online Metrics (A/B Testing)
Revenue metrics:
- Revenue per thousand impressions (RPM)
- Total revenue
- Average eCPM (effective cost per mille)
Advertiser health:
- Click-through rate
- Conversion rate
- Cost per acquisition vs. target
- Budget utilization (% of advertisers hitting daily budget)
User experience (guardrails):
- Session duration
- Ad hide rate
- Content engagement (likes, comments on non-ad content)
- User return rate (next-day retention)
Testing methodology: Run multi-week experiments with stratification by user activity level. Watch for interference effects—ads are a marketplace, so changing one advertiser's outcomes affects others. Consider cluster randomization (by geography or time).
7. Common Mistakes to Avoid
- Ignoring calibration: Treating this as a ranking-only problem instead of a pricing problem
- Selection bias: Training conversion models only on clicked examples
- Feature leakage: Using future information or recomputing features at training time differently than serving
- Underestimating complexity: Thinking a single model can handle retrieval through ranking
- Forgetting business constraints: Not incorporating budget pacing, frequency caps, or diversity requirements
Summary
A production ad system requires:
- Staged architecture to handle scale (can't score millions of ads deeply)
- Multi-objective modeling to balance clicks, conversions, and negative signals
- Careful calibration because predictions drive pricing
- Explicit bias handling for position, selection, and delayed feedback
- Comprehensive metrics covering platform, advertiser, and user outcomes
The key insight: this isn't just a machine learning problem—it's a marketplace design problem where ML is one component alongside auctions, pacing, and policy constraints.