Lesson 6 of 16
26. CDNs

26.5 How does purging work?

3 min read+10 XP

In the warehouse: A batch of biscuits has the wrong price printed. The company sends a recall notice to every warehouse: pull these cartons now. It can recall one product, or "everything from batch 42".

In the system: Sometimes a cached copy must go before its TTL ends: a wrong price, a takedown request, a broken image. Purging (invalidation) tells every PoP to drop it:

  • By URL: purge /books/42. Precise, but you must know every URL (and every variant: query strings, encodings).
  • By tag (surrogate key): the origin labels responses with tags, like Surrogate-Key: book-42 author-7. Purging book-42 drops the book page, its cover, the search snippet and anything else tagged with it. In the chapter's code, one tag purge removes both the book page and its cover.
  • By prefix or wildcard: /covers/*. Convenient, heavier.
  • Purge everything: a last resort; every PoP goes cold and the origin gets hit hard.

Better than purging, where you can:

  • Versioned URLs for static files: change the file name when the content changes. Old URLs can stay cached forever; new pages point to new URLs.
  • Short TTLs plus stale-while-revalidate for things that change often, so they refresh themselves.

Purges take a little time to reach every PoP (usually seconds, depending on the CDN), and browsers may still hold their own copy until their max-age runs out. A CDN purge can't reach into users' browsers, which is another reason to keep browser TTLs short for content that might change.

Memory code: "Recall by product or by batch, but better to change the label than chase the cartons."