Learning pathsPricingChecking sign-in…
Question Breakdowns

Instagram

Design photo publishing, processing, and a personalized home feed.

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 interviewerWhy 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.

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

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
URL: Uniform Resource LocatorNames a resource and access location. Normalize carefully and do not trust an imported address as a safe server fetch destination.
PK: Primary KeyThe 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

Contract / pseudocode
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

Contract / pseudocode
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

Three architecture decisions for Instagram, including the pressure each introduces.
Three architecture decisions for Instagram, including the pressure each introduces.
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.

Open original
Instagram · architecture decisions
Three architecture decisions for Instagram, including the pressure each introduces.

Three architecture decisions for Instagram, including the pressure each introduces.

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

Connected responsibilities for Instagram. Trace the authoritative and derived paths separately.
Connected responsibilities for Instagram. Trace the authoritative and derived paths separately.
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

Open original
Instagram · connected architecture
Connected responsibilities for Instagram. Trace the authoritative and derived paths separately.

Connected responsibilities for Instagram. Trace the authoritative and derived paths separately.

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

Instagram: baseline request paths.
Instagram · working baseline
Read the diagram

Upload → object storage → derivative workers; Ready media → post transaction → publish event; Feed candidates → authorization → media grants

Open original
Instagram · working baseline
Instagram: baseline request paths.

Instagram · working baseline

  1. Upload → object storage → derivative workers.
  2. Ready media → post transaction → publish event.
  3. Feed candidates → authorization → media grants.

Evolve the design under load

Instagram: additional scaling and recovery paths.
Instagram · scale and recovery paths
Read the diagram

Hybrid feed fanout → inbox and author timelines; Immutable derivatives → CDN caches; Like events → counter projection → display

Open original
Instagram · scale and recovery paths
Instagram: additional scaling and recovery paths.

Instagram · scale and recovery paths

  1. Hybrid feed fanout → inbox and author timelines.
  2. Immutable derivatives → CDN caches.
  3. 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

ChoiceBenefitCost
Direct multipart media uploadAPI does not stream huge bytesSession verification and cleanup
Hybrid fanoutHandles author skewRead merge and versioning
Immutable media renditionsCDN reuseLifecycle retention
Visibility recheckProtects stale candidate listsAuthorization 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.

Media readiness before post fanout. Creator to Media authority: Create upload session and transfer signed bytes; Transform worker to Media authority: Verify source; produce immutable generation-3 renditions; Creator to Media authority: Publish post linked to ready media generation 3; Media authority to Feed projector: Post/version event after publication commit; Feed projector to Feed projector: Project unique viewer/post candidates for ordinary author; Creator to Media authority: Retry same publish key returns original post
Media readiness before post fanout.
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

Open original
Media readiness before post fanout
Media readiness before post fanout. Creator to Media authority: Create upload session and transfer signed bytes; Transform worker to Media authority: Verify source; produce immutable generation-3 renditions; Creator to Media authority: Publish post linked to ready media generation 3; Media authority to Feed projector: Post/version event after publication commit; Feed projector to Feed projector: Project unique viewer/post candidates for ordinary author; Creator to Media authority: Retry same publish key returns original post

Media readiness before post fanout.

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.

Like/unlike transitions and private delivery. 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
Like/unlike transitions and private delivery.
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

Open original
Like/unlike transitions and private delivery
Like/unlike transitions and private delivery. 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

Like/unlike transitions and private delivery.

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.

One verified upload generation creates immutable thumbnail, feed, and detail renditions served through current edge authorization.
Publish verified renditions, then grant scoped media access
Read the diagram

Rendition identity includes generation and size; private delivery still checks current audience policy.

Open original
Publish verified renditions, then grant scoped media access
One verified upload generation creates immutable thumbnail, feed, and detail renditions served through current edge authorization.

Publish verified renditions, then grant scoped media access

Requirement trace and verification

RequirementImplementing design blockVerification 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

AreaDecision and signals
SLIsMedia processing age; failed derivatives; feed fanout lag; private-content suppression; CDN cache misses.
Overload limitsCap upload size/parts, derivative jobs, fanout batch size, and celebrity read-time merge candidates.
RecoveryRetry immutable media generation; rebuild feed candidates from post events; revoke new grants when privacy version changes.
Access controlsCheck current post audience before issuing media grants; isolate upload capabilities and user data.
Dominant costMedia 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.

Real-time Updates Redis

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.

Contract / pseudocode
media v8: verified complete
post p7: draft -> ready, references v8
feed f2: candidate p7
access revoked: filter p7; deny new media capability
media v8: verified complete; post p7: draft -> ready, references v8; feed f2: candidate p7; access revoked: filter p7; deny new media capability
Publish the post and protect the media separately
Read the diagram

media v8: verified complete; post p7: draft -> ready, references v8; feed f2: candidate p7; access revoked: filter p7; deny new media capability

Open original
Publish the post and protect the media separately
media v8: verified complete; post p7: draft -> ready, references v8; feed f2: candidate p7; access revoked: filter p7; deny new media capability

Publish the post and protect the media separately

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.

Instagram: 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
Instagram: a concrete state and recovery trace under the exercise assumptions.
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

Open original
Instagram: worked example
Instagram: 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

Instagram: a concrete state and recovery trace under the exercise assumptions.

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.

Your study notes