Development
Implementing deferred deployment with Cloudflare Durable Objects
A personal site using Astro, Sanity, and Cloudflare Pages hit long build times as content grew. To avoid redundant rebuilds from frequent Sanity webhooks, the author built a deferred build system on Cloudflare using Durable Objects as a webhook relay with configurable delay, URL, and token via headers, creating a reusable webhook delay trigger for multiple projects.
- #Webhook
- #Cloudflare Workers
- #Durable Objects
- #Static Website
37
Previously I worked on a project. Since it was a personal website–type content site, I chose a purely static website solution, using Astro as the framework and Sanity as the CMS, and deployed the project on Cloudflare Pages. In Sanity, I set it up so that whenever content changes, a webhook is triggered to rebuild the site.
But as the amount of content increased (one type of content has more than 600 entries), the build time increased as well, and each build could even take 7 minutes. And since Sanity doesn’t support manually triggering a webhook, it means that if you save an article several times, it will trigger the build task the same number of times. This not only results in a large number of pointless deployments, but is also extremely time‑consuming. If you’ve updated a dozen or so articles, you’ll have to wait an hour to see the latest content.
So when working on new features for this project this year, I took deferred building into consideration as well.
This feature is very simple: it acts as a webhook relay. After receiving a build request, it waits for a period of time before sending it out; if a new request arrives within that period, the timer is reset. If the delay is 20 minutes, then no matter how many times you make changes, as long as the interval between them does not exceed 20 minutes, there will be only one actual build.
Since my principle is to avoid interacting with servers whenever possible, I want to use Cloudflare as much as possible to achieve this requirement.
Using only workers is not enough, because workers are stateless and you can’t simply use setInterval. After some searching, I found that Durable Objects can fulfill this requirement.
In this document, Cloudflare explains how to configure Durable Objects to be woken up at a certain time in the future.
And you can also use getByName(“scheduler”) so that these trigger events obtain the same instance. New requests will overwrite previous requests, so no duplicate builds will be generated.
In order to make it more generic, I didn’t hard-code the target webhook URL. Instead, I require it to be passed in via HTTP headers, and I also accept the delay time and verification token. In this way, it becomes a general-purpose webhook delay trigger that can be shared across multiple projects.
For detailed code and usage instructions, see GitHub.