Build a Click-Through Rate Model for a News Feed
Machine LearningModel answerLast updated
Design an end-to-end CTR prediction pipeline covering temporal feature engineering, leakage prevention, high-cardinality encoding, and offline-to-online metric gaps.
Setup
You are building a click-through rate (CTR) prediction model for a personalized news feed. Your dataset has 100 million rows. Each row represents one article impression and contains:
| Field | Type | Description |
|---|---|---|
user_id | string | Unique user identifier |
article_id | string | Unique article identifier |
category | string | Content category (e.g., "sports", "tech") |
timestamp | datetime | Time the article was shown |
device_type | string | e.g., "mobile", "desktop" |
clicked | int (0/1) | Whether the user clicked |
Example row:
{
"user_id": "u123",
"article_id": "a456",
"category": "tech",
"timestamp": "2023-10-01 10:00:00",
"device_type": "mobile",
"clicked": 0
}
What you are asked to address
Part 1 — Feature engineering and leakage
- How would you convert
timestampinto model features? Pay particular attention to capturing cyclical patterns in user behavior. - How would you turn
article_idinto a useful signal? - A teammate proposes adding a feature
article_avg_ctr, computed as the article's mean click rate over the whole training set. Explain what goes wrong and how you would fix it. - As a follow-up: what happens when you apply target encoding to the
categorycolumn on a small dataset?
Part 2 — Encoding high-cardinality IDs
user_id and article_id each have millions of unique values. Describe a practical encoding strategy for:
- A Logistic Regression model
- A Gradient Boosted Decision Tree (GBDT) model
Explain why the same approach does not work equally well for both.
Part 3 — Diagnosing an offline/online gap
Your model reaches a strong AUC-ROC score on the held-out set, but after deployment the click rate in production is disappointing. Walk through how you would diagnose this discrepancy. What metrics and validation strategies would you check, and in what order?
Constraints and expectations
- Treat the data as a time series: rows are not independent draws from a static distribution.
- At 100 million rows, memory efficiency matters.
- For each decision you make, briefly state the trade-off you are accepting.
Hints
Hint 1
For timestamp features, think about what "10:00" means to a model that sees hour as an integer — is 23:00 truly as far from 00:00 as it is from 12:00?
Hint 2
Before computing any article-level aggregate, ask: at prediction time, which rows would you actually have access to? Work backward from that constraint to define your training feature.
Hint 3
AUC measures global pairwise ranking across all users. Think about what question your production metric is really asking — is it the same question?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
The through-line for all three parts is the same principle: only use information that would exist at prediction time. Every leakage problem, every offline/online gap, and every calibration failure in CTR modeling traces back to violating that rule somewhere.
Part 1 — Feature engineering and leakage
Turning timestamp into features
Cyclical encodings for time-of-day and day-of-week. Hour-of-day is a circle: 23:00 and 00:00 are one hour apart, not 23. An integer encoding destroys that structure. Encode with sine and cosine pairs:
hour_sin = sin(2π · h / 24)
hour_cos = cos(2π · h / 24)
Apply the same treatment to day-of-week (period 7). For the example row (hour = 10, Sunday = dow 6):
hour_sin ≈ 0.50,hour_cos ≈ −0.87dow_sin ≈ −0.78,dow_cos ≈ 0.62
Convert to the user's local timezone before encoding. "10:00 UTC" represents very different moments for a user in Tokyo versus São Paulo.
Recency features usually matter more than clock time. Useful ones include article age (timestamp minus publish or first-seen time), time since the user's last session, and time since the user last engaged with this category.
Calendar flags like weekend and public holidays add cheap signal on top.
Turning article_id into features
The raw ID is a sparse categorical (covered in Part 2). On top of that, build trailing-window aggregates: impression count, click count, and smoothed CTR over the past 1 hour, 24 hours, and 7 days. A CTR trend ratio like ctr_1h / ctr_24h captures articles going viral. All of these only look backward from the current row's timestamp.
The leakage in article_avg_ctr
Computing the average CTR over the entire training set and attaching it to every row creates two distinct problems:
- Target leakage. Each row's own
clickedlabel is inside the aggregate it is being predicted from. For a rare article with only three impressions, this nearly encodes the answer directly. - Look-ahead bias. A row at 10:00 sees clicks that occurred at 18:00 of the same day. The model learns "articles that will become popular get clicked," which is a relationship that does not exist at serving time. Offline AUC inflates and production performance collapses.
Fix: use a strictly-prior expanding window with Bayesian smoothing. Sort by timestamp and, for each row, aggregate only events where t' < t:
ctr_prior(a, t) = (clicks_before(a, t) + α · p0) / (impressions_before(a, t) + α)
p0 is the global or category-level base rate; α is a pseudo-count (100 is a reasonable starting point). Low-traffic articles shrink toward the prior rather than producing a noisy estimate. Implement this in the same code path used at serving time so train and serve stay consistent.
Target encoding category on a small dataset
With few rows per category, the in-sample mean click rate is noisy and it leaks each row's own label into the feature. The model trusts a signal that is partly memorizing labels, which overfits and degrades on unseen data. Mitigations are the same smoothing approach above, out-of-fold encoding, or simply one-hot encoding — category is typically low-cardinality, so target encoding often is not needed for it at all.
Part 2 — Encoding high-cardinality IDs
Logistic Regression
Linear models handle sparse, high-dimensional input naturally.
- Feature hashing. Map
user_id,article_id, and interaction crosses likeuser × categoryordevice × hour_bucketinto a fixed hash space (2²⁴ buckets is a common starting point). Memory stays constant and unseen IDs fall into existing buckets. The cost is hash collisions; size the space so collision rates on frequent IDs are low. - Frequency filtering. IDs below a threshold (say, fewer than 5 impressions) go to a shared
<rare>bucket. - Optimizer. FTRL-Proximal produces sparse weight vectors and supports online updates efficiently at this scale.
- Interaction crosses are essential. A linear model cannot learn interactions on its own, so explicit crosses like
user_id × categoryare where personalization comes from.
GBDT
Trees split one feature at a time. One-hot encoding millions of IDs makes each split isolate a single ID, which is computationally wasteful and overfits immediately.
- Replace IDs with dense statistics: time-ordered smoothed CTR encodings, count/frequency encodings, and user-level aggregates such as the user's CTR broken down by category and device.
- Use pretrained dense embeddings from matrix factorization or a two-tower retrieval model as input columns.
- LightGBM's native categorical handling works at moderate cardinality. At millions of unique values, the encodings above are more reliable.
A well-known hybrid worth mentioning: use GBDT leaf indices as sparse features into a logistic regression layer. Trees learn nonlinear interactions; the LR head handles scale and sparsity. Modern deep models with embedding tables (DLRM, DCN) generalize this idea further and are the production default at large platforms.
Part 3 — Diagnosing the offline/online gap
Work through this roughly in order of how quickly each check can be done.
Validation design first. The most common cause of inflated offline AUC is a random train/test split. Click logs are a time series; use a walk-forward split — train on days 1 through N, evaluate on day N+1, then roll forward. Random splits let future behavior and trending articles leak into training.
Leakage audit. Inspect every feature for future information. A single feature with suspiciously high importance and that disappears or changes distribution at serving time is the tell.
Train–serve skew. Log the feature values actually computed online and compare their distributions to offline values. Common culprits: pipeline freshness differences, timezone handling, and defaults for missing values.
Per-user ranking metrics. Global AUC can look healthy while per-user ranking is poor, because a model that simply separates heavy clickers from non-clickers gets rewarded globally. GAUC (impression-weighted AUC computed within each user) and NDCG@k / Precision@k on the actual displayed slate are more diagnostic.
Calibration. AUC is rank-order only — it ignores whether predicted probabilities are accurate. Check log loss, plot a reliability curve, and compute predicted/observed click ratio (target: near 1.0). Downstream systems like bid auctions and score blending depend on calibrated probabilities.
Objective mismatch. The model optimizes clicks; the business may measure dwell time, downstream conversion, or retention. Clickbait articles raise CTR and hurt every other metric. Fix by redefining the label (e.g., clicks with at least 30 seconds of dwell) or by multi-task training.
Bias in logged data. Position bias means top slots get clicked regardless of relevance. Add position as a training feature and hold it fixed at inference. Selection bias means labels only exist for items the previous policy showed.
Segment slices. Break metrics by new vs. returning users, cold-start articles, device type, and category. A model can look fine in aggregate while failing on the segments that matter.
Online A/B test. This is the final arbiter. All offline metrics are proxies.
Common mistakes to avoid
- Random splits on click log data.
- Global CTR features that include the current row or future rows.
- Encoding hour as an integer 0–23.
- Reporting AUC alone with no calibration or per-user metric.
- One-hot encoding millions of IDs into a GBDT.
- Confusing a high global AUC with good personalization.