Designing a Feed Ad Recommendation and Ranking Engine
Machine LearningModel answerLast updated
Architect an end-to-end Machine Learning ad recommendation system for a content feed, balancing ad revenue with user experience, delayed feedback, counterfactual evaluation, and budget pacing.
You are tasked with designing an end-to-end ad recommendation and ranking system for an integrated content feed (such as a short-form video application or news stream). At each position in the feed, the application can insert either an organic content item or a targeted advertisement.
Your solution should address the following requirements:
- System Objectives & Trade-offs: Define the multi-objective optimization problem. Explain how to mathematically combine user retention/experience metrics with advertiser monetization goals, and how to decide whether to show an ad or an organic item at a given slot.
- Predictive Modeling Architecture: Propose the ML modeling framework for predicting key engagement events (pCTR, pCVR, expected value/revenue, negative feedback). Define the data schema, feature engineering, and label generation strategies, explicitly addressing sample selection bias (e.g., in conversion modeling) and delayed feedback.
- Core ML Challenges: Detail how your design handles:
- Counterfactual evaluation and logged-policy selection bias.
- Exploration vs. exploitation (e.g., cold start for new ads/creatives).
- Real-time advertiser budget pacing and delivery constraints.
- Evaluation Strategy: Outline an offline metrics framework (including counterfactual estimators) and an online A/B testing plan with business and guardrail metrics.
Hints
Hint 1
Formulate the slot decision as a constrained optimization problem, using a Lagrangian multiplier (or exchange rate) to convert organic user-experience degradation into monetary units.
Hint 2
Address CVR sample selection bias via Entire Space Sequential Pattern Structuring (such as ESMM) to avoid training exclusively on clicked impressions.
Hint 3
For delayed conversion feedback, consider importance weighting (fake-negative correction) or survival/delay modeling rather than waiting for full attribution windows to close.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Objectives and Constrained Optimization
An ad ranking system must balance three competing forces:
- User Experience: Retaining users long-term by minimizing ad fatigue, fast skips, hides, and reports.
- Advertiser Value: Delivering meaningful actions (clicks, video views, conversions, app installs) within budget.
- Platform Revenue: Maximizing total yield (eCPM) while maintaining platform health.
Mathematical Formulation
Rather than attempting a heuristic weighted sum, we frame the problem as constrained optimization:
$$\max_{\boldsymbol{x}} \sum_{i \in \text{Ads}} \text{Revenue}(i) \cdot x_i \quad \text{subject to} \quad \sum_{i \in \text{Ads}} \text{UserHarm}(i) \cdot x_i \le B_{\text{harm}}, \quad \text{Spend}(c) \le \text{Budget}(c) \ \forall c$$
Using a Lagrangian relaxation, this optimizes an unconstrained total score for candidate ad $a$:
$$\text{TotalValue}(a) = \text{eCPM}(a) + \alpha \cdot \text{OrganicQuality}(a) - \lambda \cdot p(\text{NegativeFeedback}(a))$$
Where:
- $\text{eCPM}(a) = \text{Bid}(a) \times p(\text{Objective Event} \mid \text{Impression})$.
- For Cost-Per-Click (CPC): $\text{Bid}_{\text{CPC}} \times p(\text{CTR})$.
- For Cost-Per-Action (CPA): $\text{Bid}_{\text{CPA}} \times p(\text{CTR}) \times p(\text{CVR})$.
- $\text{OrganicQuality}(a)$: The predicted engagement value (e.g., $p(\text{Watch} > 15s)$) if the creative was evaluated as organic content.
- $p(\text{NegativeFeedback}(a))$: Predicted probability of an immediate skip, hide, or user report.
- $\alpha, \lambda$: Hyperparameters representing the trade-off exchange rate between monetization and user experience.
Ad vs. Organic Insertion Policy
An ad is eligible to displace an organic item at slot $k$ if and only if:
$$\text{TotalValue}(a) > \text{OrganicScore}(\text{Item}_k) \times \gamma$$
where $\gamma$ is a parameter tuned via long-term holdout A/B tests to enforce retention guardrails. Hard constraints sit on top of this scoring mechanism:
- Minimum distance between ads (e.g., at least 3 organic items between any two ads).
- Maximum ad load limit per session (e.g., $\le 15%$ total feed items).
- Per-user daily frequency caps per campaign and per advertiser.
2. System Architecture
[Ad Request]
│
▼
┌────────────────────────────────────────────────────────┐
│ 1. Retrieval & Filtering (~10M -> ~2k ads) │
│ Targeting, Geo/Age, Hard Caps, Dual-Tower ANN │
└────────────────────────────┬───────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 2. Light Ranker / Candidate Reduction (~2k -> ~200) │
│ Distilled Multi-Layer Perceptron │
└────────────────────────────┬───────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 3. Heavy Ranker (Multi-Task DLRM / MMoE) │
│ Predicts: pCTR, pCVR, p(Watch), p(Hide) │
└────────────────────────────┬───────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 4. Calibration & Pacing Adjustment │
│ Isotonic Regression + Pacing Multiplier (w_c) │
└────────────────────────────┬───────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 5. Auction & Slot Allocation │
│ GSP Pricing, Organic Interleaving, Score Selection │
└────────────────────────────────────────────────────────┘
The system budget latency is < 80 ms at p99 over a scale of ~1M requests/sec.
3. Predictive Modeling Deep Dive
Deep Learning Architecture
We employ a Multi-gate Mixture-of-Experts (MMoE) Deep Learning Recommendation Model (DLRM) architecture:
┌────────────┐ ┌────────────┐ ┌────────────┐
Heads: │ p(CTR) │ │ p(CVR) │ │ p(Hide) │
└─────▲──────┘ └─────▲──────┘ └─────▲──────┘
│ │ │
┌─────┴────────────────┴────────────────┴─────┐
Task Gates: │ MMoE Layer │
└─────▲────────────────▲────────────────▲─────┘
│ │ │
┌─────┴────────┐ ┌─────┴────────┐ ┌─────┴────────┐
Experts: │ Expert 1 │ │ Expert 2 │ │ Expert 3 │
└─────▲────────┘ └─────▲────────┘ └─────▲────────┘
│ │ │
Shared Layer: └─────┴────────────────┴────────────────┴─────┘
Dense & Sparse Embeddings
- Shared Input Layer: Sparse categorical features (User ID, Ad ID, Campaign ID, Device Type, Context) combined with continuous dense embeddings (User engagement vectors, Creative video embeddings generated via a vision transformer).
- Sequential Features: A Transformer (DIN/BST style) encoding the user's last 50 viewed items, clicked ads, and skipped items.
Key Modeling Challenges & Solutions
A. CVR Sample Selection Bias (ESMM)
Standard CVR models are trained only on clicked impressions ($S_{\text{click}}$), but deployed across all impressions ($S_{\text{imp}}$). This causes severe selection bias during inference.
Solution: Use an Entire Space Sequential Pattern Model (ESMM). Instead of training $p(\text{CVR}) = p(y=1 \mid x, z=1)$ directly on clicked data, train two auxiliary tasks over the entire space $S_{\text{imp}}$:
- $p(\text{CTR}) = p(z=1 \mid x)$
- $p(\text{CTCVR}) = p(y=1, z=1 \mid x) = p(z=1 \mid x) \times p(y=1 \mid x, z=1)$
Where $z$ indicates a click and $y$ indicates a conversion. The CVR score is derived as $\text{pCVR} = \frac{\text{pCTCVR}}{\text{pCTR}}$.
B. Delayed Feedback Loop
Conversions can take hours or days to materialize. Training on immediate streaming logs leads to false negatives for recent impressions.
Solutions:
-
Fake Negative Calibration with Importance Weighting: Log impressions immediately as negatives ($y=0$). When a delayed conversion event arrives later, ingest a duplicate record with $y=1$ and an importance weight to adjust the gradient loss:
$$L = - w_{fn} \cdot y \log(\hat{p}) - (1 - y) \log(1 - \hat{p})$$
-
Survival / Hazard Modeling (Chapelle's Delay Model): Jointly predict the probability of conversion $p(y=1)$ and the delay distribution $p(d \mid y=1)$ parameterized as an exponential or Weibull distribution. Samples that have not yet converted are treated as right-censored observations rather than true negatives.
C. Position Bias
Feed positions strongly influence CTR regardless of ad quality.
-
Training: Pass position as an explicit feature or use a dedicated Position Bias Tower added to the logit:
$$\text{Logit}{\text{final}} = \text{Logit}{\text{content}}(x) + \text{Logit}_{\text{position}}(\text{pos})$$
-
Inference: Set $\text{pos} = 0$ or average position to evaluate pure ad relevance independently of slot placement.
4. Exploration, Pacing, and Auction
Exploration for Cold Start Ads
New ads lack historical interaction data, leading to low pCTR estimates and starved impressions.
-
Content Feature Warm-start: Initialize new Ad ID embeddings using an average of historical embeddings from the same advertiser category and multi-modal creative embeddings (Text + Vision).
-
Upper Confidence Bound (UCB) / Thompson Sampling Boost: Score ads using posterior estimates:
$$\text{Score}(a) = \hat{\mu}_a + c \cdot \sqrt{\frac{\ln N}{n_a}}$$
where $n_a$ is the number of impressions received by ad $a$. The exploration allocation is capped at a strict global system budget (e.g., $1.5%$ of total impression opportunities).
Real-time Budget Pacing
To prevent an advertiser's budget from being exhausted early in the day, a dynamic pacing multiplier $w_c \in [0, 1]$ is applied to campaign $c$:
$$\text{eCPM}_{\text{paced}}(a) = w_c \cdot \text{eCPM}(a)$$
- Probabilistic Pacing: $w_c$ is calculated by comparing actual cumulative spend to the target linear spend rate at time $t$. If spending is too fast, $w_c$ decreases, effectively raising the auction threshold for that campaign.
Pricing Mechanism
We implement a Generalized Second Price (GSP) auction over the calculated TotalValue. The minimum bid required for ad $a_i$ to retain its position over ad $a_{i+1}$ is:
$$\text{Charged Price}(a_i) = \frac{\text{TotalValue}(a_{i+1}) - \alpha \cdot \text{OrganicQuality}(a_i) + \lambda \cdot p(\text{NegativeFeedback}(a_i))}{p(\text{Objective Event} \mid a_i)}$$
5. Offline & Online Evaluation Strategy
Offline Evaluation Framework
| Metric Type | Metric Name | Purpose / Focus |
|---|---|---|
| Predictive Accuracy | Relative Cross-Entropy (RCE) | Assesses calibration & log-loss improvements over baseline priors across pCTR and pCVR heads. |
| Ranking Quality | Group AUC (GAUC) | Measures intra-user intra-session ranking quality, preventing bias from global active user distributions. |
| Counterfactual | Normalized Doubly Robust (NDR) Estimator | Combines Inverse Propensity Scoring (IPS) with a learned baseline reward model to evaluate new policies on logged data without online risk. |
$$\hat{V}{\text{DR}}(\pi{\text{new}}) = \frac{1}{N} \sum_{i=1}^N \left( \frac{\pi_{\text{new}}(a_i \mid x_i)}{\pi_{\text{old}}(a_i \mid x_i)} (r_i - \hat{r}(x_i, a_i)) + \hat{r}(x_i, \pi_{\text{new}}(x_i)) \right)$$
Note: Logging propensities $\pi_{\text{old}}(a_i \mid x_i)$ during online serving is mandatory to calculate IPS weights offline.
Online A/B Metrics & Guardrails
- Primary Monetization Metrics:
- Ad Revenue per Daily Active User (ARPDAU).
- Average Effective Cost Per Thousand Impressions (eCPM).
- Advertiser Campaign Budget Utilization Rate.
- Primary User Engagement Metrics:
- Total Feed Time Spent per User per Day.
- Days-Active Retention ($D1, D7, D30$).
- Guardrail Metrics (Must not regress beyond threshold $\epsilon$):
- Negative Feedback Rate (Hides, Reports, Fast Skips $< 2\text{s}$) $\rightarrow$ Threshold: $\le +0.5%$.
- Organic Video View Through Rate (VTR) $\rightarrow$ Threshold: $\ge -0.1%$.
- App Latency p99 $\rightarrow$ Threshold: $\le 80\text{ms}$.