case study · cloudflare-workers · admin-api · webhooks
The sync that keeps three surfaces honest
The job. Product pages on this store render promo pricing from metafields (that case study). Someone has to keep those metafields truthful as merchants create and delete discounts. That someone is a Cloudflare Worker — no server, one cron trigger, KV for state, short-lived API tokens minted per run through the client credentials grant (nothing long-lived stored anywhere).
The loop. Every five minutes: read active automatic discounts (function-backed discounts excluded — free shipping is not a product promo), expand their collections into a desired per-product state, diff against the products it manages, apply the difference. Discount webhooks only mark the store dirty so the next minute’s run reacts fast; the cron remains the single authority, so a missing or renamed webhook topic degrades reaction time, never correctness. Measured on this store: discount created → storefront showing struck prices in 62 seconds.
Three rails, each earned the hard way:
- Value-compare before every write. A product already in the right state
is untouched — which also breaks the loop where writing metafields fires
products/update, which would re-trigger the sync forever. - Managed-set bookkeeping. Cleanup only ever deletes metafields from products this system wrote to. It cannot strip data it doesn’t own.
- Clear-sweep safety ratio. A run that wants to remove promos from more than half of everything it manages (past an absolute floor) assumes upstream breakage — an API blip, a fat-fingered mass deletion — and aborts loudly instead of obeying.
The day the demo healed itself. While staging the ownership-guard
exhibit, the duplicated product turned out to still sit inside the
discounted collection (productDuplicate copies manual-collection
membership — a fact worth knowing). The Worker looked at it, concluded the
duplicate genuinely deserved the promo, claimed it, and made the display
consistent with checkout. The “broken” exhibit had to be re-staged by
removing the duplicate from the collection — after which the Worker cleaned
it up and never touched it again. A sync you have to fight to keep wrong is
the kind you want in production.
Watch it run. The architecture page renders the Worker’s live run history — real timestamps, write/delete counts, and the webhook topic that triggered each run.