Cloudflare Workers A/B Testing
A pattern for running A/B tests using Cloudflare Workers to bucket users and rewrite responses at the edge, with or without a formal experimentation platform.
What Is Cloudflare Workers A/B Testing?
Cloudflare Workers A/B testing is a specific implementation of edge worker experimentation using Cloudflare's Workers platform. Workers intercept requests at Cloudflare's global edge, run lightweight JavaScript (or WASM), and return modified responses. For A/B testing, the worker assigns a bucket and either rewrites HTML inline or routes to different origins.
Also Known As
- CF Workers A/B testing
- Edge-side A/B with Cloudflare
- Workers-based bucketing
How It Works
A request arrives at Cloudflare. The Worker checks for an existing bucket cookie; if absent, it hashes the visitor ID into a bucket (e.g., 50/50) and sets the cookie. Depending on bucket, the Worker either fetches the control page from origin or a variant page, or uses HTMLRewriter to modify the response on the fly. The response reaches the user with zero flicker.
Best Practices
- Use HTMLRewriter for simple element-level variants; use multi-origin routing for full-page variants.
- Store bucketing decisions in cookies with sensible expiry (aligned to experiment duration, not session).
- Log exposure events to a KV store, Durable Object, or your analytics platform — without exposure logs, your experiment has no data.
- Keep Worker CPU time well under Cloudflare's limits; complex bucketing or rewriting can exceed the 10-50ms free tier budget.
Common Mistakes
- Rolling your own bucketing algorithm without salting properly, leading to correlated buckets across experiments.
- Not handling bots and crawlers explicitly, which pollutes experiment data.
- Using Workers for experiments when a commercial platform's edge SDK would have sufficed and saved maintenance.
Industry Context
Cloudflare Workers A/B testing is popular with Ecommerce on headless stacks, SaaS marketing sites, and media publishers already on Cloudflare. Teams not already on Cloudflare usually don't adopt Workers just for A/B testing — the total cost beats the benefit.
The Behavioral Science Connection
Building your own edge testing is a classic case of the maker's high — the satisfaction of shipping infrastructure can crowd out the actual experimental learning. Teams that build sophisticated edge testing sometimes end up running fewer experiments than before because the tool became the end rather than the means.
Key Takeaway
Cloudflare Workers enable clean edge A/B testing for teams already on the platform — but use a commercial edge-compatible SDK if you want experimentation without becoming a platform team.