Design a Machine Learning System for Social Feed Ad Ranking
Machine LearningModel answerLast updated
Design an end-to-end ML architecture to optimize feed ad click-through rates, detailing metric trade-offs, multi-stage serving pipelines, graph/two-tower embeddings, and bias mitigation.
You lead the ad ranking engineering team for a major social networking platform. Your team is tasked with building a machine learning system to improve the Click-Through Rate (CTR) of sponsored posts interleaved within the primary user activity feed.
The business wants to increase user engagement with ads while preserving the quality of the organic feed experience and maintaining long-term user retention. The model predictions feed directly into an downstream ad auction where bids are weighted by expected action probabilities.
Walk through how you would frame, build, train, serve, and operate this ad recommendation system end to end. Be prepared to go into technical depth on:
- System Goals and Business Constraints: Balancing CTR optimization against user experience guardrails and auction integrity.
- Multi-Stage Serving Architecture: Designing a latency-constrained system from retrieval through ranking to auction.
- Training Data Pipeline: Designing log schemas, constructing positive/negative labels without data leakage, and preventing sampling bias.
- User & Ad Representation Learning: Implementing two-tower representations and graph-based embedding approaches (e.g., GNNs/PinSage).
- Operational Realities: Handling position bias, delayed feedback, cold-start items, model calibration, and explore-exploit trade-offs.
Hints
Hint 1
CTR cannot be optimized in a vacuum; raw CTR models will over-index on clickbait. Explain how probability calibration impacts auction scoring (eCPM = Bid × pCTR).
Hint 2
Pay close attention to negative sampling: using unclicked feed impressions is mandatory, but how do you handle unseen or filtered candidates without introducing selection bias?
Hint 3
For embeddings, contrast how two-tower networks (optimized for ANN low-latency retrieval) differ in structure and feature usage from graph-based architectures (optimized for structural similarity across heterogeneous graphs).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Goals and Metric Architecture
Optimizing pure Click-Through Rate (CTR) in isolation leads to undesirable outcomes, such as showing clickbait or low-quality ads that burn user trust and degrade organic retention. Because ad ranking feeds an auction mechanism, predicted probabilities ($p\text{CTR}$) directly scale ad bids to compute expected revenue per mille ($\text{eCPM} = \text{Bid} \times p\text{CTR} \times 1000$). Thus, predictions must be both well-calibrated probabilities and accurately ordered.
Metric Framework
┌─────────────────────────┐
│ Business Success │
│ (Ad Revenue & ROAS) │
└────────────┬────────────┘
│
┌──────────────────────────┴──────────────────────────┐
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ Primary Metrics │ │ Guardrail Metrics │
│ │ │ │
│ • Ad CTR │ │ • Organic session length│
│ • Long-term conversion │ │ • Ad hide / report rate │
│ • eCPM / Publisher Rev │ │ • D7 / D30 retention │
└─────────────────────────┘ └─────────────────────────┘
- Primary Online Metrics:
- Ad CTR: $\frac{\text{Total Ad Clicks}}{\text{Total Ad Impressions}}$.
- Conversion Rate (CVR) & Advertiser ROAS: Downstream actions (purchases, app installs) within an attribution window (e.g., 7-day click-through).
- Ad Revenue / eCPM: Effective revenue generated per 1,000 ad impressions.
- Guardrail Metrics:
- Organic Retention & Session Duration: Daily Active Users (DAU), D7/D30 retention, and session length must not drop statistically significantly ($p < 0.01$).
- Negative Feedback Rate: Ad hides, reports, and explicitly marked "not relevant" actions per 1,000 impressions.
- Ad-to-Organic Ratio: Capped strictly (e.g., maximum 1 ad per 5 organic feed items).
- Offline Model Evaluation:
- Log Loss / Cross-Entropy: Measures probability quality.
- Normalized Entropy (NE): $\text{NE} = \frac{\text{Cross Entropy}}{\text{Background Entropy}}$. Measures model lift over baseline prevalence.
- ROC-AUC / PR-AUC: Measures ranking capability per user session (evaluated within user groups to remove cross-user distribution skew).
- Calibration Ratio (Expected / Observed): $E/O = \frac{\sum \hat{y}_i}{\sum y_i}$. Must sit strictly within $[0.99, 1.01]$ overall and across key slices (ad categories, user activity tiers).
2. Overall System Architecture
To serve millions of requests per second under strict latency budgets ($\le 30\text{ ms}$ p99 budget for the ad sub-system), candidate ads flow through a multi-stage funnel that progressively trades down candidate volume for model complexity.
+-----------------------------------------------------------------------------------+
| 1. Candidate Eligibility & Targeting Filter (~1,000,000 ads -> ~10,000 ads) |
| - Geo, age, device, demographic targeting, budget pacing, frequency caps |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 2. Dual Retrieval Stage (~10,000 ads -> ~500 ads) |
| - Two-Tower ANN Retrieval (HNSW / ScaNN vector indices) |
| - Graph-Based Nearest Neighbors (PinSage graph traversal) |
| - Real-Time Contextual & Keyword Matchers |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 3. Pre-Ranking / Lightweight Ranker (~500 ads -> ~50 ads) |
| - Factorization Machine / Small DNN with distilled features |
| - Latency budget: ~5ms |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 4. Heavy Ranking Model (~50 ads -> Top candidates rated by pCTR & pCVR) |
| - Deep & Cross Network (DCNv2) / Deep Interest Evolution Network (DIEN) |
| - Full cross-features: user sequence, deep ad embeddings, dynamic context |
| - Latency budget: ~15ms |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 5. Auction, Business Logic & Re-Ranking (Top candidate selected) |
| - Expected Value Scoring: Score = Bid * pCTR * (pCVR)^alpha - Disutility_Penalty |
| - Diversity filtering, ad-spacing rules, exploration/exploitation injection |
+-----------------------------------------------------------------------------------+
3. Training Data Construction and Log Pipeline
Log Schema and Event Joining
A major failure mode in recommendation ML is logging unshown candidates or relying exclusively on organic historical interactions. Training data must be generated directly from logged ad impressions.
LOG JOINING ARCHITECTURE
┌────────────────────────┐ ┌────────────────────────┐ ┌────────────────────────┐
│ Impression Log │ │ Click Log │ │ Conversion Log │
│ (Impression ID, User, │ │ (Impression ID, User, │ │ (Impression ID, User, │
│ Ad, Context, Rank) │ │ Timestamp, Meta) │ │ Value, Timestamp) │
└───────────┬────────────┘ └───────────┬────────────┘ └───────────┬────────────┘
│ │ │
└───────────────┬───────────────┘ │
▼ │
┌───────────────────────────────┐ │
│ Stream Joiner (Flink/Spark) │ │
│ Join Window: e.g., 30 mins │ │
└──────────────┬────────────────┘ │
│ │
▼ │
┌───────────────────────────────┐ │
│ CTR Dataset: │ │
│ Label = 1 if Clicked else 0 │ │
└──────────────┬────────────────┘ │
│ │
└───────────────────────┬───────────────────────┘
▼
┌───────────────────────────────┐
│ CVR Dataset: │
│ Delayed Join Window (7 days) │
│ Label = 1 if Converted else 0 │
└───────────────────────────────┘
- Impression Stream: Generated when an ad unit renders on the user's viewport. Records
impression_id,user_id,ad_id,position_slot,context_features, andserving_propensity. - Click Stream: Emitted on click events. Joined with the Impression Stream over a real-time window (e.g., 30 minutes via Apache Flink) on
impression_id. - Negative Label Construction: If an impression expires from the join window without a matching click event, it is emitted as a negative sample ($y = 0$). If a click arrives within the window, it is emitted as a positive sample ($y = 1$).
Data Leakage and Bias Safeguards
- No Future Information: Aggregated historical features (e.g.,
user_click_count_past_7d) must be strictly timestamp-point-in-time correct, computed using state prior to the impression event. - Sample Selection Bias Mitigation: Do not train the ranker on unrendered retrieved candidates without explicit propensity weighting. Models trained only on top-ranked impressions suffer from selection bias; unselected items never receive feedback. We maintain a small random exploration slice ($\approx 1%$) where candidates are shown non-optimally to collect unbiased ground-truth labels.
4. Deep Embedding Infrastructure
A. Two-Tower Deep Neural Network (Retrieval Stage)
The two-tower model maps candidate ads and user context into a shared vector space $\mathbb{R}^d$, allowing fast Approximate Nearest Neighbor (ANN) search via HNSW or ScaNN algorithms.
USER TOWER AD TOWER
┌───────────────────────┐ ┌───────────────────────┐
│ Real-time Context │ │ Creative Image/Text │
│ User Demographic │ │ (ResNet / Transformer)│
│ Engagement History │ │ Ad Metadata, Category │
└───────────┬───────────┘ └───────────┬───────────┘
│ │
▼ ▼
┌───────────────────────┐ ┌───────────────────────┐
│ Multi-Layer Perceptron│ │ Multi-Layer Perceptron│
└───────────┬───────────┘ └───────────┬───────────┘
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ User Vector U │ │ Ad Vector V │
└───────┬───────┘ └───────┬───────┘
│ │
└───────────────────────┬──────────────────────┘
▼
Dot Product / Cosine
s(U, V) = U^T * V
- Training Loss: Temperature-parameterized In-Batch Sampled Softmax Loss over positive interactions $(u_i, a_i)$: $$\mathcal{L} = -\sum_{i=1}^{B} \log \frac{\exp(\mathbf{u}_i^T \mathbf{a}_i / \tau)}{\exp(\mathbf{u}_i^T \mathbf{a}i / \tau) + \sum{j \neq i} \exp(\mathbf{u}_i^T \mathbf{a}_j / \tau)}$$
- Correcting Sampled Softmax Bias: Standard in-batch negatives over-sample popular ads. We subtract $\log(p_j)$ from logits, where $p_j$ is the background selection probability of ad $j$, preventing the representation from collapsing into a simple popularity estimator.
B. Graph Neural Network Embeddings (PinSage / PinnerSage Style)
Ads and users exist within a dynamic heterogeneous interaction graph. We construct a bipartite graph with node sets $\mathcal{U}$ (Users) and $\mathcal{A}$ (Ads), connected by directed edges $\mathcal{E}$ representing positive historical engagements (e.g., clicks, long views, conversions).
GRAPH STRUCTURE GRAPH CONVOLUTION
( User 1 ) ( User 2 ) ┌─────────────────┐
/ \ / │ Neighbor Agg: │
/ \ / │ Importance- │
[Ad A] [Ad B] │ weighted pool │
\ / └────────┬────────┘
\ / │
( User 3 ) ▼
┌─────────────────┐
│ Multi-layer MLP │
│ + L2 Normalizer │
└─────────────────┘
- Neighborhood Aggregation: Rather than computing convolutions over the full neighborhood (which causes exponential expansion), compute Random Walks with Restart (RWR) from a query node. Select the top $K$ nodes with the highest visit counts as the localized neighborhood $\mathcal{N}(v)$.
- Feature Aggregation Routine: $$\mathbf{h}_{\mathcal{N}(v)}^{(l)} = \text{Aggregate}\left(\left{ \text{ReLU}\left(\mathbf{W}_Q \mathbf{h}_u^{(l-1)} + \mathbf{b}_Q\right), \forall u \in \mathcal{N}(v) \right}\right)$$ Where the aggregation function uses importance weights derived from the random walk visit counts.
- Graph Embedding Serving Strategy:
- Offline / Batch: Generate node embeddings for the ad catalog daily/hourly using graph convolution updates on GPU clusters. Store embeddings in a low-latency key-value store (e.g., Redis / DynamoDB).
- Real-time User Aggregation (PinnerSage Approach): Represent active users on the fly by dynamically pooling the pre-computed graph embeddings of their recent $N$ interacted ad items using a multi-head self-attention layer, avoiding full real-time GNN inference overhead during serving.
5. Practical Operational Challenges
Position Bias Handling
Users tend to click top items regardless of underlying relevance. If a ranking model trains on raw historical data, it learns to associate rank positions with higher click probabilities, creating a feedback loop.
- Architecture Solution: Position-debiasing network during training.
TRAINING PHASE SERVING PHASE
Features ──► Main Ranker Features ──► Main Ranker
│ │
▼ ▼
Position ──► Position Tower Predicted pCTR
│ (Logits Sum) (Position set
▼ to Null/Default)
Final Sigmoid
│
▼
Loss (BCE)
- Implementation: Feed the ad position slot as a feature into an auxiliary shallow tower (or single parameter embedding) that outputs a scalar adjustment logit. Sum the main model logit and the position logit before the final Sigmoid activation: $$\hat{y} = \sigma\left( f_{\text{main}}(\mathbf{x}) + f_{\text{position}}(\text{position_slot}) \right)$$
- Inference Routine: During online inference, completely strip or set the position feature input to a constant reference value (e.g.,
position_slot = 0). This isolates true ad relevance $f_{\text{main}}(\mathbf{x})$ independent of screen position.
Delayed Feedback Mitigation
Conversions can occur hours, days, or weeks after an ad click. If we construct training samples quickly, late-converting positives are incorrectly ingested as negative samples.
- Importance Weighting / FSIW: Use Frequently-Updated Importance Sampling Weights.
- Duplicate Sample Correction: Log impressions immediately as negative examples ($y=0$). If a conversion occurs later at time $t + \Delta t$, ingest a duplicate record for that same impression with label $y=1$ alongside a negative weight correction coefficient $w_-$.
- Loss Formulation: Use a split cross-entropy loss function: $$\mathcal{L} = - y \log(p) - (1-y) w(t) \log(1 - p)$$ where $w(t)$ adjusts down the weight of unobserved samples based on the empirical cumulative distribution function (CDF) of conversion delay times.
Cold Start Strategy for New Ads
New ad creatives lack historical impression and click counts, causing them to be ignored by standard statistical features.
- Content Feature Fallbacks: Pass raw ad creative assets through zero-shot feature extraction models (Vision Transformer for images, text LLM embeddings for ad copy) so the model ranks based on visual and semantic similarity to existing high-performing ads.
- Explore/Exploit (LinUCB / Upper Confidence Bound): For new ads with low impression counts, add an uncertainty bonus to the score: $$\text{Score}_{\text{auction}} = \text{Bid} \times \left( \hat{pCTR} + c \cdot \sqrt{\frac{\ln N}{n_a}} \right)$$ where $N$ is total session count, $n_a$ is the new ad's impression count, and $c$ controls exploration intensity.
Probability Calibration
Machine learning models (especially complex DNNs with cross-features) can yield uncalibrated probability outputs despite high AUC scores. An uncalibrated model corrupts auction mechanics, leading to mispriced bids.
- Isotonic Regression Post-Processing: Train a monotonic non-parametric mapping function $g(\hat{y}) \to p$ on a held-out validation dataset collected from the recent hour.
- Platt Scaling: Fit a logistic regression model on raw model logits $z$: $$p_{\text{calibrated}} = \frac{1}{1 + \exp(A \cdot z + B)}$$
- Operational Pipeline: Calibration params ($A, B$ or isotonic lookup tables) are re-estimated continuously in near-real-time (every 5–15 minutes) and pushed to the online serving engine independently of full deep model retraining schedules.
6. Code Implementation: Complete Two-Tower & Debiasing Layer (PyTorch)
import torch
import torch.nn as nn
import torch.nn.functional as F
class PositionDebiasedCTRModel(nn.Module):
"""
Complete CTR Ranking Network featuring:
- User/Context Deep Network
- Ad Content Network
- Explicit Feature Interaction Layer (DCNv2 style)
- Auxiliary Position Bias Tower for Unbiased Serving
"""
def __init__(self, user_dim: int, ad_dim: int, num_positions: int, embed_dim: int = 64):
super().__init__()
# User Representation Tower
self.user_layer = nn.Sequential(
nn.Linear(user_dim, 128),
nn.ReLU(),
nn.BatchNorm1d(128),
nn.Linear(128, embed_dim)
)
# Ad Representation Tower
self.ad_layer = nn.Sequential(
nn.Linear(ad_dim, 128),
nn.ReLU(),
nn.BatchNorm1d(128),
nn.Linear(128, embed_dim)
)
# Cross Network Layer (Deep & Cross component)
self.cross_weight = nn.Parameter(torch.randn(embed_dim * 2, embed_dim * 2) * 0.01)
self.cross_bias = nn.Parameter(torch.zeros(embed_dim * 2, 1))
# Main Prediction MLP
self.main_mlp = nn.Sequential(
nn.Linear(embed_dim * 2, 64),
nn.ReLU(),
nn.Linear(64, 1) # Outputs main relevance logit
)
# Position Bias Auxiliary Network (Used ONLY during training)
self.position_embed = nn.Embedding(num_embeddings=num_positions, embedding_dim=16)
self.position_mlp = nn.Sequential(
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 1) # Outputs position bias logit
)
def forward(self, user_features: torch.Tensor, ad_features: torch.Tensor,
position_ids: torch.Tensor = None, is_training: bool = True) -> torch.Tensor:
"""
Forward pass.
- During training: combines main logit + position logit.
- During serving (is_training=False): returns pure relevance calibrated probabilities.
"""
# 1. Compute Base Embeddings
u_emb = self.user_layer(user_features) # [Batch, embed_dim]
a_emb = self.ad_layer(ad_features) # [Batch, embed_dim]
# Concat User & Ad representations
x_0 = torch.cat([u_emb, a_emb], dim=1) # [Batch, embed_dim * 2]
# 2. Compute Explicit Feature Interaction (1-layer Cross Network)
# x_1 = x_0 * (W * x_0 + b) + x_0
x_0_col = x_0.unsqueeze(-1) # [Batch, 2*embed_dim, 1]
mat_mul = torch.matmul(self.cross_weight, x_0_col) + self.cross_bias
x_cross = x_0 * mat_mul.squeeze(-1) + x_0
# 3. Main Relevance Logit
main_logit = self.main_mlp(x_cross) # [Batch, 1]
# 4. Position Bias Adjustment
if is_training and position_ids is not None:
pos_emb = self.position_embed(position_ids)
pos_logit = self.position_mlp(pos_emb)
final_logit = main_logit + pos_logit
else:
# At inference time, strip position bias completely
final_logit = main_logit
# Return calibrated probability estimation
return torch.sigmoid(final_logit)
# Example Instantiation & Quick Sanity Check
if __name__ == "__main__":
batch_size = 4
model = PositionDebiasedCTRModel(user_dim=32, ad_dim=48, num_positions=10)
dummy_user_feat = torch.randn(batch_size, 32)
dummy_ad_feat = torch.randn(batch_size, 48)
dummy_positions = torch.tensor([0, 1, 2, 0]) # Shown rank slots
# Training pass (includes position bias logit)
train_pctr = model(dummy_user_feat, dummy_ad_feat, position_ids=dummy_positions, is_training=True)
# Online Serving pass (position bias removed for fair auction scoring)
serving_pctr = model(dummy_user_feat, dummy_ad_feat, is_training=False)
print("Training Predicted pCTR:\n", train_pctr.squeeze().tolist())
print("Serving Unbiased pCTR:\n", serving_pctr.squeeze().tolist())
Summary Table: Key Pitfalls vs. Solutions
| System Aspect | Common Pitfall / Failure Mode | Architecture Solution |
|---|---|---|
| Metrics | Optimizing raw CTR causes clickbait proliferation. | Optimize for $V = \text{Bid} \times p\text{CTR} \times (p\text{CVR})^\alpha$; set strict guardrails on session retention and ad hides. |
| Retrieval | Sampled Softmax over-represents popular items in candidate vector space. | Subtract $\log(p_j)$ background frequency bias inside the Two-Tower loss function. |
| Position Bias | Model learns to score top slots higher regardless of relevance. | Train with an auxiliary position bias tower; set position input to null/constant during inference. |
| Delayed Feedback | Conversions logged days later cause false negative labels in fast training streams. | Implement FSIW (Importance-Weighted Cross-Entropy) and duplicate sample correction logs. |
| Auction Integrity | Deep learning logits produce miscalibrated probabilities, breaking bid math. | Run streaming near-real-time Platt Scaling / Isotonic Regression post-processing on output logits. |