Design the database for a short-video app like TikTok

Video metadata in a database, video bytes in object storage behind a CDN, a write-heavy like and view stream, and a recommendation feed built offline.

More on Database design case studies

Keep learning

Overview

Every daily user uploads 2 videos That is 2 billion uploads a day, or 5 views per video if there are 10 billion views. Uploaders are a small minority. Assume 1 to 3% of daily users post one video. 1 billion x 2 x 50 MB is 100,000 TB, which is 100 PB. Adding 6 TB to it gives about 100 PB, not 106 TB: the units were dropped, an error of roughly 1,000 times. 100 likes per video on 2 billion videos That is 200 billion likes against 10 billion views: more likes than views. Derive likes from views (a few percent of views), never from a per-video average. View events are negligible 10 billion views at about 100 bytes each is 1 TB a day and 116,000 writes per second on average. Views are the largest write stream in the system, not a rounding error. Only the uploaded file is stored Every video is kept in several renditions, and the bytes sent to viewers (CDN egress) are about 100 times the bytes stored each day. Egress drives the cost. Counters as columns of the videos row, interactions keyed by a random interaction_id Every like then rewrites the hottest row, and "comments of this video" needs a secondary index across all nodes. Key comments by video and keep counters apart from metadata. Next batch of the For You feed Every swipe batch, the hottest read < 50 ms for the ids and metadata Video by id (player screen) Once per view Point lookup on video_id, almost always from cache < 10 ms from cache Playback bytes Once per view, megabytes each CDN URL built from video_id and rendition First frame < 300 ms (CDN) Record a view Once per view, about 580,000 a second Append event to a log, never an UPDATE Fire and forget Like / unlike, and "did I like this?" About 23,000 likes a second Liker sees it at once Comments of a video, newest or top first Each time comments open Range scan by video, cursor paging, 20 per page < 50 ms per page Videos on a profile, newest first Each profile visit Range scan by user_id, ordered by video_id descending Follow / unfollow, follower counts Rare per user, huge fan-in for stars Edge rows in two directions Seconds of lag are fine Upload a video About 230 a second Insert metadata row, then bytes to object storage Playable within about a minute users, videos, video_renditions, hashtags Relational (sharded) or a document store Small rows, point lookups by id, a state machine that needs conditional updates, unique usernames. Original and rendition files Object storage behind a CDN Megabytes per object, written once, read millions of times. A database is the wrong place for blobs. likes, comments, follows Wide-column / LSM store Billions of small rows a day, written append-style, read as ranges by one key. LSM writes are sequential, see LSM compaction. view_events and other events Streaming log, then a column store The log absorbs the write rate and feeds counters, the recommender and analytics. The column store answers "views per country per day". Counters (views, likes, comments) Counter rows updated in batches from the log Hot metadata, feed lists, counts In-memory cache The For You feed reads the same few thousand viral videos millions of times. user_id (hash) username UNIQUE, display_name, bio, avatar_url, created_at, status video_id (hash) video_id (same shard as the video) codec, height, bitrate_kbps, object_key, bytes Relational or wide-column video_id DESC state (only PUBLISHED shown to others) hashtags / video_hashtags tag / (tag, bucket) (video_id, bucket) liked_at DESC, user_id comment_id DESC author_id, text, parent_id, like_count, state following / followers user_id / (user_id, bucket) Wide-column or relational Log, then column store user_id, video_id, watch_ms, completed, device, country Cache / key-value list of about 200 video ids written by the recommender, TTL in hours A creator with 50M followers posts Pre-warm the CDN, request coalescing at the origin shield, replicate the hot metadata in cache, batch counters from the log. Partition by time-ordered video_id ranges All new videos, and so all new writes, land in the last range. Comments partition of a viral video grows to gigabytes Partition by (video_id, time bucket), hourly for hot videos, and read buckets newest first. Feed list holds a video that was just deleted A removed video still appears in someone's For You batch. Takedown, but the CDN still has the file Deleted content keeps playing for the edge TTL. Short-lived signed URLs, explicit CDN purge, and a state check before issuing any URL. Replica lag on the liker's own like The user likes, refreshes, and the heart is empty again. Counter double counting after a consumer restart Events replayed from the last committed offset are added twice. Commit offsets and counter deltas together, or dedupe by (consumer, offset). Upload stuck in PROCESSING Sweepers with deadlines per state, FAILED and ABANDONED states, lifecycle rules on object storage. chapters · database design case studies Design the database for a short-video app like TikTok People record short clips on their phones, everybody else swipes through an endless personalised feed, and every swipe is a view that has to be counted. This chapter walks the seven steps from the design framework: requirements, numbers, entities, access patterns, a store for each kind of data, partition keys and consistency. Three kinds of data, three stores. Video bytes go to object storage and a CDN, metadata to a sharded relational or document store, and the event firehose (views, likes) to a log that feeds batched counters and analytics. The For You feed is a precomputed list of ids in a cache, then a multi-get of metadata. PB / day of video bytes written egress vs bytes stored each day event writes acceptable lag on view counts Video files in the database, and a view_count column incremented on every view of a viral video. A video goes viral: millions of views a minute on one row. What do you change?

Three paths through the system

upload, scroll, like Object storage + CDN originals and renditions Metadata store videos, users, state machine Event log views, likes, watch time Counters + column store batched counts, analytics Likes, comments and follows sit in a wide-column store keyed by user or by (video, time bucket).

