If I build edge caching with Cloudflare Workers + KV, how do I do invalidation?
Question
Some endpoints of my API (e.g. dynamic price lists) don't change often but must return very fast from the location nearest the user. Instead of sending all traffic to origin (EC2), I want to handle requests at the edge with Cloudflare Workers and cache them in KV. How should I set up cache invalidation so that when a price changes at origin, the edge updates instantly?
Answer
Short answer: don’t rely on TTL alone — TTL is eventual and serves the stale price until it expires. Make invalidation push-based and event-driven.
In your scenario the unacceptable thing is the “wrong price” window. The fix is to push the change to the edge, not leave it waiting:
- Write-through (or purge) on change. The moment a price changes at origin, call Cloudflare’s API in the same transaction/outbox and write the new value into KV, or delete the key. That makes the update part of the write itself, not a separate “hope it runs” step.
- Treat KV as a cache, not the source of truth. Your source of truth is the origin DB; KV is a fast copy of it. This mindset lets you re-seed from origin whenever KV gets corrupted or inconsistent.
- Key by entity+version. Stamp each value with a version (like
price:42:v7). If the Worker sees an old version it can serve-stale-while-revalidate and refresh in the background; the user doesn’t wait, but doesn’t get the wrong value either. - Keep a short TTL as a safety net. If a push invalidation misses for some reason, a short TTL caps staleness to a few seconds at worst. Let TTL be the last line of defense, not the only one.
- Accept KV’s global eventual consistency. KV writes can take a few seconds to propagate worldwide; a small inconsistency window is unavoidable. If you need instant global correctness, KV is the wrong layer — go to origin or choose a different consistency model.
Bottom line: I’d set up the trio of write-through (or purge) on change + a short TTL safety net + versioned keys. A TTL-only solution is wrong for money-affecting data like prices; with push-based invalidation, the edge updates the instant origin changes. Design knowing KV’s seconds-long propagation window — use it as a fast, refreshable cache, not as the source of truth.
Comments
Sign in with your GitHub account to join the discussion. Comments are stored in GitHub Discussions.