Object storage, CDNs and search

Three components that each take a job off your service and leave you a copy of something. The copy is the cost.

11 min read🏗️ System Design Fundamentals

Three components that show up in most designs and rarely get thought about, which is how each becomes the thing that breaks. They share a shape: each takes a job away from your application server, and each introduces a copy of something.

Object storage: never through your service

The wrong design is the obvious one — the browser uploads to your API, your API writes to storage. It costs you the bandwidth twice, ties up a request thread for the length of a large upload, and puts a file-sized object through your heap.

The right design is a pre-signed URL:

  1. The client asks your API where to put a file.
  2. Your API checks permission, generates a pre-signed URL valid for a few minutes, and returns it.
  3. The client uploads straight to S3. Your service is not in the path.
  4. S3 fires an event, or the client calls back, and your service records the metadata.

Your API stays fast and small; the storage does what it is good at. The same works in reverse for downloads — a pre-signed GET means you authorise the download without proxying it.

Three details that decide whether it works in practice:

  • The metadata row is the system of record. The file is in S3, the row in Postgres says it exists, who owns it and its state. A file with no row is invisible; a row with no file is a broken link. Write the row on the callback, and reconcile.
  • Uploads fail halfway. Multipart upload for anything large, and a lifecycle rule that deletes incomplete uploads after a day — otherwise you pay for them forever.
  • Storage classes are the whole cost story. Standard, infrequent access, and archival differ by an order of magnitude. A lifecycle policy moving objects after 30 or 90 days is usually the single largest saving available in a storage bill.

A CDN, and the thing it is actually for

A CDN caches your content at hundreds of locations near users. The obvious benefit is latency; the one that matters more is that the request never reaches you at all.

For a static asset served a million times, the CDN serves it a million times and your origin serves it once. That is not a percentage improvement — it is the difference between needing an autoscaling group and not.

What decides whether it works is cache-control and cache keys, which is the HTTP caching lesson applied at a different layer:

  • Cache-Control: public, max-age=31536000 plus a content hash in the filename. app.a1b2c3.js never changes, so cache it for a year; a new build produces a new name. This is why every front-end build tool hashes filenames, and it removes invalidation from your life.
  • Never cache a personalised response as public. The security lesson's incident shape: a CDN stores one user's response under a URL and serves it to everyone.
  • The cache key matters. If your response varies by a header — language, currency — the CDN must be told to vary on it, or users get each other's variant.

Invalidation is slow and rate-limited on every CDN. Designing so that you never need it — immutable URLs — is the difference between a deploy and an incident.

Search, and why it is never the system of record

Text search is a different problem from data retrieval, and a relational LIKE '%term%' cannot use an index, so it scans. That is fine at ten thousand rows and not at ten million.

An inverted index answers a different question: which documents contain this term, ranked by relevance. Tokenising, stemming, stop words, fuzzy matching and scoring are what you are buying, and none is expressible in SQL.

The architecture is always the same, and the direction is the important part:

plaintext
Postgres (the truth)  ──indexed into──▶  Elasticsearch (derived, rebuildable)

One direction. Search is never written to directly and never holds anything that is not in the store of record, because it can be rebuilt from scratch and must be — after a bad mapping change, a lost cluster, or a bug in the indexer.

Which leaves the design decision that actually matters: how the index is fed.

HowLagCost
synchronously, in the same transactionnoneyour write path now depends on the search cluster being up
an event, after commitsecondsthe write path stays independent; you must handle failure
a periodic batch reindexminutes to hourssimplest, and usually acceptable

The middle row is the usual answer, and it is the idempotency lesson again: the indexer must tolerate the same event twice, because at-least-once delivery is what you get.

What they have in common

All three take a job off your service and leave you with a copy of something. That copy is the whole cost:

  • The CDN has a copy of your asset, and it is stale until it expires.
  • Search has a copy of your data, and it is behind by the indexing lag.
  • Object storage has the file, and your database has a row claiming it exists.

So the questions to ask of each are the same two: how stale can this get, and who notices? And: what happens when the copy and the truth disagree? A design that has answers for those is a design that survives; one that assumes they agree will produce a bug report that reads "the search says it exists but the page 404s".

Under the hood: what a CDN edge actually decides on a cache miss, and how an inverted index answers a query

