Multi-Origin Failover Router
Automatically routes traffic to a secondary origin if the primary returns 5xx errors. Configurable retry logic and failure thresholds.
Automatic Origin Failover at the Edge — Zero Downtime Routing
A Cloudflare Worker that monitors your primary origin and automatically reroutes traffic to a secondary origin when the primary returns 5xx errors. Configurable retry logic, failure thresholds, and recovery detection — all without touching DNS or your app.
What's Included
- Cloudflare Worker with primary/secondary origin failover logic
- Configurable failure threshold before failover triggers (e.g. 3 consecutive 5xx errors)
- Automatic recovery detection — traffic returns to primary when healthy
- KV-backed failover state shared across all edge locations globally
- Configurable retry count per request before marking origin failed
- Optional alert webhook (Slack, PagerDuty) on failover events
wrangler.tomlwith KV binding pre-configured- README with architecture explanation and tuning guide
How It Works
On each request, the Worker checks a KV flag to determine the current active origin. Requests are forwarded to the primary unless the flag indicates failover mode. When a 5xx response is detected, the Worker increments a failure counter in KV. Once the threshold is hit, the failover flag flips and all subsequent traffic routes to the secondary. A background health check periodically probes the primary and flips the flag back when it recovers.
What You Get
- Transparent origin failover in under 50ms, globally at Cloudflare's edge
- No DNS TTL delays — failover is instantaneous
- KV-backed state ensures all edge nodes fail over simultaneously
- Configurable thresholds prevent flapping on transient errors
- Automatic recovery — no manual intervention needed when primary comes back
- Works with any two HTTP origins: app servers, S3, Render, Railway, etc.
Requirements
- Cloudflare account with Workers and KV enabled
- Two origin URLs (primary and secondary)
- Wrangler CLI installed (
npm install -g wrangler)