Exactly-Once Publishing on Cloudflare D1 Without Transactions
Learn how to prevent duplicate writes in Cloudflare D1 using fencing tokens, guarded SQL batches, and revision-based cache invalidation.
The wire material details a migration process at Cloudflare Workers where two separate Workers were merged into a single Worker, causing an overlap in scheduling jobs. To ensure exactly once publishing of answer pages, the author implemented a lease system with a fencing token. This lease, stored in a job_leases table, determines who may publish, while a guard statement inside every batch statement checks if the lease is still valid.
If the lease is lost, the writer changes nothing. The batch insert statement also includes a random token, which subsequent statements check to ensure the lease was not lost. If the lease is lost, no changes are made. This system ensures that no page is published multiple times, and the publication revision number is incremented exactly once per page, even when multiple Workers are competing for the same keys.
Written by urgent.news from HackerNoon's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.