SysDesignAtlas

Build an Image Host

Where the write path starts doing real work — direct uploads, async processing, and derivative generation without blocking the user.

HLDEasy8 min readlevel-1mediaasync
Confidence

#The product

Upload an image, get a URL. The image is served fast, worldwide, at whatever size the page needs.

Simple to state, and it introduces the pattern behind every media system in this atlas: the write path does work asynchronously, the read path does nothing at all.

#Estimation first

   1M uploads/day, average 3 MB original

   Writes:  10⁶ / 10⁵ s = 10 uploads/s avg → ~30 peak
   Storage: 1M × 3 MB   = 3 TB/day of originals
            + derivatives (~1 MB total across sizes)
            ≈ 4 TB/day → 1.5 PB/year

   Reads:   say 50 views per upload
            50M views/day / 10⁵ = 500 QPS avg → 1,500 peak
            at 200 KB served = 300 MB/s egress

What those numbers decided: 1.5 PB/year rules out the database immediately and makes storage tiering mandatory. 300 MB/s of egress (data sent out to viewers) is affordable from a CDN and expensive from your own origin. And the 50:1 read:write ratio says: spend effort on the write path so the read path can be trivial.

#Phase 1 — Don't proxy the bytes

The instinct is to POST the file to your API. Don't.

Instead, use a presigned URL: your server asks the object store for a temporary upload link that carries its own signature, and hands it to the client. Whoever holds that link can upload one file to one key until it expires — without needing your storage credentials.

   NAIVE
   client ──3MB──► app server ──3MB──► object storage
                    ▲
              your bandwidth, your memory, a request thread
              held for the entire upload

   PRESIGNED (correct)
   1. client ──► app: "I want to upload"
   2. app ──► client: signed URL + key (15 min, size/type capped)
   3. client ──3MB──────────────────► object storage  (direct)
   4. client ──► app: "done, key=X"
   5. app: VERIFY the object exists and matches, then write metadata

Your application tier never touches image bytes. It stays small, stateless, and unaffected by someone uploading over a slow mobile connection.

#Phase 2 — Derivatives, asynchronously

A page needs a thumbnail, not a 3 MB original. So every upload has to become several files — a thumbnail, a medium version, maybe a WebP variant. Those generated copies are called derivatives, and deciding when to make them is the whole of this phase.

Do not generate them on upload synchronously — that makes the user wait several seconds for work they don't need finished. And do not generate them on read — that makes the first viewer of every image wait.

   upload complete
        │ event
        ▼
   ┌─────────┐    ┌──────────────────┐
   │  Queue  │───►│  Worker fleet    │
   └─────────┘    │  · validate      │
                  │  · strip metadata│  ← EXIF holds GPS coordinates
                  │  · resize (4)    │
                  │  · re-encode     │
                  │  · scan          │
                  └────────┬─────────┘
                           ▼
                  derivatives → object storage
                  status = ready → database

The user gets an immediate response with status: processing, and the UI shows a placeholder. This is the queue pattern doing exactly what it's for. Without the queue, the slow work sits inside the user's request and they feel every second of it (a latency problem). With the queue, the user gets an answer instantly, and the only question left is whether you have enough workers to keep up with the backlog (a throughput problem) — which you fix by adding workers.

Workers must be idempotent — running the same job twice must leave the same result as running it once. The queue is at-least-once: it guarantees every message is delivered, but sometimes delivers one more than once (for example, when a worker crashes before confirming it finished). So the same image will be processed twice. Key the output on (image_id, size, version) so a reprocess overwrites rather than duplicating. See Idempotency.

#Phase 3 — Serving

   client ──► CDN ──miss──► object storage
              │
              └── 95%+ hit rate for popular images

Two rules that make this work:

Immutable URLs. Include a content hash in the key: /img/a3f9c2b1/800x600.webp. Now you can cache for a year with immutable, never invalidate anything, and a re-upload just creates a new URL. This is the single highest-leverage decision in the read path.

Serve modern formats with fallback. WebP/AVIF cut bytes substantially versus JPEG at equal quality. Browsers list the formats they support in the Accept request header, so you pick the format from that. But be careful: if the CDN uses the full Accept header as part of its cache key, every slightly different browser string gets its own cached copy, and your hit rate collapses. Normalize the header to a small set of buckets first — say "supports AVIF", "supports WebP", "JPEG only" — and cache one copy per bucket.

