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.
Short answer
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. This is a classic backend architecture decision: treat the cache as a speed layer and keep the source of truth at origin.
Why
-
TTL is a staleness bound, not an invalidation mechanism. Until it expires the edge keeps serving the old value; for money-affecting data that window is unacceptable.
-
KV is a cache, not the source. 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.
-
KV is globally eventually consistent. Writes can take up to 60 seconds or more to propagate worldwide; a small inconsistency window is unavoidable. If you need instant global correctness, KV is the wrong layer.
What to do
-
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.
-
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. -
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.
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.