The Problem#
Design a mobile app where people watch an endless, personalised stream of short videos and upload their own:
- A user opens the app and a video starts playing immediately, full screen. They swipe up and the next video plays with no visible loading. They can do this for an hour.
- The stream, called the For You feed, is chosen by a recommendation system. It is not limited to accounts the user follows. A video from someone with zero followers can reach millions of people if viewers respond well to it.
- Users upload videos recorded on their phone (typically 15 seconds to 3 minutes, sometimes up to 10 minutes), add a caption, hashtags and a sound, and publish. The video must be watchable by others within a minute or two.
- Users like, comment, share, follow creators and save videos. Every one of these actions, and also how long they watched each video and whether they swiped away early, feeds back into the recommendations, ideally within seconds to minutes.
- The app serves hundreds of millions of daily users in many countries, on phones ranging from flagship devices on fibre to cheap Android phones on congested 3G.
TikTok (and its Chinese sibling Douyin, both from ByteDance) made this format dominant. TikTok announced in September 2021 that it had passed 1 billion monthly active users. YouTube Shorts, Instagram Reels, Snapchat Spotlight and Kuaishou solve the same problem. ByteDance has published part of its recommendation infrastructure in the paper "Monolith: Real Time Recommendation System With Collisionless Embedding Table" (Liu et al., 2022), which we use as a reference point for the real-time training part of this design.
What makes the problem interesting:
- The recommendation system is the product. In a follow-based feed (the Instagram or Twitter model), the candidate set is small: posts from people you follow. In a For You feed, the candidate set is every video on the platform, potentially billions of items, and the system must pick the next one in about 100–200 ms.
- Feedback is dense and fast. A user swipes through 50–200 videos per session. Each swipe is a labelled data point ("watched 2 of 15 seconds" is a strong negative; "watched twice and shared" is a strong positive). This is far more signal per minute than on any other kind of feed, and the system that learns fastest from it wins.
- Playback must feel instant. A swipe that shows a spinner for 500 ms breaks the experience. The client must prefetch the next few videos before the user asks for them, which means the feed API, the CDN and the player are designed together.
- Upload volume is huge and the long tail matters. Tens of millions of videos are uploaded per day, and most get few views. Transcoding every upload into many formats is expensive, and the CDN cannot cache everything at the edge.
- Cold start is constant. Every new video starts with no engagement history, and every new user starts with no profile. The system must explore (show new things to learn about them) without wasting users' time.
Analogy. Imagine a radio station with one listener per channel and a DJ who has read the entire record library. The DJ plays a song, watches your face, and within seconds decides the next song based on whether you smiled, frowned or turned the volume down. To make the switch seamless, an assistant has already pulled the next three records from the shelf and placed them on spare turntables (prefetching). Behind the scenes, a record label is pressing millions of new records a day into formats for every kind of player (transcoding), and copies of the hits are kept in small shops on every street corner (the CDN), while rare records stay in the central warehouse. Every few minutes, the DJ's notes on what everyone liked are shared with all the other DJs, so they all get better at guessing (online training).
Background: a few terms used in this design#
- For You feed (FYP): the main recommended stream of videos, not limited to followed accounts.
- Following feed: the stream of videos from accounts the user follows, ordered mostly by recency. It is a classic fan-out feed and is secondary in this app.
- Recommendation funnel: the standard multi-stage design for large-scale recommendation. Candidate generation (retrieval) picks a few thousand plausible items out of billions, a ranking model scores those carefully, and a re-ranking step applies diversity and business rules to produce the final list.
- Embedding: a vector of numbers (for example, 64 or 128 floats) that represents a user, a video, a creator or a sound, learned so that similar things have similar vectors.
- Two-tower model: a retrieval model with one neural network for the user ("user tower") and one for the item ("item tower"). Each produces an embedding, and relevance is their dot product. Item embeddings can be precomputed and searched with approximate nearest neighbour search.
- ANN (approximate nearest neighbour) search: finding the vectors closest to a query vector without comparing against every vector, using indexes such as HNSW graphs or IVF with product quantisation. It trades a little accuracy for speed of 1–10 ms over hundreds of millions of vectors.
- Feature store: a system that stores and serves the input features of ML models (for example, "videos this user watched in the last hour" or "a video's like rate in the last 10 minutes"), with the same values used in training and serving.
- Online training (continuous training): updating a model's parameters continuously from a stream of fresh labelled examples, instead of retraining in daily batches.
- Watch time and completion rate: how long a user watched a video, and the fraction of the video watched. For short videos, completion and replays are among the strongest signals.
- Cold start: making good decisions about a new user or a new item that has no history.
- Exploration versus exploitation: the trade-off between showing items known to be good (exploit) and showing uncertain items to learn about them (explore).
- Transcoding: decoding an uploaded video and re-encoding it into other codecs, resolutions and bitrates.
- Codec: the compression algorithm for video (H.264/AVC, H.265/HEVC, VP9, AV1) or audio (AAC, Opus). Newer codecs give smaller files at the same quality but cost more CPU to encode and need device support to decode.
- Container: the file format that packages encoded video, audio and metadata (MP4, fragmented MP4, WebM, MPEG-TS).
- Bitrate: bits per second of encoded video. A 720p short video might be encoded at 1–2 Mbit/s; a 1080p one at 2–4 Mbit/s.
- Bitrate ladder (rendition ladder): the set of resolution and bitrate pairs a video is encoded into, for example 360p at 400 kbit/s, 540p at 800 kbit/s, 720p at 1.5 Mbit/s, 1080p at 3 Mbit/s.
- ABR (adaptive bitrate streaming): the player switches between renditions as bandwidth changes. HLS (from Apple) and MPEG-DASH are the main protocols. Both use a manifest that lists renditions and their segments.
- Segment: a small, independently playable chunk of video, usually 2–6 seconds long.
- Time to first frame (TTFF): the delay from the user's action (opening the app or swiping) to the first video frame on screen. The single most important playback metric for this app.
- Rebuffering (stall): playback pauses because the buffer ran empty.
- Prefetch: downloading data before the user asks for it, here the beginning of the next few videos in the feed.
- CDN (content delivery network): a network of caching servers close to users that serves static content such as video segments and thumbnails.
- Origin: the storage behind the CDN that holds the authoritative copy of every file.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Which features are in scope? | Upload, For You feed, playback, like, comment, share, follow, Following feed. Live streaming, DMs, shopping and ads are out of scope (ads mentioned only where they touch the feed). | Keeps focus on the core loop: upload, recommend, play, learn. |
| How many users? | 1 billion monthly, 300 million daily active users (DAU). | Drives feed QPS, event volume and CDN egress. |
| How much do they watch? | About 60 minutes per DAU per day, about 120 videos per DAU per day. | Sets playback bandwidth and event volume, which dominate cost. |
| How many uploads? | 30 million new videos per day (about 10% of DAU upload on a given day, many once). | Drives transcoding, storage and moderation load. |
| Video length and size? | Median 30 seconds, up to 10 minutes; uploads of 10–200 MB after phone compression. | Determines transcode cost and segment strategy. |
| How fast must a new video be available? | Playable by followers within about 60 seconds of upload; in the For You pool after moderation, typically within a few minutes. | Shapes the transcode pipeline and moderation ordering. |
| How fresh must recommendations be? | A swipe-away or like should influence the next few videos in the same session (seconds), and the global model should learn from it within minutes. | Forces real-time features and online training. |
| What does "instant" playback mean? | Median time to first frame under 200 ms after a swipe, 95th percentile under 500 ms, rebuffering under 0.5% of watch time. | Forces prefetching and a fast CDN. |
| Which devices and networks? | iOS and Android, plus web; networks from 5G and Wi-Fi down to 3G. | Requires an ABR ladder with low rungs and device-aware codec choice. |
| Is the For You feed global or regional? | Regional pools by default (country and language), with global content when it travels well. Data residency rules apply in some regions. | Affects multi-region design and candidate sources. |
| Do we need exact like and view counts? | Approximate and eventually consistent counts are acceptable for display; exact counts are needed for creator payouts later in batch. | Allows sharded, buffered counters. |
| What about safety? | Every video passes automated moderation before broad distribution, with human review for borderline cases. | Moderation sits in the publish path and gates distribution. |
Requirements#
Functional requirements#
- Upload: users upload a video with a caption, hashtags and an optional sound, and it becomes playable for others.
- Process: each upload is transcoded into streamable renditions, a cover image and metadata, and passes content moderation.
- For You feed: users get an endless, personalised sequence of videos, fetched in pages, that reacts to their behaviour within the session.
- Playback: videos start almost instantly on swipe and play smoothly on varying networks.
- Engagement: users like, comment, share, save and follow, and see counts on each video.
- Signals: every view (with watch duration), swipe, like, share and follow is collected and used to update features and models.
- Following feed: users can switch to a feed of recent videos from accounts they follow.
- Cold start: new users get a reasonable feed from the first video, and new videos get a fair first audience.
Non-functional requirements#
- Low latency: feed API p99 under 300 ms server time; time to first frame median under 200 ms on swipe.
- High availability: 99.95% or better for feed and playback. If the recommender is degraded, the app still shows good videos (fallback to cached or popular lists). Availability beats consistency for counts and feeds.
- Scalability: 300 million DAU, about 36 billion video views per day, peak playback egress of about 30 terabits per second globally.
- Freshness: engagement reflected in session features within seconds, model updates within minutes, counts within seconds to a minute.
- Durability: an uploaded original is never lost once the upload is acknowledged.
- Cost efficiency: CDN egress and transcoding are the biggest bills, so the design must minimise bytes per view and transcode work per upload.
- Safety and compliance: moderation before broad reach, takedowns that propagate to caches within minutes, regional data rules.
Capacity Estimation#
The method follows Back-of-the-Envelope Estimation. These are design assumptions, not published TikTok figures.
Viewing.
- 300 million DAU × 120 videos per day = 36 billion video views per day.
- Average rate: 36 billion / 86,400 ≈ 420,000 views per second. Evening peaks are about 2 times average in each region; because regions peak at different times, the global peak is about 1.5–2 times average, so plan for 800,000 view starts per second globally.
- Average watch per video: 60 minutes / 120 videos = 30 seconds. Many videos are swiped away in 1–3 seconds; others are watched in full or replayed.
Feed API.
- The client fetches feed pages of about 8–10 videos and asks for the next page when 3–4 remain. 36 billion views / 9 per page ≈ 4 billion feed requests per day, about 46,000 per second on average and 100,000 per second at peak.
- Each request runs retrieval from several candidate sources (a few thousand candidates), a lightweight pre-ranking pass, and a heavy ranking model over the top 500–1,000. At peak that is 100,000 × 1,000 = 100 million heavy model scorings per second. This is a large GPU (or optimised CPU) inference fleet, and it is the main compute cost of the recommender.
Engagement events.
- Per view, the client logs about 5 events (impression, play start, progress checkpoints, end with watch duration, swipe or interaction). 36 billion × 5 = 180 billion events per day, about 2 million per second on average and 5 million per second at peak.
- At about 200 bytes per event after compression, that is 36 TB per day of raw events, about 13 PB per year before sampling and retention rules.
- Explicit actions are much rarer: likes at about 6% of views (about 2 billion per day, 25,000 per second), comments at 0.3% (100 million per day), shares at 0.3%, follows at about 200 million per day.
Uploads and storage.
- 30 million uploads per day, about 350 per second on average and 1,000 per second at peak.
- An original from a phone averages about 40 MB (30 seconds at 1080p and about 10 Mbit/s). Originals: 30 million × 40 MB = 1.2 PB per day.
- Renditions: a ladder of 4–5 H.264 renditions totalling about 6 Mbit/s for a 30-second video is about 22 MB. Popular videos also get an H.265 or AV1 ladder at about 60% of that size. Average about 30 MB per video, or 0.9 PB per day.
- Total new storage: about 2 PB per day, over 700 PB per year before replication. This forces tiering: originals go to cold storage after processing, and videos that nobody watches keep only a minimal ladder. See Data Lifecycle, Tiering and Retention.
- Metadata: about 1 KB per video, 30 GB per day, about 11 TB per year. Easy for a sharded database.
Transcoding compute. 30 million × 0.5 minutes = 15 million minutes of video per day. A software H.264 ladder costs roughly 2–4 CPU-minutes per minute of 1080p input at a fast preset, so about 45 million CPU-minutes per day, or about 30,000 cores busy around the clock, plus headroom for peaks. H.265 and AV1 cost 5–20 times more CPU per minute of output, which is why they are applied only to videos that earn views (see deep dive 2).
CDN egress.
- Average delivered bitrate across a mix of 540p and 720p renditions, much of it in HEVC: about 1 Mbit/s. A 30-second view is about 3.75 MB.
- Prefetched data that is never watched (the user swiped before reaching that video, or left the app) adds about 20%: about 4.5 MB per view.
- 36 billion × 4.5 MB ≈ 160 PB per day, which is about 15 Tbit/s on average and about 30 Tbit/s at peak. Egress dominates the cost of the whole platform. Every 10% cut in bytes per view saves petabytes per day.
- Covers and thumbnails: about 50 KB per video shown, 36 billion × 50 KB = 1.8 PB per day, small next to video.
Recommendation state.
- Eligible video pool for retrieval: videos from roughly the last 6–12 months with some engagement, plus all fresh uploads: about 2–5 billion videos. Indexed embeddings at 64 dimensions in 8-bit form are 64 bytes each, so 5 billion × 64 B = 320 GB per full copy, sharded across ANN servers, per region.
- User state: 1 billion users × about 5 KB (embeddings, recent watch history of the last few hundred video IDs, aggregated features) = 5 TB, served from a low-latency key-value store.
- Model parameters: large ranking models with sparse ID embeddings reach terabytes. The Monolith paper reports production models several terabytes in size with around 1,000 embedding tables, which is why parameters live on sharded parameter servers rather than in one process.
Summary table.
| Quantity | Average | Peak |
|---|---|---|
| Video views | 420,000/s | 800,000/s |
| Feed requests | 46,000/s | 100,000/s |
| Ranking scorings | 46 million/s | 100 million/s |
| Client events | 2 million/s | 5 million/s |
| Uploads | 350/s | 1,000/s |
| New storage | 2 PB/day | |
| CDN egress | 15 Tbit/s | 30 Tbit/s |
The shape is clear: this is a read-, compute- and bandwidth-heavy system. Uploads are modest in count but expensive per item; views are enormous in count and cheap per item only if almost every byte is served from a CDN edge.
Core Entities#
- User: account, profile, language, country, device, settings, follower and following counts.
- Video: the metadata record for one upload: author, caption, hashtags, sound, duration, status (uploading, processing, in review, published, restricted, removed), visibility, region, created time.
- Asset (rendition): one encoded form of a video: codec, resolution, bitrate, segment list or byte ranges, storage path, size. Plus the cover image and the original.
- Sound: an audio track that many videos can reuse (an original sound or licensed music). Sounds are a major discovery path and a strong recommendation feature.
- Hashtag / topic: labels from captions and from content understanding models.
- Engagement: like, comment, share, save and follow records, plus view (watch) events with watch duration and how the view ended.
- Embedding: learned vectors for users, videos, creators, sounds and hashtags, versioned with the model that produced them.
- Impression: a record that a video was served to a user in a feed response, with the request ID and model version, so outcomes can be joined back to the decision that caused them.
- Feed session: the short-lived state of one viewing session: what was served, what was watched, the current interest mix.
API Design#
The client talks to an API gateway over HTTPS (HTTP/2 or HTTP/3). Video bytes never pass through application servers: uploads go straight to object storage through pre-signed URLs, and playback comes from the CDN. See API Design Best Practices and Pattern: Handling Large Files and Blobs.
Upload.
POST /v1/uploads -> { upload_id, part_size, part_urls[], expires_at }
body: { size_bytes, content_type, sha256, duration_ms, width, height }
PUT <part_url> (direct to object storage, one per 5-8 MB part)
POST /v1/uploads/{upload_id}/complete -> { status: "uploaded" }
body: { parts: [ { part_number, etag } ] }
POST /v1/videos -> { video_id, status: "processing" }
body: { upload_id, caption, hashtags[], sound_id?, visibility, allow_duet, cover_time_ms }
header: Idempotency-Key
GET /v1/videos/{video_id} -> { video_id, status, author, caption, counts, playback, ... }Feeds.
GET /v1/feed/foryou?count=8&cursor=<opaque>
-> { items: [ { video_id, author, caption, sound, counts,
playback: { manifest_url, renditions[], first_segment_url, cover_url },
rec_token } ],
next_cursor, prefetch_hint: { count: 3, bytes_per_item: 500000 } }
GET /v1/feed/following?count=10&cursor=<opaque>The rec_token is an opaque, signed identifier of the impression (request ID, position, model version). The client sends it back with every event about that video, so the training pipeline can join "what we showed" with "what happened". The cursor encodes session state such as the page number and a session ID; the server keeps the list of already-served videos so pages never repeat.
Events and actions.
POST /v1/events (batched, every few seconds or on app background)
body: { events: [ { type: "impression" | "play" | "progress" | "finish" | "swipe",
rec_token, video_id, ts, position_ms, watch_ms, loops, network, ... } ] }
POST /v1/videos/{id}/like DELETE /v1/videos/{id}/like
POST /v1/videos/{id}/comments GET /v1/videos/{id}/comments?cursor=
POST /v1/videos/{id}/share body: { channel }
POST /v1/users/{id}/follow DELETE /v1/users/{id}/follow
POST /v1/videos/{id}/not-interestedActions are idempotent: a like is keyed by (user_id, video_id), so retries do not double count. Events carry a client-generated event ID for deduplication. See Idempotency and Safe Retries.
High-Level Design#
We build the design one requirement at a time, then combine the pieces.
1) Users can upload videos#
The phone records and usually compresses the video on the device (for example, H.264 or H.265 at about 8–12 Mbit/s for 1080p) before upload. This alone can cut the upload size by 3–10 times compared with the camera's raw output, which matters on mobile networks.
The client asks the Upload Service for an upload session. The service creates an upload_id, starts a multipart upload in object storage (Amazon S3, Google Cloud Storage or an in-house equivalent), and returns pre-signed URLs, one per 5–8 MB part. The client uploads parts directly to storage, in parallel (2–4 at a time), and retries failed parts alone. When all parts are done, it calls complete; the service finalises the multipart upload, which makes the object visible atomically.
The client then calls POST /v1/videos with the caption, hashtags and sound. The Video Service writes a video record with status processing into the metadata database and publishes a video.uploaded event to the event log (Kafka). Separating "bytes uploaded" from "video created" lets the user write the caption while the bytes are still uploading.
Why not upload through the API servers? A 40 MB body held open for 20 seconds on a slow network ties up a server connection and memory for each upload. At 1,000 uploads per second, direct-to-storage upload removes about 40 GB/s of traffic from the application tier. The application tier only signs URLs and records metadata.
2) Uploaded videos are processed and moderated#
A processing pipeline consumes video.uploaded and runs a workflow (a directed acyclic graph of steps, orchestrated by a workflow engine such as Temporal or an in-house equivalent):
- Probe and validate: read the container, codec, duration, resolution, frame rate and rotation. Reject corrupt files.
- Transcode into the base ladder (for example, 360p, 540p, 720p, 1080p in H.264), split into segments or fragmented MP4 with byte-range indexes.
- Extract the cover image and a few keyframe thumbnails, and the audio track for sound matching.
- Content understanding: run vision, audio and text models to produce embeddings, topic labels, detected objects, speech-to-text captions, language and quality scores.
- Moderation: hash matching against known prohibited content, classifiers for nudity, violence, self-harm, spam and other policies; borderline cases go to human review.
- Publish: write asset records, the manifest and the content features; set status to
published(orrestricted); emitvideo.published.
Steps 2–5 run in parallel because they all read the original and do not depend on each other. Publish waits for all of them. The whole workflow takes 20–90 seconds for a typical short video. The heavy details are in deep dives 1 and 2.
3) Users get a personalised For You feed#
The Feed Service answers GET /v1/feed/foryou. It is a thin orchestrator in front of the recommendation stack:
- Load context: the user's profile features, long-term embedding, recent watch history and in-session signals (the last 20–50 videos and how each ended), from the feature store.
- Candidate generation: ask several retrieval sources in parallel for candidates: an ANN search on the user embedding, "more from creators you watch to the end", "videos with sounds you like", "trending in your region and language", "fresh videos needing exploration", and "followed creators' new videos". Together they return 2,000–10,000 candidates in 20–40 ms.
- Filter: remove videos already seen (a per-user seen set), blocked creators, videos not available in the user's region, and videos still under review.
- Pre-rank: a cheap model (for example, a small two-tower or tree model) cuts the candidates to about 500–1,000.
- Rank: a heavy multi-task neural network predicts, for each candidate, the probabilities of finishing, replaying, liking, commenting, sharing, following and of a fast skip, plus expected watch time. A weighted formula combines these into one score.
- Re-rank: apply diversity rules (no two videos from the same creator or sound in a row, topic mix), freshness and exploration quotas, and safety rules.
- Return the top 8–10 with playback URLs, and record the impression (served list, model version) for training and for the seen set.
The target is under 150 ms at the median and under 300 ms at p99, inside the server. The detail is in deep dives 3 to 5.
4) Videos start instantly and play smoothly#
The feed response includes, for each video, a manifest URL, the rendition list and the first segment URL for the rendition the server expects to fit the user's network. The client:
- Starts playing video 1 from the CDN as soon as the first segment arrives.
- Prefetches the first 1–2 seconds (often a few hundred KB) of videos 2, 3 and sometimes 4 while video 1 plays. When the user swipes, the first frames are already on the phone, so playback starts in tens of milliseconds.
- Picks renditions with an ABR algorithm based on measured throughput and buffer level, preferring a lower rung at startup to start fast, and stepping up if bandwidth allows.
- Keeps 2–3 decoder and player instances warm, so that switching videos does not pay the cost of creating a new decoder.
Video bytes come from the CDN. Popular segments are served from edge caches near the user; misses go to regional mid-tier caches and finally to origin object storage. Deep dives 9 and 10 cover prefetching and CDN design.
5) Engagement is recorded and shown#
Explicit actions (like, comment, share, save, follow) go to the Engagement Service, which writes them durably (for example, a like row keyed by user and video in a wide-column store such as Cassandra), updates counters, and publishes an event. Comments go to a Comment Service with its own store, ranking and moderation. Follows go to a Graph Service, which also feeds the Following feed.
Counters (likes, comments, shares, views) are hot: a viral video receives thousands of likes per second. They use sharded counters in Redis with periodic flushes to the durable store, so reads are fast and writes do not contend on one row. Displayed counts are approximate and update within a second or two.
6) Signals flow back into recommendations#
All implicit events (impressions, plays, watch time, swipes) and explicit actions flow through the event log (Kafka). Three consumers matter most:
- Real-time feature pipelines (Flink) update user session features ("this user just skipped three cooking videos") within seconds, and item features ("this video's completion rate in the last 10 minutes") within tens of seconds.
- A training example joiner matches each impression (and the features used at serving time) with the outcome events, producing labelled training examples for online training. Updated model parameters are synchronised to the serving fleet every few minutes.
- The data lake stores everything for batch training, analytics, creator analytics and experiments.
7) Users can watch a Following feed#
The Following feed is the classic home timeline problem: for most creators, new video IDs are fanned out on write into followers' inboxes; for creators with millions of followers, followers pull their recent videos at read time, and the two are merged. Because the For You feed is the default, the Following feed has lower traffic, and it can reuse the same playback, prefetch and engagement paths. The fan-out mechanics are the same as in the news feed case study, Design a News Feed (Facebook / Twitter).
The full high-level design#
Components:
- CDN: serves all video segments, manifests and images from edge caches. Usually several commercial CDNs plus, at TikTok's scale, the company's own edge capacity.
- API gateway: TLS termination, authentication, rate limits, routing, request IDs.
- Upload Service: creates upload sessions and signs part URLs; never touches video bytes.
- Video Service: owns video metadata and status; the source of truth for whether a video is playable and where.
- Processing workflow: probe, transcode, thumbnail, content understanding, moderation and publish steps, on CPU, GPU and hardware encoder pools.
- Feed Service: orchestrates the recommendation funnel per request, manages session state and the seen set, and falls back to cached lists when the recommender is slow.
- Retrieval servers: ANN indexes of video embeddings, plus inverted indexes for creator, sound, hashtag, trending and fresh-video sources.
- Ranking service: heavy multi-task models on GPU inference servers, with sparse embeddings on parameter servers.
- Engagement, comment and graph services: likes, saves, shares, comments and follows, with their stores.
- Counters: sharded in-memory counters for display, flushed to durable storage.
- Event log (Kafka): the backbone for uploads, publishes, engagement and client events.
- Stream processing (Flink): real-time features, counters, trending detection and training example joins.
- Feature store: online key-value store for low-latency features, with an offline twin in the lake for training.
- Training: online training that updates the model continuously, and batch training for new architectures and backfills.
- Object storage: originals (moved to cold tiers after processing) and renditions.
- Metadata DB: sharded database for users, videos, assets and relationships.
- Data lake: all events and snapshots for training, analytics, experiments and creator dashboards.
Key Flows#
Flow 1: upload to published#
Notes on the flow:
- The client can call
POST /v1/videosbefore the upload completes. The Video Service then holds the record inuploadingand starts the workflow when thecompleteevent arrives. This hides the time spent typing a caption. - Every step in the workflow is idempotent and keyed by
video_idplus step name, so a retried step overwrites the same outputs. The workflow engine persists progress, so a worker crash resumes at the failed step, not from scratch. See Pattern: Managing Long-Running Tasks. - The author can see their own video immediately: the app plays the local file while the server processes it, and shows "processing" to others until publish.
Flow 2: For You feed request and playback#
Latency budget inside the server (median, p99 in brackets): feature fetch 5 ms (15), retrieval 30 ms (60), filtering and pre-ranking 15 ms (30), ranking 50 ms (100), re-ranking and response assembly 10 ms (20), for a total of about 110 ms (225). The client hides even this by requesting the next page early: the user never waits for the feed API after the first page.
Flow 3: a swipe changes the next videos#
Two levels of freshness work together. The session features in the feature store change within 1–3 seconds of the event, so the next page already reflects the skip. The model parameters change within minutes through online training (deep dive 6). Some apps also send the last few events inline in the feed request (for example, the last 10 watch outcomes), so the very next page reacts even if the stream pipeline lags. This costs a few hundred bytes per request and removes a dependency on pipeline latency for the most important signal.
Flow 4: like on a viral video#
The app updates the heart and the count optimistically before the server responds. If the request fails after retries, it reverts. Because the like row is keyed by (user, video), a retried request finds the existing row and does not increment the counter again.
Data Model#
Video metadata in a sharded relational store (for example, MySQL with Vitess, or a distributed SQL database such as TiDB or CockroachDB):
CREATE TABLE videos (
video_id BIGINT PRIMARY KEY, -- time-ordered 64-bit ID
author_id BIGINT NOT NULL,
sound_id BIGINT,
caption VARCHAR(2200),
duration_ms INT NOT NULL,
status ENUM('uploading','processing','in_review','published','restricted','removed'),
visibility ENUM('public','friends','private'),
region CHAR(2) NOT NULL, -- data residency and default pool
manifest_path VARCHAR(512),
created_at TIMESTAMP NOT NULL,
published_at TIMESTAMP,
KEY by_author (author_id, created_at) -- profile grid, newest first
);
-- Shard key: video_id for point reads.
-- The by_author lookup lives in a separate table sharded by author_id.
CREATE TABLE author_videos (
author_id BIGINT,
created_at TIMESTAMP,
video_id BIGINT,
PRIMARY KEY (author_id, created_at, video_id)
);Likes and follows in a wide-column store (Cassandra-style CQL):
CREATE TABLE likes_by_video (
video_id bigint, bucket int, user_id bigint, created_at timestamp,
PRIMARY KEY ((video_id, bucket), user_id)
); -- bucket splits hot videos across partitions
CREATE TABLE likes_by_user (
user_id bigint, created_at timestamp, video_id bigint,
PRIMARY KEY (user_id, created_at, video_id)
) WITH CLUSTERING ORDER BY (created_at DESC); -- "liked videos" tabWe make no claim about which databases TikTok uses in production; the design works with any horizontally sharded store that supports point reads and a secondary lookup table.
Store choices.
| Data | Store | Why |
|---|---|---|
| Video and user metadata | Sharded MySQL (Vitess) or distributed SQL | Point reads by ID, secondary lookups by author, transactional status changes |
| Likes, saves, follows | Cassandra, ScyllaDB or similar | Very high write rate, simple key access, linear scaling |
| Counters | Redis cluster with sharded keys, flushed to the wide-column store | Thousands of increments per second on one video |
| Comments | Wide-column store keyed by (video_id, bucket), plus a search index | Append-heavy, paginated reads, ranking by likes |
| Originals and renditions | Object storage with lifecycle tiers | Exabyte-scale blobs, cheap and durable |
| Online features and user state | Low-latency key-value store (Redis, Aerospike, or an in-house store on SSD) | 1–5 ms reads, millions of reads per second |
| Embedding indexes | ANN servers (HNSW or IVF-PQ in memory), or a vector database | Nearest-neighbour search over billions of vectors |
| Events | Kafka, then the data lake (Parquet on object storage, with a table format such as Iceberg or Hudi) | Replayable streams and cheap long-term storage |
| Seen sets | Per-user Bloom filters or recent-ID lists in the KV store | Fast "already shown" checks with bounded memory |
For the reasoning behind these choices, see Choosing a Database: A Decision Guide, Apache Cassandra in Practice and Redis in Practice.
Deep Dives#
1. Upload: fast, resumable and cheap on mobile networks#
Why upload is hard on phones. Creators often upload on mobile data, while moving, with the app going to the background. A 40 MB upload at 4 Mbit/s takes 80 seconds; at 1 Mbit/s, over 5 minutes. A single HTTP request for the whole file would fail often, and a failure would throw away all progress.
Option A: one request through the API servers (bad). Simple, but it ties up application servers, fails on any network blip and restarts from zero.
Option B: one direct request to object storage with a pre-signed URL (better). It removes the API tier from the data path, but it is still all-or-nothing.
Option C: chunked, resumable, direct upload (best).
- The client splits the compressed file into parts of about 5–8 MB (object stores such as S3 require parts of at least 5 MB, except the last). Each part gets a fingerprint (for example, SHA-256 of the part).
- The Upload Service stores the session:
upload_id, the expected part count, and each part's status (pending,uploadedwith its ETag). The client reports each completed part (or the service lists parts from the object store with a ListParts call). - If the app is killed or the network drops, the client asks for the session state on restart, skips completed parts and continues with the rest.
- When all parts are present, the client calls
complete. The object store assembles the object and emits a single object-created notification (for S3, anObjectCreated:CompleteMultipartUploadevent), which can trigger processing. Part-level progress stays client-driven. - Sessions that are not completed within, say, 24 hours are aborted, and their parts deleted, by a lifecycle rule, so abandoned uploads do not leak storage.
On iOS and Android, uploads should use the OS background transfer APIs (background URLSession on iOS, WorkManager with foreground service notifications on Android), so they continue when the user switches apps. See Mobile System Design.
Make uploads smaller before they start.
- Client-side transcoding: the app encodes to a target such as 1080p H.264 or H.265 at about 8–10 Mbit/s using the phone's hardware encoder, which is fast and battery-efficient. A raw 4K camera file at 50 Mbit/s shrinks 5 times or more.
- Edits on device: filters, effects, trims and music overlay are rendered on the phone, so the server receives one final file instead of a project to render.
- Network-aware quality: on a slow connection, upload a 720p version first so the video publishes quickly, then optionally upload a higher-quality version in the background on Wi-Fi and swap renditions later.
Pipelining upload and processing. For long uploads, the client can split the video into independently decodable segments (for example, at keyframes every 2–4 seconds) and upload them as separate objects. The server starts transcoding segment 1 while segment 5 is still uploading. For a 3-minute video, this can cut the time from "upload finished" to "published" from about a minute to a few seconds. The costs: the client does more work, and if the user abandons the upload, the server has already spent compute on segments that will be thrown away. For typical 15–60 second videos, the simpler "upload then process" flow is good enough; pipelining pays off for long videos.
Deduplication. Many uploads are re-uploads of the same file (reposts of viral clips). The client sends the SHA-256 of the whole file at session start. If an identical, already-processed original exists, the service can reuse the processed assets and skip the upload entirely. Exact hashes only catch identical bytes; near-duplicates (re-encoded or cropped copies) are caught later by perceptual video fingerprints in the processing pipeline, which matter for copyright and for recommendation diversity (two copies of the same clip should not appear back to back).
Idempotent creation. POST /v1/videos carries an Idempotency-Key. If the app retries after a timeout, the server returns the same video_id instead of creating a duplicate post.
2. Transcoding: from one upload to a streamable ladder#
What we must produce. Devices differ in which codecs they decode in hardware, screens differ in resolution, and networks differ in bandwidth. Storing only the raw upload would fail on many devices and waste bandwidth everywhere. Storing a few whole-file formats is better, but whole files make it hard to switch quality mid-video. The best approach stores several renditions, each split into short segments (or fragmented MP4 with a byte-range index), plus manifests that list renditions and segments. This enables adaptive bitrate streaming.
Key video terms in one place.
- Codec decides how frames are compressed. H.264 (AVC) decodes on essentially every device. H.265 (HEVC) gives similar quality at roughly 30–50% lower bitrate and is widely supported in hardware on modern phones. AV1 (royalty-free, from the Alliance for Open Media) saves a further 20–30% but costs much more to encode, and hardware decode is common only on recent devices. VP9 sits between H.264 and AV1 and is mostly used on Android and the web.
- Container decides how encoded streams are packaged: MP4 and fragmented MP4 (CMAF) for HLS and DASH, WebM for VP9 and AV1 on the web, MPEG-TS for older HLS.
- Bitrate is how many bits per second the encoded video uses. Higher resolution and frame rate need more bits for the same visual quality. Better codecs need fewer.
- Manifests: a primary (multivariant) manifest lists every rendition and points to a media manifest per rendition, which lists the segment URLs. HLS uses
.m3u8text files; DASH uses an XML.mpdfile.
A ladder for short, vertical video. Short videos are vertical (9:16) and watched on phones, so the ladder can be smaller than for a TV-oriented service. An example base ladder in H.264:
| Rendition | Resolution | Bitrate | 30-second size |
|---|---|---|---|
| Low | 360×640 | 350 kbit/s | 1.3 MB |
| Medium | 540×960 | 700 kbit/s | 2.6 MB |
| High | 720×1280 | 1.3 Mbit/s | 4.9 MB |
| Full HD | 1080×1920 | 2.8 Mbit/s | 10.5 MB |
Audio is AAC at 64–128 kbit/s, often muxed into each rendition for simplicity, because short videos rarely need separate audio tracks.
The processing DAG. The pipeline is a directed acyclic graph of steps:
- Probe the original (codec, resolution, frame rate, rotation, HDR, duration).
- Split into chunks at keyframes (for example, 4–10 second chunks) so they can be encoded in parallel. For a 30-second video, splitting may not be worth it; for a 10-minute video it cuts wall-clock time by 10 times or more.
- Encode each chunk into each rendition on a pool of workers. This is the most expensive step and is CPU-bound (or runs on GPUs or video-encoding chips).
- Assemble encoded chunks into renditions, package them as CMAF segments, and write manifests.
- In parallel: thumbnails and cover image; audio fingerprint for sound matching and copyright; speech-to-text; visual and audio embeddings; moderation models.
- Publish when the required steps succeed.
Intermediate files go to object storage, and steps pass URLs, not bytes, between each other. A workflow engine (Temporal, or an in-house orchestrator) holds the DAG state, retries failed steps with backoff, and records progress so a crashed worker loses only its current chunk. Queue depth drives autoscaling of encoder pools. See Temporal and Workflow Engines and Pattern: Multi-Step Processes and Workflows.
Prioritise what makes the video watchable. The publish step does not need the whole ladder. A good order is: encode the 720p and 360p renditions first (enough for most users), publish, then encode 1080p and the remaining rungs, and update the manifest. Viewers who start early get a slightly shorter ladder for a minute.
Encode better codecs only where they pay off. Encoding cost is paid once per video; bandwidth savings are paid back on every view. For a video with 100 views, an AV1 ladder costing 10 times the H.264 CPU saves almost nothing. For a video with 10 million views, a 30% bitrate saving is worth a great deal of egress. The pipeline therefore uses popularity-triggered re-encoding: all videos get the H.264 base ladder; when a video's view velocity crosses a threshold (say, 10,000 views in an hour), a background job encodes an H.265 ladder; at a higher threshold (say, 1 million views), it also encodes AV1 with slow, high-quality presets. The manifest is updated, and new viewers get the better codec if their device supports it. Because the top 1% of videos receive the large majority of views, this captures most of the possible saving for a small fraction of the encoding cost.
Per-title (content-aware) encoding. A static talking-head video needs far fewer bits than fast dance moves or confetti. Netflix described per-title encode optimisation in 2015: run trial encodes, measure quality (for example with VMAF, the perceptual quality metric Netflix open-sourced in 2016), and choose the bitrate ladder for each title. For a short-video service, full per-title analysis on every upload is expensive, but a cheaper version works well: a complexity estimate from a fast first-pass encode picks one of several preset ladders, and popular videos get a full per-title or per-shot optimisation during re-encoding.
Hardware. At very large scale, software encoding on CPUs is the biggest compute cost of video. Google described its custom video transcoding chip (the Argos "Video Coding Unit") in "Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild" (Ranganathan et al., ASPLOS 2021), and Meta announced its own video processing ASIC (MSVP) in 2023. Smaller services use GPU encoders (NVENC) for fast, lower-efficiency encodes and CPUs for high-efficiency encodes of popular content.
Quality checks. Each rendition is checked automatically: duration matches the original, audio and video stay in sync, there are no black or frozen frames introduced by the encoder, and a sampled quality score (VMAF or SSIM) meets a floor. Failed checks retry with different settings.
Cost summary for the pipeline. With the numbers in Capacity Estimation, base H.264 ladders need about 30,000 busy cores; H.265 for the top 5% of videos adds about 5–10 times that per video, so roughly 10,000–15,000 more cores; AV1 for the top 0.1% adds less than that. The total is tens of thousands of servers' worth of CPU, which is why hardware encoders become attractive.
3. The For You feed: what it optimises and how the funnel fits together#
What "a good feed" means. The system needs an objective it can measure. Options:
- Clicks or plays: meaningless here, because every video in the feed autoplays.
- Watch time: the total time a user spends watching. Strongly tied to business value, but on its own it rewards long videos and attention-grabbing content.
- Completion and replays: normalised by video length, so a 10-second video watched twice counts more than a 60-second video abandoned at 20 seconds.
- Explicit positive actions: likes, comments, shares, follows, saves. Rarer but more deliberate signals of value.
- Negative actions: fast skips (under 1–2 seconds), "not interested", reports, unfollows. These must count against a video, not just be ignored.
- Long-term outcomes: whether the user comes back tomorrow (retention), and whether they report feeling the feed is repetitive. These are slow to measure but are what matters.
Production systems combine these. The ranking model predicts several short-term outcomes per candidate, and a value formula combines them, for example:
score = w_finish * P(finish) + w_watch * E[watch_seconds] / norm
+ w_like * P(like) + w_comment * P(comment) + w_share * P(share)
+ w_follow * P(follow) - w_skip * P(skip_under_2s) - w_report * P(report)The weights are tuned by online experiments against long-term metrics (retention, daily active days, user satisfaction surveys). This separation is important: the model learns what will happen; the formula expresses what we want. Changing priorities (for example, valuing shares more to grow the network) is a weight change, not a model retrain.
TikTok's own public explanation (published in 2020) describes the same general picture: recommendations are based on user interactions such as likes, shares, comments, follows and watching a video to the end; on video information such as captions, sounds and hashtags; and, with lower weight, on device and account settings such as language and country. It also says that a strong signal such as finishing a longer video weighs more than weaker ones. We should not claim more detail than that about TikTok's actual model.
Why a funnel. Scoring every eligible video with the heavy ranking model is impossible: 5 billion candidates × 100,000 requests per second is 5 × 10^14 scorings per second. The funnel narrows the set in stages, with each stage using a model whose cost matches its input size:
| Stage | Input | Output | Model cost per item | Budget |
|---|---|---|---|---|
| Retrieval | Billions | 2,000–10,000 | Dot product or index lookup, about 0.1–1 µs | 20–40 ms |
| Pre-ranking | 5,000 | 500–1,000 | Small neural net or trees, about 1–5 µs | 10–15 ms |
| Ranking | 800 | 800 scored | Large multi-task net, about 50–100 µs on GPU, batched | 30–60 ms |
| Re-ranking | 800 | 8–10 | Rules and a small list-wise model | 5–10 ms |
The funnel creates a classic risk: a good video lost at an early stage can never be recovered by a later one. To limit this, retrieval sources are diverse, pre-ranking is trained to mimic the ranker on the same objectives (often by distillation from the ranker's scores), and every stage's recall is monitored offline ("how many of the ranker's top 10 would retrieval have found?").
Session-awareness is the TikTok twist. On a follow-based feed, a user scrolls past 20–50 posts per session. On a short-video feed, they see 50–200 videos, each one a labelled example. The feed should change within the session: if a user watches three skateboarding videos to the end, the fourth page should have more skateboarding, and if they skip three in a row, less. This needs:
- Real-time session features (last 50 watch outcomes with topic, creator and sound), refreshed within seconds (Flow 3).
- Sequence-aware models: the ranking model takes the user's recent sequence as input (for example, through attention over the last N videos), not only long-term averages.
- Short pages: 8–10 videos per request instead of 50, so the system re-decides often. The cost is more feed requests per session, which is why the funnel must be fast.
Fallbacks. If the ranking service is slow or down, the Feed Service still answers: first with pre-ranked candidates (lower quality but personalised), then with a cached personalised list computed in the last session, and finally with a regional popular list that is precomputed every few minutes. The user sees a slightly worse feed instead of an error. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
4. Candidate generation: finding a few thousand videos out of billions#
Retrieval must be fast, high-recall and diverse. No single method does all three, so production systems run many retrieval sources in parallel and merge their outputs, typically with a quota per source.
Source 1: embedding retrieval with a two-tower model. A user tower turns the user's features (long-term interests, recent watch sequence, language, country, device) into a vector u. An item tower turns a video's features (content embedding, creator, sound, hashtags, early engagement) into a vector v. The model is trained so that the dot product u·v is high for videos the user engaged with and low for others.
- Training uses positives from engagement (finished, liked, shared) and in-batch negatives: the other videos in the same training batch serve as negatives for each user. Because popular videos appear in batches more often, they are over-penalised as negatives; sampling-bias correction subtracts the log of each item's sampling probability from its logit. This method is described for YouTube in "Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations" (Yi et al., RecSys 2019).
- At serving time, item vectors are precomputed and loaded into an ANN index; the user vector is computed per request (about 1–2 ms), and the index returns the top 1,000–2,000 videos by dot product in a few milliseconds.
- The two-tower design is cheap because user and item never interact inside the network until the final dot product. That same property limits accuracy, which is why ranking uses a model with full feature interaction.
The two-stage "candidate generation then ranking" structure, with a deep network for each, was described for YouTube in "Deep Neural Networks for YouTube Recommendations" (Covington, Adams and Sargin, RecSys 2016). That paper also introduced several practical tricks still used today: treating recommendation as extreme multi-class classification with sampled softmax, using the age of training examples as a feature to model freshness, and predicting expected watch time with weighted logistic regression.
The ANN index. Five billion 64-dimensional vectors cannot be scanned per request, so they go into an approximate index:
- HNSW (Hierarchical Navigable Small World graphs, Malkov and Yashunin, published in IEEE TPAMI in 2018): a layered proximity graph with excellent recall at low latency, but memory-heavy (vectors plus about 100–200 bytes of graph links per item).
- IVF-PQ (inverted file with product quantisation, as in the FAISS library from Meta): vectors are clustered into, say, 100,000 lists; each vector is compressed to 16–32 bytes; a query probes the nearest few dozen lists. Much smaller memory, slightly lower recall.
- ScaNN (Google) uses anisotropic quantisation to improve maximum-inner-product recall at a given speed.
The index is sharded by item (each shard holds a slice of the corpus; the query goes to all shards and the results are merged), and replicated for QPS. With 320 GB of compressed vectors per region split into 32 shards of 10 GB, each shard fits comfortably in memory with its graph, and 20–50 replicas per shard handle 100,000 queries per second. See Vector Databases and Similarity Search.
Keeping the index fresh. A video uploaded five minutes ago must be retrievable. Two techniques:
- Real-time insertion: HNSW supports inserting new vectors online. The publish event triggers the item tower to compute the video's vector from its content features, and the vector is inserted into a small fresh index that is searched alongside the main index.
- Periodic rebuild: the main index is rebuilt every few hours from the latest item tower, because the item vectors drift as the model trains. The fresh index is then cleared of videos that made it into the new main index.
A subtle problem: if the user tower updates continuously (online training) but item vectors in the index were computed by an older item tower, the two spaces drift apart and retrieval quality drops. Fixes include versioning the towers together, re-embedding popular items frequently (they matter most), and limiting how fast the user tower can change between index rebuilds.
Source 2: item-to-item ("more like what you just finished"). For each recently finished or liked video, look up videos that are similar by content embedding, or that are frequently watched to the end by the same users (co-engagement). Item-to-item neighbour lists are precomputed in batch and refreshed for hot videos in near real time. This source is why the feed reacts strongly to one video watched to the end.
Source 3: creator and sound sources. Recent videos from creators the user finishes often (even if they do not follow them), and popular videos using sounds the user engages with. On TikTok, sounds and trends spread together, so a sound-based source is unusually useful.
Source 4: followed creators. New videos from followed accounts, so the For You feed occasionally includes them.
Source 5: trending and regional popularity. Videos with high engagement velocity in the user's region and language over the last hour or day. Computed by stream processing (see the trending case study, Design Top-K / Trending (Top Videos, Leaderboards)).
Source 6: exploration pool. Fresh videos that need impressions to be evaluated (deep dive 8), and topics the user has not seen yet. This source has a fixed quota so that exploration always happens.
Source 7: graph-based and community sources. Random walks on the user–video interaction graph (in the style of Pinterest's Pixie, described in "Pixie: A System for Recommending 3+ Billion Items to 200+ Million Users in Real-Time", Eksombatchai et al., WWW 2018) find videos that similar users engaged with.
Merging sources. Each source returns its own top list with scores that are not comparable. The merger keeps a quota per source (for example, 40% embedding, 20% item-to-item, 10% creator, 10% trending, 10% exploration, 10% other), deduplicates by video ID and near-duplicate cluster, and passes the union to filtering. Quotas are themselves tuned by experiment, and a source that has stopped contributing to final impressions is a sign of a bug or a stale index.
Filtering. After merging:
- Seen filter: remove videos the user has already been shown. A per-user list of the last few thousand served video IDs, or a Bloom filter over a longer history (a filter for 10,000 items at 1% false positives needs about 12 KB). A false positive hides a video the user never saw, which is harmless; the filter never lets a seen video through, as long as it is updated at serve time. See Probabilistic Data Structures for Big Data.
- Eligibility: region availability, age restrictions, user blocks and mutes, creator privacy settings, takedowns and "under review" status.
- Not-interested rules: if a user tapped "not interested" on a video, down-weight or exclude its creator, sound and close neighbours for a period.
5. Ranking: predicting what each user will do with each video#
Inputs. For each (user, candidate) pair, the ranker sees hundreds of features:
- User features: long-term interest embeddings, language, country, device class, network type, account age, follow count, activity level.
- Sequence features: the last 50–200 videos watched, each with its watch fraction, loops, likes and skip time, and with the video's topic, creator and sound IDs.
- Video features: content embeddings (visual, audio, text), duration, creator ID and creator stats, sound ID, hashtags, upload age, and real-time engagement statistics (impressions, completion rate, like rate and skip rate over the last 10 minutes, 1 hour and 1 day).
- Cross features: has this user watched this creator before, and how much? How did the user respond to this sound or topic in the last day? These are often the most predictive features of all.
- Context: time of day, position in the session, what was shown just before.
Sparse ID features (user ID, video ID, creator ID, sound ID, hashtag IDs) are turned into learned embeddings. There are billions of distinct IDs, so the embedding tables dominate the model's size. The Monolith paper describes why ByteDance moved away from hashing IDs into fixed-size tables: collisions between popular and rare IDs hurt model quality. Instead it uses a collisionless hash table (based on cuckoo hashing) that grows as new IDs arrive, with two memory controls: IDs are admitted only after appearing a minimum number of times (with a probabilistic filter to cut memory further), and IDs expire after a configurable period of inactivity. In that paper's MovieLens experiment, hashing users into a smaller space produced a 7.7% collision rate, and the collisionless table gave consistently higher AUC.
Architecture: a multi-task network. One shared model predicts many outcomes, because they share most of the information and one model is cheaper to serve than ten:
- A shared bottom (embeddings, feature interaction layers such as DCN or factorisation-machine components, and attention over the user's sequence).
- Task towers: one per outcome (finish, watch time, like, comment, share, follow, fast skip, report).
- Tasks can conflict (comments correlate with controversial content; finishes correlate with short length). Multi-gate Mixture-of-Experts (MMoE) (Ma et al., KDD 2018) lets each task mix a shared set of expert sub-networks with its own gate, so tasks share where they agree and separate where they do not. YouTube described an MMoE ranker for "what to watch next" in "Recommending What Video to Watch Next: A Multitask Ranking System" (Zhao et al., RecSys 2019).
Watch-time modelling. Predicting watch time directly with regression is noisy. A common approach, from the 2016 YouTube paper, trains a logistic classifier where positive examples are weighted by watch time, so the learned odds approximate expected watch time. For short videos, it is often better to predict completion probability and loop count, because they are normalised by video length and do not systematically favour longer videos. A model that only maximises seconds watched drifts towards longer videos; a model that only maximises completion drifts towards very short ones. The value formula balances both.
Biases in the training data. The model learns from what it chose to show, so its data is biased:
- Position bias: videos at the start of a session are watched more because users are fresh. Include position as a feature during training and set it to a constant at serving time, or learn a separate shallow "bias tower" whose output is dropped at serving (the YouTube 2019 paper takes this approach).
- Exposure bias: videos never shown have no labels. Exploration traffic (deep dive 8) provides some unbiased data.
- Selection bias from the previous model: the training data reflects the old model's choices. Logging the propensity (probability of being shown) for exploration slots allows inverse-propensity weighting in offline evaluation.
- Negative sampling: there are far more negatives (skips) than positives (shares). Down-sampling negatives speeds up training but shifts predicted probabilities upwards. The Monolith paper applies log-odds correction at serving time so predictions stay calibrated. Calibration matters because the value formula adds probabilities from different towers: if P(like) is inflated by 3 times, likes dominate the formula by accident.
Serving the ranker. At 100 million scorings per second at peak:
- The ranking service batches the 800 candidates of one request into one GPU inference call (and batches across requests), so the GPU runs large matrix multiplies efficiently.
- User-side computation is done once per request, not 800 times: the user and sequence part of the network is computed first, then broadcast to all candidates. This alone cuts the work several times.
- Sparse embeddings are fetched from parameter servers (or a sharded embedding cache on the inference hosts). Hot embeddings (popular videos, creators, sounds) are cached locally.
- If a model server is slow, the request uses a timeout and partial result (score what finished, use pre-ranking scores for the rest) rather than failing.
With an assumed 50 µs of GPU time per candidate (amortised by batching), 100 million candidates per second need about 5,000 GPU-seconds per second, so roughly 5,000 GPUs at full use, or 8,000–10,000 with headroom and redundancy across regions. These are rough planning numbers; real costs depend on model size and hardware.
Re-ranking. The ranker scores videos independently; a feed is a list, and users get bored by repetition. Re-ranking turns scores into a page:
- Diversity constraints: no two videos from the same creator, or with the same sound, in a window of, say, 5; limits on the share of one topic per page; spread of video lengths.
- Diversity-aware selection: greedy selection with a penalty for similarity to already-chosen items (Maximal Marginal Relevance), or determinantal point processes, which pick sets that are both high-scoring and dissimilar.
- Exploration slots: reserve, for example, 1 of every 8–10 positions for exploration candidates (new videos or new topics).
- Policy rules: reduce distribution of borderline content, apply well-being features (for example, interrupt very long sessions with reminders, which TikTok has offered as screen-time tools), and apply regional rules.
- Ads and other insertions are placed in fixed slots by a separate system and are out of scope here.
6. Real-time training: learning from every swipe within minutes#
Why freshness matters so much here. Two things change quickly. Users' interests shift within minutes (a new trend, a mood). Videos' quality is unknown at upload and becomes clear only from the first few thousand views. A model retrained once a day cannot learn about a video uploaded this morning that is going viral this afternoon, except through real-time statistics features.
The Monolith paper quantifies this. On the public Criteo ads dataset with a DeepFM model, online training with parameter sync intervals of 5 hours, 1 hour and 30 minutes gave steadily higher average AUC (79.66, 79.78 and 79.80) than batch training (about 79.43), and a live A/B test on a production ads model showed a large improvement from online training. In production, ByteDance syncs sparse parameters every minute or so and dense parameters about daily.
The pipeline.
- Serving logs features. When the ranker scores a candidate, the features used are logged with the request key (the
rec_token). Logging served features, instead of recomputing them later, avoids training–serving skew: the model trains on exactly what it saw at serving time. - Client logs actions. Watch outcomes, likes and shares arrive later, with the same key.
- The online joiner (a Flink job in Monolith's design, reading feature and action topics from Kafka) matches features with actions by request key. Actions arrive out of order and with variable delay, so the joiner keeps features in an in-memory cache with a spill-over to an on-disk key-value store for late actions. After a label window (for example, 30–60 seconds after the video ended, long enough for a like or share), it emits a training example with its labels.
- Negative sampling reduces the volume of negatives, and the sampling rate is recorded for log-odds correction.
- Training workers consume examples from Kafka and update the model on training parameter servers. A parallel job dumps the same examples to HDFS or object storage for batch training (needed when the model architecture changes and history must be replayed).
- Parameter sync. Every minute or so, the training PS sends only the embeddings touched since the last sync to the serving PS. Most IDs are untouched in a minute, so the update is small. Monolith's paper argues that dense parameters move slowly because they average over huge amounts of data, so syncing them daily is acceptable.
Fault tolerance trade-off. Snapshotting a multi-terabyte model is expensive. Monolith snapshots the training PS daily and accepts losing up to a day of updates on a failed shard. The paper's reasoning: with about 1,000 parameter server shards and a 0.01% daily failure rate per machine, one shard fails about every 10 days, and losing one day of updates on 0.1% of parameters has almost no measurable effect on quality. This is a good example of trading reliability for cost when the data itself is constantly refreshed.
Guarding online training. Continuous updates can also break the model quickly:
- Data quality checks on the example stream (label rates, feature null rates, volume) stop training when a client bug corrupts events.
- Shadow evaluation: the newly synced model is evaluated on the most recent minutes of data before it takes traffic, and a sharp drop in online AUC or calibration triggers rollback to the previous snapshot.
- Feedback loops: the model influences what it later learns from. Exploration traffic and diversity rules keep the data from collapsing onto a few topics.
- Adversarial behaviour: coordinated bot engagement can push a video quickly. Engagement from accounts with low trust scores is down-weighted or excluded from training and from real-time stats (deep dive 12).
See ML System Design and Feature Stores for the general training and serving architecture.
7. The engagement signals pipeline#
Every recommendation decision depends on signals, so the signal pipeline is as important as the models. It must handle about 5 million events per second at peak, keep latency to features under a few seconds, and keep data trustworthy.
What the client logs. For each video shown:
impressionwhen the video becomes the visible item (withrec_token, position, network type).play_startwith startup time and rendition (also a playback quality signal).progressat checkpoints (for example, 25%, 50%, 75%) or a heartbeat every few seconds for longer videos.finishandloopevents, with total watch milliseconds.swipe(orexit) with the position in the video when the user left.- Explicit actions (
like,comment_open,share,follow,profile_open,not_interested) also go through their own services, but the client logs a copy so the training joiner has everything on one stream.
Batching on the client. Sending one HTTP request per event would cost battery and radio time. The client batches events (every 5–10 seconds, or 50 events, or when the app goes to background), compresses the batch (gzip or zstd) and sends it to the event collector. Events are stored on disk until acknowledged, so a crash or a lost connection does not lose them. Each event carries a client-generated event ID and client timestamp. On a flaky network, a batch may be sent twice; the event ID makes the duplicate harmless.
Collectors. The collector tier is stateless: it authenticates the request, validates the schema, attaches server receive time, the user's region and a trust score from the anti-abuse system, and appends to Kafka. It acknowledges only after Kafka acknowledges, so an acknowledged event is durable. Topics are partitioned by user ID, which keeps a user's events in order within a partition and lets stateful consumers keep per-user state locally.
Kafka sizing. 5 million events per second at peak at about 200 bytes is 1 GB/s compressed in, replicated 3 times, with several consumer groups reading it. A cluster of a few hundred brokers per major region is plausible. Retention is short (24–72 hours) because the data lake is the long-term copy. See Apache Kafka in Practice.
Stream processing jobs. Separate Flink jobs consume the same topic:
- Session features (per user): keyed by user ID, keep the last 50–200 watch outcomes and running aggregates over short windows (topics and creators finished or skipped in the last 10 minutes). Write to the online feature store within 1–2 seconds.
- Item statistics (per video): keyed by video ID, maintain impressions, plays, completion counts, average watch fraction, like, share and skip counts in sliding windows (10 minutes, 1 hour, 1 day). These are the features that tell the ranker that a fresh video is doing well, long before any model update. Hot videos produce millions of events per minute, so this job does local pre-aggregation before the keyed shuffle: each task sums its share for a few seconds and then emits one partial count per video.
- Creator, sound and hashtag statistics: the same windows, keyed by creator, sound and hashtag, feeding trend detection.
- Training example joiner (deep dive 6).
- Counters for display: view counts shown on videos, which can be approximate.
- Quality monitoring: startup time, stall rate and error rate by region, CDN, device and app version, for operations dashboards and CDN steering.
Exactly-once where it matters. Session features and item statistics can tolerate occasional duplicates or losses: one extra impression on a video with 10,000 impressions barely moves a rate. Creator payouts and advertiser billing cannot. The design uses at-least-once delivery with ID-based deduplication for the real-time path, and exact batch recomputation from the data lake for money-related counts. Flink's checkpointing with transactional sinks gives exactly-once state updates when it is needed. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
What counts as a view? Product decisions shape the pipeline. A "view" might be counted when playback starts, or after a minimum time (say, 1–3 seconds) to discard accidental impressions. A loop of a 10-second video might or might not count as another view. Whatever the rule, it must be implemented identically in the real-time counter and in the batch recomputation, or creators will see their numbers jump when one replaces the other.
Late and out-of-order events. Phones go offline and send events hours later. Windowed statistics use event time with a watermark that allows, for example, 2 minutes of lateness for real-time features; events later than that are dropped from real-time windows but still land in the lake and in batch features. Training examples whose labels arrive after the label window are emitted as corrections or simply missed by the online path and included in the next batch training run.
Feature store consistency. The online feature store holds the latest values; the offline store (in the lake) holds the history of values with timestamps so that batch training can reconstruct what a feature's value was at the time of each impression ("point-in-time correct" joins). Without this, training would use future information and the model would look better offline than it performs online. Logging served features (deep dive 6) avoids the problem entirely for online training.
Privacy controls. Signals are personal data. Raw events are kept for a limited time, aggregated or anonymised beyond it, deleted when users delete their accounts, and kept in-region where residency rules require. Access to raw event tables is audited. See Security Fundamentals for System Design.
8. Cold start: new videos and new users#
New videos
Every new video starts with no engagement, and most of the platform's appeal (anyone can go viral) depends on new videos getting a fair chance. The approach is staged exploration, often described as "traffic pools" in discussions of short-video platforms:
- Content-based first estimate. When a video is published, the item tower computes an embedding from content features only: visual and audio embeddings, speech-to-text, caption, hashtags, sound, creator history (if any) and quality scores (sharpness, lighting, duration). This lets retrieval place the video near similar videos and near users who like that kind of content, before anyone has watched it.
- Small test audience. The exploration source shows the video to a small number of users (for example, 200–1,000) who are likely to be interested, based on that content embedding, and who are spread across a few interest clusters.
- Measure. Real-time statistics (completion rate, average watch fraction, like rate, share rate, skip rate, compared with the creator's and the category's baselines) accumulate in minutes.
- Promote or stop. If the video performs well relative to similar new videos, it moves to a larger pool (10,000 impressions, then 100,000, then unrestricted). If not, its exploration stops and it is shown only to followers and through search.
This is a multi-armed bandit problem. Each new video is an arm with an unknown reward rate. Thompson sampling is a natural fit: keep a Beta distribution over each video's completion or engagement rate, sample from it, and show the videos with the highest samples. New videos have wide distributions, so they sometimes sample high and get exposure; as data accumulates, the distribution narrows around the true rate. Upper confidence bound (UCB) methods give a similar effect with a deterministic bonus for uncertainty. Contextual bandits such as LinUCB (Li et al., "A Contextual-Bandit Approach to Personalized News Article Recommendation", WWW 2010) add user features, so the uncertainty bonus is specific to the kind of user.
A worked example. Suppose new videos in a category have a mean completion rate of 30%. Video A gets 300 impressions and 120 completions (40%); video B gets 300 impressions and 75 completions (25%). With a Beta(1 + successes, 1 + failures) posterior, A's posterior mean is about 0.40 with a standard deviation of about 0.028, so it is very likely above the category mean; B's mean is 0.25 with a similar spread, likely below. A is promoted to the next pool; B's exploration ends. A third video C with only 30 impressions and 12 completions (also 40%) has a standard deviation of about 0.09, so it gets more exploration before a decision. Comparing against category baselines matters because completion rates differ widely between, say, 8-second jokes and 3-minute tutorials.
Keeping exploration fair and cheap.
- A fixed exploration budget (for example, 5–10% of impressions) caps the cost to user experience.
- Exploration impressions are given to users whose recent behaviour suggests openness (they finish many videos and are early in a session), not to users who are skipping everything.
- New creators get a minimum guaranteed test audience; established creators' new videos start in a larger pool because their prior is better.
- Exploration traffic is logged with its propensity, which provides less biased training data for the main models.
Fresh videos and the main model. The ranking model has a video ID embedding that is untrained for a new video. Two common fixes: initialise new ID embeddings from the content embedding (or a creator average), and rely on real-time statistics features (the 10-minute completion rate) that do not need any training. Monolith's collisionless table admits new IDs only after a minimum number of occurrences, so a brand-new video is represented by its content features until then.
New users
A new user has no watch history. The first session decides whether they come back, so it must be good from the first video.
- Context at sign-up: country, language, device type, time of day, app install source (an ad for a cooking channel suggests interest in cooking), and, if the user agrees, an interest picker ("pick topics you like") during onboarding.
- A strong default: the first few videos come from a regional popular and broadly appealing set, diversified across 8–12 topics, each a "probe" of a different interest. Quality matters more than personalisation here: the videos with the highest completion rates for new users in that region.
- Fast learning in session: with each swipe, session features update, and the user tower (which takes the recent sequence as input) moves the user vector quickly. After 10–20 videos, the feed is noticeably personalised. This is why session-level freshness (Flow 3) is so important for cold start.
- Explore broadly early, narrow later. The re-ranker keeps topic diversity high in the first sessions and gradually allows more concentration as confidence grows. Narrowing too early gives the user a feed dominated by whatever they happened to watch first.
- Similar-user priors: the system can find look-alike users (same region, language, device, early responses) and borrow their interests as a starting point.
Logged-out users (web visitors, users who skip sign-up) get a device-scoped profile stored by a device ID or cookie, with the same session learning. If they later sign up, the device profile can merge into the account, with user consent where required.
Cold start for creators and sounds follows the same idea: a new sound starts with content features (audio embedding, genre) and an exploration budget; a new creator's first videos get a guaranteed small test audience.
9. Prefetching and preloading: making every swipe instant#
Where the startup time goes without prefetching. When a user swipes to a video that has not been fetched:
| Step | Typical time on 4G |
|---|---|
| DNS lookup for the CDN host (if not cached) | 20–100 ms |
| TCP and TLS handshake (or QUIC 1-RTT) | 50–150 ms |
| Fetch manifest | 50–100 ms |
| Fetch first segment (300–500 KB) | 100–400 ms |
| Decoder setup and first frame render | 30–100 ms |
| Total | 250–850 ms |
That is a visible spinner on every swipe. Prefetching removes almost all of it.
What the client does.
- Keep connections warm. Use HTTP/2 or HTTP/3 (QUIC) to a small set of CDN hostnames, with connections opened at app start and kept alive. This removes DNS and handshakes from each swipe. QUIC also handles network switches (Wi-Fi to mobile) better through connection migration. See HTTP, HTTP/2, HTTP/3 and HTTPS.
- Avoid a manifest round trip. The feed response includes the rendition list and the URL of the first segment (or the byte range of the first part of a fragmented MP4) for each video, so the client can request video bytes immediately. Some short-video apps skip HLS manifests entirely for short clips and use progressive MP4 with byte-range requests, picking one rendition per video at start, because the video is short enough that mid-video switching is rarely needed.
- Prefetch the head of the next videos. While video N plays, download the first 1–2 seconds (for example, 300–600 KB) of videos N+1 and N+2, and sometimes N+3. When the user swipes, playback starts from local memory or disk, in tens of milliseconds.
- Preload the decoder. Keep a pool of 2–3 player instances: the next video's player is created, its first frame is decoded and ready (sometimes already rendered off-screen), so the swipe animation reveals a video that is already playing. This is "preloading" as opposed to "prefetching": prefetching gets bytes, preloading prepares playback.
- Prefetch the cover image for videos further ahead (N+3 to N+8), which is cheap and gives a good visual if the user swipes faster than video bytes arrive.
- Prioritise. The currently playing video's buffer always has priority over prefetches. Prefetch requests use lower HTTP/2 or HTTP/3 priority, and the client pauses prefetching if the current buffer drops below a threshold.
How much to prefetch: the trade-off. Prefetching costs bytes, and bytes cost money (CDN egress) and the user's data plan. If users swipe away from most videos within 3 seconds, prefetching 10 seconds of each next video wastes most of what is downloaded.
A simple model: let p be the probability the user reaches video N+1 (very high, about 0.95, because they keep swiping), and q the probability they reach N+3 before leaving the session (lower, say 0.8). Expected waste from prefetching b bytes of video N+k is (1 − P(reach N+k)) × b, plus the bytes beyond what they watch if they swipe away early. With a head prefetch of 500 KB for two videos ahead, expected waste is small (tens of KB per view). With 2 MB prefetched for four videos ahead, waste can reach 20–30% of bytes. So the default is small heads for 2–3 videos, and the rest of each video is fetched only when it starts playing.
The server helps with a prefetch hint in the feed response (how many videos and how many bytes), tuned per region and network: on Wi-Fi in a region with cheap bandwidth, prefetch more; on metered mobile data or with "data saver" on, prefetch less and choose lower renditions.
Adaptive bitrate for short videos.
- Startup rendition: choose from the last measured throughput (kept across videos, because the network is the same), but bias towards a lower rung for the first segment, so startup is fast. A 360p or 540p first second on a fast network switches up within 1–2 seconds.
- Throughput and buffer-based logic: classic ABR algorithms use measured throughput (rate-based), the buffer level (buffer-based, as in BBA from Huang et al., SIGCOMM 2014), or both (for example, model-predictive control). For short videos, the buffer is shallow by design (only a few seconds), so throughput estimates from recent downloads, including prefetches, matter more.
- Per-video vs per-segment switching: for 15-second videos, switching mid-video is rare; the main decision is which rendition to start with. For longer videos (1–10 minutes), normal segment-level ABR applies.
- Codec choice by device: the client tells the server which codecs it decodes in hardware (H.264, HEVC, AV1). Software decoding of HEVC or AV1 on a cheap phone drains the battery and drops frames, so the server only offers those codecs to capable devices.
Measuring it. The client reports, for every video, time to first frame, whether the first frame came from prefetched bytes, stall count and duration, rendition switches, and bytes downloaded versus bytes played. Dashboards split these by region, network type, CDN, app version and device class. A regression in any of them is visible within minutes of a release and can be rolled back with a feature flag.
Offline and low-connectivity modes. In very poor networks, the app can download a small batch of videos in full at a low rendition on Wi-Fi (or when signal is good) and play them later, accepting stale recommendations in exchange for smooth playback. This is a product decision, but the same prefetch machinery supports it.
10. CDN delivery at tens of terabits per second#
Why the CDN is the centre of the cost model. At about 160 PB of video egress per day, even a cheap commercial rate of $0.002–0.005 per GB (large-volume pricing varies widely and is mostly private) costs hundreds of thousands of dollars per day. Most large video platforms therefore combine commercial CDNs with their own edge capacity: caches in internet exchanges and, for the biggest ISPs, cache appliances inside the ISP's network, as Netflix does with Open Connect and Google with Google Global Cache. Embedded caches also improve quality, because bytes travel fewer hops. We do not claim specifics about TikTok's own CDN arrangements; the general approach applies.
Popularity is very skewed, and that helps. A small fraction of videos produce most views at any moment (viral and trending content), so edge caches with a few hundred TB each achieve high hit ratios for bytes even though the catalogue is exabytes. But short-video feeds have a heavier long tail than film catalogues, because personalisation spreads views across many moderately popular videos, and every new video's test audience is small. A realistic picture:
- The top tier of videos (the hottest few million) fits in every edge cache and gives perhaps 60–70% of bytes.
- The middle tier fits in regional mid-tier caches.
- The tail (videos with tens or hundreds of views) is served from regional caches or the origin shield, with higher latency, which prefetching hides.
Tiered caching. Edge caches (close to users) miss to regional mid-tier caches, which miss to an origin shield (one cache layer in front of the origin per region), which reads from object storage. The shield collapses many concurrent misses for the same object into one origin read (request coalescing), which protects object storage from bursts when a video suddenly goes viral. See Content Delivery Networks (CDN).
Pre-positioning hot content. The recommender knows what it will show before users ask. When a video is promoted to a large pool or detected as trending in a region, the platform can push its first segments to the edge caches in that region (cache warming) before the wave of requests arrives. The same signals can drive which renditions to pre-position: 540p and 720p heads in the common codecs.
Choosing a CDN per request (steering). With several CDNs, the Feed Service (or a steering service it consults) chooses a CDN hostname per user or per region, based on real-time quality (time to first byte, throughput, error rate measured by clients) and cost. If one CDN degrades in a region, steering moves traffic to another within minutes. The playback URLs in the feed response embed the chosen CDN host, and the client can fail over to an alternative host on errors.
Cache keys and URL design.
- Segments are immutable: a URL like
/v/{video_id}/{rendition}/{segment}.m4s(or.mp4with byte ranges) never changes content. Caches can store them for a long time (Cache-Control: max-age=31536000, immutable). - If a video is re-encoded (for example, a new HEVC ladder), the new renditions get new paths, and the manifest (short TTL, or versioned) points to them. Old segments simply age out.
- URLs are signed with a short expiry (for example, a token valid for a few hours), so they cannot be hotlinked or scraped at scale, and the signature is checked at the edge. The token is excluded from the cache key so all users share one cached copy.
Takedowns. When a video is removed (policy violation, legal request, user deletion), the Video Service marks it removed, the feed stops serving it immediately, and a CDN purge by path prefix removes cached segments, typically within seconds to minutes. Because the feed no longer returns signed URLs for it and existing tokens expire, even caches that purge slowly serve it only to clients that already had the URL.
Origin storage layout. Renditions are stored per region where the video is popular, with cross-region replication for globally popular videos. Rarely viewed videos keep fewer renditions in a cheaper storage class; if one becomes popular again, the shield fetches it from the colder tier once and the CDN takes over. See Object Storage and Blob Storage.
Bytes per view, the main lever. Ways to reduce bytes without hurting quality:
- Better codecs for popular videos (HEVC and AV1), as in deep dive 2.
- Lower default renditions on small screens: 720p is visually enough on most phones for most content.
- Prefetch tuning (deep dive 9), which directly reduces waste.
- Content-aware encoding, which gives fewer bits to simple scenes.
- Covers in WebP or AVIF instead of JPEG.
A 20% reduction in bytes per view at 160 PB per day saves 32 PB per day of egress, which is why video teams spend years on these optimisations.
11. Feed sessions, pagination and the seen set#
Why pagination is unusual here. A For You feed has no fixed order to paginate through: each page is computed fresh from the latest signals. The cursor therefore does not point to a position in a list; it identifies a session whose state lives on the server.
Session state (per active session, kept for about 30 minutes after the last request):
- Session ID, start time, page count.
- The IDs of every video served in this session (a few hundred), so pages never repeat.
- The interest mix served so far (topics, creators, sounds), so re-ranking can keep the session diverse.
- Optionally, precomputed next-page candidates: when computing page 3, the funnel keeps the top 50 scored videos, and page 4 can be served from them (after re-scoring with fresh session features) if the recommender is overloaded.
This lives in a low-latency store (for example, Redis) keyed by session ID, with a TTL. If it is lost, the next request starts a new session; the user might see a repeat, which is a small cost.
The long-term seen set. Users should not see the same video again on later days unless it is a deliberate replay. Storing every video a heavy user has ever been shown (tens of thousands per month) per user is expensive at a billion users. A layered design:
- Recent served IDs: an exact list of the last 2,000–5,000 served videos, in the user state store (about 16–40 KB per user).
- Long-term Bloom filter: a filter over, say, the last 90 days of impressions, sized for 20,000 items at a 1% false-positive rate (about 24 KB). Older history is dropped; seeing a 4-month-old video again is acceptable.
- Filters are partitioned by time (one per month), so old months can be dropped without rebuilding.
At 1 billion users × about 50 KB = 50 TB of seen state. Only active users' data needs to be hot; the rest can live on SSD-backed stores and be loaded at session start.
Why "served" and not "watched". The seen set records what was served, not only what was watched, because a video the user swiped past in half a second was still shown and should not come back tomorrow.
Concurrency across devices. A user watching on a phone and a tablet at once gets two sessions; both update the same long-term seen set. Small races (both devices get the same video in the same minute) are acceptable.
12. Trust and safety, integrity of signals and global operation#
Moderation in the publish path. Distribution makes harm scale: a harmful video that reaches a million users in an hour cannot be taken back. Moderation is therefore staged with distribution:
- Before publishing: hash matching against databases of known illegal content (for example, PhotoDNA-style perceptual hashes for child sexual abuse material, and industry hash-sharing databases for terrorist content), plus classifiers. Clear violations are blocked and reported where the law requires it.
- Before broad distribution: videos entering larger traffic pools get more expensive checks (more classifiers, and human review for borderline scores). The gate is tied to the exploration stages in deep dive 8, so review effort concentrates on videos that are about to reach many people.
- After publishing: user reports, sudden spikes in negative signals, and re-scans with improved models can remove or restrict videos at any time; removal propagates to the feed immediately and to CDNs by purge.
Moderation decisions are recorded with the policy, model version and reviewer, so appeals can be handled and models audited.
Integrity of engagement signals. If bots can fake engagement, they can buy reach. Defences:
- Account and device trust scores from the anti-abuse system (account age, device attestation, behaviour patterns, IP reputation). Events from low-trust sources are down-weighted or excluded in real-time statistics and training.
- Rate limits on actions per account and device. See Rate Limiting and Throttling.
- Anomaly detection on videos and creators: an engagement pattern that does not match normal viewing (likes without watch time, bursts from one network) triggers review and freezes promotion.
- Robust statistics: use completion and watch-time signals, which are harder to fake at scale than likes, and cap the influence of any single cluster of accounts.
Global operation and data residency.
- Regional deployment. Each major region runs the full serving stack (feed, recommendation, feature store, CDN origins) so requests stay local and latency stays low. Candidate pools are regional by default, with global "content that travels" (music, dance, visual comedy) added through a global trending source.
- Data residency. Some jurisdictions require user data to stay in-region. TikTok has publicly described programmes for this, such as storing US user data in the United States with Oracle as a cloud provider (often called Project Texas, announced in 2022) and a European data programme. The design consequence: user state, events and models trained on that data stay in-region, while content (videos) may be global. Cross-region features (a video's global engagement) are exported as aggregates rather than raw user events.
- Failover. If a region's recommender fails, the Feed Service falls back to cached and popular lists (deep dive 3). If a region's storage fails, CDNs and shields can serve hot content from other regions' origins. See Multi-Region and Global Data.
Creator and user controls. Users can mark "not interested", filter keywords and hashtags, reset their For You feed (TikTok added a feed-refresh option in 2023), and see why a video was recommended (TikTok has published simple explanations of this kind). Each of these needs support in the pipeline: "reset" means starting a new user profile for recommendation while keeping the account, and "why this video" means logging the main reasons (retrieval source, top contributing features) with each impression.
Counts at scale. Displayed view and like counts use sharded counters (section 5 of the high-level design): a hot video's like counter is split into, say, 64 Redis keys; increments pick a random shard; reads sum the shards (cached for one second). Periodic jobs flush totals to durable storage, and nightly batch jobs recompute exact counts from the lake for creator analytics and payouts. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Ranking service slow or down | Feed latency spikes or errors; users see spinners | Strict timeouts with partial scoring; fall back to pre-ranking scores, cached personalised lists, then regional popular lists |
| ANN index stale or out of sync with user tower | Retrieval returns weak candidates; feed quality drops quietly | Version towers together, rebuild indexes every few hours, fresh index for new videos, monitor retrieval recall |
| Viral video creates hot keys | One metadata row, counter or cache key gets millions of reads or writes per minute | Replicate hot metadata in local caches, shard counters, coalesce CDN misses at the origin shield, pre-warm edges |
| Event pipeline lag | Session features stale; feed stops reacting to skips; training lags | Autoscale consumers on lag, send recent outcomes inline with feed requests, alert on lag over a few seconds |
| Online training corrupted by bad data | Model quality drops within minutes across all users | Data validation gates, shadow evaluation before sync, automatic rollback to last good snapshot |
| Transcoding backlog during upload surge | New videos take minutes or hours to publish | Queue-depth autoscaling, priority for base ladder renditions, defer expensive codecs, shed optional steps |
| CDN regional degradation | High startup times and stalls in one region | Multi-CDN steering by real-time client metrics, client-side host failover |
| Prefetch over-fetching | Egress cost rises 20–40%, users' data plans drained | Small heads for 2–3 videos, server prefetch hints per network, data-saver mode, monitor bytes downloaded versus played |
| Feedback loop narrows feeds | Users see repetitive content and churn; creators outside popular topics starve | Diversity constraints, exploration budget, topic caps, long-term retention as the tuning metric |
| Fake engagement and bots | Bought reach, polluted training data | Trust-weighted signals, anomaly detection, rate limits, completion-based signals over likes |
| Harmful video spreads before review | Large-scale harm and legal exposure | Moderation gates tied to traffic pools, fast takedown with CDN purge and short-lived signed URLs |
| Region outage | Users in a region lose the app | Regional fallbacks, read-only serving of cached feeds, cross-region origin access for hot content, tested failover |
What Interviewers Expect#
Mid-level. Define the core entities and API, including direct-to-storage upload with pre-signed URLs and multipart parts. Explain why videos are transcoded into several renditions and served from a CDN in segments, and what a manifest is. Describe the For You feed as a recommendation pipeline with candidate generation and ranking, even at a high level, and show that engagement events are collected through a queue into a store the recommender reads. Mention caching for metadata and counters for likes.
Senior. Go into the funnel with numbers: sources, candidate counts, latency budgets per stage, and why the heavy model only sees hundreds of candidates. Explain two-tower retrieval with ANN indexes and how fresh videos get into the index. Design the event pipeline (client batching, Kafka partitioned by user, Flink jobs for session and item features) and explain how a skip changes the next page within seconds. Cover prefetching in detail (heads of the next videos, warm connections, player pools, ABR at startup) and the cost trade-off of over-fetching. Explain cold start for videos (content embeddings plus staged exploration with bandits) and for users (onboarding, diverse probes, fast session learning). Discuss transcode prioritisation and popularity-based re-encoding.
Staff and above. Treat the system as a learning loop and reason about its dynamics: training–serving skew, logging served features, joining delayed labels, negative sampling and calibration, position and exposure bias, and the risk of feedback loops. Discuss online training with incremental parameter sync and the reliability trade-offs (as in Monolith). Connect cost to architecture: CDN egress as the main cost, bytes per view as the lever, multi-CDN and embedded caches, codec economics. Address integrity (fake engagement), moderation staged with distribution, data residency and regional design, and the choice of objective (short-term engagement versus long-term retention and well-being), including how the value formula and experiments implement it.
Deep Dive: Sizing every tierShow
All numbers follow from the assumptions in Capacity Estimation (300 million DAU, 36 billion views per day, 100,000 feed requests per second at peak). They are planning estimates, not published figures.
API gateway and Feed Service. 100,000 feed requests per second plus about 50,000 per second of other API calls (likes, comments, profiles) and 300,000 per second of event batches (each client sends a batch every few seconds) at peak. A gateway node handles about 20,000–40,000 lightweight requests per second, so about 20–30 gateway nodes per large region, with headroom. The Feed Service is CPU-light but holds many in-flight requests waiting on retrieval and ranking; at 150 ms each, 100,000 per second means 15,000 concurrent requests, comfortably handled by a few hundred instances with async I/O.
Feature store. Each feed request reads user features, session state, the seen list and perhaps 5,000 candidates' item features (batched by key). Item features for the hot set are cached locally on the ranking hosts, so the store mostly serves user reads: about 100,000 × 5 keys = 500,000 reads per second, plus item misses of a few million keyed reads per second. Writes from Flink are a few million per second (session updates and windowed item stats). A sharded in-memory or SSD-backed key-value cluster of 200–400 nodes per region fits this, with reads at 1–3 ms.
Retrieval. ANN: 32 shards × 30 replicas ≈ 1,000 index servers per region, each holding 10 GB of vectors plus graph, serving about 3,000 queries per second each. Item-to-item and inverted-index sources: a few hundred more servers. These numbers depend heavily on index type and vector size; IVF-PQ cuts memory several times at a small recall cost.
Pre-ranking. 100,000 × 5,000 = 500 million light scorings per second. At about 1 µs each on CPU with vectorised code, that is 500 CPU-seconds per second: a few hundred servers, or a small GPU pool.
Ranking. About 100 million heavy scorings per second; with the earlier estimate of 50 µs of GPU time per candidate, 5,000 GPUs at full use, or about 8,000–10,000 deployed across regions with headroom. Parameter servers for multi-terabyte sparse embeddings: with 4 TB of embeddings and 256 GB of RAM per server, about 16 servers hold one copy; serving reads at millions of lookups per second need 5–10 times that for throughput and replication, plus local caches of hot embeddings on GPU hosts.
Kafka. Ingest about 1 GB/s compressed at peak for client events plus feature logs from ranking (the features of every scored candidate in the top few hundred are large; logging only the final served items with their features keeps this to about 1–2 GB/s). With replication factor 3 and 4–5 consumer groups, cluster I/O is around 10–15 GB/s: 150–300 brokers per large region.
Flink. Session-feature and item-statistics jobs at 5 million events per second, with keyed state of about 1–5 KB per active user and per active video: about 1–2 TB of state per region on RocksDB with incremental checkpoints. A few thousand task slots across a few hundred machines.
Training. Online training consumes the joined example stream (after negative sampling, perhaps 500,000–1,000,000 examples per second) on a cluster of training workers with GPUs, and the training PS mirrors the serving PS layout. Batch retraining for architecture changes replays days or weeks of examples from the lake, which needs a much larger temporary allocation.
Transcoding. About 30,000 busy cores for the base ladder at average load; with peak factor 2 and spare capacity for re-encoding popular videos into HEVC and AV1, about 60,000–80,000 cores, or 600–1,000 large servers, unless hardware encoders take part of the load.
Storage. About 2 PB per day of new originals and renditions before tiering. With originals moved to an archival class after 30 days and tail videos trimmed to two renditions after 90 days, the hot tier stays in the tens of PB per region while total stored data grows by several hundred PB per year.
CDN. About 30 Tbit/s at global peak. A modern cache server with 2 × 100 Gbit/s NICs serving at about 100–150 Gbit/s needs about 200–300 servers' worth of capacity at full use; real deployments need many times that, because capacity must sit in hundreds of locations close to users, each sized for its local peak, plus headroom for failures.
Metadata databases. Video reads mostly hit caches; the database sees a few hundred thousand reads per second and a few thousand writes per second. Users and videos together are tens of TB, split across a few hundred shards.
Deep Dive: Real-world systems comparedShow
ByteDance (TikTok and Douyin). The published Monolith paper (Liu et al., 2022) describes the real-time training side: collisionless cuckoo-hash embedding tables with frequency-based admission and expiry, a Kafka and Flink online joiner, minute-level sync of touched sparse parameters, day-level sync of dense parameters and daily snapshots. ByteDance also sells the recommender as a product (BytePlus Recommend), which the paper mentions. The company's public explanation of For You (2020) names interactions, video information and device and account settings as inputs, with completion as a strong signal. Details of TikTok's ranking models, CDN contracts and infrastructure beyond what has been published should be treated as unknown.
YouTube (including Shorts). Google has published several landmark recommendation papers: the two-stage deep network design ("Deep Neural Networks for YouTube Recommendations", 2016), sampling-bias-corrected two-tower retrieval (2019), and the MMoE multi-task ranker for "watch next" with a shallow tower for position bias (2019). On video infrastructure, Google described its custom video transcoding chips in 2021, and it runs its own edge caches inside ISPs (Google Global Cache). Shorts reuses this infrastructure with a vertical, swipe-based player.
Instagram Reels and Facebook (Meta). Meta has published widely on recommendation infrastructure, including the DLRM model architecture ("Deep Learning Recommendation Model for Personalization and Recommendation Systems", Naumov et al., 2019) and work on large embedding tables, and announced its MSVP video ASIC in 2023. Reels combines a For You style ranked feed with Instagram's social graph. See the photo-sharing case study, Design a Photo Sharing App (Instagram), for the upload and feed basics shared by both.
Netflix. A long-form catalogue with far fewer, much longer titles: the opposite trade-offs. Netflix pioneered per-title encoding (2015) and VMAF (2016), and runs Open Connect appliances inside ISPs, pre-filled overnight with content predicted to be popular, which works because its catalogue is small and changes slowly. A short-video app cannot pre-fill everything, because tens of millions of new videos arrive per day; it relies more on pull-through caching and selective pre-warming. See Design a Video Streaming Platform (YouTube / Netflix).
Pinterest. Pixie (2018) showed real-time random walks over a graph of billions of pins and boards for candidate generation; later work moved to learned embeddings (for example, PinSage, a graph convolutional network from 2018). Graph-based candidate sources are a useful addition to embedding retrieval.
Kuaishou. Another major Chinese short-video platform with a similar product. It has published research on short-video recommendation, but we do not rely on specific claims here.
What the comparisons teach.
- The two-stage funnel (retrieval, then ranking) is universal at this scale; the differences are in features, objectives and freshness.
- Freshness is where short-video platforms push hardest: minute-level model updates and second-level session features.
- Video infrastructure converges on segmented, multi-codec ladders, popularity-based re-encoding and edge caches inside ISPs; the hardware (custom ASICs) is a cost play at the largest scale.
- Catalogue dynamics decide the CDN strategy: pre-fill for small, stable catalogues (Netflix), pull-through with targeted pre-warming for huge, fast-changing ones (TikTok, YouTube).
Deep Dive: A 45-minute interview planShow
| Minutes | Focus | What to say and draw |
|---|---|---|
| 0–5 | Clarify | Scope: upload, For You, playback, engagement; DAU, views per user, uploads per day; freshness and startup targets |
| 5–10 | Estimate | 36 billion views per day, 100,000 feed requests per second at peak, 5 million events per second, 30 million uploads per day, about 30 Tbit/s of egress |
| 10–15 | API and entities | Pre-signed multipart upload, feed with cursor and rec_token, batched events, idempotent actions |
| 15–25 | High-level design | Upload path, processing DAG, Feed Service with the funnel, CDN path, event pipeline to features and training |
| 25–40 | Deep dives (pick 2–3) | Funnel stages with budgets; two-tower and ANN; real-time features and online training; prefetching; cold start with staged exploration |
| 40–45 | Wrap up | Bottlenecks and fallbacks, cost levers (bytes per view), safety gates, what to measure |
Tips. Say early that the recommender is the product and that the feed is computed, not fetched from a timeline. Draw the funnel with numbers at each stage; interviewers remember a design that explains why each stage exists. When discussing playback, start from time-to-first-frame and work back to prefetching and the CDN. When discussing learning, start from a single swipe and follow it until it changes the next page.
Deep Dive: Follow-up questions and strong answersShow
"How does a video with zero followers go viral?" Content features place it in embedding space at publish time; the exploration source gives it a small test audience; real-time completion and share rates, compared with similar new videos, promote it through larger pools; once it has engagement, normal retrieval sources (item-to-item, trending) pick it up. The whole chain can take minutes to hours.
"A user complains their feed is all one topic. Why, and what do you change?" A feedback loop: they watched a few of one topic to the end, the session features and retrieval sources amplified it, and re-ranking allowed it. Fixes: stronger topic caps per page, an exploration quota that probes other interests, a decay on session features, and an objective that values long-term satisfaction (surveys, retention) over short-term completion. Also offer "not interested" and a feed reset.
"Ranking is taking 400 ms at p99. What do you do?" Find where: feature fetch, GPU queueing or embedding lookups. Options: reduce candidates sent to the heavy ranker (better pre-ranking), cache user-side computations per session, enlarge GPU batches, cache hot embeddings locally, and enforce a deadline with partial scoring. Never let the p99 of ranking define the p99 of the feed: fall back to pre-ranking scores past the deadline.
"How do you know a new model is better?" Offline metrics (AUC, calibration, recall at K of retrieval) only gate what reaches online testing. Decisions come from A/B tests on watch time, completion, explicit engagement, negative feedback, retention and session counts, run for long enough to see novelty effects fade, with long-term holdout groups for cumulative effects. See the experimentation case study, Design an A/B Testing and Experimentation Platform.
"How do you handle a viral video that suddenly gets 100 times more traffic in one region?" Trending detection promotes it; CDN pre-warming pushes its first segments to that region's edges; the origin shield coalesces misses; metadata and counters for it are served from local caches and sharded counters; popularity triggers HEVC and AV1 re-encoding to cut egress.
"How would you design the Following feed?" A hybrid fan-out: push new video IDs into followers' inboxes for normal creators, pull for creators with millions of followers, merge at read time, and lightly rank for freshness. It reuses the same playback and prefetch paths.
"What if the event pipeline is down for 10 minutes?" Clients keep events on disk and resend; the feed still works from older session features and inline recent outcomes in requests; online training pauses and resumes from Kafka offsets; real-time counts lag and catch up; nothing is lost if Kafka retention covers the gap.
"How do you stop people gaming the algorithm with bots?" Trust scores on accounts and devices, rate limits, anomaly detection on engagement patterns, reliance on watch-time signals that are expensive to fake, and excluding suspicious engagement from both real-time statistics and training.
"Why not use a graph database or a single big model for everything?" The candidate set is billions of items and the latency budget is tens of milliseconds, so the work must be split into stages with matching costs. A single model cannot score everything in time, and a graph database is useful as one retrieval source, not as the whole recommender.
"How do you make the app work well in a market with mostly 3G and cheap phones?" Low ladder rungs (240p or 360p at 200–350 kbit/s), H.264 only for weak decoders, smaller prefetch heads, data-saver defaults, lighter app builds, aggressive cover prefetching, and CDN capacity placed inside local ISPs.
Deep Dive: Evaluating and experimenting with the recommenderShow
Offline evaluation. Before a model takes traffic, it is evaluated on held-out recent data:
- Ranking metrics: AUC per task (finish, like, share), normalised cross-entropy, and calibration (predicted versus observed rates, per task and per segment). A model with better AUC but worse calibration can hurt, because the value formula adds probabilities across tasks.
- Retrieval metrics: recall at K (does the retrieval set contain the videos users actually finished, or the videos the full ranker would choose?), and coverage (how much of the eligible pool ever gets retrieved).
- Slice analysis: new users, new videos, small creators, each language and region, low-end devices. A model that wins on average can lose badly on a slice.
Offline metrics have a known weakness: they are measured on data generated by the old model's choices. A new model that would show very different videos cannot be evaluated well on data that never showed them. Counterfactual evaluation with logged propensities from exploration traffic (inverse propensity scoring) gives a less biased estimate, at the price of high variance.
Online experiments. Real decisions come from A/B tests:
- Unit of randomisation: the user (not the request), because the feed is a session-level experience.
- Metrics: primary metrics such as total watch time per user, active days per week and retention; guardrail metrics such as negative feedback rate, reports, app crashes, startup time and creator-side metrics (how many creators got at least N views).
- Duration: at least 1–2 weeks to absorb novelty effects and weekly cycles; a long-term holdout (a small share of users kept on an older system for months) measures cumulative effects that short tests miss.
- Interference: the recommender for one group changes which videos become popular, which affects the other group (for example, through trending and exploration pools). Large changes may need region-level or time-sliced experiments to measure creator-side effects.
- Interleaving: for ranking changes, interleaving results from two models in one feed and seeing which model's items get more engagement detects differences with far fewer users than A/B tests.
Choosing the value formula weights. Weights are tuned against long-term metrics. A practical approach: run a set of experiments with different weights, measure both short-term proxies and long-term outcomes, and fit which short-term mix best predicts long-term retention; then optimise the weights for that mix. Surveys ("did you enjoy this video?") shown to a sample of users add a direct satisfaction signal that is harder to game than any behavioural metric.
Why online training complicates experiments. If both arms share the same online-trained model, the treatment's choices affect the control's training data. Strong setups train separate model copies per arm for significant changes, or ensure that the arms' data are kept apart for the duration of the test.
Deep Dive: Worked example, the bytes and cost of one viewShow
Follow one 30-second video watched by one user on a mid-range Android phone over 4G.
Encoding. The base ladder is H.264; the video became popular, so it also has HEVC renditions. The phone reports hardware HEVC decode, so the server offers HEVC. The HEVC 720p rendition is encoded at about 900 kbit/s (versus 1.3 Mbit/s for H.264 at similar quality, about 30% less).
Prefetch. While the previous video played, the client fetched the first 1.5 seconds of this one at the 540p HEVC rung: about 1.5 × 600 kbit/s ≈ 110 KB. The swipe reveals a decoded first frame in about 40 ms.
Playback. The throughput estimate is 8 Mbit/s, so ABR steps up to 720p after the first segment. The user watches 22 of 30 seconds: 110 KB + 20.5 s × 900 kbit/s ≈ 110 KB + 2.3 MB ≈ 2.4 MB. Meanwhile the client prefetched heads of the next two videos (about 220 KB).
If it were H.264 without prefetch tuning. 22 s × 1.3 Mbit/s ≈ 3.6 MB, plus 4 MB of prefetching for four videos ahead, of which half is wasted: about 5.6 MB attributable to this view. The tuned path uses less than half the bytes.
At platform scale. Saving 1 MB per view on 36 billion views per day is 36 PB per day. At an assumed blended cost of $0.002 per GB, that is about $72,000 per day, or about $26 million per year, from one optimisation. The HEVC encode for this video cost about 10 times the H.264 CPU, but it was paid once and amortised over millions of views.
Encoding break-even. Suppose a full HEVC ladder costs about $0.01 of compute for a 30-second video (an assumed figure) and saves 30% of 3 MB per view, about 0.9 MB, worth about $0.0000018 at $0.002 per GB. Break-even is about 5,500 views. Videos below a few thousand expected views stay on H.264; videos crossing that threshold get HEVC; AV1, at several times the HEVC cost for another 20–30% saving, breaks even only at much higher view counts. This is the arithmetic behind popularity-triggered re-encoding.
Deep Dive: Designing the client for low-end devices and poor networksShow
A large share of short-video users are on low-cost Android phones and congested mobile networks. The client design is part of the system design here.
- App size and startup: a small install size and fast cold start (under 2 seconds to the first video) matter in markets with limited storage and slow downloads. Some apps ship "lite" versions with fewer effects.
- Decoder limits: cheap phones may decode only H.264 in hardware, and only one or two streams at once. The player pool shrinks to one warm player, and preloading falls back to prefetching bytes only.
- Memory: prefetched bytes are held in a bounded memory cache with disk overflow; on low-memory devices, the cache is smaller and older entries are evicted first.
- Battery and data: batch events, avoid waking the radio for small requests, respect data-saver settings, and prefer lower renditions on metered networks.
- Network variability: throughput estimates use a short history with fast reaction to drops; the startup rung is conservative; the client retries failed segments on an alternative CDN host.
- Upload on poor networks: chunked resumable upload, lower default upload quality, background transfer, and an optional higher-quality replacement over Wi-Fi.
- Graceful degradation: if the feed request fails, show cached videos from the last session (already on disk from prefetching) while retrying, so the user is never facing an empty screen.
Key Takeaways#
- The recommender is the product. The For You feed is computed per request from the whole catalogue, not read from a timeline, so the core of the design is the funnel: many retrieval sources, a light pre-ranker, a heavy multi-task ranker and a diversity-aware re-ranker, each sized to its input and latency budget.
- Learn from every swipe, fast. Session features update within seconds through Kafka and Flink; model parameters update within minutes through online training with incremental sync of touched embeddings, as ByteDance's Monolith describes. Log the features used at serving time and join them with delayed labels to avoid training–serving skew.
- Define the objective explicitly. Predict several outcomes (finish, watch time, likes, shares, follows, fast skips, reports) and combine them with a tunable value formula, tuned by experiments against long-term retention and satisfaction, not only watch time.
- Cold start is constant. New videos get content-based embeddings and staged exploration with bandit-style promotion through larger audiences; new users get diverse, high-quality probes and fast in-session learning.
- Upload directly to object storage with chunked, resumable, pre-signed multipart uploads; compress on the device; process in a DAG with idempotent steps; publish when the base ladder is ready.
- Encode for the views you will get. Every video gets an H.264 base ladder in segments with manifests; popular videos are re-encoded to HEVC and AV1 because codec cost is paid once and bandwidth savings are paid back on every view.
- Make swipes instant with prefetching. Warm connections, playback URLs in the feed response, small heads of the next 2–3 videos, warm decoders and a conservative startup rung. Tune prefetch size, because over-fetching directly raises the biggest bill.
- The CDN is the cost centre. Tens of terabits per second of egress need multi-CDN steering, tiered caches with request coalescing, embedded ISP caches at the largest scale, pre-warming for trending videos and constant work on bytes per view.
- Plan for failure at every stage. Fallback feeds when ranking is slow, inline recent outcomes when pipelines lag, rollback for bad online training, and moderation gates tied to distribution so harmful content cannot spread before review.