Dynamic Retrieval Depth Selection in a Recommender Pipeline
Machine LearningModel answerLast updated
Design a system that decides, per request, how many candidates to pass from the recall stage to the heavy ranker in a recommender system.
Background
A large-scale recommender system is typically split into two stages:
- Recall / retrieval: a fast, lightweight stage that pulls K candidate items from a corpus of millions using approximate nearest-neighbor search, item-to-item signals, trending queues, and similar channels. A cheap pre-ranker scores and merges these into a single ordered list.
- Heavy ranking: a deep neural network that rescores only those K candidates. This is the most expensive step in the pipeline — it dominates GPU serving cost and is the main latency bottleneck.
Today, K is a fixed constant (say, 1,000) applied to every request. That is wasteful: a casual user browsing trending content probably needs far fewer candidates to produce a great feed, while a cold-start user with a noisy interest profile might benefit from a larger pool.
The Problem
Design a system — including a model, training procedure, inference integration, and feedback mechanism — that selects K dynamically, per request, rather than using a static value.
Your answer should address:
- Framing: what is the right objective, and why is "proportion of retrieved candidates that survive ranking" not a good standalone metric?
- What the model predicts: justify the choice of output representation. Why is directly regressing an "optimal K" label harder than it sounds?
- Features: what signals are available after the recall stage and before the heavy ranker fires, and which are most predictive?
- Training data: how do you generate labels without running a separate A/B test for every possible value of K?
- Decision rule: how do you turn a model output into a concrete integer K under a fleet-wide compute budget, and how does the system adapt to real-time load spikes?
- Safety and fairness guardrails: what can go wrong when you start truncating the candidate list, and how do you mitigate it?
A strong answer connects the model design choices back to latency, cost, and engagement trade-offs, and names at least one concrete failure mode.
Hints
Hint 1
Think about what you are actually optimizing across the whole fleet of requests — it is a resource allocation problem, not a per-request classification problem. What does the objective look like when you write it out mathematically?
Hint 2
Instead of predicting a single number K, consider predicting a quality-versus-K curve for each request. That representation is easier to label and lets you separate the model from the budget decision.
Hint 3
The global compute budget introduces a shadow price on ranking compute. Look up Lagrangian relaxation for knapsack-style problems — it reduces the fleet-wide allocation to a simple per-request rule with one shared scalar parameter.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to Frame This Problem
The instinct to frame this as "predict the right K" leads you into a dead end, because there is no single right K without knowing how much compute the fleet has left. The correct frame is a compute allocation problem: you have a fixed ranking budget across all requests, and you want to distribute it so total user value is maximized. Spend more K on requests where extra candidates are likely to change the final slate; spend less where the top candidates are already obvious.
This reframe also resolves two common confusions:
- "Proportion of candidates that survive ranking" is the wrong metric. It measures precision on what you retrieved, not recall of what you missed. Cutting K from 1,000 to 100 will make that ratio look great while silently discarding good items. You need to measure what you lose by truncating.
- "Choosing a threshold is just choosing K" — this is only a problem if the threshold is per-request and hand-tuned. The solution is a single global budget parameter that sets itself automatically, described below.
Step 1: Define a Trainable Quality Signal
The right label is the counterfactual gain of truncating to K:
Gain(r, K) = U(r, K) / U(r, K_max)
where U(r, K) is the total utility (e.g., sum of heavy-ranker scores) of the top-N items chosen from only the first K pre-ranked candidates, and K_max is a large ceiling (say, 3,000). This signal is:
- Monotone non-decreasing in K (more candidates never hurts).
- Concave in practice (diminishing returns set in quickly for most requests).
- Cheap to compute offline — one fully ranked request at K_max produces labels for every K bucket simultaneously by truncating the logged pre-ranker list.
Offline metrics: average Gain at matched average K, and the cost–quality Pareto curve versus static K baselines. Online A/B metrics: watch time and session length at equal compute, or compute saved at neutral engagement. Guardrails: p99 ranker latency, diversity, and fresh/new-creator exposure (these items tend to sit deep in the list and get cut first).
Step 2: Predict the Gain Curve, Not a Single K
Rather than regressing "optimal K," predict ĝ(r, K_b) at a small set of discrete buckets — for example {100, 200, 400, 700, 1,000, 1,500, 2,000, 3,000}. This is a multi-output regression. To enforce monotonicity, either predict non-negative increments and take a cumulative sum, or use a monotone GBDT.
Features (all available after recall, all cheap to compute):
- Recall score distribution: top score, scores at ranks 50/200/500/1,000, gaps between ranks, slope, entropy of pre-ranker scores.
- Channel mix: candidates per channel, inter-channel overlap, share from exploration or freshness channels.
- User signals: activity level, history length, cold-start flag, recent skip rate, interest breadth (number of distinct topic clusters).
- Context: surface (For You vs. Following), time of day, device type, session depth.
Model architecture: a small MLP or GBDT with a few thousand parameters. It runs on CPU inside the recall service and adds under 1 ms of latency. Large models are unnecessary here — the feature set is tabular and low-dimensional.
Step 3: Turn the Curve Into K — the Budget Mechanism
With a per-request gain curve and a fleet-wide compute budget B, the allocation problem is:
maximize Σ_r ĝ(r, K_r)
subject to Σ_r cost(K_r) ≤ B
Lagrangian relaxation decomposes this into one decision per request:
K_r = argmax_K ĝ(r, K) − λ · cost(K)
In plain terms: keep increasing K as long as the marginal gain per unit of compute exceeds a threshold λ. This is the core idea behind Alibaba's DCAF framework and is worth naming in an interview.
λ is one global scalar, not per-request tuning. Fit it offline so that the average cost across a sample of traffic hits the budget. Then run a lightweight PID controller that adjusts λ every few seconds based on observed GPU utilization. When traffic spikes, λ rises automatically, K shrinks everywhere, and the system sheds load gracefully — cutting the low-value tails first rather than dropping requests or breaching latency SLOs. Add hard bounds K ∈ [K_min, K_max] and a reserved quota for exploration and freshness channels so they are never fully truncated.
Step 4: Generating Training Data
This is the hardest engineering piece. You need ground-truth heavy-ranker scores for all K_max candidates on a representative slice of traffic.
- Exploration slice (~1% of traffic): always rank all K_max = 3,000 candidates. Log the pre-ranker order, all heavy-ranker scores, and the final slate.
- Label generation: for each K bucket, truncate the logged list, pick top N by logged ranker scores, and compute Gain(r, K_b). One request yields the full curve.
- Watch for feedback loops: the heavy ranker is trained on items it sees. If dynamic K persistently hides deep candidates, the ranker loses signal on them and will rank them lower in future — a self-reinforcing narrowing of the funnel. The exploration slice doubles as unbiased training data for the ranker to counter this. Retrain the gain model at least daily as the recall model, ranker, and content pool drift.
Step 5: Architecture and Safety
Request → Recall channels (parallel)
→ Merge + pre-ranker
→ Feature extractor (score stats, user, context)
→ K-Allocator: ĝ(r, ·) + λ → K_r
→ Truncate (with freshness quota) → Heavy Ranker (GPU)
→ Re-rank / policy layer → Feed
Ranker GPU utilization → λ PID controller → K-Allocator (config push)
Exploration slice → Log store → Label pipeline → Gain model (daily retrain)
The allocator is a stateless microservice. Its API is choose_k(recall_stats, user_ctx, lambda) → int, making it easy to test, roll back, and shadow-deploy.
Common Mistakes to Avoid
- Optimizing precision of retrieved candidates rather than recall of final slate items — this makes K smaller without measuring the cost.
- Per-request threshold tuning instead of a global budget parameter — it does not generalize and is impossible to calibrate at scale.
- Ignoring feedback loops between the K policy, the pre-ranker, and the heavy ranker — this is the subtlest and most important long-term failure mode.
- No freshness or diversity floor — truncation disproportionately removes new and niche items, which concentrates recommendations on already-popular content and degrades long-term ecosystem health.