1. Requirements: what we build, what we leave out

Functional, in the order users meet them: Like, comment, follow, and see your own action at once. Counts: views, likes and comments on each video, followers on each profile. Profile: a creator's videos, newest first. Delete and takedown: a removed video stops playing everywhere within minutes.

2. Estimation: three kinds of data, three orders of magnitude

Errors in the usual version of this estimate, and the correction What is wrong and what to use instead

3. Entities

Eight entities, grouped by how they change: users: about a billion rows, updated rarely (bio, avatar). Username must be unique. videos: 20 million new rows a day, each with a state that moves through the upload pipeline, then almost never changes. video_renditions: 3 to 8 rows per video, one per encoding, written by the transcoder. likes: a pair (user, video). Billions a day, can be removed (unlike), must be unique per pair. comments: text that belongs to one video, optionally a reply to another comment. Append-mostly. follows: a directed edge between two users. Some users have 100 million incoming edges. view_events: immutable facts, the largest stream. Never updated, only aggregated. Counts (views, likes, comments, followers) are not entities. They are derived from likes, comments, follows and view_events, and stored separately so the derived number can lag without the facts being wrong.

4. Access patterns

List the queries before choosing any store. The table follows the order of a session: open the app, get a feed batch, watch, react. Access patterns, rate and shape How often The For You feed is not a query over videos. A recommender, offline and near-real-time, picks a few hundred candidates per user and writes the ids to a list in a key-value cache. The app pulls 10 ids at a time, then fetches their metadata with one multi-get. The database never sorts the world's videos for one user. This is a read model, the idea behind read models: precompute in the shape the screen reads.

5. A store for each kind of data

Data, store and reason The wide-column choice for likes and comments follows from the write pattern: billions of small appends a day, each read later as a range under one key. An LSM engine turns them into sequential writes and pays later in compaction (see LSM compaction). The analytics side reads a few columns of billions of view rows, the case a column store is built for. Two stores now hold one video: the bytes in object storage, the row in the metadata database. They cannot be updated in one transaction, so the row's state is the source of truth and every step is safe to retry. Walk through the pipeline and make steps fail.

6. Keys, partitioning and the hot video

Ids. Use 64-bit time-ordered ids for videos and comments: about 41 bits of milliseconds, 10 bits of generator id and 12 bits of sequence. Sorting by id is then sorting by creation time, so the profile page and the comment list need no separate timestamp index, and inserts land at the end of each partition's B-tree or memtable (see primary key order). Placement. Partition by a hash of the key, not by id ranges. Time-ordered ids in range partitions send every new video to the last range, the hotspot described in hotspot updates. Inside a partition the time order is exactly what we want. The choices: videos and video_renditions: hash of video_id, renditions on the same shard so one lookup gets both. user_videos: partition owner_id, clustering video_id DESC. A profile page is one range read. comments: partition (video_id, bucket), where the bucket is a time slice taken from comment_id. Five million comments at about 300 bytes is 1.5 GB, far beyond the tens of megabytes a wide-column partition handles comfortably. A month bucket does not help, because a viral video gets most of its comments in its first two days. Use one bucket per day by default and one per hour for videos flagged hot: 5 million comments in a day is about 210,000 an hour, or about 63 MB per bucket. The reader walks buckets newest first, and the cursor carries the bucket along with the last comment_id. followers: partition (user_id, bucket) for accounts above a threshold, so a star's 100 million followers are not one partition. See partition skew and shard splits. The hot video. Hashing spreads videos, but one viral video is still one key. Its metadata read is solved by caching: the row hardly changes, so many cache replicas can hold it. Its counters are the hard part, because every like wants to change the same number. Compare three designs.

7. Consistency, data by data

Upload states: one row per video, moved forward by conditional updates, as in the pipeline lab. Only PUBLISHED is visible to others. Delete and takedown must reach copies the database does not control. The order matters: Invalidate the metadata cache entry and publish a video_removed event. Purge the CDN paths of every rendition. Playback URLs are signed with a short expiry (minutes), so even a missed purge ends soon. Delete the objects after a retention period (legal hold, appeals), with an audit record of the deletion. Doing step 3 before step 1 is the classic mistake: the purge succeeds, the next request refills the edge from the origin, and the video keeps playing.

Schema reference

Tables, stores and keys Partition key Sort / clustering Main columns

What can go wrong

Failure, symptom and fix What happens Split the estimate by kind of data: bytes (PB/day), metadata (TB/year), events (hundreds of thousands of writes per second). Egress is the biggest number: the CDN, not the database, serves video. The feed is a cached list of ids plus a metadata multi-get. Hot counters are never one row: batch from the stream or shard the counter, and accept seconds of staleness. The metadata row’s state drives upload and takedown: remove access first, then purge copies.

Recap

Split the estimate: video bytes (petabytes a day, object storage plus CDN), metadata (tens of terabytes a year), events (half a million writes a second). Egress, not storage, is the biggest byte number: about 100 times the bytes stored each day. The For You feed is a precomputed list of ids in a cache, followed by a multi-get of metadata. Likes keyed by user, comments by (video, time bucket) and paged with a cursor, events appended to a log. A hot video's counter cannot be one row: batch from the stream, or shard it, and accept seconds of staleness.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.