Design the database for an ephemeral messaging app like Snapchat
Snaps that expire, stories for 24 hours, chat ordered per conversation, and deletes that happen by TTL rather than by a job that scans everything.
More on Database design case studies
- Database Design Interview: A 7-Step Framework
- Design the database for a Q&A site like Quora
- Design the database for a short-video app like TikTok
- Design the database for a booking site like Airbnb
- Who gets the last phone in a flash sale
- Which database for a food delivery app
- The cache expired and the database fell over
- A live final: scale before the toss
- An app like ChatGPT: the answer is written live
- A product Q&A box on sale day
- Tatkal at 10:00: one seat, sold in stretches
- A group chat: one register, many sockets
Keep learning
Overview
Snap sends 400 M DAU × 5 sends/day Inbox rows (one per recipient) 2.0 B sends × 3 recipients Snap media, new per day Snap media, held 1.92 PB/day × 3.45 days mean lifetime (see below) 6.6 PB, about 9.3 PB raw with 1.4× erasure coding. Flat over time Story media 15% of DAU post 4 items: 240 M items × 1.5 MB Chat messages 400 M × 40 messages/day, 250 B per row on disk Chat rows, held 4.0 TB/day × 1.5 days, × 3 replicas 18 TB live, plus about 24 TB of tombstones (16 B deletes/day × 50 B × 10 days × 3) Saved chats (the part that does grow) 5% of messages kept: 0.2 TB/day × 3 replicas +219 TB per year Inbox metadata, held 6.0 B rows/day × 150 B × 3.45 days × 3 replicas 9.3 TB live, plus about 8 TB of tombstones from opens Users and friendships 50 M users online at once × 100 B about 5 GB: fits in memory on a few cache nodes Open the app: my unopened snaps, newest first Very high (every app open) One recipient, sorted by time, first page snap_inbox: partition recipient_id, clustering snap_id DESC Open one snap: fetch media, then make it disappear Point read by snap_id, then a write Open a chat: latest 50 messages, then scroll back Very high One conversation, ordered, paged by cursor messages: partition (conversation_id, bucket), clustering message_id DESC Chat list: my conversations by last activity One user, a few hundred rows at most user_conversations: partition user_id Stories from my friends in the last 24 h Friends list, then each friend’s recent stories stories: partition author_id, clustering story_id DESC Who viewed my story Medium (author only) One story, bounded by friend count story_views: partition story_id, clustering viewer_id High, small One user, or one key lookup friendships: primary key (user_id, friend_id) Is my friend online / typing? Very high, short-lived Key lookup, value valid for seconds Delivered / opened receipts Update of one recipient’s state Relational (PostgreSQL / MySQL), sharded by user_id Profile, login. Unique username needs a global lookup table or a single-region owner. Relational, sharded by user_id Wide-column (Cassandra / ScyllaDB) 31 days sender_id, media_key, media_type, recipients_left. One row per send, not per recipient. snap_id DESC (timeuuid) 30 days sender_id, media_key, status (sent/delivered/opened). TimeWindowCompactionStrategy. story_id DESC media_key, caption, privacy. Readers also check expires_at. viewed_at. Keyed by viewer so a second view overwrites instead of adding a row. members, current_bucket, retention setting. last_activity, last_read_id. Sorted by last_activity in the app (a few hundred rows). (conversation_id, bucket) message_id DESC (client ULID/timeuuid) 24 h after read, 30 days unread sender_id, body or media_key. Saved messages are copied to saved_messages without a TTL. Wide-column, written with IF NOT EXISTS (sender_id, client_msg_id) 1 day Dedupe record that guards counters and push notifications. In-memory cache (Redis-like) 60 s, refreshed by heartbeat media objects Object storage behind a CDN lifecycle rule: delete after 31 days (stories/: 2 days) An opened snap comes back after a node rejoins Inbox reads get slow, then fail Thousands of tombstones from opened snaps sit at the head of the partition and every read scans them TTL-only expiry with time-window compaction, a shorter tuned gc_grace, bucket the inbox by week Disk does not shrink after a mass expiry Expired data leaves only at compaction, and tombstones only after gc_grace Media still downloadable after the row is gone Delete job on open, lifecycle rule as a backstop, short-lived signed URLs, CDN purge The friend sees a message twice Retry after a lost reply, with an id made on the server or a key that includes server time Client-made time-ordered id as the whole clustering key Unread badge says 2 for one message Dedupe table with IF NOT EXISTS, or compute unread from a read pointer One group chat times out every evening Single partition per conversation grew past 100 MB / 100,000 rows Push notification arrives before the message Cross-region replication lag: the recipient reads its local replica first Carry the message in the push, or retry the read by id for a short window Story still visible at 25 h Lifecycle rules and compaction run on their own schedule, not at the exact second A reported snap is gone when the safety team looks Deletion ran before the hold was recorded chapters · database design case studies Design the database for an ephemeral messaging app like Snapchat Most systems are designed to keep data. This one is designed to lose it on time: a snap disappears after it is opened, a story after 24 hours, a chat message after it has been read. That single rule changes the storage estimate, the choice of store, the keys and the failure cases. We walk through the seven steps of the design framework in order. steady state, not 700 PB a year rate × size × life the sizing formula how long tombstones must live A nightly job that scans every table for expired snaps and deletes them row by row, and sizing storage as if nothing ever expires. A deleted snap came back after a node rejoined. How?
A snap from send to gone
Sender phone id made on the phone Message store partition (recipient | conv, bucket) Object storage media under a date prefix Open event mark opened, schedule delete TTL + lifecycle compaction drops whole SSTables media key Readers check expires_at, so a snap that is past its time is never shown, even before the bytes are gone.
Step 1 · Requirements: what must happen, and what must stop happening
Functional requirements, phrased so that each one turns into a query or a write: Stories: post a snap that all friends can view for 24 hours. The author sees who viewed it. Chat: one-to-one and group text messages, ordered, deleted 24 hours after every member has read them unless someone saves the message. Non-functional requirements, with numbers so they can be checked: Writes are never lost once acknowledged, and a retried send never shows up twice. Deletion is a product promise: an opened snap must not be fetchable again from any replica, cache or CDN. Expiry has to be reliable, not best effort. Exception to deletion: content under a legal hold or an abuse report must be preserved, out of the normal read path.
Step 2 · Estimation: rate × size × how long it stays
A first draft of this estimate usually multiplies users by snaps by megabytes and calls the result the storage requirement. Three things go wrong with that. It reports bytes per day as if they were kept forever, when the whole point is that they are not. It tends to count photos for every snap and then add videos on top, so the shares add up to more than 100%. And it says nothing about requests per second, which is what sizes the database cluster. Here is the estimate again with every assumption stated. Assumption and arithmetic Two practical consequences. First, the object store is sized by the unopened deadline, so a product decision (30 days versus 7) changes the bill by a factor of three. Second, the database is sized by throughput and by tombstones, not by live bytes: the inbox and chat tables hold only tens of terabytes, but they take hundreds of thousands of writes per second, and half of those writes are deletions or updates.
Step 3 · Entities, grouped by how long they live
Sorting entities by lifetime is more useful here than drawing foreign keys, because lifetime decides the store and the deletion mechanism. Permanent: users, friendships, conversations (the container, not its content), saved messages. Hours: stories and story_views (24 hours), presence (seconds to minutes). Until an event, with a deadline: snaps and snap_recipients (until opened, at most 30 days), messages (24 hours after being read, at most 30 days unread). Large binary: the media bytes behind snaps and stories, kept outside the database and referenced by an object key.
Step 4 · Access patterns: list the queries before choosing keys
Queries, how often they run, and the key that serves each one Served by
Step 5 · Store per data type
Inbox, chat, stories, views: a wide-column LSM store (Cassandra, ScyllaDB). Writes are appends to a log and an in-memory table, so 400,000 writes/s spread over a cluster is normal work. Per-row TTL is built in. Partitions keep rows sorted by the clustering key. The price is that a delete is another write, which is the subject of the next section. Background: LSM compaction and durable logs. Presence and typing: an in-memory cache with a 60-second TTL refreshed by heartbeats. Losing it on failover costs one heartbeat, so it needs no replication guarantees.
Step 5, continued · Making data disappear: TTL, tombstones and media
An LSM store never edits a file in place. Deleting a row writes a tombstone, a marker newer than the data that hides it. Expired TTL cells behave the same way. The data and the marker are both removed only when compaction rewrites the files, and the marker itself must survive gc_grace_seconds (10 days by default). The reason is replication: if one replica was down when the delete happened and the tombstone were already purged when it returns, its stale copy would look like the only version and come back. For an ephemeral app that bug is a privacy breach, not a glitch. Try the inbox below: send, open, move the clock, read, compact. What to take from the lab, scaled up to 5 billion opens a day: Reads pay for tombstones. Users open their newest snaps first, so tombstones collect at the head of a newest-first partition and every inbox read walks over them. Cassandra warns at 1,000 tombstones in one read and fails the query at 100,000. Prefer TTL to explicit deletes for metadata. If every row in a table carries the same kind of TTL, time-window compaction (TWCS) groups rows by write time and drops a whole file once everything in it has expired, with no row-by-row work. Explicit deletes scatter tombstones across windows and defeat that. What must vanish on open is the content. On open, delete the media object (or the per-recipient decryption key) right away, and mark the inbox row as opened. The small metadata row can then expire by TTL. That keeps the promise without filling the hottest partition with tombstones. Tune gc_grace only with repair. Lowering it to a day or two shrinks tombstone space, but only if anti-entropy repair completes more often than that. Otherwise you trade disk for resurrected snaps. Deleting media is a separate job. The database row and the object are two systems. A queue consumer deletes the object when recipients_left reaches zero, and must be idempotent because the queue redelivers (the same job runs twice). A lifecycle rule on the date prefix catches anything the job missed. CDN copies need a purge or short-lived signed URLs. Expiry is not the gatekeeper. Lifecycle rules run about once a day and compaction runs when it runs, so readers filter on expires_at themselves. Legal and abuse holds. A reported snap or a law-enforcement preservation request must stop deletion. The delete job checks a hold table first and copies held items into a restricted store with its own access log. Backups age out on their own schedule, which the privacy policy must state plainly. The relational side of deletion is covered in what DELETE does.
Step 6 · Partition keys: bounded partitions, one read per screen
The other tables follow the same rule: snap_inbox: partition recipient_id. Bounded because only friends can send, and a 30-day TTL caps the history. If tombstones still pile up, add a week bucket. stories: partition author_id. A friend's story tray is fan-out on read: get the friends list (hundreds), keep a cached last_story_at per author, and read only the authors who posted in the last 24 hours. Friend lists are capped, unlike follower counts, so this stays cheap. story_views: partition story_id, clustering viewer_id. A repeat view overwrites one row, and the viewer count is the row count, bounded by the friend count. No counter column to drift. user_conversations: partition user_id, clustering conversation_id, with last_activity as a plain column. Making last_activity the clustering key would turn every new message into a delete plus an insert, which means a tombstone per message.
Step 7 · Consistency: delivery, ordering and regions
Ids are born on the phone. A time-ordered id (ULID or a version-1/7 style UUID) created once, stored with the outgoing message and reused by every retry, makes the row write an upsert. Side effects (badge counter, push) need their own guard: a conditional insert into a small sent_ids table with a one-day TTL, or an unread count derived from the member's last_read_id instead of a counter. Ordering is per conversation, not global. The clustering key orders a chat by the id. A sender's clock that runs ahead could place a message out of order, so the server rejects or rewrites ids more than a few seconds from its own clock and keeps the client id for dedupe. Nobody needs a global order across conversations. Receipts are state, not events. Store status on the recipient's inbox row and a last_read_id per chat member. Each is one overwritten cell, not a new row per message per reader. Friend graph and blocks live in the relational store with a single owner per user, so a block is visible on the next read in every region that asks the owner. Send checks the friendship there (or in a short-lived cache invalidated on change).
Schema reference
Tables, stores, keys and expiry Partition key Clustering key
What can go wrong
Symptoms, causes and fixes Size the databases by writes, and count deletes and opens as writes too. Media: delete on open, a lifecycle rule as the backstop, readers check expires_at.
Recap
Hot queries name an owner and want recent items: partition by recipient or by (conversation, bucket), cluster by a time-ordered id. Media lives in object storage under a date prefix: delete job on open, lifecycle rule as backstop, readers check expires_at. Tombstones must outlive gc_grace, and repair must run within it, or deleted snaps come back. Prefer TTL with time-window compaction over row deletes. Retries are certain: make ids on the phone, make the row write an upsert, and guard side effects separately.
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.