A CDN request is not "cached or not" — it is a decision made at one specific edge location, independently of every other edge. A user in Mumbai and a user in São Paulo hit different edge nodes, and a cache miss at one tells you nothing about the state at the other: the object may be warm at one edge and cold at the other for the same URL at the same moment, simply because nobody nearby has asked for it yet. On a miss, the edge does not have a copy to serve, so it fetches from the origin (or a regional mid-tier cache some CDNs place between edge and origin specifically to avoid every edge hitting the origin independently), stores the response according to the response's own cache headers, and serves it — which is why the first request from any given region is always an origin round trip, however aggressively the object is cached everywhere else.

Cache-Control directives are read literally, and the differences matter. max-age sets how long a response is fresh in seconds; s-maxage overrides max-age specifically for shared caches like a CDN, which lets an origin tell browsers "don't cache this long" while telling the CDN "cache this long" in the same response; stale-while-revalidate lets the edge serve a stale copy immediately while it fetches a fresh one in the background, trading a small staleness window for never making a user wait on a revalidation; private tells any shared cache — a CDN included — not to store the response at all, which is the header-level mechanism behind the "never cache a personalised response as public" rule above: it is not a CDN best practice you have to remember, it is a header the origin sets to make the mistake structurally unavailable.

An inverted index is a map from term to the list of documents containing it — the literal opposite of a normal index, which maps a document to its contents.

plaintext
forward index (what a row/document is):  doc 7 → "the quick brown fox"
inverted index (what search actually stores):
  "quick" → [7, 19, 42]
  "brown" → [7, 55]
  "fox"   → [7, 12, 42]

A search for "quick brown" becomes: look up the postings list for "quick", look up the list for "brown", and intersect them — document 7 is the only id in both, so it is the (unranked) result. Relevance ranking is a separate layer on top of that intersection, typically weighing how often a term appears in a document relative to how common it is across the whole corpus (the TF-IDF family of scores, or BM25, its more refined and widely used successor) — a term that appears in every document (like "the") is intersected the same as any other term but contributes almost nothing to ranking, because its presence says nothing about which document is a better match. Tokenising ("the quick" → ["quick"], dropping the stop word and lower-casing) and stemming ("running" → "run", so a search for one matches the other) both happen before the index is built, which is why re-tokenising with new rules means rebuilding the whole index rather than patching it — exactly the "derived, rebuildable, never the system of record" property the lesson's architecture diagram already states.

Try it yourself

Decide the cache-control header for three different endpoints

A site serves three kinds of responses: (1) /static/logo.a1b2c3.png, a hashed, immutable asset; (2) /api/products/42, a product page that changes a few times a day and is the same for every visitor; (3) /api/me, a per-user profile response. For each, decide whether a CDN should cache it at all, and if so, roughly how — using only the directives named above.

Why the three cases need three different headers, not three different CDN configurations

/static/logo.a1b2c3.png gets the longest possible cache: Cache-Control: public, max-age=31536000, immutable — the content hash in the filename means a change produces a new URL, so there is no staleness risk to bound, exactly the "never need invalidation" pattern the lesson names for hashed build assets. /api/products/42 is public (same for everyone) but does change, so something like Cache-Control: public, max-age=300, stale-while-revalidate=60 is reasonable: cache it at the edge for five minutes, and if a request arrives just after expiry, serve the stale copy while refreshing in the background rather than making that one unlucky user pay for an origin round trip. /api/me must never be cached by a shared cache regardless of how fast it changes, because it differs per user — Cache-Control: private, no-store (or at minimum private) tells every CDN and shared proxy in the path not to store it at all; getting this one wrong is exactly the incident shape the lesson calls out, where one user's response is served to everyone from a CDN that did not know the response was personal. The general principle underneath all three: the header is answering "is this the same response for anyone who asks" before it answers "how long is it good for" — staleness tuning only matters once shareability is settled correctly.

Misconceptions

  • "The CDN either has the file cached everywhere or nowhere." Caching is per-edge-location; a global purge does not mean every edge round-trips to origin at the same instant, and a cold edge in a low-traffic region can miss on a URL that is hot everywhere else.
  • "A search index needs to store the same rich data as the database, so results are complete." An index should store only what search needs to rank and identify a result (terms, maybe a snippet, the id) and fetch everything else from the system of record by that id — storing full rows in the index doubles the data you must keep in sync and makes "index is behind the database" a bigger and more visible problem when it happens.

Sources

  • Fastly and Cloudflare documentation on Cache-Control, s-maxage and stale-while-revalidate — the directives a CDN edge actually reads.
  • Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval — inverted indexes, tokenisation, and TF-IDF/BM25 ranking.
  • Amazon S3 documentation, "Uploading and copying objects using multipart upload" and "Using presigned URLs" — the upload pattern this lesson describes.
Progress is saved on this device and to your account when signed in.