Instagram lets people upload photos, follow other people, and scroll a feed of the latest photos from the accounts they follow. Three things make it a classic interview question. First, the data is mostly big binary files (photos), which do not belong in a database. Second, it is extremely read-heavy: a photo is uploaded once and viewed thousands of times. Third, building each user's feed forces a real decision about who does the work, the writer or the reader, and that decision breaks down for accounts with 100 million followers. This lesson walks the eight-step interview framework and shows what to say out loud at each step.
Detailed Notes
How to use this lesson
Treat this as a 45-minute interview. The numbers below are assumptions you state out loud, not facts about the real Instagram. The interviewer will not check them; they will check that your estimates drive your design choices.
Step 1: Clarify Requirements
Spend the first five minutes turning "design Instagram" into a precise scope. A good opening: "Instagram has many features. Can we agree on the core ones, the scale, and what I can leave out?"
Functional requirements
A user can upload a photo with a caption.
A user can follow and unfollow other users.
A user can see a home feed: recent photos from the accounts they follow, newest first, loaded page by page.
A user can like (and unlike) a photo and see the like count.
A user can open another user's profile and see their photos.
Extended requirements
Mention these and ask whether to include them. Do not design them unless asked.
Comments, hashtags, search and explore recommendations.
Stories and video (video adds transcoding, which is a different lesson).
Notifications ("Maya liked your photo").
A ranked (machine-learning) feed instead of a chronological one.
Non-functional requirements
Low latency: opening the feed should feel instant. Target p99 (99 of 100 requests faster than this) under 200 ms for the feed API, and images starting to render within about 300 ms thanks to a CDN.
High availability: the feed and photo viewing must stay up, target 99.99% (about 52 minutes of downtime a year). Availability matters more than strict consistency here.
Eventual consistency is acceptable for the feed and like counts. A new photo appearing in a follower's feed a few seconds late is fine. A like count that lags by a second is fine.
Durability: once we confirm an upload, the photo must never be lost. Photos are people's memories.
Scalability: 100 million daily active users, billions of photos, petabytes of storage.
Reliable uploads on bad networks: mobile uploads often fail halfway, so they must be retryable.
Consistency decision. Say this early: uploads must be durable and a user must see their own new photo immediately, but other people's feeds and counters may be slightly stale. This is the per-operation view of consistency from the consistency lesson.
Out of scope
User registration and login, ads, direct messages, a recommendation model, and video. We will mention content moderation, but only as a step in the upload pipeline.
Interview tip. Candidates often start with "I'd store photos in a MySQL BLOB column." Ask first about scale and what the feed looks like. The scoping questions that matter here: chronological or ranked feed? Is there a celebrity-size account? Do we need video?
Step 2: Estimate Scale
Back-of-the-envelope estimation tells you which parts of the system will be hard. Round everything so you can do the arithmetic aloud.
Assumptions to state
100 million daily active users (DAU).
10% of them upload a photo on a given day, so 10 million uploads per day.
Each user opens the feed 10 times a day, and each feed load shows 10 photos.
Average user follows 200 accounts. A few accounts have 100 million followers.
An uploaded original is about 2 MB. We store four versions of every photo (explained below).
Each user likes about 5 photos a day.
A day has about 100,000 seconds, and the peak factor is 3.
Upload load
text
10M uploads per day / 100,000 s = 100 uploads per second
100 x 3 peak factor = 300 uploads per second at peak
300 uploads x 2 MB = 600 MB/s of incoming photo bytes at peak
So what? 300 uploads per second is modest for the API, but 600 MB/s of photo data would saturate our application servers' network cards. That is the reason to let clients upload directly to object storage instead of through our servers (Step 6.1).
Feed reads
text
100M users x 10 feed loads = 1 billion feed loads per day
1B / 100,000 s = 10,000 feed reads per second
10,000 x 3 peak factor = 30,000 feed reads per second at peak
30,000 feed reads x 10 photos = 300,000 photo-metadata lookups per second at peak
Uploads are 100 per second and feed reads are 10,000 per second, a 100 : 1 read-to-write ratio, and photo views are higher still. So what? Optimize reads: precompute feeds, cache metadata, push images to a CDN.
Storage per year
A phone sends a large original, but the app never shows it directly. We create smaller resolutions (versions): a large one for full-screen viewing, a medium one for the feed, and a small thumbnail (a tiny preview used in grids and lists). Four versions are stored:
text
Original 2 MB
Large 500 KB (1080 px wide)
Medium 200 KB (feed, 640 px wide)
Thumbnail 30 KB (grids, notifications)
Total about 2.7 MB, round to 3 MB per photo
10M photos per day x 3 MB = 30 TB per day
30 TB x 365 days = about 11 PB per year
Metadata: 3.65B photos x 500 bytes = about 2 TB per year
So what? 11 petabytes a year of blobs and only 2 TB of metadata. They need completely different storage: object storage (a service that stores files as objects by key, built for huge, cheap, durable storage) for the photos and a database for metadata. The original is 2 of the 3 MB and is rarely read after processing, so move originals to a cheaper archive tier after about 30 days.
CDN egress bandwidth
A CDN (content delivery network) keeps copies of files on servers close to users. Egress means data leaving our system toward users.
text
1B feed loads x 10 photos = 10 billion photo views per day
10B x 200 KB (medium version) = 2,000 TB = 2 PB per day
2 PB / 100,000 s = 20 GB/s average
20 GB/s x 8 bits = 160 Gbps average
160 Gbps x 3 peak factor = 480 Gbps at peak
A single data center link cannot serve that, and doing so from one region would be slow for far-away users. So what? Almost all photo bytes must be served from a CDN. With a 95% CDN hit rate, only 5% reaches our object storage: about 1 GB/s (8 Gbps), which is easy.
Instagram: Estimate the ScaleEstimation
Request load
100Mdaily active users
given
10Muploads / day
× 10% upload
100/suploads (300 peak)
÷ 100,000 s
1Bfeed loads / day
× 10 per user
10K/sfeed reads
÷ 100,000 s
30K/sfeed reads at peak
× 3 peak factor
Storage per year
~11 PB
10M photos/day × 3 MB (4 versions) × 365
Object storage for photos; archive old originals
CDN egress
160 Gbps
10B views/day × 200 KB = 2 PB/day; about 480 Gbps at peak
Serve images from a CDN; origin sees only 5%
Feed reads
10K/s
1B loads/day; 30K/s at peak, 300K metadata lookups/s
Precompute feeds and cache metadata
Key point. Photos are petabytes (object storage), views are hundreds of Gbps (CDN), and feeds are read 100x more than written.
Everything derives from 100 million daily users, 10% of whom upload and all of whom open the feed 10 times a day.
Other sizing checks
Likes: 100M users x 5 likes = 500M likes per day = 5,000 likes/s, 15,000 at peak. Each like row is about 24 bytes, so 500M x 365 x 24 B = about 4.4 TB a year.
Follows: 500M total users x 200 follows = 100 billion edges x 16 bytes = about 1.6 TB. Small enough to shard on a handful of machines.
Feed cache: store only photo ids, 500 most recent per active user: 100M x 500 x 8 bytes = 400 GB. That fits in the memory of a modest cache cluster.
Fan-out writes: 10M photos x 200 followers = 2 billion feed inserts per day = 20,000 inserts/s. Remember this number when we reach the celebrity problem.
Interview tip. Finish every estimate with "so what": "600 MB/s means direct-to-storage uploads", "480 Gbps means CDN", "11 PB means object storage, not a database."
Step 3: Define the APIs
An API is the contract between the app and our servers. All calls need Authorization: Bearer <token>.
Upload a photo (two steps)
Our servers never receive the photo bytes. The client first asks for permission to upload, then uploads directly to storage using a pre-signed URL: a temporary, signed link that lets the holder upload one specific object to storage without having storage credentials.
http
POST /v1/photos
Content-Type: application/json
Idempotency-Key: 7c1f0d2e-5b1a-4c55-9a4e-0f3b6f2a9d11
{ "caption": "Sunset at the pier", "content_type": "image/jpeg", "size_bytes": 2097152 }
The client then sends PUT <upload_url> with the bytes straight to object storage, and finally confirms:
http
POST /v1/photos/1832947100321792/complete
201 Created for the first call; 202 Accepted for complete (processing happens in the background).
400 for a bad content type or size over a limit (for example 20 MB); 401 if not logged in; 429 if the user uploads too fast.
Idempotency: a retry with the same Idempotency-Key returns the same photo_id instead of creating a second photo.
Read the feed
http
GET /v1/feed?limit=10&cursor=1832947100321792
json
{"photos":[{"photo_id":"1832947100321792","owner":{"user_id":"42","username":"maya","avatar_url":"https://cdn.example.com/a/42.jpg"},"caption":"Sunset at the pier","image_url":"https://cdn.example.com/m/1832947100321792.jpg","like_count":128,"liked_by_me":false,"created_at":"2026-11-28T10:15:00Z"}],"next_cursor":"1832947099871233"}
We use cursor pagination with the last photo id seen. Offset pagination (page=7) breaks when new photos arrive while you scroll, because every item shifts down and you see duplicates. A cursor means "give me photos older than this id", which stays correct.
Other endpoints
http
PUT /v1/photos/{photo_id}/like # idempotent: liking twice is the same as once
DELETE /v1/photos/{photo_id}/like
POST /v1/users/{user_id}/follow
DELETE /v1/users/{user_id}/follow
GET /v1/users/{user_id}/photos?limit=20&cursor=... # profile grid
How the API shapes the design
The feed call returns a list of photo ids plus their metadata, and image bytes are fetched separately from the CDN by URL. This split keeps our API servers out of the heavy byte-serving path.
Step 4: Define the Data Model
Start with the access patterns:
Get a photo by id (300,000/s at peak, mostly cache).
Get a user's latest photos by owner, newest first (profile page, and fan-out on read).
Who does user X follow? and who follows user X? (fan-out needs the second).
Has user X liked photo Y? and how many likes does Y have?
Get a user's precomputed feed (30,000/s at peak).
Fields and why each exists
photos.photo_id: a 64-bit, time-sortable id (Step 6.5). Sorting by id equals sorting by time, so we need no index on time.
photos.owner_id: who uploaded it; also the shard key for the photo table.
photos.storage_key: the object-storage path of the original; other versions are derived from it by naming convention.
photos.status: pending (waiting for bytes), processing, published, rejected. Only published photos are visible.
photos.like_count: a denormalized counter (a copy of a value we could compute from likes, stored for speed). Updated in batches.
follows: one row per follow edge, stored twice (by follower and by followee) because we query both directions.
likes: one row per (photo, user) pair. The primary key itself enforces "one like per user per photo".
feed: a per-user sorted list of photo ids, kept in an in-memory cache.
The Data ModelData model
photosSharded relational DB
PKphoto_idbigint
time bits + shard bits + sequence
IDXowner_idbigint
shard key; index with photo_id for profiles
captionvarchar(2200)
storage_keyvarchar(128)
path of original in object storage
statuspending | processing | published | rejected
like_countbigint
denormalized, flushed in batches
created_attimestamp
Sharded by owner_id; the shard number is embedded in photo_id.
usersSharded relational DB
PKuser_idbigint
UQusernamevarchar(30)
follower_countbigint
decides is_celebrity
is_celebrityboolean
skip push fan-out if true
last_active_attimestamp
skip inactive users in fan-out
Small table; username is unique so profile lookups by name work.
followsWide-column store
PKfollower_idbigint
partition key
SKfollowee_idbigint
who they follow
created_attimestamp
Also stored reversed (followee_id, follower_id) so fan-out can list a user's followers.
likesWide-column store
PKphoto_idbigint
partition key
SKuser_idbigint
primary key makes likes idempotent
created_attimestamp
Source of truth for who liked what; counters are rebuilt from it.
feed:{user_id}In-memory sorted set
SKphoto_idbigint
score = photo_id, so newest first
About 500 ids per active user. Rebuildable by pull, so loss is not data loss.
photos.owner_idusers.user_id· many to one
follows.follower_idusers.user_id· many to one
likes.photo_idphotos.photo_id· many to one
Key point. The photo id is time-sortable and carries the shard, so the primary key index serves both lookups and 'latest photos'.
Photo metadata is small and relational, likes and follows are huge and key-based, feeds are cached lists of ids.
Which database?
Reason from the access patterns:
Photo metadata and users: there are real relationships (owner, status transitions), the data is small (2 TB a year), and we want transactions and secondary indexes. A relational database (MySQL or PostgreSQL) sharded by owner fits. This matches the sharded relational setup the real Instagram used for years.
Follows and likes: huge row counts (billions to hundreds of billions), simple key-based access, no joins. A wide-column or key-value store partitioned by key scales out automatically and handles 15,000 writes/s easily.
Feeds and counters: need microsecond reads and fast increments, and can be rebuilt if lost. An in-memory store like Redis (sorted sets for feeds, counters for likes) fits.
Photo bytes: object storage, never a database. A BLOB column makes backups huge, wastes expensive database memory on files, and cannot serve through a CDN.
Trade-off thinking. One database for everything is simple but cannot be both cheap for 100 billion like rows and transactional for photo status. Polyglot storage (several stores, each matched to one access pattern) costs more operational work, but each store is simple and scales on its own.
Step 5: High-Level Design
Separate three concerns, because each has a different scaling profile: uploading and processing (bursty, heavy), serving images (huge bandwidth, cacheable), and building and reading feeds (high request rate, small payloads).
High-Level ArchitectureArchitecture
Key point. Keep heavy bytes off the application servers: uploads go direct to storage, images come from the CDN.
Bytes flow through object storage and the CDN. Our servers only handle small metadata requests.
Components and why each exists
API gateway / load balancer: single entry point for authentication, rate limiting and TLS. It spreads requests over identical, stateless servers.
Upload service: creates the photo record, issues the pre-signed URL, and confirms completion. It never touches photo bytes.
Object storage: the durable home of every photo version. It keeps multiple copies across zones.
CDN: serves images from servers near the user. On a miss it fetches from object storage (the origin) and keeps a copy.
Feed service: reads the user's feed cache, merges in celebrity photos, then loads photo and owner metadata.
Photo metadata DB: sharded source of truth for photos, users, follows.
Feed cache: precomputed list of photo ids for each active user.
Upload with a Pre-Signed URLRequest flow
Mobile appUpload serviceObject storageImage workers1POST /photoscaption, type, size2photo_id + signed URLrow saved as pending3PUT bytes (direct)multipart, resumable4200 OK5POST /completereturns 202 Accepted6object created eventvia queue7write 3 more sizes8status = publishedthen fan-out starts
Our service signs the permission; the photo bytes never pass through our servers.
Request flow
Upload.
The client asks the upload service for permission. The service inserts a pending photo row and returns a pre-signed URL.
The client uploads the bytes directly to object storage.
Object storage emits an event that goes to a queue; background workers process the photo (Step 6.2).
When processing finishes, the photo becomes published and is fanned out to followers' feeds.
View the feed.
The client calls GET /v1/feed. The feed service reads the first photo ids from the feed cache.
It adds recent photos from followed celebrities and merges by id.
It loads metadata for those ids from the metadata cache, falling back to the database.
The client receives JSON, then fetches each image from the CDN.
Step 6: Deep Dive
The interviewer will pick one or two areas. Cover the upload path and the feed in depth, and be ready for counters and sharding.
6.1 Direct-to-storage uploads with pre-signed URLs
If photos travel through our app servers, each server must hold a connection open for the whole slow mobile upload and relay 2 MB. At 300 uploads/s and 600 MB/s that wastes network and threads. With a pre-signed URL, our service signs a short-lived permission (valid about 15 minutes, for one exact object key, with a maximum size and content type), and the phone writes directly to object storage.
Why signed? Our service holds the storage credentials; the client never sees them. The signature proves we approved this one upload, and expires quickly.
Resumable uploads for bad networks. Large files use multipart upload: the client splits the file into chunks (for example 5 MB) and uploads each separately. If the connection drops, only unfinished chunks are retried. Object storage assembles the parts.
Why a separate complete call? The client could abandon the upload after getting the URL. The row stays pending, and a cleanup job deletes pending rows older than 24 hours, along with orphaned objects.
Validate what we received. The signed URL limits size and type, but the processing worker still decodes the image to confirm it really is an image. Never trust a content-type header.
Trade-off thinking. Proxying uploads through our servers gives easy validation and one place to log, but costs bandwidth and ties up servers. Pre-signed uploads scale to any size at the cost of an extra API call and validation after the fact. For photos, direct upload wins.
6.2 Asynchronous image processing pipeline
The user should not wait for resizing, so the pipeline is asynchronous: the upload is confirmed quickly, and the work happens later. Object storage publishes an "object created" event into a message queue (a durable buffer; producers append, consumers read at their own pace).
Key point. Every step is idempotent, because the queue delivers at least once and a photo may be processed twice.
A queue decouples uploading from processing. Failed messages end in a dead-letter queue.
A worker takes one message and:
Decodes and validates the image, and strips private metadata such as GPS location in EXIF data (the camera information embedded in the file).
Resizes it into the large, medium and thumbnail versions, written back to object storage under predictable names. Auto-rotate according to the camera orientation.
Moderates it: an automated check for banned content (a machine-learning classifier, plus matching against a list of fingerprints of known illegal images). Suspicious photos go to a human review queue.
Publishes: updates the row to published, then emits a photo.published event that triggers feed fan-out.
Why a queue and not a direct call? It absorbs bursts (a holiday can double uploads), lets us scale workers by queue depth, and survives worker crashes: an unacknowledged message returns to the queue and is retried. Delivery is at least once, so a photo may occasionally be processed twice. Make the steps idempotent: output keys are derived from photo_id, so writing the same thumbnail twice just overwrites it, and the status update is guarded by "only change processing to published". A message that fails repeatedly (a corrupt file) moves to a dead-letter queue (DLQ) for inspection, and the photo is marked rejected so the user is notified.
Processing takes a few seconds. Meanwhile the uploader sees their own photo immediately from the local copy on their device, a UI trick that hides the delay.
6.3 Serving images through a CDN
At 480 Gbps peak, the CDN does most of the work.
Immutable URLs. Each version has a URL that includes the photo id and size, for example /m/1832947100321792.jpg. A photo's bytes never change, so the CDN may cache it for a year. To edit or delete a photo, we remove it from the CDN with an invalidation request and set status, instead of overwriting.
Multiple resolutions. The client asks for the size matching its screen, saving bandwidth on phones and thumbnails in grids.
Origin shield. A second, regional cache layer in front of object storage means that if a thousand edge locations miss the same photo, the origin sees one request, not a thousand.
Hit rate. Newer photos are hot and old ones are cold (the long tail). We expect about 95% hit rate overall, so the origin handles around 8 Gbps.
Privacy. For private accounts, the URL is signed and short-lived, just like the upload URL.
6.4 Feed generation: fan-out on write, on read, or hybrid
Fan-out means copying one event to many recipients. When Maya posts a photo, every follower must eventually see it. Two simple strategies exist (the push-versus-pull lesson covered the general trade-off):
Feed Generation: Push, Pull or HybridComparison
Fan-out on write
push at post time
1
User posts a photo
photo becomes published
2
Look up followers
about 200 on average
3
Insert id into each feed
cached sorted lists
4
Reader fetches own list
one cheap lookup
Feed reads are one fast lookup
100M followers means 100M writes for one post
Wasted work for inactive followers
Great for normal accounts, fatal for celebrities
Fan-out on read
pull at view time
1
User posts a photo
only one row is written
2
Reader opens the feed
30K reads per second
3
Load all followed accounts
about 200 lookups
4
Fetch latest and merge
sort by photo_id
Posting is one write
No wasted work
Slow, heavy reads on the hot path
Cheap writes, too slow for every read
Hybrid
choose by follower count
1
Under 100K followers: push
skip inactive users
2
Over 100K: skip fan-out
flag is_celebrity
3
Read cached list
the push part
4
Pull celebrity photos, merge
usually under 10 accounts
Fast reads and bounded write work
Two code paths and a threshold to tune
What real systems do
Key point. Push for normal accounts, pull for celebrities, and skip users who are not active.
The celebrity problem breaks pure push; the read cost of pure pull breaks the feed API.
Fan-out on write (push). At post time, a worker looks up Maya's followers and inserts the photo_id into each follower's feed list in the cache. Reading is one cheap list lookup. The cost is write amplification: one photo causes many writes. At an average of 200 followers, that is 20,000 inserts per second in total, which is manageable.
Fan-out on read (pull). Nothing happens at post time. When a user opens the feed, the service loads the user's follow list, fetches each followed account's latest photos, and merges them. Writes are free, but each feed read does 200 lookups plus a merge, which is too slow and too heavy at 30,000 reads/s.
The celebrity problem. One account with 100 million followers posts a photo. Pure push would do 100 million inserts for that single post. At our 20,000 inserts/s capacity, that single photo would take about 80 minutes to fan out, and it would delay every other user's feed behind it in the queue. Also, most of those followers are inactive, so the work is mostly wasted.
Hybrid (recommended). Choose per account:
Accounts below a threshold (for example 100,000 followers) use push. This covers over 99.9% of accounts and keeps reads cheap.
Accounts above the threshold are not fanned out. They are flagged is_celebrity.
At read time, the feed service takes the pre-built list (push part), then fetches the latest photos of the few celebrities this user follows (pull part, usually under 10 accounts, each answered from a hot cache), and merges by photo id.
Skip inactive users in fan-out. If someone has not opened the app in 30 days, do not push to them. When they come back, rebuild their feed on demand with the pull method.
Other details:
The feed list stores only ids, capped at about 500 entries, which keeps memory to the 400 GB we estimated. Anything deeper is rebuilt by pull.
A sorted set keyed by photo_id makes merge and cursor pagination natural, because ids are time-ordered.
Unfollow and delete. On unfollow, lazily filter out photos from non-followed owners at read time. On photo deletion, the status check during metadata loading hides it, so we never need to scrub millions of lists.
Ordering. We assume a chronological feed. A ranked feed would add a scoring step after the merge, using the same candidate list.
Interview discussion. "I'd use a hybrid. For normal accounts I push the photo id into followers' cached feeds, so reading is one lookup. For accounts above roughly 100K followers I skip the push, because one post would cause tens of millions of writes, and instead merge their latest photos at read time. Inactive users are skipped and rebuilt on demand."
6.5 Sharding photo metadata and time-sortable IDs
At 2 TB a year the metadata fits on a few machines, but 300,000 lookups/s and the growth of users, follows and likes require sharding (splitting a table across machines). The key question is what to shard by.
Sharding Photo Metadata: Owner or Photo ID?Comparison
Shard by photo id
even spread
1
hash(photo_id) picks a shard
photos spread evenly
2
Lookup by photo id
one shard, fast
3
Profile page needs all photos of a user
asks every shard
4
Merge results
slowest shard decides latency
No hot shard from a busy user
Even storage
Profile and celebrity pull are scatter-gather
More load per request
Even, but expensive for per-user queries
Shard by owner id
locality per user
1
hash(owner_id) picks a shard
photo_id embeds the shard
2
Lookup by photo id
read shard bits, one shard
3
Profile page
single shard, primary key order
4
Hot celebrity shard
absorbed by cache and CDN
Single-shard profile and latest-photos queries
Time-sortable ids need no extra index
Uneven shard sizes
Needs caching for celebrity reads
Our choice, with 4,096 logical shards
Key point. Profile queries stay on one shard, and any photo id tells us its shard without a lookup.
We shard by owner and embed the shard number in a time-sortable photo id.
Shard by user id (owner). All of a user's photos live on one shard. Profile page and "latest photos of user X" (needed for celebrity pull) hit one shard. The risk is a hot shard: a celebrity's data is read constantly, and a prolific uploader makes one shard bigger. Mitigation: those reads are overwhelmingly served from cache and CDN, so the database sees little of it.
Shard by photo id. Photos spread perfectly evenly, so no hot shard. But "all photos of user X" must ask every shard (scatter-gather), and the slowest shard decides latency. A profile page would be slow and expensive.
Our choice: shard by owner, but embed the shard in the photo id. We want lookups by photo_id (most common) to know which shard to ask without a directory lookup, and we want ids sortable by time. Use a 64-bit snowflake-style id:
text
| 41 bits: milliseconds since our epoch | 12 bits: logical shard | 10 bits: sequence |
41 bits of milliseconds = about 69 years of ids
12 bits of logical shard = 4,096 logical shards
10 bits of sequence = 1,024 ids per shard per millisecond
The id generator is the database shard itself (or a small library inside the upload service): it combines the current time, the owner's shard number, and a per-shard counter. No central id server exists to become a bottleneck.
Time-sortable means a bigger id is a newer photo, so "latest 20 photos" is just ORDER BY photo_id DESC, using the primary key index, and cursors are just ids.
Logical shards are many small virtual shards (4,096) mapped onto a few physical servers (say 32 at first). When a server fills up, we move some logical shards to a new server without changing any id, avoiding the data reshuffle that "hash mod N" would cause. This is the same idea as the consistent hashing from the partitioning lesson, with a fixed table instead of a ring.
Replication. Each physical shard has a leader and two followers in different zones. Reads go to followers, except a user reading their own just-uploaded photo, who reads from the leader (read-your-writes).
6.6 Like counters
5,000 likes/s on average, but they are not evenly spread: a celebrity photo can receive thousands of likes per second.
Record the like. Insert (photo_id, user_id) into the likes table. The primary key makes it idempotent: a double tap or a retry inserts the same row once.
Count with a cache, not a row update. Only if the insert actually created a new row, increment a counter in Redis. Updating photos.like_count on every like would make one row a hot spot, the same problem as click counts in the URL shortener lesson.
Flush in batches. A background job writes the Redis counters to photos.like_count every few seconds.
Hot photos. One Redis key taking 5,000 increments per second can become hot. Split it into N sub-counters (say 16) such as likes:photo:ID:0..15; each like increments a random one, and a read sums them.
Display the count from Redis, falling back to the database. Exact accuracy is unnecessary; showing 1.2M instead of 1,203,417 is how the real app does it.
Recovery. If Redis loses counters, rebuild them from the likes table. The table is the truth; the counter is a fast cache.
liked_by_me is a per-user lookup: check the likes table (or a small per-user cache) for each photo returned in the feed.
Step 7: Bottlenecks and Failure Handling
Bottlenecks
Fan-out backlog.Cause: a burst of posts, or a big account just below the threshold. Mitigation: fan-out workers consume from a queue and scale by queue depth; prioritize active users; batch inserts.
Hot metadata rows.Cause: a celebrity's profile and latest photos. Mitigation: cache with a short TTL, replicate entries across cache nodes, add a small in-process cache on each server.
CDN miss storm.Cause: a new viral photo requested everywhere at once. Mitigation: origin shield and request coalescing (simultaneous misses for the same object produce one origin fetch).
Processing backlog.Cause: more uploads than workers. Mitigation: autoscale workers on queue age; show the user's own photo from the device meanwhile.
Storage growth.Mitigation: archive originals after 30 days, and delete versions of removed photos.
Failures
Upload fails halfway. The client resumes multipart upload. The pending row is cleaned up after 24 hours if it never completes.
Worker crashes while processing. The queue redelivers the message after a visibility timeout; idempotent steps make the retry safe.
Poison message (corrupt image). After 5 attempts it goes to the DLQ; the photo is rejected and an alert fires if the DLQ grows.
Feed cache node fails. Its users' feeds are rebuilt by pull on demand and refilled; replicate the cache across nodes to reduce misses. Rate limit rebuilds so the database is not flooded.
Metadata shard leader fails. Promote a follower. Writes to that shard pause briefly; cached reads and the CDN keep working, so most users notice nothing.
Object storage zone fails. Storage keeps copies across zones, so reads continue; the CDN also hides short outages for popular photos.
Graceful degradation. If feed generation is slow, return the cached part of the feed without celebrities, rather than an error. If the moderation service is down, hold photos in processing instead of publishing unchecked.
Interview tip. Pick two failure scenarios, say what the user sees, and say what you monitor: feed p99 latency, CDN hit rate, upload success rate, processing queue age, DLQ size, fan-out lag, and cache hit rate.
Solid arrows are synchronous requests. Dashed arrows are asynchronous or fallback paths.
Request flow
Upload: client, gateway, upload service (creates pending row, signs URL), direct PUT to object storage, complete call. View feed: client, gateway, feed service, feed cache plus celebrity merge, metadata lookup, JSON response, then images from the CDN.
Data flow
Photo bytes live only in object storage (and the CDN edge copies). Metadata lives in the sharded relational database. Follows and likes live in a key-based store. Feed lists and like counters live in the in-memory cache and can be rebuilt from the durable stores.
Background processing
Image workers resize, strip EXIF and moderate. Fan-out workers push published photo ids to followers' feeds. A counter flusher writes like totals to the database. Cleanup jobs delete stale pending uploads and archive old originals.
Critical design decisions
Pre-signed direct uploads, so photo bytes never touch application servers.
Object storage plus CDN for 11 PB a year and 480 Gbps of peak delivery; the database stores only metadata.
An asynchronous queue-driven pipeline for resize and moderation, made safe by idempotent steps and a DLQ.
Hybrid fan-out: push for normal accounts, pull for celebrities, skip inactive users.
Shard by owner with a time-sortable id containing the shard, so profile queries are single-shard and photo lookups need no directory.
Cached, batched like counters with an idempotent likes table as the truth.
If time remains, discuss a ranked feed (score candidates by recency, closeness to the poster, and engagement), multi-region deployment (replicate metadata, serve images from the nearest CDN, keep uploads in the home region), and video, which adds transcoding.