Design TikTok's Video Recommendation System
Understanding the Problem
🎬 What is a short-video recommendation system? It's the model stack that decides which video plays next when you swipe up on TikTok's For You feed, Instagram Reels or YouTube Shorts. The user never searches and rarely follows anyone in particular; the feed is almost entirely chosen by the system. Each swipe is both a request for the next video and a label for the last one, so the system learns from every second the user spends in the app.
Reels and Shorts are the same problem. The differences are in the inputs (Instagram has a strong follow graph to draw on, TikTok mostly doesn't) and in how much weight social signals like shares to friends get. We'll design for a TikTok-style feed and point out where Reels differs.
The serving side of this product, video upload, CDN delivery and prefetching, is covered in Design TikTok. Here we go deep on the models: what they predict, what they learn from, how they're trained and how they're served.
Functional Requirements
Core Requirements
- The system should return an endless, personalized sequence of short videos for each user, a few at a time.
- The feed should react to what the user does in this session within a swipe or two: watch three cooking videos to the end and the next batch should have more cooking.
- New videos, including ones from creators with no followers, should get a fair chance to reach an audience.
- New users should get a decent feed from their first swipe, before we know anything about them.
Below the line (out of scope)
- Video upload, transcoding and delivery.
- Content moderation (we assume a policy model has already removed violating videos and labeled borderline ones).
- Ads insertion in the feed. See Ads Ranking.
- Search and the Following tab.
Non-Functional Requirements
Ask your interviewer for scale, because it decides how much model you can afford per request. We'll assume:
Core Requirements
- 500 million daily active users, each watching around 100 videos a day.
- A corpus of hundreds of millions of eligible videos, with tens of millions of new uploads per day.
- The server should return the next batch in under 200 ms at p99. The client prefetches, so the user never actually waits for it.
- Freshness: in-session behavior affects the next request (seconds), the model itself picks up new trends within minutes, and a new upload is eligible within minutes of passing moderation.
- Safety and fairness: the feed must respect integrity labels (no borderline content for teens), avoid narrowing a user into one topic, and give new creators exposure.
Below the line (out of scope)
- Multi-region model consistency. Each region trains and serves its own copy.
Now the arithmetic. 500M users × 100 videos is 50 billion views a day, about 580,000 per second. If the client asks for 8 videos at a time, that's around 6 billion feed requests a day, ~70,000 QPS on average and something like 200,000 QPS at peak.
Ranking is where this bites. If we score 1,000 candidates per request with a heavy model, peak load is 200,000 × 1,000 = 200 million model evaluations per second. That's a large GPU fleet, but a buildable one. Scoring the whole corpus, a few hundred million videos per request, would be five orders of magnitude more. So we need a funnel: cheap retrieval to get to thousands, a light model to get to about a thousand, and the expensive model only on those.
The event side is just as big. Each view produces several events (impression, play progress, swipe, maybe a like), so call it 250 billion events a day, around 3 million per second. Every one of those is a training label, which is why this system can learn so fast, and why the training pipeline is a real system on its own.
Notice what makes short video different from Netflix-style recommendations: the item is consumed in 15 to 60 seconds, so a user gives you 30 or more labeled examples in a 15-minute session. That's why the strongest answers lean on real-time features and online training. A model that updates daily throws away most of the signal.
Framing It as an ML Problem
ML Objective
The business wants people to come back and spend time in the app: daily active users, retention and total time spent. Those are terrible training targets. Retention is measured over weeks and is the result of thousands of recommendations, so you can't attribute it to any single video.
Instead we predict short-term proxies that we can label for every impression, and that correlate with long-term retention:
- Watch time and completion: did the user watch to the end? Did they loop it?
- Explicit engagement: like, comment, share, follow the creator, save.
- Negative signals: a fast skip (swiped away in under ~2 seconds), "not interested", report.
The model predicts each of these, and a value model combines them into one score:
score = w1·P(finish) + w2·E[watch_time_norm] + w3·P(like) + w4·P(share)
+ w5·P(follow) − w6·P(fast_skip) − w7·P(not_interested)
The weights are a product decision, tuned by A/B tests against the long-term metrics. This split is important: the model learns what will happen, and a separate, small, human-readable formula decides what we want. When product says "we want more shares," you change a weight, not retrain a model.
Optimizing raw watch time alone is the classic mistake. It favors long videos (a 3-minute video gets more seconds than a 15-second one even when nobody likes it) and rewards clickbait that holds attention without satisfying anyone. Normalize watch time by video length and balance it with explicit and negative signals.
Inputs and Outputs
- Input: a user (ID, profile, recent behavior), a request context (time, device, network, how deep into the session they are) and a corpus of eligible videos.
- Output: an ordered list of ~8 videos to play next, plus a request ID so later events can be joined back to what we served.
Choosing the ML Approach
This is a ranking problem solved as a multi-stage funnel:
- Candidate generation (retrieval): several cheap sources each propose a few hundred to a few thousand videos. We care about recall here.
- Pre-ranking: a light model trims ~5,000 candidates to ~1,000.
- Ranking: a heavy multi-task neural network predicts the engagement probabilities for each candidate. We care about precision at the top.
- Re-ranking: business logic and diversity turn a ranked list into a good sequence.
Each stage is a pointwise model at heart: it predicts per-video probabilities, and we sort by the combined score. Listwise ranking objectives exist, but for a feed with this many cheap labels, pointwise multi-task prediction plus a re-ranking stage works well and is much easier to calibrate and debug. Say that, and say why.
Data and Labels
Sources
- Client events: impression, play start, play progress (25/50/75/100%), loop, swipe away with time-on-video, like, comment, share, follow, "not interested", report. Sent in small batches from the app.
- Served features: a log, written by the ranking service, of the exact feature values it used for each candidate it served. This is how we avoid training-serving skew (more below).
- Video metadata: creator, duration, upload time, caption, hashtags, sound, moderation labels, plus content embeddings computed from frames, audio and text.
- User data: account age, language, country, declared interests from onboarding, the follow graph.
How labels are produced
Almost all labels are implicit. A positive "finish" label means the user watched to the end; "fast skip" means they swiped away within 2 seconds. Explicit labels (like, share) are rarer and stronger. A small human-rated set, where raters judge whether a recommendation was good for a given user history, is useful for evaluation and for checking that the proxies still track satisfaction, but it's far too small to train the ranker on.
Delayed labels. Watch time is known the moment the user swipes, but a like can come after a loop, a share after a comment thread, and a follow from the creator's profile page a minute later. We handle it with a join window: when an impression comes in, hold it for a while (say 10 to 30 minutes), attach any events that arrive, then emit the training example. A longer window catches more late labels but makes the model staler. Some teams emit the example early and send a correction when a late positive arrives.
Class imbalance. Shares and follows happen on well under 1% of impressions; finishes on a much larger fraction. Per-task imbalance is handled in training (see below), not by throwing away the rare positives.
Sampling. 50 billion impressions a day is more than we need to train on. We keep all positives for rare tasks and downsample the negatives, and we record the sampling rate so predictions can be corrected back to true probabilities.
Label leakage. The usual trap here is a feature computed after the impression. If "this video's like count" is read from a table at training time, it includes likes that happened after the user saw it, including the user's own like. Train on the served-feature log, where the values are exactly what the model saw at serving time, and this disappears.
Position matters too. A video served first in the session gets more attention than one served 7th in a batch of 8. Log the position and feed it to the model during training as a feature, then set it to a fixed value at serving time. That lets the model learn the bias without baking it into its relevance estimate.
Feature Engineering
User features
- Long-term interest embedding (built from months of history, refreshed daily).
- Aggregate stats: average completion rate, likes per session, preferred video length, active hours.
- Behavior sequence: the last few hundred videos the user watched, each with its ID, creator, watch ratio and action taken. This is the single most valuable input.
Video features
- Video ID and creator ID (learned embeddings).
- Content embedding from a multimodal encoder over frames, audio and caption. It's what lets us recommend a video with zero views.
- Counters over several windows (1 hour, 1 day, 7 days): impressions, completion rate, like rate, share rate, smoothed with a prior so a video with 3 views and 2 likes doesn't look like a hit.
- Duration, age, sound ID, hashtags, language.
Context features
- Time of day, day of week, device, network type (a user on cellular may prefer shorter videos), position in session, how long since the last session.
Cross features
- User × creator: has this user watched this creator before, and how much?
- User × topic and user × sound affinity scores.
- The similarity between the candidate's content embedding and the user's recent-watch embeddings.
Deep models learn many interactions on their own, but explicit user × creator history is still worth computing; it's strong and cheap.
Real-time vs batch
- Batch (Spark, daily): long-term embeddings, 7-day stats, creator profiles.
- Streaming (Flink, seconds): the user's behavior sequence, in-session counts ("skipped 4 dance videos in a row"), video counters over the last hour. A trending video can go from 0 to millions of views in an afternoon, and an hourly batch job would miss the climb.
Both land in a feature store with an offline copy for training and an online, low-latency copy (Redis or a similar key-value store) for serving. See Feature Store.
Modeling
We'll walk through ranking first, since that's where most interviews spend their time, then candidate generation and re-ranking.
Ranking
Bad Solution: Popularity and Rules
Approach
Rank candidates by recent engagement rate (likes per view over the last day), filtered to the user's language and boosted for creators they follow.
Challenges
Everyone gets nearly the same feed. It can't learn that this user loves woodworking and hates dance videos, and it rewards whatever is already popular, which starves new creators. It's a fine fallback when the model is down, and a fine cold-start feed for a user we know nothing about, but not a recommender.
Good Solution: Gradient-Boosted Trees on Hand-Built Features
Approach
Train a GBDT (XGBoost or LightGBM) to predict P(finish) from a few hundred hand-built features: the counters, the user × creator and user × topic affinities, embedding similarities, context. Train one model per important label, or one model on a combined target.
Challenges
GBDTs are strong, fast and easy to debug, and they're a good baseline to state first. But they can't use raw IDs or sequences. A GBDT can't look at the last 500 videos a user watched and work out that they're drifting from cooking to travel; you have to hand-build a feature for every pattern you want it to see. Training separate models per task also means separate feature pipelines and no sharing of what one task learns with another.
Great Solution: Multi-Task Deep Ranker With Sequence Attention
Approach
A deep model that consumes IDs, sequences and dense features directly, and predicts every task at once.
- Embeddings for every sparse ID (user, video, creator, sound, hashtag), typically 32 to 128 dimensions.
- Target attention over the behavior sequence: for each candidate, attend over the user's recent watches using the candidate as the query. Watches similar to the candidate get high weight. This is the idea behind Deep Interest Network (DIN) and its successors; a transformer over the sequence is the bigger version. It's what lets the model say "this user's history is mixed, but the parts that look like this video were all finished."
- Shared bottom + task towers. A plain shared bottom lets the tasks hurt each other (the share task is tiny and gets drowned out by the finish task). MMoE (multi-gate mixture of experts) or PLE gives each task its own gate over a set of shared experts, so related tasks share and unrelated ones don't.
- Heads: sigmoids for P(finish), P(like), P(share), P(follow), P(fast skip); a head for normalized watch time.
Challenges
ID embedding tables are huge. A billion video IDs × 64 dimensions × 4 bytes is 256 GB before the user and creator tables, so they're sharded across parameter servers or GPUs (TorchRec-style model parallelism for embeddings, data parallelism for the dense layers). Sequence attention over 500 items × 1,000 candidates per request is the main inference cost; we compute the user-side sequence encoding once per request and reuse it across all candidates. The multi-task value weights need constant tuning, and every new head is a new thing to calibrate and monitor.
Candidate Generation
Ranking is only as good as the candidates it sees. We run several sources in parallel and merge them:
- Two-tower retrieval: a user tower (user features + recent sequence) and a video tower (ID + content embedding + stats) trained so that their dot product predicts engagement. Video embeddings go into an approximate nearest neighbor index (HNSW or IVF-PQ, in Faiss or a vector database); at request time we compute the user embedding and fetch the nearest ~1,500 videos in a few milliseconds.
- Item-to-item: videos similar to the last few the user finished, from co-engagement ("people who finished X also finished Y") or content embeddings.
- Followed creators: recent uploads from accounts the user follows. Much bigger for Reels than for TikTok.
- Trending and local: videos rising fast in the user's region or language.
- Fresh pool: recent uploads in their exploration phase (see the deep dives).
Each source gets a quota, so one source can't flood the funnel. Pre-ranking then scores the merged ~5,000 with a small model (often a two-tower model with a few extra features, because the dot product is very cheap) and passes ~1,000 to the ranker.
A single two-tower model can't do everything. The user tower has to compress a person into one vector, so it captures their dominant interests and misses the niche ones. Multiple sources with quotas are how you keep recall high for the minority interests.
Re-Ranking
The ranker scores each video independently, so its top 8 might be four videos from the same creator and three with the same sound. Re-ranking turns scores into a good sequence:
- Diversity: a greedy pass that penalizes similarity to videos already chosen (maximal marginal relevance, or a determinantal point process for a more principled version), using content embeddings.
- Hard rules: no more than one video from the same creator in a batch, no repeats of anything seen recently (a per-user Bloom filter of seen IDs), integrity filters (no borderline content for teen accounts), freshness quotas.
- Exploration slots: one slot in every few batches for a video outside the user's known interests, to keep learning about them.
Training
Losses. Binary cross-entropy for each classification head, summed with per-task weights. For watch time, two choices work: regression on a normalized target (watch time divided by duration, or the watch-time quantile within videos of a similar length, which removes the duration bias), or weighted logistic regression, where positive examples are weighted by watch time so the predicted odds approximate expected watch time.
Retrieval negatives. The two-tower model is trained with a softmax over in-batch negatives: other users' positive videos in the same batch serve as negatives. That oversamples popular videos as negatives, so apply a logQ correction (subtract the log of each item's sampling probability from its logit) or the model learns to underrate popular items. Add some random negatives from the whole corpus, and a few hard negatives (videos the user was shown and fast-skipped).
Ranker negatives. The ranker trains on impressions only: videos the user was actually shown, labeled with what happened. Random unseen videos don't belong here; the ranker's job is to sort things retrieval already thought were plausible.
Imbalance. Downsample negatives for rare tasks, then correct the predicted probability. If you kept negatives at rate w, a raw prediction q maps back to p = q / (q + (1 − q) / w). The value model and calibration both need real probabilities.
Retraining cadence.
Bad Solution: Daily Batch Retrain
Approach
Retrain the ranker every night on the last few weeks of data and push it in the morning.
Challenges
A sound that went viral at noon is invisible to the model until tomorrow. New video IDs have untrained embeddings for up to a day. User interests that shifted this afternoon are only picked up through real-time features, not the model.
Good Solution: Hourly Incremental Training
Approach
Start from yesterday's weights and train on each new hour of data, then push.
Challenges
Much better, and simple to run. Still an hour behind, and the deploy pipeline (validate, copy hundreds of GB of embeddings, load) runs 24 times a day, so it needs to be automatic and safe.
Great Solution: Streaming Training With Frequent Parameter Sync
Approach
Flink joins the served-feature log with events and streams training examples straight into a trainer that never stops. Sparse embedding rows that changed are pushed to the serving parameter servers every minute or so; the dense layers, which change slowly, sync every few minutes to an hour. A new video's ID embedding starts learning from its first impressions. ByteDance has published work on this style of system (Monolith), including collision-free embedding tables that add rows for new IDs on the fly and expire IDs that stop appearing.
We still run a daily batch retrain from the data lake as a reference: it catches drift in the streaming model, it's what new architectures are tested against, and it's the model we fall back to if the streaming model degrades.
Challenges
Streaming training needs guardrails. A bug in the event pipeline (a client release that stops sending likes) is learned in minutes. We validate each parameter push against a held-out stream and a canary slice of traffic, and we keep a checkpoint to roll back to.
Evaluation
Offline Metrics
- Ranking heads: AUC per task, and normalized cross-entropy (log loss), because the value model needs calibrated probabilities, not just a good order. GAUC (AUC computed per user and averaged) matters more than global AUC: global AUC rewards separating heavy users from light ones, which doesn't help rank anyone's feed.
- Calibration: predicted vs observed rate, per task and per segment (new users, new videos).
- Retrieval: recall@K, the fraction of the videos a user engaged with that the source would have returned in its top K.
- Whole funnel: NDCG on held-out sessions, plus diversity and creator-coverage metrics.
Use a time-based split (train on days 1–14, test on day 15), never a random split. A random split leaks the future into training and makes everything look better than it is.
Online Metrics and A/B Testing
Offline AUC gains often don't move online metrics, so everything ships through an A/B test.
- Primary: time spent per user, sessions per user, day-1 and day-7 retention.
- Secondary: likes, shares and follows per user, average completion rate.
- Guardrails: "not interested" and report rates, share of views going to new creators, topic diversity per user, integrity metrics.
Feeds have novelty effects: users react to anything different for a few days. Run tests for at least a week or two. Keep a small long-term holdout (users who don't get new launches for a quarter) to measure the cumulative effect of many small wins. Creator-side changes, such as more exposure for new uploads, also affect creators who aren't in the experiment, so those are better measured with creator-level randomization.
Serving
When the client is two or three videos from the end of its buffer, it requests the next batch, sending the events from the current session with the request so the server doesn't depend on the event pipeline having caught up.
A latency budget for a 200 ms p99:
| Step | Budget |
|---|---|
| Load user features and behavior sequence | ~15 ms |
| Candidate sources, in parallel (ANN, item-to-item, follows, trending) | ~30 ms |
| Merge, dedupe against seen-set, pre-rank ~5,000 | ~20 ms |
| Fetch candidate features (batched multi-get) | ~20 ms |
| Heavy ranker on ~1,000 candidates (GPU, batched) | ~50 ms |
| Re-rank and assemble | ~10 ms |
| Network, serialization, slack | the rest |
A few things make this fit:
- Compute the user side once. The sequence encoder and user tower run once per request; only the candidate side runs 1,000 times.
- Batch on the GPU. The ranking service batches candidates from several requests together and runs in reduced precision (FP16 or INT8), with the embedding lookups on CPU or a separate tier.
- Cache video features in-process for hot videos. A few million popular videos account for most candidates.
This is online prediction on purpose: the feed must reflect what the user did 10 seconds ago. Batch prediction still has a role, though. A nightly job precomputes a few hundred candidates per user as a fallback, and the "trending in your region" list is computed every few minutes, not per request.
Fallbacks. If the ranker times out, serve the pre-ranker's order. If retrieval fails, serve the precomputed list. If everything fails, serve regional trending. The feed must never be empty.
Potential Deep Dives
1) How do we adapt to what the user is doing right now?
A user opens the app and the first two videos are dance clips; they skip both in a second. The third batch had better not be more dance.
Three mechanisms work together:
- The request carries the session. The client sends its recent events with every feed request, so the ranker sees the skips immediately, without waiting for Kafka and Flink.
- Real-time features. Flink keeps per-user streaming features (last 50 watches with watch ratios, per-topic skip counts in the session) in the online store within seconds.
- The model reads the sequence. Because the ranker attends over the behavior sequence, the newest events change its predictions without any retraining. The model already knows what "skipped three of these in a row" means.
Small batches help. Asking for 8 videos at a time instead of 30 means the system re-ranks after every few swipes. The cost is more requests, which is why the 200,000 QPS figure above is as high as it is.
2) How do new videos and new users get started?
New videos have no engagement, no trained ID embedding and no co-watch neighbors.
Bad Solution: Wait for Organic Engagement
Approach
Let new videos compete in the normal ranker and rise if people like them.
Challenges
They never get shown, so they never get engagement. The ranker leans heavily on counters and ID embeddings, and a new video has neither. The feed fills up with established creators, and new creators leave.
Good Solution: Content-Based Embeddings
Approach
Use the multimodal content embedding (frames, audio, caption) in both the video tower and the ranker. A new cooking video lands near other cooking videos in embedding space on its first second, and retrieval can match it to cooking fans.
Challenges
Content similarity gets the video to the right kind of user, but says nothing about whether it's good. Two cooking videos look the same to an encoder; one is great and one is boring.
Great Solution: Staged Exploration With Traffic Pools
Approach
Give every new video that passes moderation a small guaranteed audience, targeted by its content embedding, and promote it based on how that audience reacts.
The fresh-video retrieval source reserves a small share of impressions (a few percent) for videos in their exploration phase. A video gets a few hundred views from well-matched users. If its completion, like and share rates beat videos of a similar length and topic, it's promoted to a pool of thousands, then into normal ranking. If it doesn't, it stops getting exploration traffic. Within a pool, a bandit (Thompson sampling on the engagement rate) decides which new videos get the next impression, so promising ones are tested faster.
Challenges
The exploration budget is real cost: those impressions would have gone to proven videos, so short-term time spent drops slightly. Measure that against new-creator retention and corpus freshness, and set the budget explicitly. Creators will also try to game the first pool (bought views, engagement pods), so pool metrics should only count trusted accounts.
New users are handled with the same ideas. Onboarding asks for a few interests; until we have history, we serve popular, high-quality videos across a spread of topics for the user's country and language, deliberately diverse so each swipe teaches us something. Because each video is short, a new user gives us a dozen labels in the first few minutes, and the sequence model adapts from there. Device, language and referral source (an install from a shared cooking video) are useful priors.
3) How do we avoid feedback loops and filter bubbles?
The model learns from what it shows. Videos it ranks highly get more impressions, more engagement and more training data, so it becomes more confident about them; things it never shows never get a chance to prove it wrong. Left alone, the feed narrows: popular creators get more popular, and a user who watched two sad videos at midnight gets nothing but sad videos.
Counter it on purpose:
- Exploration: the exploration slots in re-ranking and the fresh pool, so the model keeps seeing outcomes for things it wouldn't have chosen.
- Debias training data: the logQ correction for popularity in retrieval, position as a training-only feature, and inverse-propensity weighting for impressions that came from exploration.
- Diversity as an objective: per-batch topic diversity in re-ranking, and caps on how much of a session one topic can take.
- Measure it: track per-user topic entropy and creator concentration over time as guardrail metrics, so a launch that narrows feeds shows up in the A/B test.
- Well-being rules: hard limits on repetitive exposure to sensitive themes, regardless of predicted engagement. This one is a policy decision more than an ML one, and it's good to say so.
Interviewers like hearing that the model's own outputs shape its training data. Naming the loop, and the specific counter for each part of it, separates a senior answer from someone who has only trained models on static datasets.
4) How do we monitor the models in production?
The models change every minute, so monitoring has to be automatic:
- Data quality: event volume by type and client version (a release that drops "share" events shows up as a drop in share labels), null and default rates per feature, and the gap between served features and what the offline pipeline computes for the same rows.
- Prediction drift: distribution of each head's predictions, and calibration (predicted vs observed rate) by hour. A calibration break usually means a pipeline problem, not a world change.
- Online health: per-model latency, timeout and fallback rates.
- Business metrics: time spent, skip rate and "not interested" rate per region, with alerts on sudden moves.
Every parameter push is checked against a held-out evaluation stream before it reaches all servers. If calibration or AUC drops past a threshold, the push is blocked and the previous checkpoint stays live.
5) What changes for Instagram Reels?
Reels has a strong social graph, so the follow and friend sources contribute far more candidates, and shares to friends (DMs) deserve a big weight in the value model; they're a stronger satisfaction signal than a like. Reels also shares users and creators with the photo feed and Stories, so user embeddings can be trained on cross-surface behavior. The funnel, the multi-task ranker, the exploration machinery and streaming training are the same.
What is Expected at Each Level?
Mid-level
You should frame the problem as multi-stage retrieval and ranking, pick sensible labels (completion, likes, fast skips) and explain why raw watch time is a biased target. You should propose a reasonable baseline (GBDT on engineered features), know AUC and log loss, and describe an A/B test with time spent as the metric. Cold start should come up with some prompting, and content embeddings are an acceptable answer.
Senior
You should design the multi-task ranker with a value model, explain the behavior-sequence features, and describe two-tower retrieval with ANN, including negative sampling and why it needs correction. Expect to discuss delayed labels and the join window, training on logged served features to avoid skew, GAUC vs AUC, and a latency budget for the funnel. You should bring up real-time features and the exploration budget for new videos without being asked.
Staff+
You should drive toward the system-level trade-offs: streaming training and how you'd keep it safe, how the value-model weights get set and who owns them, how exploration cost is measured against creator-side health, and how feedback loops shape the training data. Expect to discuss long-term holdouts, creator-side experiments that break user-level randomization, the cost of the GPU fleet at 200 million evaluations per second, and where to stop: knowing that a bigger sequence model is worth less than fixing a broken label is a strong signal.