#Phase 4 — Cost

The trigger: you're storing 1.5 PB/year and the bill is the largest line item in engineering.

Access is extremely skewed over time — an image is viewed heavily for a week, occasionally for a month, essentially never after a year.

   Age            Tier                  Relative cost
   0-30 days      Standard + CDN            1×
   30-180 days    Infrequent access        ~0.5×
   180+ days      Archive                  ~0.1×
   Originals      Deep archive             ~0.03×

Lifecycle rules automate the transitions. Keep the originals — you'll want them when a better codec arrives and re-encoding the library becomes worthwhile.

#Phase 5 — On-the-fly resizing

The trigger: product wants arbitrary sizes, and pre-generating every variant means storing dozens of derivatives for images nobody views at that size.

Flip to generating on first request, at the edge, then caching:

   /img/a3f9c2b1?w=640 ──► CDN (miss) ──► resize service ──► origin
                            │                                  │
                            └──────── cached forever ◄─────────┘

The tradeoff: you trade storage for compute, plus a slow first request per variant. Right when the variant space is large or unpredictable; wrong when there are four known sizes and every one gets used.

Guard the parameter space. An open ?w= parameter is a denial-of-service vector — an attacker requests 10,000 distinct widths and you generate 10,000 derivatives. Allow-list the dimensions or sign the parameters.

#The decision log

DecisionRejectedBecause
Presigned direct uploadProxy through the APIKeeps bytes off the app tier; slow clients don't hold threads
Verify object after uploadTrust the client's callbackClients can claim files they never uploaded
Async derivative generationSynchronous on uploadUser shouldn't wait for work they don't need finished
Content-hash URLs, cached foreverMutable paths + invalidationInvalidation is unnecessary if URLs never change meaning
Strip EXIFPreserve itGPS coordinates in user photos is a privacy leak
Lifecycle tieringEverything in standardAt PB scale this decides whether the product is affordable

#What you'd cut for v1

Multiple formats, on-the-fly resizing, tiering, and a CDN. Ship: presigned upload, one thumbnail size generated async, served from object storage. Add the rest when the numbers demand it.

#Explaining the design

"The write path does the work and the read path does none. Uploads go directly to object storage via a presigned URL so my app tier never handles bytes — then an event triggers async workers to strip EXIF and generate derivatives. Reads are pure CDN, with content-hash URLs so I can cache immutably and never invalidate. At petabyte scale, lifecycle tiering to archive storage is what makes the economics work."

#Next

Build Instagram — the same media pipeline, now with a social graph and a feed on top.

#Check yourself

What is the media-system pattern the image host introduces?Show answer
The write path does work asynchronously; the read path does nothing at all.
Why use presigned uploads?Show answer
The client uploads directly to object storage with a short-lived, size- and type-capped signed URL, so the app tier never holds bytes or a thread for a slow upload.
Why must the server verify the upload before writing metadata?Show answer
A client can claim a file it never uploaded or point at someone else's key. Check existence, size, content type and ideally a committed checksum — a real vulnerability class.
How are derivatives generated?Show answer
An upload event goes to a queue; idempotent workers (keyed by image, size, version) validate, strip EXIF (GPS leaks), resize, re-encode and scan, then mark the image ready. The user sees "processing" meanwhile.
Why content-hash URLs?Show answer
A URL whose content never changes can be cached for a year as immutable with no invalidation; a re-upload simply gets a new URL.
Why is storage tiering a design constraint here?Show answer
At ~1.5 PB a year, moving older images to infrequent-access and archive tiers decides whether the product is affordable. Keep originals for future re-encoding.
What does on-the-fly resizing trade, and what must you guard?Show answer
Storage for compute and a slow first request per variant. An open width parameter is a denial-of-service vector — allow-list sizes or sign the parameters.

#What to carry forward

  • Keep bytes off the app tier with presigned uploads, and verify before trusting.
  • Generate derivatives asynchronously with idempotent workers.
  • Immutable content-hash URLs make the read path pure CDN.
  • Lifecycle tiering from day one at petabyte scale.
  • Resize on demand only when sizes are many and unpredictable — and guard the parameters.
00:00
/ 8m