The Problem#
Instagram lets people share photos and videos with their followers. You take a picture, maybe crop it and add a filter, write a caption, and post. Your followers see it in their feed within seconds, scroll past dozens of other posts, tap a heart to like it, and leave comments. The app feels instant: images appear the moment you scroll to them, videos start playing without a spinner, and the feed loads before you notice you are waiting.
Behind that simple experience sit four hard problems:
- Moving and storing huge amounts of media. Hundreds of millions of people upload photos and videos every day. A single photo from a phone is a few megabytes; a video can be gigabytes. The bytes must get from flaky mobile networks into durable storage reliably, without passing through (and overloading) the application servers.
- Processing media into many shapes. One uploaded photo becomes many files: several sizes for different screens, modern formats such as WebP or AVIF, a tiny thumbnail and a blurred placeholder. Videos are transcoded into several bitrates and cut into segments for streaming.
- Serving media instantly worldwide. Reads massively outnumber writes. Every feed scroll requests many images. Those must come from caches close to the user (CDNs), or the app would feel slow and the origin storage would melt.
- Building feeds and counting reactions at scale. A feed is "recent posts from everyone I follow", and some accounts have hundreds of millions of followers. Likes arrive at hundreds of thousands per second, and a celebrity post can collect millions within an hour.
A real-world analogy. Think of a photo lab combined with a newspaper. You drop off your film at a loading dock (direct upload to storage) rather than walking it through the editor's office (the application servers). The lab develops the film into prints of several sizes (image processing and variants). Copies are sent to newsstands in every neighbourhood (CDN edge caches), so readers pick them up nearby instead of travelling to the lab. The newspaper's editor decides which photos go into each subscriber's personal edition (feed generation), based on whom they subscribe to (the follow graph). And a tally clerk counts the applause for each photo (like counters), without letting a queue of a million clapping fans block the door.
This case study designs a photo- and video-sharing app at Instagram scale. It focuses on the parts that are specific to media: the upload pipeline with presigned URLs, processing into variants, CDN delivery, and storage. It also covers the follow graph, feed generation (in less depth than the news feed case study, which this page builds on) and like and comment counters. It builds on Pattern: Handling Large Files and Blobs and Object Storage and Blob Storage.
Clarifying Questions#
| Question | Typical answer | Why it matters |
|---|---|---|
| What content types? Photos, videos, captions? | Photos and videos with a short caption. One post may contain several items (a carousel). | Media pipeline must handle both images and video. |
| How big can media be? | Photos up to about 8 MB; videos up to about 4 GB. | 4 GB rules out single-request uploads; we need multipart or resumable upload. |
| How many users and posts? | 500 million daily active users, 100 million posts per day. | Sets storage growth, CDN egress and feed read rates. |
| Is the feed chronological or ranked? | Start with chronological from followed accounts; ranking is an extension. | Chronological keeps feed generation a data problem rather than an ML one. |
| Follow model: symmetric or asymmetric? Private accounts? | Asymmetric (follow without follow-back); private accounts require approval. | Asymmetric following creates celebrities with huge follower counts. |
| Likes and comments in scope? | Often below the line, but counters are a classic deep dive, so include them. | Hot counters on celebrity posts are a write-contention problem. |
| Stories, search, live, direct messages? | Out of scope for the core; mention what would change. | Keeps the core focused; stories add expiry, search adds indexing. |
| How fast must posts appear for followers? | Within seconds to a minute is fine; the author sees it immediately. | Allows asynchronous fan-out and eventual consistency. |
| What latency for the feed and media? | Feed under about 500 ms; media should appear instantly while scrolling. | Drives feed precomputation, CDN design and client prefetching. |
| Global audience? | Yes, worldwide, mostly on mobile. | CDN with global edges; multi-region metadata. |
Requirements#
Functional#
- Create posts with one or more photos or videos and a caption.
- Follow and unfollow other users (asymmetric; private accounts need approval).
- View a feed of recent posts from the people you follow, newest first, with infinite scroll.
- Like and comment on posts, and see like and comment counts. (Often called below the line in interviews; we include the counter design because it is a frequent follow-up.)
Below the line: search for users, hashtags and places; stories (ephemeral content that disappears after 24 hours); live video; direct messages; Explore and recommendations; ads. We sketch how stories, search and Explore would fit at the end of the deep dives.
Non-Functional#
- Availability over consistency for reads. The feed may be a few seconds stale. A new post may reach some followers before others. It is better to show a slightly old feed than an error. In CAP Theorem and PACELC terms, we choose availability and low latency, with eventual consistency for feeds and counts.
- Low feed latency. Under about 500 ms at p99 to return a page of the feed (metadata), so the app opens quickly.
- Media renders instantly. Photos and videos should appear as soon as the user scrolls to them. This is a delivery requirement: CDNs, appropriately sized variants, placeholders and prefetching.
- Durability of uploads. Once a post is acknowledged, its media must never be lost. Target eleven nines of object durability (99.999999999%), the level major object stores advertise.
- Scale. 500 million daily active users, 100 million new posts per day, heavy read skew (each post is viewed many times), and celebrities with over 100 million followers.
- Large uploads on unreliable networks. Uploads up to 4 GB must survive dropped connections and resume rather than restart.
What makes this problem distinctive: compared with a text news feed, the hard parts move to the media path: getting bytes in (uploads), transforming them (processing), and getting bytes out (CDN). The feed itself reuses the news feed design.
Capacity Estimation#
Assumptions, stated so they can be challenged (see Back-of-the-Envelope Estimation):
- 500 million daily active users (DAU).
- 100 million new posts per day: 80% photo posts, 20% video posts. Photo posts average 1.5 images (carousels raise the average).
- Each active user opens the feed about 10 times a day and loads about 2 pages of 10 posts per session.
- Each user has 200 followees on average; follower counts are extremely skewed (a few accounts have over 100 million followers).
- Each user likes about 20 posts and writes about 1 comment per day.
Post writes. 100 million per day ÷ 86,400 s ≈ 1,200 posts per second on average, about 3,500 per second at peak (peaks are often 2 to 3 times the average). That is a modest rate for a sharded metadata store.
Photo storage. 80 million photo posts × 1.5 images = 120 million photos per day. Phones compress before upload, so the average original is about 2 MB (the 8 MB limit covers the worst case). Originals: 120 million × 2 MB = 240 TB per day. Variants (four sizes in two formats, plus a thumbnail) add about 500 KB per photo, another 60 TB per day. Total about 300 TB per day for photos.
Video storage. 20 million videos per day at an average original of 50 MB (short clips dominate, but the 4 GB limit allows long ones) = 1 PB per day of originals. Transcoded renditions across an adaptive bitrate ladder add roughly the same again. So video dominates storage: about 2 PB per day.
Yearly growth. About 2.3 PB per day × 365 ≈ 840 PB per year before replication or erasure coding. With erasure coding at about 1.4 times overhead (rather than 3 times for triple replication), that is well over an exabyte of raw disk per year. Storage cost, not compute, is the main budget item, which is why tiering and erasure coding matter (deep dive 6).
Upload bandwidth. 2.3 PB per day ÷ 86,400 ≈ 27 GB/s of ingress on average, around 80 GB/s at peak, about 650 Gbit/s. It is spread across regions and goes straight into object storage, not through application servers.
Feed reads. 500 million users × 10 opens × 2 pages = 10 billion feed page requests per day, about 115,000 per second on average and about 350,000 per second at peak. Feed reads outnumber post writes by about 100 to 1.
Media reads. Each feed page shows about 10 posts, each with at least one image or video. That is about 100 billion media requests per day, over 1 million per second on average. At about 150 KB per image (a feed-size WebP variant), images alone are about 170 GB/s, or 1.4 Tbit/s of egress on average, and video multiplies that several times. Only a CDN can serve this; the origin should see a small fraction.
Likes. 500 million × 20 = 10 billion likes per day, about 115,000 per second on average and 350,000 per second at peak. A single viral post can receive tens of thousands of likes per second at its peak.
Follow graph. With about 2 billion accounts of which perhaps 1.5 billion follow someone, at 150 followees each, that is about 225 billion edges. Storing each edge in both directions (who I follow, who follows me) at about 40 bytes per row is about 18 TB, which fits comfortably in a sharded database with a cache.
| Quantity | Estimate |
|---|---|
| Post writes | about 1,200 per second average, 3,500 peak |
| New media | about 300 TB per day photos, 2 PB per day video (including renditions) |
| Upload ingress | about 27 GB/s average |
| Feed page reads | about 115,000 per second average, 350,000 peak |
| Media requests | over 1 million per second, more than 1.4 Tbit/s egress for images alone |
| Likes | about 115,000 per second average, 350,000 peak |
| Follow edges | about 225 billion, about 18 TB with both directions |
See Numbers Every Engineer Should Know for the latency and throughput figures used here.
Core Entities#
- User. Profile (username, display name, avatar), privacy setting (public or private), and counts (followers, following, posts).
- Post. Author, caption, creation time, visibility, an ordered list of media items, and status (draft, processing, published, deleted).
- Media. One photo or video inside a post: original object key, processing status, dimensions, duration (for video), and the set of generated variants (sizes, formats, renditions) with their object keys and CDN paths.
- Follow. A directed edge from follower to followee, with a creation time and a state (active, or requested for private accounts).
- Feed. For each user, a list of post ids from followed accounts, in time order. Precomputed for active users.
- Like and Comment. A like is a (user, post) pair; a comment is text with an author, a post and a time. Each post has like and comment counters.
API Design#
# 1. Start a post: create the record and get upload targets (presigned URLs).
POST /v1/posts
{ "caption": "Sunset in Lisbon", "media": [
{ "type": "photo", "contentType": "image/jpeg", "sizeBytes": 2483112, "sha256": "..." },
{ "type": "video", "contentType": "video/mp4", "sizeBytes": 1893004288 } ] }
-> 201 { "postId": "29384756...", "status": "draft",
"uploads": [ { "mediaId": "m1", "method": "PUT", "url": "https://upload.example/...sig" },
{ "mediaId": "m2", "multipart": { "uploadId": "...", "partSize": 16777216,
"partUrls": ["...part1", "...part2"] } } ] }
# 2. Client uploads bytes directly to object storage, then confirms.
POST /v1/posts/{postId}/complete { "parts": { "m2": [ { "n": 1, "etag": "..." } ] } }
-> 202 { "status": "processing" } # becomes "published" after processing
# 3. Follow graph.
POST /v1/users/{userId}/follow -> 200 { "state": "active" | "requested" }
DELETE /v1/users/{userId}/follow -> 204
# 4. Feed, cursor-paginated, newest first.
GET /v1/feed?cursor={opaque}&limit=10
-> 200 { "posts": [ { "postId", "author", "caption", "media": [ { "variants": {...} } ],
"likeCount", "commentCount", "likedByMe" } ], "nextCursor": "..." }
# 5. Likes and comments.
PUT /v1/posts/{postId}/like -> 204 # idempotent
DELETE /v1/posts/{postId}/like -> 204
POST /v1/posts/{postId}/comments { "text": "Wow" } -> 201 { "commentId" }
GET /v1/posts/{postId}/comments?cursor=...&limit=20Notes:
- The user id comes from the auth token, never from the request body. See Authentication and Authorization.
- Uploads are two-phase. The API never receives media bytes. It hands out short-lived, scoped, signed URLs, the client uploads directly to object storage, and then the client (or a storage event) confirms. This is the core of Pattern: Handling Large Files and Blobs.
- Like is a
PUT, so it is naturally idempotent: liking twice leaves one like. That matters for retries on flaky networks. See Idempotency and Safe Retries. - The feed returns variant URLs, not one image URL, so the client can pick the right size for its screen and network.
- Cursor pagination with an opaque cursor, as in the news feed design. See API Design Best Practices.
High-Level Design#
We satisfy each functional requirement in turn, starting simple, then let the non-functional requirements (latency, instant media, scale) drive the deep dives.
1) Users can create posts with photos, videos and a caption#
The naive version sends the photo inside the POST /posts request. The post service receives the bytes, writes them to object storage, and writes the post metadata to a database. It works for a prototype, but at scale it is a poor design:
- Application servers become a bandwidth relay. Every byte passes through them twice (in from the client, out to storage). At 27 GB/s of average ingress, that is a large fleet doing nothing but copying.
- Long uploads tie up servers. A 2 GB video over a 10 Mbit/s mobile uplink takes about 27 minutes. A server thread or connection held for 27 minutes per upload is expensive, and a deploy or crash kills the upload.
- No resumability. If the connection drops at 99%, the whole upload restarts.
The better design separates metadata from bytes. The client first asks the post service to create a draft post and hand out presigned URLs: time-limited URLs signed with the storage service's credentials that permit one specific operation (for example "PUT an object at this key, up to 8 MB, content type image/jpeg, within 15 minutes"). The client uploads directly to object storage (Amazon S3, Google Cloud Storage, Azure Blob Storage, or an in-house equivalent). When the upload finishes, object storage emits an event (or the client calls complete), a media processing pipeline generates variants, and the post flips from processing to published.
Steps:
- The app sends post metadata (caption, number of media items, their types, sizes and optional checksums).
- The post service creates a
draftpost and apendingrow per media item, with an object key such asoriginals/{mediaId}. - It returns presigned URLs: a single
PUTfor small photos, a multipart upload (an upload id plus a URL per part) for large videos. - The app uploads bytes straight to object storage, in parallel parts if large, retrying only the failed parts.
- Object storage emits an "object created" notification (S3 Event Notifications, GCS Pub/Sub notifications or Azure Event Grid) into a queue. The client also calls
complete, which is useful as a second signal and for multipart completion. - Processing workers read the original, create variants and write them to a variants bucket.
- When all media items of the post are ready, the post becomes
published. - Publishing emits an event that triggers feed fan-out (requirement 3).
The author's app shows the post in their own profile immediately, using the local copy of the media, so the author never waits for processing.
2) Users can follow other users#
Following is a directed edge. The Follow Service writes it to a follow graph store and keeps two views of each edge, because we need both questions answered quickly:
- Who does user A follow? Used to build A's feed (fan-out on read) and to show "Following".
- Who follows user B? Used to fan out B's new posts to followers (fan-out on write) and to show "Followers".
A relational table works well: follows(follower_id, followee_id, created_at, state) with primary key (follower_id, followee_id) and a second table (or a global secondary index) keyed (followee_id, follower_id). Shard each table by its leading id, so all of one user's followees (or followers) live on one shard and can be read with one range scan. Follower and following counts are kept as separate counters rather than computed with COUNT(*). Private accounts store a requested state until the owner approves.
Writing the two directions is a dual write. Make it reliable with a transactional outbox or change data capture: write the primary edge, and let a CDC stream write the reverse edge and update counters, so a crash cannot leave the two views permanently inconsistent. See Change Data Capture and the Outbox Pattern.
3) Users can see a chronological feed of posts from people they follow#
The simplest correct feed is computed on read: get the list of people I follow, fetch each one's recent posts, merge them by time, take the newest 10.
SELECT p.* FROM posts p
JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = :me AND p.created_at < :cursor_time
ORDER BY p.created_at DESC
LIMIT 10;With 200 followees, that is 200 small index reads and a merge. It is fine at small scale, but on a sharded system those 200 authors live on many shards, so one feed request becomes a scatter-gather across dozens of database servers, at 350,000 feed requests per second. That cannot meet a 500 ms p99.
The scalable answer is to precompute feeds: when a user posts, a fan-out service pushes the post id into a stored feed for each follower (fan-out on write), so reading the feed is a single lookup. Celebrities with millions of followers are handled differently (fan-out on read for their posts, merged at read time). This hybrid model is covered in deep dive 8, and in full depth in the news feed case study.
The full high-level design#
The complete system has two halves that meet only at the post record. The media plane moves bytes: uploads go straight to object storage, workers produce variants, and the CDN serves them. The metadata plane moves small records: posts, follows, feeds and counters. Drawing them separately keeps each diagram readable; in the real system, the post service ties them together by publishing a post only after its media is ready.
Components:
- API gateway. TLS termination, auth, rate limiting, routing. See API Gateway and Backend-for-Frontend.
- Post Service. Creates posts, issues presigned upload URLs, tracks media status, publishes events. Stateless.
- Object storage. Two logical buckets: originals (written by clients, kept for reprocessing) and variants (written by workers, read by the CDN). Very high durability, effectively unlimited capacity. See Object Storage and Blob Storage.
- Media queue and processing workers. Asynchronous, horizontally scaled workers that resize images, transcode video, extract metadata, generate thumbnails and placeholders, and run safety scans. See Pattern: Managing Long-Running Tasks.
- CDN and origin shield. Edge caches near users serve nearly all media; a regional mid-tier cache (the origin shield) collapses misses so object storage sees little traffic. See Content Delivery Networks (CDN).
- Metadata stores. Posts and media metadata sharded by author id; follow graph sharded by user id in both directions.
- Fan-out workers and feed cache. On publish, write the post id into followers' precomputed feeds (except for celebrity authors). The feed cache holds a capped list of recent post ids per active user.
- Feed Service. Reads the precomputed feed, merges in celebrity posts, hydrates post ids into full posts (author, caption, variant URLs, counts) using caches, and returns a page.
- Engagement Service and counter store. Records likes and comments, maintains counts that can absorb hot posts. See deep dive 10.
Key Flows#
Flow 1: Publish a photo post#
- Create the draft. The app sends metadata only. The service validates (count of items, declared sizes within limits, allowed content types) and creates the draft.
- Sign. The presigned URL encodes the bucket, the exact object key, the HTTP method, an expiry time and, where the storage service supports it, conditions such as content type and maximum size (for example, S3 presigned POST policies with a
content-length-rangecondition). The client cannot write anywhere else. - Upload directly. Bytes go from the phone to the nearest storage endpoint, often via an upload acceleration edge. Application servers never touch them.
- Double signal. The storage event and the client's
completecall both indicate the upload finished. The service treats either as sufficient and is idempotent, so a lost client call or a delayed event does not leave the post stuck. - Process. Workers produce variants (deep dive 3). For photos this takes on the order of a second; for long videos, minutes.
- Publish and fan out. When every media item is ready, the post is published and fan-out begins.
Flow 2: Upload a large video with resumable multipart upload#
- Split. A 1.9 GB video at 16 MB per part is 114 parts. S3, for example, allows parts from 5 MB to 5 GB (the last part may be smaller) and up to 10,000 parts per upload, enough for objects of terabytes; Google Cloud Storage offers resumable uploads with a session URI; Azure uses block blobs with staged blocks and a final commit.
- Parallelise. The app uploads several parts at once (3 to 6 on mobile), which improves throughput on high-latency links.
- Resume. After a drop, the app asks which parts exist and uploads only the missing ones. A failure at 99% costs one part, not the whole file.
- Commit. The final
completecall lists parts and their ETags (checksums); the storage service assembles the object atomically. Until then, no partial object is visible. - Clean up. Abandoned multipart uploads consume storage. A lifecycle rule aborts incomplete uploads after, say, 7 days.
Flow 3: Read the feed#
- Precomputed ids. For an active user, the feed cache holds a capped list of recent post ids from followed accounts. Reading 30 ids is one Redis call, under a millisecond.
- Celebrity merge. Posts by accounts with huge follower counts are not fanned out. The Feed Service fetches recent post ids for the celebrities this user follows (from a small, heavily cached per-author list) and merges them.
- Filter and hydrate. Remove posts that were deleted, from blocked users, or no longer visible (for example a private account that removed the follower). Then batch-fetch post bodies and author profiles from caches (Memcached or Redis), falling back to the metadata store on a miss.
- Counts. Batch-fetch like and comment counts and whether the viewer liked each post.
- Return variant URLs. The response lists several sizes and formats per media item, plus a tiny placeholder. The app chooses the variant that matches its screen width and network, shows the placeholder immediately, and fetches the image from the CDN.
- Prefetch. While the user reads page 1, the app fetches page 2 and the images for the next few posts, so scrolling never waits.
The whole server-side path is a handful of cache calls: about 20 to 50 ms at p50 and under 200 ms at p99, inside the 500 ms budget.
Flow 4: Like a post#
- The app sends
PUT /posts/{id}/likeand updates the heart and count locally at once (optimistic UI). - The Engagement Service inserts
(postId, userId)into the likes table if it is not already present. A duplicate insert is a no-op, which makes retries safe. - If the insert created a new row, it emits a "like" event to a stream.
- A counter aggregator consumes the stream, sums likes per post over a short window (for example 1 second), and applies one increment per post per window to the counter store. A celebrity post getting 20,000 likes per second becomes one write of +20,000 per second instead of 20,000 writes.
- The cached count is updated or refreshed. Viewers see counts that lag by a second or two, which is acceptable.
- A notification ("Ana liked your photo") is sent to the author asynchronously, batched for popular posts ("Ana and 1,203 others liked your photo").
Data Model#
The social side of the model links users to each other and to the posts they react to. The user and post entities repeat here, with the same keys, so each diagram stays readable on its own.
IDs. Use 64-bit, time-sortable ids that also encode the shard. Instagram's engineers described exactly this in their 2012 post "Sharding & IDs at Instagram": 41 bits of milliseconds since a custom epoch, 13 bits of logical shard id and 10 bits of a per-shard sequence, generated inside PostgreSQL with a PL/pgSQL function. Ids sort by time (useful for feeds and cursors), are unique without a central service, and tell you which shard holds the row. See Unique ID Generation.
Posts and media metadata. Shard by author id, so a user's posts (their profile grid) live together and the profile page is one range scan on (author_id, post_id DESC). Media rows live with their post. The status fields (draft, processing, published, deleted for posts; pending, uploaded, ready, failed for media) drive the upload state machine. Many logical shards (thousands) are mapped onto fewer physical database servers, so capacity can be added by moving logical shards without re-hashing data, the approach Instagram described.
Which database? Post metadata is relational in shape (posts, media, variants, with clear ownership and a few joins within one author's shard) and needs moderate write rates with strong per-row consistency. Sharded PostgreSQL or MySQL is a natural fit and is what Instagram started with. Very high-write, append-heavy data such as feeds, activity and likes suits a wide-column store such as Cassandra; Instagram's engineers have written about running Cassandra at large scale, and about replacing its storage engine with RocksDB ("Rocksandra", 2018) to cut tail latency. See Choosing a Database: A Decision Guide, PostgreSQL in Practice and Apache Cassandra in Practice.
Follow graph. Two tables, each sharded by its leading key:
following(follower_id, followee_id, created_at, state)with primary key(follower_id, followee_id).followers(followee_id, follower_id, created_at, state)with primary key(followee_id, follower_id), plus an index on(followee_id, created_at DESC)for "recent followers" lists.
A celebrity's followers partition is huge (over 100 million rows). In a wide-column store, bucket it, for example ((followee_id, bucket), follower_id) with bucket = hash(follower_id) mod 64, so no partition is unbounded and fan-out workers can read buckets in parallel. A graph-oriented cache such as Facebook's TAO (described at USENIX ATC 2013) sits in front of such tables at very large scale. See Graph Databases for when a native graph database helps (multi-hop queries) and when it does not (one-hop follow lists, as here).
Feeds. Per user, a capped list of post ids (say the newest 500), stored in Redis or a similar in-memory store, keyed feed:{userId}, only for users active in the last few weeks. Inactive users' feeds are rebuilt on demand. Each entry is just a 64-bit id (and perhaps the author id for filtering), so 500 entries are about 8 KB; 300 million active users need about 2.4 TB of feed cache before replication.
Likes. likes(post_id, user_id, created_at) with primary key (post_id, user_id) makes a like idempotent and answers "who liked this post". A second table user_likes(user_id, post_id) answers "did I like these posts?" for feed hydration in one batch read per viewer. Counts are not computed from these tables at read time; they live in post_counters, maintained asynchronously (deep dive 10).
Comments. comments(post_id, comment_id, author_id, text, created_at) partitioned by post id, clustered by comment id descending for "newest first" pages, with cursor pagination.
Media bytes. Object keys are random or hash-based (originals/ab/cd/{mediaId}), never user-supplied names, which avoids collisions and hot prefixes and makes URLs unguessable. Variant keys add the variant name: v/{mediaId}/1080.webp. Objects are immutable: an edit creates a new media id, so CDN caches never need invalidation.
Retention and deletion. Posts live until deleted. Deletion marks the post deleted at once (it disappears from feeds and profiles), then an asynchronous job removes variants and originals and purges CDN entries. Legal and privacy rules may require removing data within a set period after an account is deleted; design the deletion pipeline so every derived copy (variants, feeds, caches, search indexes, backups within their rotation) is covered.
Deep Dives#
1) How should media get from the phone to storage?#
Bad: upload through the application servers. The app posts the bytes to the API, which streams them to object storage. Every byte crosses the server fleet twice, long uploads hold server resources for minutes, a deploy or crash kills in-flight uploads, and there is no resume. It also makes the API tier's capacity depend on upload bandwidth rather than requests. The only good reason to do this is when bytes must be inspected or transformed inline before storage, which is rare and can usually be done after upload.
Good: presigned URLs for direct upload. The server signs a URL that grants one operation on one object key for a short time, and the client uploads straight to object storage. The API tier now handles only small metadata requests. Storage services are built for exactly this traffic: they scale horizontally, accept uploads close to the user, and give eleven nines of durability once the upload is acknowledged.
What the signature should restrict:
- Method and key. Only
PUT(orPOSTwith a form policy) to exactlyoriginals/{mediaId}. The client cannot choose the key. - Expiry. Minutes, not days. A leaked URL becomes useless quickly. For very slow links, issue fresh URLs on resume rather than long-lived ones.
- Size and content type. With S3 presigned POST policies, a
content-length-rangecondition rejects files larger than allowed (8 MB for photos). With presignedPUT, the signedContent-LengthandContent-Typeheaders must match. Other storage services offer equivalent controls (signed URLs with conditions on Google Cloud Storage, shared access signatures on Azure). - Integrity. Ask the client for a checksum (for example SHA-256 or MD5 of the content) and include it in the signed request, so storage rejects corrupted uploads.
Great: presigned direct upload with multipart or resumable uploads, a state machine and abuse controls.
- Multipart or resumable for anything large (above about 10 to 20 MB): parallel parts, resume after failure, atomic completion. See Flow 2.
- A clear state machine for each media item, persisted in metadata:
pending(URL issued) →uploaded(storage confirms the object exists) →processing→ready, orfailedandexpired. Transitions are idempotent and driven by events, so retries and duplicate events are harmless. - Two completion signals. The storage service's event notification (reliable but can be delayed by seconds) and the client's
completecall (fast but may never arrive if the app is killed). Accept either. A periodic reconciler finds media stuck inpendingfor longer than the URL expiry and either marks them expired or checks storage to see if the object arrived. - Quarantine before publish. Uploads land in an originals bucket that is not publicly readable and is not behind the CDN. Only processed, scanned variants are published. This prevents someone from using your storage as free hosting for arbitrary files.
- Validate the content, not the claim. The declared content type is a hint. Workers decode the file to check it really is an image or video, reject anything that fails to decode, and enforce real limits on dimensions and duration (a "decompression bomb" image can be small on disk but enormous when decoded).
- Rate limits and quotas per user and per device on issuing upload URLs (for example a few hundred per hour), so a compromised account cannot fill storage. See Rate Limiting and Throttling.
- Lifecycle rules. Delete originals that never became part of a published post after a day, and abort incomplete multipart uploads after a few days.
Upload acceleration. Mobile users far from a storage region suffer on long round trips, because TCP throughput falls as round-trip time rises. Terminate uploads at an edge point of presence near the user (S3 Transfer Acceleration works this way, and CDNs offer similar ingest paths), then carry the bytes over the provider's backbone. On the client, compress and resize before upload: there is no point uploading a 48-megapixel photo when the largest variant is 1080 pixels wide, so many apps resize to a sensible maximum (and keep a high-quality copy for later) before sending.
2) How do we support videos up to 4 GB on mobile networks?#
A 4 GB upload over a 10 Mbit/s uplink takes about 53 minutes. Over that time the phone will change networks, lose signal or be locked. The design must assume interruptions are normal.
Basic: one long PUT. Any interruption restarts from zero. The expected number of restarts grows with file size, so large uploads can effectively never finish on bad networks.
Better: multipart upload with fixed-size parts. Split the file into parts, upload them independently (and in parallel), retry failed parts, and commit at the end. How big should parts be?
- Too small (for example 1 MB) means thousands of requests, each with TLS and request overhead, and more metadata. S3 also has a 10,000-part cap, which forces parts of at least 400 KB for a 4 GB file, and more realistically larger.
- Too large (for example 500 MB) means a single failure loses a lot of work, and parallelism is limited.
- A sensible default is 8 to 16 MB on mobile, 64 MB or more on fast wired networks. At 16 MB, a 4 GB video is 256 parts. If the connection drops on average every 5 minutes at 10 Mbit/s (about 375 MB of progress), each drop wastes at most one part per parallel stream, about 2 to 4% of that progress.
Best: resumable, adaptive, background-friendly uploads.
- Adaptive part size and concurrency. Measure throughput and adjust: more parallel parts on high-bandwidth, high-latency links; fewer on congested ones.
- Background transfer. On iOS, background
URLSessiontransfers continue while the app is suspended; on Android, WorkManager schedules uploads that survive app restarts. The upload must be expressible as independent part requests for this to work. - Persistent upload state on the device. Store the upload id, part size and completed parts in local storage, so a restarted app resumes rather than starting over.
- Server-side status endpoint. The client can ask which parts exist (S3
ListParts, or the equivalent query on a resumable session) and continue. - Open protocols. The tus protocol (tus.io) is an open, HTTP-based protocol for resumable uploads with client and server libraries, useful if you run your own upload servers rather than using a cloud object store's multipart API.
- Early processing. For long videos, start transcoding as soon as enough of the file exists (some pipelines process segments as parts arrive), so the post becomes viewable minutes sooner.
Interview tip. When asked "what if the upload fails at 99%?", the answer is multipart or resumable upload with part-level retries, persistent client state and a status endpoint. Mention lifecycle rules for abandoned uploads.
3) How do we process images into variants?#
A phone photo is typically 3,000 to 4,000 pixels wide, several megabytes, in JPEG or HEIC, with EXIF metadata including the camera model and often GPS location. A feed on a phone screen needs about 1,080 pixels wide, a grid thumbnail about 300, and a notification icon about 150. Sending the original to every viewer would waste bandwidth, battery and time.
Basic: resize on every request. Serve GET /image/{id}?w=640 by loading the original and resizing on the fly. Flexible, but CPU-heavy and slow on cache misses, and an attacker can request thousands of odd sizes to bypass caches and burn CPU.
Better: eager variants at upload time. When an upload completes, a worker produces a fixed set of variants and stores them as immutable objects:
| Variant | Width | Typical use |
|---|---|---|
thumb | 150 px | notifications, small avatars, search results |
grid | 320 px | profile grid |
feed-sm | 640 px | feed on small screens or slow networks |
feed-lg | 1080 px | feed on modern phones |
full | 1440 or 2048 px | full-screen zoom, tablets, web |
placeholder | about 20 bytes to 2 KB | blurred preview shown instantly (BlurHash string or tiny JPEG) |
Each width may be produced in two or three formats: JPEG (universal), WebP (typically 25 to 35% smaller at similar quality, supported by all current major browsers and mobile OSs) and AVIF (often smaller still, more expensive to encode, support increasingly universal). The client advertises what it supports, through the Accept header on web or app capabilities, and the API returns the best URL.
Processing steps, in order:
- Decode and validate. Confirm it is a real image, check dimensions against limits, reject decompression bombs.
- Normalise orientation. Apply the EXIF orientation flag to the pixels, so images display correctly everywhere.
- Strip metadata. Remove EXIF data, especially GPS coordinates, to protect privacy. Keep what the product needs (for example capture time) in the metadata database instead.
- Colour management. Convert wide-gamut images (Display P3 from modern phones) carefully, either preserving an embedded profile or converting to sRGB, so colours do not shift.
- Apply edits. Filters and crops chosen by the user are either applied on the device before upload (common) or described as parameters and applied here.
- Resize with a good resampling filter (Lanczos or similar), and sharpen slightly after downscaling.
- Encode each variant at tuned quality settings, often chosen per image by a perceptual quality metric (such as SSIM or a learned metric) to hit a target visual quality at the smallest size.
- Placeholder. Compute a BlurHash string or a tiny blurred thumbnail, stored in the post metadata so it arrives with the feed response, not as a separate request.
- Safety and integrity checks. Perceptual hash matching against known abusive content (for example Microsoft's PhotoDNA, used across the industry to detect known child sexual abuse imagery), nudity and violence classifiers, and spam checks. Content that fails is blocked before publication.
- Write variants, update metadata, emit "media ready".
Best: eager common variants plus lazy, bounded on-demand variants. Precompute the handful of variants that cover nearly all traffic, and allow an image service at the edge or origin to produce uncommon sizes on demand, but only from a fixed allow-list of sizes and formats (so attackers cannot generate unbounded variants), with the result cached. This handles new devices and new formats without reprocessing billions of old images up front. When a new format is adopted, run a background backfill for popular images first (the top few percent by views account for most bytes served) and generate the rest lazily.
Cost of processing. Resizing and encoding one photo into ten outputs takes on the order of 100 to 500 ms of CPU, more for AVIF. At 120 million photos per day (about 1,400 per second on average, 4,000 per second at peak), that is roughly 400 to 2,000 CPU cores busy at peak, a modest fleet that autoscales on queue depth. Workers are stateless and idempotent: reprocessing the same media id overwrites the same variant keys, so retries are safe. See Asynchronous Processing and Message Queues.
4) How do we process videos so they start instantly?#
Video needs more than resizing. A phone records at high bitrate (often 10 to 50 Mbit/s for 1080p or 4K). Viewers on mobile networks might sustain 1 to 5 Mbit/s, and their bandwidth changes from second to second.
Basic: serve the original file. Huge, slow to start, and stalls on weak networks. Some phone codecs and containers do not play everywhere.
Better: transcode to a few fixed MP4 files. Produce, for example, 480p, 720p and 1080p H.264 MP4s with the index (the moov atom) at the front ("fast start"), so playback can begin before the whole file downloads. The client picks one. This works, but a viewer whose network drops mid-video stalls instead of switching to a lower quality.
Best: adaptive bitrate streaming (ABR) with an encoding ladder.
- Transcode into a ladder of renditions, for example 240p at 300 kbit/s up to 1080p at 4 to 6 Mbit/s, in H.264 for compatibility and in a more efficient codec (HEVC, VP9 or AV1) for devices that support it. More efficient codecs cut bytes by roughly 30 to 50% at similar quality, which matters because video dominates egress, but they cost much more CPU to encode, so they are often reserved for videos that become popular.
- Segment each rendition into short chunks (2 to 6 seconds) and write manifests: HLS playlists (
.m3u8) or DASH manifests (.mpd). The player fetches the manifest, starts with a low rendition for a fast start, measures throughput, and switches up or down between segments. - Parallelise. Split the source into chunks by time, transcode each chunk on a different worker, and stitch the outputs. A 10-minute video can be ready in about the time it takes to transcode one chunk, rather than the whole file. This is the same scatter-gather idea used by large video platforms.
- Publish progressively. Make the post viewable as soon as the lowest rendition and a thumbnail are ready, and add higher renditions as they finish. The author sees "posted" in seconds rather than minutes.
- Thumbnails and preview frames. Extract a cover frame (or let the user choose one), a short silent preview loop for autoplay in the feed, and a sprite sheet of frames for scrubbing.
- Per-title tuning. Simple content (a talking head) needs fewer bits than complex content (confetti, water). Choosing the ladder per video, based on a quick complexity analysis, saves bandwidth at the same perceived quality. Netflix popularised this idea as "per-title encoding" in 2015.
Transcoding is CPU- or accelerator-heavy and slow, so it runs as a workflow: a queue of jobs, a worker pool that scales on queue depth, retries for failed chunks, and a final step that marks the media ready. A workflow engine is a good fit when the pipeline has many steps (scan, transcode chunks, stitch, generate thumbnails, run classifiers, publish). See Pattern: Multi-Step Processes and Workflows and the video streaming case study for the full transcoding and ABR design.
5) How do we make media render instantly while scrolling?#
"Instant" is a client and delivery problem. The goal is that by the time a post scrolls into view, its image is already on the device, or at worst one fast round trip away.
Basic: fetch each image from origin when it appears. Every request crosses the internet to the storage region. 100 to 300 ms of latency per image, plus origin load of over a million requests per second. Images pop in visibly late.
Better: a CDN in front of the variants bucket. Edge caches near users serve repeated requests. Because variant URLs are immutable (the content at a URL never changes), they can be cached with very long lifetimes (Cache-Control: public, max-age=31536000, immutable) and never need invalidation. Popular images are almost always served from an edge a few milliseconds away.
Best: a layered cache hierarchy plus smart clients.
- Client cache. The app keeps a disk cache of recently seen images (hundreds of MB). Scrolling back, or reopening the app, hits the device. In Facebook's study of its photo-serving stack, "An Analysis of Facebook Photo Caching" (Huang and others, SOSP 2013), the browser cache alone served a large share of photo requests, and a stack of browser, edge and origin caches together left only roughly a tenth of requests for the backend storage.
- Edge caches in hundreds of locations serve the popular head of content.
- Origin shield. A regional mid-tier cache that all edges in a region miss into. Many edges missing on the same new image produce one request to storage, not hundreds (request coalescing). This is crucial for a celebrity's new post, which is requested by millions of viewers within minutes.
- Object storage serves only the long tail of cold misses.
- Right-sized variants. The client requests the variant that matches its display size and pixel density. A 1080-pixel WebP at about 150 KB instead of a 3 MB original is 20 times fewer bytes: faster on every network.
- Placeholders. The feed response includes a BlurHash or tiny thumbnail per image (tens of bytes). The app paints a blurred preview with the right aspect ratio immediately, so the layout never jumps and the screen never shows blank boxes. Progressive JPEGs give a similar effect for the full image.
- Prefetching. While the user views post N, the app fetches images for posts N+1 to N+5, and the next feed page when the user is a few posts from the end. On Wi-Fi it can prefetch more aggressively; on metered networks or in low-data mode, less. Videos prefetch just the first segment or two of the lowest rendition so autoplay starts instantly.
- Connection reuse and protocols. HTTP/2 or HTTP/3 to the CDN, with one connection carrying many image requests, avoids repeated handshakes. HTTP/3 over QUIC helps on lossy mobile networks because a lost packet does not block other streams. See HTTP, HTTP/2, HTTP/3 and HTTPS.
Access control on media. Private accounts' photos must not be fetchable by anyone who guesses a URL. Unguessable keys help but are not access control, because URLs leak (shared screenshots of network logs, browser history). For private content, use signed CDN URLs or signed cookies with short expiry, issued by the Feed Service only to authorised viewers. The CDN validates the signature at the edge without calling back to the origin. Public content can use plain URLs for maximum cacheability.
CDN cost and placement. At over 1.4 Tbit/s for images and several times that for video, CDN egress is one of the biggest bills. Very large companies build their own edge networks and also place caches inside internet service providers' networks; Meta, Google and Netflix all operate such programmes. A smaller company relies on commercial CDNs and negotiates committed-use pricing. See Content Delivery Networks (CDN) and Edge Computing and Edge Functions.
6) How do we store petabytes of media durably and cheaply?#
At over 2 PB of new media per day, storage cost dominates. The design questions are durability, cost per byte, and how access patterns change with age.
Basic: a cloud object store with default settings. S3, Google Cloud Storage or Azure Blob give eleven nines of durability and unlimited scale. Pay the standard price for everything forever. Fine for a startup, very expensive at exabyte scale.
Better: tiering by age and popularity. Media is hot for a few days after posting (most views of a typical post happen early), warm for months, and cold after that, but must remain available because people revisit old profiles. Use lifecycle policies to move objects to cheaper storage classes: standard for recent media, infrequent-access classes after 30 to 90 days, and archive classes only for data that is almost never read (originals kept for reprocessing, for example). Keep popular old content in a hot tier based on access statistics, not just age. Delete redundant variants that can be regenerated, keeping the original plus the few variants that serve most traffic.
Best: purpose-built blob storage with erasure coding (what the largest companies do).
- Haystack. Facebook's paper "Finding a needle in Haystack: Facebook's photo storage" (Beaver, Kumar, Li, Sobel and Vajgel, OSDI 2010) explained why storing each photo as a file in a normal file system was too slow: looking up a file's metadata cost extra disk reads per photo. Haystack packs many photos into large append-only volume files and keeps a small in-memory index of where each photo lives, so a read needs about one disk seek.
- f4. "f4: Facebook's Warm BLOB Storage System" (Muralidhar and others, OSDI 2014) added a warm tier using Reed-Solomon erasure coding across racks and XOR coding across data centres. It brought the effective replication factor for warm data from about 3.6 to about 2.1, while keeping durability, a large cost saving at Facebook's scale.
- Erasure coding in general. Instead of storing 3 full copies (3 times overhead), split data into k data fragments and compute m parity fragments; any k of the k + m fragments rebuild the data. For example, RS(10, 4) has 1.4 times overhead and survives the loss of any 4 fragments. The trade-off is more CPU and network on reconstruction, and slower reads when fragments are missing, which is why hot data often stays replicated and warm data is erasure-coded.
Deduplication. Identical files (the same meme reposted many times) can be detected by content hash and stored once, with reference counts. Savings are real for reposted content, but deletion becomes a reference-counting problem and privacy rules need care, so many systems deduplicate only within narrow scopes.
Durability is end to end. Eleven nines in the store means little if a bug in the processing pipeline deletes originals. Protect against logical errors with versioning or delayed deletion (soft delete for N days), write-once policies on originals, and periodic integrity scans (comparing stored checksums against content). See Storage Fundamentals: Memory, Disk, Block, File and Object and Disaster Recovery and Backups.
7) How do we store and serve the follow graph?#
The follow graph answers four questions, each with different volume:
| Question | Used by | Volume |
|---|---|---|
| Does A follow B? | Visibility checks for private accounts, "Follow" button state | Very high, many per feed page |
| Whom does A follow? | Fan-out on read, "Following" list | High |
| Who follows B? | Fan-out on write, "Followers" list | Moderate, but huge lists for celebrities |
| How many followers does B have? | Profile header | Very high |
Basic: one relational table with two indexes. follows(follower_id, followee_id) with indexes on both columns. Correct and simple at small scale. Once sharded, only one direction can be shard-local: if you shard by follower, "who follows B" becomes a scatter-gather across every shard.
Better: store both directions, each sharded by its own key. The following table is sharded by follower id and the followers table by followee id, so every list query is a single-shard range scan. Writes become a dual write, handled reliably with an outbox or CDC (see the high-level design). The two views can briefly disagree after a follow (milliseconds to seconds), which is acceptable.
Best: sharded edge storage plus a graph-aware cache and counters.
- Cache "does A follow B" and follow lists. A write-through cache keyed by
(user, direction)holds the list, or for huge lists a membership structure. "Does A follow B?" can be answered from A's following list (usually small; 200 entries on average), so cache that list per active user. Facebook's TAO paper ("TAO: Facebook's Distributed Data Store for the Social Graph", Bronson and others, USENIX ATC 2013) describes a read-optimised, geographically distributed cache for objects and associations of this kind, serving very high read rates with a tiered cache over MySQL. - Counters separate from edges. Follower counts are read on every profile view. Maintain them as counters updated asynchronously from the follow event stream, rather than counting rows. Celebrity follower counts can be shown approximately ("612M").
- Bucket huge follower lists. A celebrity with 600 million followers has a followers list of about 600 million rows. Bucket it so no single partition is enormous, and let fan-out and listing jobs read buckets in parallel.
- Private accounts. A follow request creates an edge in state
requested. Approval flips it toactiveand triggers feed backfill. Visibility checks must consult state, not just existence. - Blocks and mutes. Blocking removes follow edges in both directions and adds a block edge consulted at read time. Muting keeps the follow but excludes posts from the muted user's feed at read time.
Follow and unfollow side effects. On follow, backfill a few recent posts from the new followee into the follower's feed so it is not empty. On unfollow, either remove the followee's posts from the precomputed feed (a scan of up to 500 ids, cheap) or filter at read time. On a private account removing a follower, filtering at read time is mandatory, because a stale precomputed feed must never leak private posts.
For multi-hop questions ("people you may know", shortest paths), a native graph database or a graph-processing system helps; see the social graph case study and Graph Databases.
8) How do we generate the feed with under 500 ms latency?#
The feed is the heart of the read path. The news feed case study covers this problem in full depth; here is the design and the Instagram-specific angles.
Basic: fan-out on read (pull). At request time, fetch recent posts from each followee and merge. With 200 followees on many shards, this is a scatter-gather of 200 reads per page view at 350,000 page views per second: 70 million reads per second, with tail latency set by the slowest shard. It misses 500 ms at p99 and costs a lot.
Better: fan-out on write (push). When a user publishes, fan-out workers append the post id to each follower's precomputed feed list. Reading is one list read plus hydration. Write cost is the follower count: an average user with 200 followers costs 200 small writes per post. At 1,200 posts per second × 200 followers on average, that is about 240,000 feed-list writes per second, which is easy for an in-memory store spread over many nodes.
The problem is celebrities. One post by an account with 600 million followers would require 600 million writes, taking many minutes even at high throughput, delaying everyone else's fan-out in the same queue, and wasting writes on followers who will not open the app before the post is buried.
Best: hybrid fan-out plus precomputation only where it pays.
- Push for normal accounts. Accounts below a follower threshold (for example 100,000 to 1 million) fan out on write.
- Pull for celebrities. High-follower accounts do not fan out. Each celebrity has a small, heavily cached list of their recent post ids. At read time the Feed Service fetches the recent posts of the (few) celebrities the viewer follows and merges them with the precomputed list. Even a user following 50 celebrities adds only 50 cache reads, typically batched into one multiget.
- Only precompute for active users. About 500 million of perhaps 2 billion accounts are active on a given day. Fan-out skips users who have not opened the app in, say, 30 days. When an inactive user returns, their feed is built on demand with fan-out on read (slow once, then cached), and they are added back to the active set. This saves most of the fan-out writes and cache memory.
- Precompute ahead and refill in the background. The same idea used for dating apps applies: keep a cached, ready-to-serve stack of items so the first screen is instant, and refill it before the user runs out. When the user is a few posts from the end of what is cached, fetch and merge more in the background, so the feed feels infinite.
- Bound staleness with tunable parameters. Cached feeds can go stale (a post deleted, a user blocked, a followee made private). Filter at read time for correctness, and give feed entries a TTL so abandoned feeds expire. Expose knobs (feed length kept per user, activity window for precomputation, celebrity threshold, TTL) that operators can tune without redesigning the system. Systems with good knobs are easier to keep healthy as the scale changes.
- Hydrate from caches. Post bodies, author profiles and counts come from caches with very high hit rates. Use batched multigets and keep the number of sequential round trips small (about two or three).
Pagination. The cursor encodes the position in the precomputed list and the celebrity merge (for example the time and id of the last post returned), so the next page continues precisely. New posts arriving at the top do not shift the cursor, unlike offsets. See Pattern: Scaling Reads and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
Fan-out mechanics. The publish event goes onto a partitioned stream (Kafka). Fan-out workers read the author's followers in pages of a few thousand, filter out inactive users, and pipeline LPUSH and LTRIM commands (or the equivalent) to the feed cache shards. A post from an account with 50,000 followers completes fan-out in well under a second. Separate queues or priority lanes for large fan-outs keep them from delaying small ones.
9) Chronological or ranked feed?#
The requirements say chronological, which is simpler and predictable. It is worth knowing what changes with ranking, because interviewers often ask.
Chronological. The feed is the merge of followees' posts by time. Easy to explain, easy to debug, cacheable as a list. Its weakness is that people who follow hundreds of accounts miss most posts, and the posts they would care about most (a close friend's wedding) can be buried by frequent posters.
Ranked. Instagram moved from a purely chronological feed to a ranked one in 2016, and in 2022 added options to view a chronological "Following" feed and a "Favorites" feed alongside the ranked home feed. A ranked feed is generated in stages:
- Candidate generation. Take recent posts from followees (the same precomputed list, a bit longer, for example the last few days or 500 to 1,000 posts).
- Feature lookup. For each candidate: author-viewer affinity (how often the viewer interacts with this author), post age, post type, early engagement, the viewer's preference for photos versus videos.
- Scoring. A model predicts the probabilities of actions (like, comment, save, share, dwell time) and combines them into a score.
- Re-ranking and rules. Diversity (do not show five posts from one author in a row), freshness boosts, integrity demotions, and inserted ads or recommended posts.
Ranking adds a model-serving tier and feature stores, and makes caching harder (rankings change as engagement arrives), so systems often cache candidates and re-rank on each request in tens of milliseconds. See ML System Design and Feature Stores. A good interview answer: build chronological first, keep the candidate list generic so a ranker can be inserted later, and note that ranking changes caching and latency budgets.
10) How do we count likes and comments on hot posts?#
Every feed item shows a like count and a comment count, so counts are read on nearly every request (350,000 feed pages per second × 10 posts = 3.5 million count reads per second). Likes arrive at about 115,000 per second on average, and one viral post can take tens of thousands of likes per second.
Bad: SELECT COUNT(*) at read time. Counting rows in the likes table for every post on every feed page is far too slow: a post with 10 million likes means scanning 10 million rows.
Okay: a counter column incremented in the same transaction as the like. UPDATE post_counters SET like_count = like_count + 1 WHERE post_id = ?. Reads are cheap. But every like on a hot post updates the same row. Row locks serialise them, and a single database row can take perhaps a few thousand updates per second before lock contention and replication lag become problems. A celebrity post getting 30,000 likes per second will throttle the database and slow every like. This is a classic contention problem; see Pattern: Dealing with Contention.
Good: sharded counters. Split a hot post's counter into N sub-counters (like_count:{postId}:{0..N-1}) and increment a random one. Reads sum the N values (cheap, and cacheable). With N = 64, each sub-counter sees 1/64 of the write rate. Make N adaptive: 1 for ordinary posts, larger for posts detected as hot. Redis INCRBY on in-memory sub-counters handles very high rates, with periodic persistence to the database.
Great: idempotent like records plus asynchronous, batched aggregation.
- Record the fact idempotently. Insert
(post_id, user_id)into the likes table (a wide-column store is ideal: partition by post id, cluster by user id). A duplicate insert is a no-op, so a double tap or a retry never double counts. Unlike works the same way with a delete. - Emit a change event only when a row is actually inserted or deleted (via CDC or the service).
- Aggregate in a stream processor. Consumers partitioned by post id sum +1 and −1 events per post over a short window (for example 1 to 5 seconds) and apply one
INCRBY deltaper post per window to the counter store. 30,000 likes per second on one post become one increment per second. See Pattern: Scaling Writes and Apache Flink and Stream Processing. - Serve counts from cache. Counts are read from a cache refreshed by the aggregator. Displayed values are rounded for large numbers ("1.2M likes"), which hides small lags.
- Reconcile. A periodic job recounts likes for a sample of posts (or all posts above a threshold) from the likes table and corrects drift caused by lost events.
- "Did I like this?" is a separate question answered by the
user_likestable (or a per-viewer cache of recently liked post ids), batched per feed page.
Read-your-own-writes. The viewer who liked a post sees the heart filled and the count +1 immediately, because the client updates locally. Other viewers see the new count a second or two later. That matches the requirements.
Comments. Comments are writes of real content (they must be stored durably and shown in order), but their counter works exactly like likes. Comment lists are partitioned by post id and paginated by cursor; very popular posts get a "top comments" ranking so the first screen shows the most relevant comments, not just the newest. Hot comment threads on celebrity posts can use the same techniques as the live comments case study (caching the first page, write sharding).
Hidden like counts. Instagram tested hiding like counts in 2019 and in 2021 gave users the option to hide them. That is a product decision, but it shows that exact public counts are not essential, which supports approximate or lagging counts.
11) How does the system scale to 500 million daily users?#
Most components already scale horizontally. The scaling work is in how data is partitioned, how reads are absorbed by caches, and how the system spans regions.
Shard by user, with logical shards. Posts, media metadata and follow lists are sharded by user id (author for posts, follower or followee for the two follow tables). Using thousands of logical shards mapped to a smaller number of physical servers means you can rebalance by moving logical shards between machines, without rehashing every row. Ids that embed the logical shard (as in Instagram's scheme) let any service route a lookup by id without a directory. See Partitioning and Sharding and Consistent Hashing.
Caches absorb reads. Post bodies, user profiles, follow lists, counters and feeds are all cached (Memcached or Redis), with hit rates above 95% for hot data. The database serves mostly cache misses and writes. Watch for the classic cache failure modes: thundering herds when a hot key expires (use request coalescing or "lease" mechanisms, as Facebook described in "Scaling Memcache at Facebook", NSDI 2013), hot keys (replicate them or cache them locally in the service for a second), and stale data after writes (invalidate on write, or update via CDC). See Cache Failure Modes: Stampedes, Hot Keys and Penetration and Distributed Caching with Redis and Memcached.
Read replicas and regional copies. Metadata databases have read replicas in each region. Writes go to the shard's primary (in its home region), and replication delivers them elsewhere within about a second. After a user posts, their own subsequent reads are routed to the primary or served from the local cache that was updated on write, to give read-your-own-writes. See Database Replication and Consistency Models.
Multi-region. Run full stacks in several regions. Users are served by their nearest region for reads; writes for a user go to that user's home region. Media uploads land in the nearest storage region and are replicated asynchronously; the CDN serves media globally regardless of where it is stored. A region failure fails users over to another region with replicas of their data, accepting that the last few seconds of writes may be delayed. See Multi-Region and Global Data.
Asynchronous everything that can be. Media processing, fan-out, counters, notifications, search indexing, and analytics are all consumers of event streams. The synchronous path for a post is just "create draft, sign URLs, mark complete". The synchronous path for a feed read is just cache reads. Everything else can lag, retry and scale independently. See Event-Driven Architecture.
Load and capacity planning. Daily peaks follow time zones, and global events (New Year's Eve, major sports finals) produce posting spikes several times the norm. Plan headroom for the peak, autoscale stateless tiers on CPU and queue depth, and pre-warm caches and CDN capacity for predictable events. See Capacity Planning and Load Testing.
A real-world note. Instagram's early engineers described their stack publicly: Django (Python) application servers, PostgreSQL sharded into thousands of logical shards, Redis and Memcached, on AWS. Instagram was acquired by Facebook in 2012 and later moved from AWS into Facebook's data centres, which they wrote about in 2014. They have also written about running one of the largest Django deployments and about tuning Python's garbage collection to improve memory efficiency (2017). The lesson for interviews: a mainstream stack, sharded carefully and cached heavily, scales a very long way.
12) What changes for stories, search and Explore?#
These are below the line, but a good answer sketches how the design extends.
Stories (ephemeral content). A story is a photo or short video visible for 24 hours. Upload and processing are identical. Differences:
- Expiry. Store stories with a TTL (Cassandra and DynamoDB support per-row TTLs) and use object-storage lifecycle rules to delete media after the window (plus any retention needed for the author's archive, if the product offers one).
- The story tray. The row of avatars at the top is a per-user list of followees with unseen active stories, ordered by affinity. It is a feed of authors, not posts, recomputed often because it changes as stories expire and are viewed.
- Seen state. Track which stories each user has seen (a per-user set with a 24-hour TTL), so the tray shows unseen ones first. This is a high write rate: every view is a write.
- Prefetch. When the user opens the tray, prefetch the first few stories of the next few authors, because users tap through rapidly.
Search for users, hashtags and places. Index users (username and display name), hashtags (with post counts) and places in a search engine such as Elasticsearch, fed by change events from the metadata stores. Username search is a prefix and typo-tolerant problem (see the search autocomplete case study); hashtag pages are feeds of posts with that tag, sorted by recency or popularity, stored as per-hashtag lists much like per-author lists. See Elasticsearch and Search Systems.
Explore (recommendations). Explore shows posts from accounts you do not follow. It is a recommendation system: candidate generation from embeddings and co-engagement (people who liked X also liked Y), ranking with a model, and filtering for integrity. Meta's engineers wrote about the Explore system in 2019, describing account embeddings and a multi-stage ranking funnel. It reuses the media and serving infrastructure but adds a large ML stack. See Vector Databases and Similarity Search.
Reels (short video). A full-screen, recommendation-driven video feed is a different product with different bottlenecks (video egress and the recommendation loop); see the short-video case study.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Uploads routed through API servers | Server fleet saturated by bytes, long requests, no resume | Presigned direct uploads to object storage, multipart and resumable uploads |
| Upload interrupted near the end | User restarts a 2 GB upload, abandons the post | Multipart parts with per-part retry, persisted client state, status endpoint, background transfers |
| Media stuck in processing | Post never publishes, author confused | Idempotent state machine, double completion signal, reconciler for stuck items, retries and dead-letter queue |
| Abuse of upload URLs | Storage used for arbitrary files, huge objects, malware | Scoped short-lived signatures, size and type conditions, quarantine bucket, decode validation, quotas |
| Celebrity new post | Millions of simultaneous media requests and origin overload | Immutable URLs, origin shield with request coalescing, edge caches, prewarming popular authors' new posts |
| Celebrity fan-out | Hundreds of millions of feed writes delay all fan-out | Hybrid: pull for high-follower accounts, push for others, priority lanes |
| Hot like counter | Row contention, throttled database, slow likes | Idempotent like rows, stream aggregation, sharded counters, cached rounded counts |
| Feed cache node failure | Feeds for some users missing or slow | Replicated cache, rebuild on miss via fan-out on read, request coalescing on rebuild |
| Stale precomputed feeds | Deleted or private posts shown | Read-time filtering for deletes, blocks and privacy; TTLs; tunable feed parameters |
| Cache stampede on hot keys | Database overload when a popular profile or post expires | Leases or single-flight refresh, jittered TTLs, local hot-key caches |
| Storage cost growth | Exabyte-scale bills | Tiering by age and popularity, erasure coding, efficient formats, regenerate rare variants lazily |
| Region outage | Users in that region cannot post or read | Multi-region stacks, replicas, CDN serves media from other regions, failover with bounded write delay |
What Interviewers Expect#
Mid-level#
- Clear requirements and a working design: post service, metadata database, object storage for media, follow table, and a feed.
- Know that media belongs in object storage, not the database, and serve it through a CDN.
- Use presigned URLs for direct upload once prompted, and explain why routing bytes through servers is a problem.
- Produce a basic feed with fan-out on read, and with some guidance move to precomputed feeds.
- Reasonable entities, API and data model; cursor pagination for the feed.
Senior#
- Drive the design quickly to the deep dives: presigned and multipart uploads with a state machine, image variants and formats, CDN caching with immutable URLs.
- Design the hybrid fan-out with a celebrity threshold, precompute only for active users, and explain hydration from caches within a 500 ms budget.
- Handle hot like counters with idempotent writes and aggregation or sharded counters.
- Shard metadata by user with time-sortable ids, store the follow graph in both directions, and use CDC to keep views consistent.
- Discuss trade-offs clearly: eager versus lazy variants, push versus pull, consistency of counts.
Staff+#
- Identify that the media path dominates cost and latency, and quantify it: ingress, storage growth, egress, cache hit rates.
- Design storage economics: tiering, erasure coding, format choices, regeneration versus storage, deduplication trade-offs.
- Make "render instantly" concrete across client and server: placeholders, right-sized variants, prefetching, origin shields, signed URLs for private media.
- Treat the pipeline as a set of event-driven workflows with idempotency, reconciliation and backpressure; explain failure handling end to end.
- Discuss evolution (from a monolith on one database to sharded services), multi-region topology, and operational concerns such as cost, abuse, privacy and deletion guarantees. The interviewer mainly listens and focuses rather than steers.
Deep Dive: The maths of a photo-sharing serviceShow
Popularity is Zipf-like, and that is why CDNs work. Views per post follow a heavy-tailed distribution: a small fraction of posts (from popular accounts, or viral ones) receive most views. When request frequency for the item of rank i is proportional to 1/i^s with s near 1, a cache holding the top fraction f of items captures a disproportionately large share of requests. For example, with s = 1 over 1 billion items, caching the top 1% (10 million items) captures roughly ln(10^7) / ln(10^9) ≈ 16 / 21 ≈ 77% of requests, because the harmonic sum grows logarithmically. Add recency (new posts are hot, old ones cold) and per-region locality, and edge hit rates of 90% or more for images are realistic. Lee Breslau and others analysed Zipf-like web request distributions and their consequences for caching in "Web Caching and Zipf-like Distributions" (INFOCOM 1999).
Byte hit rate versus request hit rate. CDNs report both. Videos are large and their popularity is also skewed, so a cache may have a high request hit rate on images but a lower byte hit rate on long-tail videos. Since egress cost is per byte, the byte hit rate is what the finance team cares about. Origin egress = total bytes × (1 − byte hit rate). Moving from 90% to 95% byte hit rate halves origin egress.
Storage growth and cost. At 2.3 PB of new media per day, a year adds about 840 PB of logical data. With replication factor 3 that is 2.5 EB of raw disk; with RS(10, 4) erasure coding (1.4 times), about 1.2 EB. At an illustrative $10 per raw TB per month for owned disk capacity (real figures vary widely), the difference between 2.5 EB and 1.2 EB is about $13 million per month, for one year's data alone. This is why storage efficiency is a staff-level discussion.
Format savings compound. If WebP saves 30% over JPEG on images, and 80% of image bytes are served as WebP, image egress falls by about 24%. At 1.4 Tbit/s, that is about 340 Gbit/s saved, continuously. Similar arithmetic justifies the CPU cost of better video codecs for popular videos: encoding cost is paid once per video, while savings accrue on every view. A video viewed 1 million times at 20 MB per view moves 20 TB; a codec 30% more efficient saves 6 TB of egress for that one video, which easily pays for minutes of extra encoding compute.
Fan-out write cost. Total fan-out writes per day = Σ over posts of (active followers of the author, if below the celebrity threshold). With 100 million posts per day and a median of perhaps 100 to 200 active followers per poster, that is 10 to 20 billion feed-list inserts per day (115,000 to 230,000 per second). Excluding the few thousand accounts above the threshold removes the extreme tail. Without that cut, one account with 500 million followers posting five times a day would add 2.5 billion writes on its own.
Feed latency budget. A 500 ms p99 target for the API, measured at the server, decomposes into gateway and auth (5 ms), feed list read (1 to 5 ms), celebrity merge (5 ms), hydration multigets (10 to 30 ms, two rounds), counts (5 to 10 ms), serialisation (5 ms). The p50 is about 50 ms. The p99 is dominated by tail effects: one slow cache node among the dozens touched by a multiget. With fan-out to k shards, the chance that at least one is slow is 1 − (1 − p)^k. With p = 0.5% and k = 40 shards, that is about 18%, which is why multigets should use hedged requests or replicas for the slowest shards, as described by Dean and Barroso in "The Tail at Scale" (Communications of the ACM, 2013).
Upload time. Time = size / throughput + per-request overheads. A 2 MB photo at 5 Mbit/s uplink takes about 3.2 seconds; resized on device to 1 MB, 1.6 seconds. A 1.9 GB video at 10 Mbit/s takes about 25 minutes; at 50 Mbit/s on good Wi-Fi, about 5 minutes. These numbers are why on-device compression, background uploads and progressive publishing matter more to user-perceived speed than server optimisations.
Counter aggregation savings. If a post receives L likes per second and the aggregator flushes every T seconds, counter writes fall from L per second to 1/T per second for that post. With L = 30,000 and T = 1, that is a 30,000 times reduction, at the cost of showing a count up to about T seconds stale.
Deep Dive: How Instagram and Facebook built itShow
This section collects what the companies' engineers have described publicly. Details change over time, so treat it as history and inspiration rather than a description of today's systems.
The early years. Instagram launched in October 2010 and grew extremely fast with a tiny team. When Facebook announced its acquisition in April 2012 (for about $1 billion), the company famously had around a dozen employees. Its engineering blog post "What Powers Instagram: Hundreds of Instances, Dozens of Technologies" (2011) described a pragmatic stack: Django on Python behind NGINX and Gunicorn, PostgreSQL for core data, Redis for feeds and other fast-changing structures, Memcached for caching, Amazon S3 for photo storage with CloudFront as the CDN, and asynchronous task queues for work such as fan-out. The theme was "use proven technology and keep it simple".
Sharding and ids. The 2012 post "Sharding & IDs at Instagram" explained why they did not adopt a separate id service: they wanted time-sortable 64-bit ids that encode the shard, generated where the data lives. Each PostgreSQL logical shard (a schema) generated ids from a PL/pgSQL function combining a millisecond timestamp, the logical shard id and a per-shard sequence. Thousands of logical shards were mapped to a small number of physical servers, so moving a logical shard to new hardware rebalanced load without changing ids.
Moving into Facebook's infrastructure. In 2014 Instagram engineers described migrating from AWS into Facebook's data centres, a large move of a running service with many machines. Afterwards Instagram could use Facebook's infrastructure, including its edge network and storage systems.
Python at scale. Instagram has written about running one of the world's largest Django deployments, and about engineering work to make Python efficient at their scale. One well-known 2017 post, "Dismissing Python Garbage Collection at Instagram", described disabling the cyclic garbage collector in their web workers to improve memory sharing between forked processes, gaining capacity. Later work included contributions to CPython performance and a performance-oriented fork, Cinder, which they open-sourced in 2021.
Cassandra. Instagram engineers have talked about running Apache Cassandra for high-write data (such as feeds, activity and messaging data) and in 2018 open-sourced "Rocksandra", a version of Cassandra with a RocksDB-based storage engine, reporting large reductions in tail latency.
Photo storage at Facebook. Haystack (OSDI 2010) and f4 (OSDI 2014), described in deep dive 6, are the published designs for Facebook's hot and warm blob storage. "An Analysis of Facebook Photo Caching" (SOSP 2013) studied the full serving path, from browser caches through edge caches and origin caches to Haystack, and showed how each layer absorbed traffic and where more cache capacity would help (notably that larger edge caches and collaborative edge caching would raise hit rates).
The social graph. TAO (USENIX ATC 2013) describes Facebook's read-optimised, geo-distributed store for objects and associations, built over sharded MySQL with layered caches, serving very high read rates with eventual consistency. It is the published model for serving follow graphs, likes and comments at this scale.
Caching. "Scaling Memcache at Facebook" (NSDI 2013) introduced techniques that every large feed system uses in some form: leases to prevent thundering herds and stale sets, regional pools, and invalidation driven by database commit logs.
The feed. Instagram's feed was chronological until 2016, when it moved to ranking. In 2022 Instagram added chronological "Following" and "Favorites" views. Meta has also written about Explore's recommendation system (2019), which uses account embeddings and a multi-stage ranking funnel.
Takeaways from the history. Start with boring, well-understood components. Shard early with ids that make rebalancing possible. Push media to object storage and CDNs from day one. Invest in storage efficiency and caching as the dominant costs. Adopt specialised systems (wide-column stores, custom blob storage, graph caches) only when a measured bottleneck justifies them.
Deep Dive: Inside the media processing pipelineShow
The pipeline turns an uploaded object into published variants. At about 4,000 photos and hundreds of videos per second at peak, it has to be robust to bad input, retries, partial failures and changing requirements.
Event intake. Storage notifications (object created) and client complete calls both produce a "media uploaded" event keyed by media id. Events go to a partitioned queue (Kafka partitions or SQS queues). Using the media id as the key means duplicate events for one media item land on the same partition, where a worker can detect that the job is already done.
Job model. Each media item gets a job record: input object key, requested outputs (variant list and pipeline version), attempt count, status and timestamps. Workers claim jobs with a lease (a visibility timeout in SQS, or a lease column with expiry). If a worker dies, the lease expires and another worker retries.
Idempotency. Outputs are written to deterministic keys (v/{mediaId}/{variant}.{format}). Re-running a job overwrites the same objects with identical results, so retries are harmless. The final "mark ready" update is conditional ("set status to ready where status is processing"), so a slow, duplicate worker cannot regress the state. See Idempotency and Safe Retries.
Poison inputs. Some files crash decoders (corrupt data, malicious inputs crafted to exploit image libraries). Run decoders in sandboxed processes with memory and time limits, so a crash affects one job, not the worker. After N failed attempts, move the job to a dead-letter queue, mark the media failed, and tell the client so the user can retry or choose another file. Image-decoding libraries have had serious vulnerabilities over the years, so sandboxing is a security control as well as a reliability one.
Priorities and lanes. Separate queues for photos (fast, small) and videos (slow, large), so a burst of long videos cannot delay photos. Within video, prioritise short clips and the first, lowest rendition, because they unblock publication. Backfills (re-encoding old content into a new format) run in a low-priority lane that yields to live traffic.
Backpressure and autoscaling. Scale workers on queue depth and age of the oldest message, not on CPU alone. If the queue grows faster than workers can scale (a global event, a regional outage elsewhere), degrade gracefully: produce only the essential variants first (for example feed-lg in WebP plus the placeholder), and generate the rest later.
Hardware choices. Image processing is CPU work that vectorises well (libraries such as libvips are fast and memory-efficient for resizing). Video encoding can use CPUs for the best quality per bit, GPUs or dedicated video encoding hardware for throughput and cost. Large video platforms, including Meta and Google, have described custom video transcoding chips; the trade-off is flexibility (software encoders improve continuously) against cost per encoded minute.
Pipeline versioning. Record the pipeline version that produced each variant. When you improve the encoder or add a format, new uploads get the new version immediately, and a backfill job upgrades old content, most-viewed first. Because variants are immutable and keyed by version or format, old and new coexist safely, and the API chooses the best available.
Safety integration. Hash matching against known illegal content runs before publication, and its results can block publication and trigger mandatory reporting processes. Classifier-based checks (nudity, violence, spam) may run before or shortly after publication depending on the risk and latency trade-off. Results are stored with the media so feeds and search can filter consistently.
Observability. Track end-to-end time from upload complete to published (p50 and p99 for photos and for videos), queue depth per lane, failure rate by error type and by client version (a bad app release can upload malformed files), and per-variant output sizes (a sudden rise suggests an encoder regression). See Observability: Logs, Metrics and Traces.
Deep Dive: Privacy, safety and securityShow
Location and metadata. Photos from phones often contain GPS coordinates and device details in EXIF. Strip them from every served variant. If the user tags a location explicitly, store it as structured metadata with its own privacy controls.
Private accounts. Visibility must be enforced on every read path: feed hydration, profile pages, comments, search results, notifications, share links and media URLs. A precomputed feed or a cached profile grid must never bypass the check, so the check happens at read time against current follow state. Media for private accounts uses signed, expiring CDN URLs.
Upload security. Short-lived, narrowly scoped presigned URLs; size and type conditions; quarantine buckets not exposed publicly; content validation by decoding; sandboxed decoders; malware scanning for any non-media files.
Account security and abuse. Authenticate every API call with short-lived tokens; detect automation (bots that mass-follow, mass-like or scrape) with rate limits and behavioural signals; protect against credential stuffing with multi-factor authentication. See Security Fundamentals for System Design.
Scraping. Public profiles are a scraping target. Rate limits per IP and per account, signed URLs with expiry for media, and limits on how deep unauthenticated users can browse all raise the cost of scraping.
Deletion and data rights. When a user deletes a post, it must disappear from feeds, profiles, search and caches quickly, and the media must be deleted from storage and purged from CDNs within a bounded time. When a user deletes their account, the same must happen for all their content, plus likes, comments and graph edges. Track every derived copy so the deletion pipeline is complete, and keep audit logs proving it ran.
Child safety and illegal content. Hash matching against known abusive images (such as PhotoDNA, developed by Microsoft and widely used in industry), classifier-based detection, reporting tools and human review are all part of a responsible photo platform, with legal reporting obligations in many countries.
Deep Dive: Walking through the failure casesShow
- The app dies after the upload but before calling
complete. The storage event still fires; the media moves touploadedand processing starts. When the app restarts, it finds the post already processing. - The storage event is delayed by minutes. The client's
completecall has already started processing. When the event arrives, the idempotent handler sees the job is done and ignores it. - Neither signal arrives (app killed mid-upload). The media stays
pending. After the URL expires, the reconciler checks storage: if the object exists, it starts processing; if not, it marks the mediaexpired, and a lifecycle rule cleans up any partial multipart upload. - A processing worker crashes mid-job. Its lease expires; another worker retries. Deterministic output keys and the conditional "ready" update make the retry safe.
- A file crashes the decoder every time. After a few attempts the job goes to the dead-letter queue, the media is marked
failed, and the user is asked to try again. Engineers inspect the dead-letter queue for patterns (such as a new phone's file format). - Fan-out workers fall behind during a posting spike. New posts appear in followers' feeds with a delay of seconds to minutes. The author sees their post immediately (local), and followers who open the profile see it directly. Fan-out catches up as workers scale.
- A feed cache shard fails. Users on that shard get their feed rebuilt by fan-out on read (slower, about 100 to 300 ms), written back to the replacement shard. Request coalescing ensures one rebuild per user even if they refresh repeatedly.
- A celebrity posts and the edge has no copy. Thousands of edges miss at once; the origin shield coalesces them into a handful of storage reads. Optionally, the system prewarms edges with the first variants of posts from very popular accounts as soon as they publish.
- The counter aggregator lags. Like counts update slowly, but likes are recorded durably in the likes table. When the aggregator catches up, counts converge. The reconciler fixes any drift.
- The metadata primary for a shard fails. A replica is promoted (seconds to a minute). Writes to that shard fail briefly, and clients retry with idempotency keys. Reads continue from caches and replicas.
- An object storage region is degraded. Uploads are redirected to another region's storage (the presigned URL points to a different endpoint). Reads continue from the CDN and from replicated copies.
- A bad app release uploads corrupt files. Processing failures spike for one client version. Alerts by client version catch it; the server can reject uploads from that version with a clear error until a fix ships.
Deep Dive: Evolving, operating and adapting the designShow
Stage 1: launch. One web framework app, one PostgreSQL database, an object storage bucket with a CDN, presigned uploads from day one (they are no harder than server uploads), a background job queue for resizing, and fan-out on read for feeds. This serves millions of users.
Stage 2: growth. Shard PostgreSQL by user with logical shards and time-sortable ids. Add Redis for precomputed feeds with fan-out on write, Memcached for objects, and read replicas. Add multipart uploads for video and a transcoding pipeline.
Stage 3: large scale. The hybrid celebrity model, counter aggregation, WebP and AVIF variants, origin shields, wide-column stores for high-write data, multiple regions, and event-driven pipelines for everything asynchronous.
Stage 4: very large scale. Custom blob storage or heavy use of erasure-coded tiers, private edge networks and ISP-embedded caches, ranking and recommendation stacks, hardware video encoding, and sophisticated integrity systems.
Testing. Load-test the upload path with realistic file sizes and network conditions (including throttled, lossy links), chaos-test processing by killing workers and injecting corrupt files, and verify the reconciler by dropping storage events deliberately. Measure feed latency under cache-node failure. See Capacity Planning and Load Testing.
Service level objectives. Examples: 99.9% of photo posts published within 10 seconds of upload completion; p99 feed API latency under 500 ms; 99.95% availability for feed reads; image time-to-first-paint under 300 ms at p75 on mobile (measured from the client).
Deploying. Stateless services roll out with canaries; processing workers drain their leases before shutdown; changes to variant formats are introduced behind flags and backfilled gradually. See CI/CD and Deployment Strategies.
Variants of the problem.
- Photo backup (Google Photos, iCloud Photos). Private by default, no feed, huge per-user libraries, deduplication across devices, search by content (on-device or server ML), and full-resolution originals kept forever. The upload and processing pipeline is the same; the read path is personal browsing and search, not a social feed.
- Pinterest-style boards. Content is mostly re-shared images from the web. Deduplication by perceptual hash matters a lot, the "follow" unit is a board or topic, and discovery is recommendation-driven.
- Ephemeral messaging (Snapchat-style). Media is sent to specific recipients and deleted after viewing. Storage is short-lived, encryption and deletion guarantees are central, and the feed is replaced by an inbox (see the chat system case study).
- Professional photography sites. Very large originals, high-quality colour management, licensing metadata and watermarking, with lower volumes.
Deep Dive: The client side of capture, upload and renderShow
Much of what makes a photo app feel fast happens on the phone, before and after the servers are involved. Interviewers increasingly ask about this, and it changes the server design. See Client, Mobile and Frontend Considerations.
Compress before you send. A modern phone camera produces 12 to 48 megapixel images of 3 to 12 MB. Nobody views a feed photo at that resolution. The client resizes to the largest size the service will ever serve (for example 1,440 px wide for feed posts) and re-encodes at a sensible quality, which typically cuts the upload to 300 KB to 1.5 MB. That is a 5 to 10 times saving in upload time, mobile data and storage. The trade-off: the service never sees the true original. For a social feed that is fine; for a photo backup product it is not, so backup services upload originals and process them on the server.
Start the upload early. Instagram engineers have described starting the upload while the user is still writing the caption and choosing filters. The client requests a presigned URL as soon as the user picks a photo, uploads in the background, and when the user taps Share only the small post-creation call remains. The perceived posting time drops from several seconds to almost nothing. The cost: some uploads are abandoned when the user cancels, so the server needs the lifecycle rules and reconciler described earlier to clean up orphaned objects. At a cancel rate of 10 to 20%, that waste is small compared with the user-experience gain.
Survive the network. Mobile networks drop, switch from Wi-Fi to cellular, and stall in lifts and tunnels. The client keeps a persistent upload queue on disk: each entry stores the local file path, the media id, the presigned URL (or the multipart upload id and the list of completed parts) and the retry count. On restart, the app resumes from the last completed part. Retries use exponential backoff with jitter, and the client asks for a fresh presigned URL if the old one has expired. Operating-system background transfer services (such as background URL sessions on iOS and WorkManager on Android) let uploads continue after the user leaves the app.
Show the post immediately. The app inserts the new post at the top of the author's own feed and profile using the local file, marked as "posting". When the server confirms publication, the client swaps in the server's media URLs. If processing fails, the post shows a retry button. This optimistic display explains why the author never sees the fan-out delay.
Render fast on the way back. The feed response includes, for each post, the aspect ratio (so the layout does not jump), a tiny placeholder (a blurred preview of a few hundred bytes, or a dominant colour) and a list of variant URLs with widths. The client picks the variant that matches the screen width times the pixel density, rounded up to the nearest available size. It prefetches images for the next few posts below the viewport, and cancels prefetches when the user scrolls quickly past them, so bandwidth goes to what the user will actually see.
Client caches. A memory cache of decoded bitmaps for the visible and nearby posts, and a disk cache of encoded images, typically a few hundred megabytes with least-recently-used eviction. Because media URLs are immutable (a new variant gets a new URL), the client never has to revalidate; a cache hit is always correct.
Adapt to the network. On a slow connection, the client asks for smaller variants, prefers lower video renditions, and delays autoplay. The feed API can return a "network class" hint, or the client measures throughput itself from recent downloads. A user on 2G should still see a usable feed, just with smaller images.
Video on the client. Short videos autoplay muted when they enter the viewport. The player starts with a low rendition for a fast first frame, then switches up as the buffer fills. Prefetching only the first one or two segments of upcoming videos gives instant starts without downloading whole files that may never be watched. The rest of the stream follows the adaptive bitrate logic covered in the video streaming case study.
Battery and data budgets. Every prefetch costs battery and data. A good client limits concurrent downloads (for example four to six), avoids prefetching on metered connections when the user has turned on a data saver, and batches analytics events (impressions, view times) into compressed uploads every few seconds rather than sending one request per event.
Deep Dive: Presenting this design in a 45-minute interviewShow
A strong answer spends time where the problem is distinctive. A suggested time budget:
- Minutes 0 to 5: requirements. Confirm the core features (upload photo or video, follow, feed, like and comment), the scale (hundreds of millions of daily users), the read-to-write ratio (very read-heavy), and the key non-functional goals: fast feed loads (under 500 ms), fast image rendering, durable media, eventual consistency acceptable for feeds and counts.
- Minutes 5 to 10: estimates. Uploads per second (thousands), storage per day (hundreds of terabytes including variants), feed reads per second (hundreds of thousands), and egress bandwidth (terabits per second at peak). These numbers justify presigned uploads, the CDN and the storage tiering.
- Minutes 10 to 15: entities and API. User, Post, Media, Follow, Like, Comment, FeedItem. The two-step upload API (request URL, then create post) is the important part.
- Minutes 15 to 25: high-level design. Draw the upload path (client to object storage directly, events to processing), the read path (feed service, caches, CDN), and the social path (follow graph, fan-out). Walk one photo from upload to a follower's screen.
- Minutes 25 to 40: deep dives. Pick two or three, ideally the ones the interviewer steers toward: large video uploads and processing, the feed and the celebrity problem, or counters on hot posts. For each, state the naive approach, why it breaks with a number, and the better design.
- Minutes 40 to 45: failure modes and evolution. What happens when processing falls behind, when a cache shard dies, when a celebrity posts. Mention what you would build first and what you would add later.
Common mistakes. Sending image bytes through the API servers; storing images in the relational database; ignoring variants and serving originals to phones; treating the feed as a simple join query at hundreds of thousands of reads per second; using a single counter row for likes on a celebrity post; and forgetting deletion and privacy on cached and precomputed data.
Key Takeaways#
- The distinctive part of Instagram is the media path. Never route bytes through application servers: issue presigned URLs and let clients upload directly to object storage, using multipart, resumable uploads for large videos. See Pattern: Handling Large Files and Blobs.
- Drive uploads with an idempotent state machine (pending, uploaded, processing, ready), two completion signals, a reconciler and lifecycle rules. See Pattern: Managing Long-Running Tasks.
- Process media into variants: several sizes, modern formats (WebP, AVIF), placeholders, stripped metadata and safety checks for images; an adaptive bitrate ladder with segments and progressive publishing for video.
- Serve media from CDNs with immutable URLs, origin shields and request coalescing, right-sized variants, placeholders and client prefetching, and signed URLs for private content. See Content Delivery Networks (CDN).
- Storage economics dominate at scale: tier by age and popularity, use erasure coding for warm data, and learn from Haystack and f4. See Object Storage and Blob Storage.
- Store the follow graph in both directions, each sharded by its leading id, kept consistent by CDC, with cached lists and counters. See Change Data Capture and the Outbox Pattern.
- Feeds use hybrid fan-out: push for most accounts, pull for celebrities, precompute only for active users, filter at read time and hydrate from caches. The news feed case study covers this in depth; see also Pattern: Scaling Reads.
- Like and comment counters need idempotent like records plus stream aggregation or sharded counters to survive hot posts. See Pattern: Scaling Writes and Pattern: Dealing with Contention.
- Shard by user with time-sortable ids that encode the shard, cache aggressively, and keep everything that can be asynchronous on event streams. See Unique ID Generation and Partitioning and Sharding.