Practice: Instagram
Design media upload and publication plus a home feed that combines ordinary-account fanout with bounded read-time merging for very large creators.
Design media upload and publication plus a home feed that combines ordinary-account fanout with bounded read-time merging for very large creators.
Write your own design before opening hints or the solution review. The numbers below are exercise assumptions, not claims about any company’s production traffic. You may challenge an assumption, but record the replacement and explain which decision changes.
Scenario and constraints
- Assume 300 million daily users, 50 million media uploads per day, and a 10x peak publish burst.
- A post is visible only after its media object is verified and the post transaction commits.
- Feed pages contain at most 50 items with a stable cursor; privacy changes apply at read time.
- Originals and derivatives are immutable objects served through a CDN; likes are eventually consistent counters.
Your deliverables
- Define upload session, media generation, post, feed candidate, privacy version, and cursor identity.
- Calculate media bytes and feed fanout; separate object transfer, processing, publication, and distribution.
- Trace media processing through a READY gate, then commit post plus outbox before feed projection.
- Compare push fanout with pull for celebrity accounts; explain media authorization and cache freshness.
Reason about this sequence
Read the diagram
Post accepted → Thumbnail processing begins → Ordinary followers get candidates → Celebrity post uses read merge → Reader checks current audience
For every step, annotate what is durable, what the caller knows, and which identity survives a retry. Identify the point where two concurrent actors could disagree. Do not assume a timeout means failure or a cache value grants ownership.
Interviewer follow-ups
- A worker finishes a derivative after the creator deleted the post. What generation/version check prevents republishing it?
- A high-follower account posts during a feed request. How does the cursor avoid duplicates or skipped items?
- A private account changes visibility while a CDN URL is cached. What does the delivery path validate?
Answer each follow-up using the same design first. If it breaks, change the smallest boundary that repairs the invariant and explain the new cost. Show whether the change adds latency, storage, coordination, or operational work.
Staged hints
Hint 1 — reveal
Answer: Hint 1 — Commit a post only after verified media is ready, then use hybrid feed fanout and current privacy checks when reading candidates.
Hint 2 — reveal
Answer: Hint 2 — Post(id, author, audience, caption, original_ref, state, version) owns publication facts. MediaAsset(post, profile, object_ref, state) tracks thumbnail and renditions. Follow edges are authoritative; FeedCandidate(viewer, post, score_version) is rebuildable. Each object is immutable by version. Do not embed full follower lists or image bytes in a post row.
Hint 3 — reveal
Answer: Hint 3 — A private account disables visibility while stale feed rows remain. Filter using current relationship and audience state before returning text, captions, or media URLs. Expire or revoke controlled grants and remove candidate rows asynchronously. Keep an idempotent delete event and tombstone so a late fanout retry cannot resurrect the post.
Evidence-based self-review
- Unverified media cannot be published; immutable media generations and version fences reject stale workers.
- Post plus feed intent is durable and idempotent; hybrid fanout bounds celebrity work.
- Authorization is checked against current privacy state even when candidates or media are cached.
- Upload/processing capacity, feed queues, CDN grants, pagination, and counter lag are observable and bounded.
Score each item 0 if absent, 1 if named without an enforceable mechanism, or 2 if the mechanism and a failure are explained. Record evidence from your own diagram beside the score. Then choose one weak decision, revise it, and repeat the relevant follow-up. This rubric is a learning tool, not a hiring forecast.
Clarify this prompt before choosing components
Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.
| Ask the interviewer | Why the answer changes the design |
|---|---|
| Upload, follow feed, stories or direct messages first? | Ephemeral media, fan-out and messaging have distinct lifecycles. |
| Privacy, deletion and story expiry guarantees? | Serving policy must enforce them beyond cached media/feed references. |
| Upload sizes, follower skew and feed freshness? | Direct blob ingestion, asynchronous transforms and hybrid fan-out follow measured load. |
Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.
Reveal the full worked solution
Save your attempt before continuing.
Instagram: Understand the building blocks
Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.
Instagram: Quick vocabulary
| Term | Meaning and role in this exercise |
|---|---|
| API: Application Programming Interface | The contract for requests, responses and errors between components. An API route does not itself enforce every business invariant. |
| URL: Uniform Resource Locator | Names a resource and access location. Normalize carefully and do not trust an imported address as a safe server fetch destination. |
| PK: Primary Key | The declared row identity in a database schema; it does not automatically enforce every cross-row business rule. |
Instagram: Object storage, chunks and content hashes
What it means: Object storage keeps large named byte objects. Chunking divides a file into smaller pieces; content hashes identify or verify bytes under a specified hash protocol.
Why this problem needs it: Original media and derived outputs are too large for ordinary metadata rows.
How to use it: Upload to a versioned session, verify all required chunks and checksums, then atomically publish metadata referencing the complete manifest.
Example in this design: Upload generation 7 under an owned session and verify required outputs.
When it fits: Useful for resume, reuse or large bytes that should not flow through metadata database rows.
Alternative and limits: Whole-file upload is simpler for small files. A hash match or completed upload does not authorize publication or resolve a concurrent file revision.
Instagram: Transcoding and a dependency graph
What it means: Transcoding converts input media into required encoded outputs. A dependency graph records which validation/encoding/packaging steps must finish before publication.
Why this problem needs it: Devices need required media sizes/formats before publication.
How to use it: Create versioned jobs for required renditions, bound compute concurrency, retry failed attempts safely, and mark the manifest ready only after required outputs are verified.
Example in this design: A late generation-7 worker cannot publish over generation 8.
When it fits: Useful when uploads must play on different devices or at multiple bandwidth levels.
Alternative and limits: Serving an already compatible source can be a simpler baseline. A completed task does not imply all outputs or a newer input generation are ready.
Instagram: Content Delivery Network (CDN)
What it means: A CDN serves cacheable content from distributed locations nearer viewers, reducing repeated origin reads and network distance.
Why this problem needs it: Many viewers can share delivery of permitted immutable media bytes.
How to use it: Use stable versioned media URLs, a bounded cache policy, and the agreed signed-access or entitlement checks. Plan cold-cache and miss admission at the origin.
Example in this design: Serve a versioned rendition from an edge while checking the required visibility grant.
When it fits: Useful when many geographically distributed users fetch the same media bytes.
Alternative and limits: Direct object storage/origin delivery can fit a small workload. A CDN neither transcodes media nor independently knows every rights change.
Instagram: Access Control List (ACL) and current authorization
What it means: An ACL records which principals may perform specified actions on an object. Authorization evaluates the applicable current policy for this request.
Why this problem needs it: Feed/cache/media references may outlive privacy changes.
How to use it: Authenticate the caller, evaluate object/tenant membership and permission version at the required disclosure/mutation boundary, and declare caching/revocation behavior.
Example in this design: A cached candidate does not keep a revoked account’s access alive.
When it fits: Needed when object access can change while connections, projections or cursors remain alive.
Alternative and limits: Capabilities/signed grants can fit a bounded expiry policy. A valid cursor, cached candidate or open socket is not permanent permission.
Interview scope and guarantees
Upload photos, publish posts, follow accounts, read a feed and like posts. Media can process asynchronously; a visible post must reference a ready media version. Private-account access must be checked independently of cached feed membership.
Capacity worksheet
Assume 20 million uploads/day at 3 MB: 60 TB/day input. Four derivative sizes totaling another 3 MB add 60 TB/day. At 200 million feed opens/day and 20 images/open, there are 4 billion image fetches/day; byte delivery belongs at CDN edges.
Concrete API contract
POST /media/uploads -> {mediaId,uploadUrl}
POST /posts {mediaIds,caption,visibility} -> {postId}
PUT /posts/{id}/likes/me -> 204
GET /feed?cursor=...Data model and access paths
media(id PK,owner_id,state,source_key,derivative_manifest)
posts(id PK,author_id,visibility,created_at,version)
likes(post_id,user_id); UNIQUE(post_id,user_id)
feed_items(user_id,sort_key,post_id)Evolve a solution and explain each change
Read the diagram
Publish media / Store an immutable media object and commit an authorized post record. / A completed upload alone does not make a post visible.; Project feed candidates / Fan out ordinary accounts and merge high-fanout accounts at read time. / Fanout delays and duplicate events complicate feed completeness.; Deliver media privately / Use renditions and CDN delivery while enforcing current post visibility. / Cached thumbnails can leak after permission changes.
Step 1: Publish media
Store an immutable media object and commit an authorized post record. A completed upload alone does not make a post visible.
Step 2: Project feed candidates
Fan out ordinary accounts and merge high-fanout accounts at read time. Fanout delays and duplicate events complicate feed completeness.
Step 3: Deliver media privately
Use renditions and CDN delivery while enforcing current post visibility. Cached thumbnails can leak after permission changes.
Responsibility overview
Read the diagram
Viewer to Feed API: feed request; Feed API to Post DB: check post audience; Creator to Feed API: publish uploaded media; Post DB to Media worker: rendition intent; Media worker to Media origin: immutable output; Viewer to Media origin: authorized media grant
Worked end-to-end scenario
A creator uploads photo object o31, then publishes post p31 referring to it. If the publish transaction fails, o31 remains an unlisted upload eligible for safe later cleanup. After publication, the outbox updates follower candidates. A follower receives the candidate twice; the post ID makes projection insertion idempotent. Opening the feed rechecks current audience membership before issuing media grants. If the creator becomes private or removes the follower, an old feed candidate and cached thumbnail must not bypass the new policy. Likes and comments are separate records with their own uniqueness and moderation semantics.
Why these access paths matter
Posts are indexed by author and publication order; media keys include immutable rendition identity. Feed candidates are indexed by recipient. A unique user-plus-post like prevents duplicate likes, but a displayed count can be an asynchronous aggregate. Store comment pagination keys explicitly; do not use the current like count as an ordering identity.
Build the baseline first
Read the diagram
Upload → object storage → derivative workers; Ready media → post transaction → publish event; Feed candidates → authorization → media grants
- Upload → object storage → derivative workers.
- Ready media → post transaction → publish event.
- Feed candidates → authorization → media grants.
Evolve the design under load
Read the diagram
Hybrid feed fanout → inbox and author timelines; Immutable derivatives → CDN caches; Like events → counter projection → display
- Hybrid feed fanout → inbox and author timelines.
- Immutable derivatives → CDN caches.
- Like events → counter projection → display.
Defend the hardest decision
Do not publish a post just because an upload URL was issued. Verify the object, scan and transform it, then move media state to ready. Publishing checks ownership and readiness. Like is a set membership operation; using PUT makes repeated requests naturally idempotent. A displayed like count may lag while the user’s own like state comes from the authoritative relation.
Failure and recovery analysis
A user changes an account to private after its posts were fanned out widely. Inbox cleanup alone is too slow to enforce the boundary; filter access before returning metadata and media grants. Cached public media URLs complicate revocation, so the privacy promise and CDN authorization design must agree.
Security and privacy boundary
Validate file types and size, strip sensitive image metadata where appropriate, and prevent unauthorized media reuse.
Interview follow-ups with reasoning
Question: How do you delete a post?
Show answer and explanation
Answer: Tombstone source state, suppress serving, remove projections, then collect media after retention.
Question: How do you handle a viral image?
Show answer and explanation
Answer: Edge cache it while protecting metadata and counter paths.
Question: What happens when derivative generation fails?
Show answer and explanation
Answer: Show processing failure and allow a retry without duplicate posts.
Operate and verify the design
Media processing age, failed derivatives, feed freshness and private-content suppression.
Switch a public account to private during cache hits and verify that new access grants are denied.
A second scenario to test transfer
An ordinary author with 800 followers writes a post; precompute candidates. A celebrity with 30 million followers posts at once; defer that author’s fanout and merge recent posts for active readers. In both cases, the feed candidate is re-authorized before content is shown. One policy handles different fanout economics without weakening privacy.
A feed worker retries an old post event after the author has gone private. What prevents it from reintroducing visible content?
Show answer and explanation
Answer: Write candidates idempotently with the source version and treat them as references only. At read time, check current audience state before returning content or URLs. Propagate removals and reject stale versions to reduce work, but preserve the current authorization check as the visibility boundary.
Compare alternatives
| Choice | Benefit | Cost |
|---|---|---|
| Direct multipart media upload | API does not stream huge bytes | Session verification and cleanup |
| Hybrid fanout | Handles author skew | Read merge and versioning |
| Immutable media renditions | CDN reuse | Lifecycle retention |
| Visibility recheck | Protects stale candidate lists | Authorization read on feed path |
A design-changing exercise
The database denies a former follower but the CDN has a cached thumbnail. Is privacy enforced?
Show answer and explanation
Answer: Only if delivery checks authorization or a valid scoped grant. Cache residency does not grant access; define existing grant expiration separately.
Design workshop: publish media separately from feed candidates
Core scope is media posts, follow feed, likes/comments and private visibility. Stories, live video and recommendation training are extensions. Assume feed p95 under 200 ms and uploaded images playable within ten seconds under admitted processing load. Bytes uploaded is not post published; feed candidates are not permission to see media.
Add media(media_id,owner_id,source_key,generation,state), post_media(post_id,media_id,ordinal), follows(follower,author) with reverse author index, comments(id,post_id,author_id,request_key,state), and like_state(post_id,user_id,version,liked). Comments and likes carry stable request identities; current post visibility governs admission and reads. Post creation atomically attaches verified ready media and emits an outbox event. It never exposes a raw unverified upload as the final thumbnail.
Read the diagram
Create upload session and transfer signed bytes; Verify source; produce immutable generation-3 renditions; Publish post linked to ready media generation 3; Post/version event after publication commit; Project unique viewer/post candidates for ordinary author; Retry same publish key returns original post
Transforms validate type and dimensions, strip unsafe metadata under the chosen privacy policy and generate pinned sizes/codecs. Task identity is media/source_version/profile/generation; conditional publication rejects stale workers. Retained renditions use immutable paths. Cleanup needs live post/media references and a deleting state, not only old timestamps.
A hybrid feed pushes ordinary authors and pulls high-fanout authors during read. With one million followers and four posts/day, push produces four million candidate writes/day for one account. If only 5% read five times/day, pull creates 250,000 author merges/day, with different per-operation cost. Use measured thresholds and workload limits. The ranking service merges pushed IDs, pulled timelines and explicitly scoped recommendation candidates, then applies current ACL before hydration.
Read the diagram
Action / Authority change / Derived effect; First Like / false -> true under unique post/user / Count +1 once; Repeated Like / true -> true / No count change; Unlike / true -> false at newer version / Count -1 once; Old Like event after Unlike / Version rejected / No resurrection or second +1; Post made private / Permission version increases / Feed and media access revalidate current policy
Counter events contain old/new state and source version. A projector tracks the last applied version per like key, or recomputes on gaps; blindly incrementing for every queue delivery inflates counts. Comments use a durable edit/delete version with current authorization before snippets.
Private media delivery uses an edge/origin authorization boundary. A post going private invalidates controlled grants and caches, but already issued bearer URLs remain usable under their defined lifetime unless the delivery layer checks current permissions. Separate public and private cache policy; changing the application feed alone does not protect a directly accessible object URL. A CDN miss coalesces protected origin reads; the app API does not stream all image bytes.
Exercise: A like version 3 is delayed until after unlike version 4. The counter worker receives 4 then 3. What should it do?
Show answer and explanation
Answer: Resolve the state using source versions; ignore 3 after 4. If a gap prevents a valid delta, recompute that like's current source state and reconcile the aggregate. Final liked state is false, not the last arriving event.
Publish immutable media renditions
One verified upload generation creates immutable thumbnail, feed, and detail renditions served through current edge authorization.
Read the diagram
Rendition identity includes generation and size; private delivery still checks current audience policy.
Requirement trace and verification
| Requirement | Implementing design block | Verification link |
|---|---|---|
| R1 — Complete the primary user journey within the stated scope. | P01–P04; P09–P10. | V1 — Exercise the successful journey and the excluded/boundary case stated in the scope. |
| R2 — Preserve the problem's authoritative data invariant under concurrency. | P05–P06; P11–P12; DD1. | V2 — Run the race/replay case below and assert the invariant at the durable authority. |
| R3 — Meet the declared scale and API behavior without unbounded work. | P05–P08; P13–P14; relevant overload deep dives. | V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity. |
| R4 — Recover from the named failure without losing or duplicating the user-visible outcome. | P15–P16; deep dives; Operations contract. | V4 — Delay media processing, switch an account to private, and replay fan-out; no broken published assets or unauthorized feed content. |
Operational contract
| Area | Decision and signals |
|---|---|
| SLIs | Media processing age; failed derivatives; feed fanout lag; private-content suppression; CDN cache misses. |
| Overload limits | Cap upload size/parts, derivative jobs, fanout batch size, and celebrity read-time merge candidates. |
| Recovery | Retry immutable media generation; rebuild feed candidates from post events; revoke new grants when privacy version changes. |
| Access controls | Check current post audience before issuing media grants; isolate upload capabilities and user data. |
| Dominant cost | Media storage/CDN egress and image/video transformation compute. |
Senior-level interviewer follow-ups
Question: A private account changes visibility after media processing but before feed fanout finishes. What does the feed serve?
Show answer and explanation
Answer: Fanout stores references, and serving rechecks current relationship and media visibility. Versioned invalidation removes stale copies; derived feed state cannot authorize access.
Question: How do you prevent a thumbnail worker retry from overwriting a newer crop or moderation result?
Show answer and explanation
Answer: Write immutable renditions under a processing generation and publish a current pointer only if the generation and moderation state remain valid.
A 60-second design answer
I would upload media directly to object storage under a verified session, process immutable renditions, and publish only after moderation and metadata commit. The feed combines fanout for normal accounts with pull for high-fanout creators. Every media read checks current privacy authorization. I would monitor processing lag, rendition errors, feed fanout, cache invalidation, and CDN egress.
Related concepts to revisit
Technical references
Object-store multipart upload.
PostgreSQL transaction isolation and concurrent updates.
Publish the post and protect the media separately
Post p7 points to immutable media version 8. Upload/processing verifies that version before publishing p7 as ready. A worker that wrote only some renditions cannot make the post playable by updating a cached ready flag. Feed fanout then places p7 into follower candidates; a later permission revocation for f2 is checked at the read and media capability boundaries.
media v8: verified complete
post p7: draft -> ready, references v8
feed f2: candidate p7
access revoked: filter p7; deny new media capabilityRead the diagram
media v8: verified complete; post p7: draft -> ready, references v8; feed f2: candidate p7; access revoked: filter p7; deny new media capability
Hybrid celebrity/ordinary fanout trades write amplification for bounded read merging. Image/video delivery uses size-appropriate variants, CDN caching and explicit private-response rules; metadata requests should not carry all video bytes. Existing long-lived signed capabilities and client caches have declared lifetime/revocation limits rather than an impossible instantaneous-erasure promise.
Show answer and explanation
Answer: Deleting a feed row eventually is cleanup, not the only privacy mechanism. A previously visible card cannot authorize a new private-media download after current access is denied.
Decision review: Instagram
Instagram: What it is
A media-feed design publishes verified renditions and selects post candidates under the current audience policy.
Instagram: Why it is needed
An uploaded object is not a ready post, and a feed entry is not permission to issue a media capability.
Instagram: When to use it
Use immutable output generations for independent processing and controlled delivery when private media must be protected.
Instagram: How to use it
Pin source generation and processing policy, validate required outputs, publish post readiness conditionally and apply current audience checks before returning text or scoped media access.
Instagram: Compare an alternative
Publishing an initial supported rendition first can reduce time to readiness if the product permits later qualities. Requiring all outputs gives a stronger readiness contract at a longer delay.
Instagram: Worked decision exercise
The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.
Input generation 7 produces a thumbnail and feed rendition. The detail rendition is still missing. Under an all-required-output contract the post stays unpublished. A later generation 8 result cannot be overwritten by a delayed generation 7 worker.
Read the diagram
Source generation 7 produces verified renditions; Missing required detail output means not ready under policy; Generation 8 becomes current; old 7 cannot publish; Feed candidate and media grant need separate policy checks
If the account becomes private, does deleting its cached feed candidates revoke all already-issued URLs?
Show answer and explanation
Answer: Not automatically. Declare the capability expiry/revocation policy and what can be enforced at the media path. Recheck current audience before new grants; cached bytes already delivered to clients cannot be recalled by deleting a feed row.
Instagram: Check the design
Monitor processing age, incomplete required outputs, stale publication rejection and private-grant behavior. Test feed revocation separately from media authorization.
A feed worker retries an old post event after the author has gone private. What prevents it from reintroducing visible content?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.