| | |

Cloudflare 09 ☁️ Gradual Deployments, Rollbacks & Cron Triggers — Managing Worker versions, percentage-based rollouts, version skew, and scheduled jobs

⏱️ Estimated read: 10 min | |

In traditional serverless environments, a deployment is often a destructive update where the new code overwrites the old code across the entire network simultaneously. While simple, this approach introduces significant risk: a single bug in the new version can instantly take down a global application. Cloudflare has evolved the Workers platform to support a more sophisticated deployment lifecycle, treating every upload as an immutable version and allowing developers to control exactly how much traffic each version receives.

This chapter covers the operational side of Cloudflare Workers, focusing on safety and automation. We will examine the mechanics of “Gradual Deployments,” which enable percentage-based rollouts of new code to a subset of users. We will also explore the critical concept of “Version Skew,” which occurs when users interact with a mix of old and new resources during a transition. Finally, we will delve into “Cron Triggers,” the mechanism for running Workers on a schedule to perform background tasks like database cleanups or report generation.

The sections that follow walk through the configuration of deployments via the Wrangler CLI and Dashboard, the strategic execution of rollbacks, and the implementation of scheduled logic that operates independently of user requests.

Key point: Cloudflare Workers utilize an immutable versioning system that supports instant rollbacks and percentage-based gradual deployments, enabling developers to mitigate the risk of global outages while automating background tasks via Cron Triggers.


Why Deployment Management exists

The “Big Bang” deployment problem. When code is deployed to 100% of users at once, any unforeseen edge case in the production environment becomes a global incident. Gradual deployments solve this by allowing a “canary” release, where only 1% or 5% of users see the new version, providing a window to monitor telemetry before a full rollout.

The “Point of No Return” problem. In legacy systems, rolling back a deployment often meant re-triggering a long CI/CD pipeline. Cloudflare maintains a history of Worker Versions, allowing for a “one-click” rollback that updates the global routing table in seconds without re-building or re-uploading code.

The Version Skew problem. A modern web app consists of a Worker (the server) and assets (the frontend). If you deploy a new Worker that expects a specific data format, but the user is still running an old version of the frontend cached in their browser, the app may break. Understanding and managing this skew is vital for maintaining a seamless user experience during transitions.

The “Human-in-the-Loop” maintenance problem. Many essential application tasks, such as clearing expired sessions or syncing cache, do not happen during a user request. Without a built-in scheduler, developers would have to maintain external “cron servers” to hit their APIs. Cron Triggers move this automation into the edge, removing external dependencies.

The cost of execution overhead. Running a full container just to execute a 10-second cleanup script once an hour is inefficient. Because Workers use V8 isolates, scheduled jobs start instantly and consume minimal resources, making background automation significantly cheaper and more reliable than traditional alternatives.


a. Worker Versions and Gradual Deployments

Cloudflare Workers now operate on a “Version-first” architecture. Every time you run wrangler deploy, Cloudflare creates a unique, immutable ID for that specific bundle of code and configuration. By default, the newest version receives 100% of traffic, but this can be overridden to perform a gradual rollout.

Gradual deployments are managed through the Cloudflare Dashboard or the Wrangler CLI. You can specify a “Traffic Split” between two active versions. This is particularly useful for large-scale applications where you want to verify performance metrics or error rates on the new version before committing to it fully.

# Deploy a new version without immediately sending 100% of traffic
wrangler deploy --dry-run # Just an example, usually handled in the dashboard or via versioning

In the Cloudflare Dashboard under the “Deployments” tab, you can select “Begin Rollout.” You define the percentage of traffic for the new version. Cloudflare uses a deterministic approach to ensure that a single user (based on their IP or a specific identifier) stays on the same version throughout their session, preventing the “flapping” experience where one request hits the new version and the next hits the old one.


b. Rollbacks and Managing Version Skew

A rollback is essentially a routing change. Because Cloudflare stores previous versions of your Worker, rolling back does not involve “un-doing” code; it involves telling the edge nodes to route traffic back to a known-good Version ID. This process is nearly instantaneous globally.

# Roll back to the previous version via Wrangler
wrangler rollback

However, rollbacks and gradual deployments introduce Version Skew. This is the phenomenon where different parts of your system are running different versions of your code. For example:

  1. User loads index.html from Version A.
  2. User’s browser requests api/data.
  3. The Worker has rolled over to Version B.
  4. If Version B changed the API response format, the Version A frontend will crash.

To handle version skew, you should design your APIs to be backward compatible or include version headers in your requests. Cloudflare’s Global Persistent Headers and the cf-deployment-id can help your frontend identify which version of the backend it is communicating with, allowing the app to reload or adapt gracefully.


c. Cron Triggers: Scheduled Edge Tasks

Cron Triggers allow you to execute a Worker at specific intervals defined by the standard Unix cron syntax. These tasks do not have an associated “Request” or “Response” object because they are not triggered by an HTTP call. Instead, they use a special scheduled handler.

You define the schedule in your wrangler.toml file:

# wrangler.toml
[triggers]
crons = ["*/30 * * * *"] # Run every 30 minutes

In your Worker code, you implement the scheduled method:

export default {
  async scheduled(event, env, ctx) {
    // event.scheduledTime: The time the fetch was scheduled
    // event.cron: The cron string that triggered the execution
  
    console.log(`Cron triggered at: ${event.scheduledTime}`);
  
    // Perform background tasks
    ctx.waitUntil(performCleanup(env));
  },
};

One critical distinction: Cron Triggers run on the Standard (not Free) plan for many advanced features, and they execute in a specific “home” region rather than every single data center simultaneously. This prevents a cron job from running 300 times at once globally; instead, it runs once at the scheduled time on a reliable node.


Complete Example Session

// ============================================
// PART 1: WRANGLER CONFIG WITH CRONS
// ============================================
// name = "admin-tasks"
// [triggers]
// crons = ["0 0 * * *", "0 12 * * *"] // Midnight and Noon

// ============================================
// PART 2: THE MULTI-HANDLER WORKER
// ============================================
export default {
  // Standard HTTP Handler
  async fetch(request, env, ctx) {
    return new Response("API is running");
  },

  // Scheduled Handler
  async scheduled(event, env, ctx) {
    switch (event.cron) {
      case "0 0 * * *":
        await handleDailyCleanup(env);
        break;
      case "0 12 * * *":
        await handleMiddaySync(env);
        break;
    }
  }
};

// ============================================
// PART 3: RE-USABLE CLEANUP LOGIC
// ============================================
async function handleDailyCleanup(env) {
  const expired = await env.DB.prepare("DELETE FROM sessions WHERE expires < ?")
    .bind(Date.now())
    .run();
  console.log(`Cleaned up ${expired.meta.changes} sessions`);
}

// ============================================
// PART 4: VERSION SKEW PROTECTION (API)
// ============================================
// In the fetch handler, check for a client-sent version
// if (request.headers.get("X-App-Version") !== "v2") {
//   return handleLegacyMode(request);
// }

// ============================================
// PART 5: DEPLOYING NEW VERSION
// ============================================
// Terminal: wrangler deploy --description "Update session cleanup logic"

// ============================================
// PART 6: INITIATING GRADUAL ROLLOUT (CLI Concept)
// ============================================
// (Currently primarily Dashboard-driven)
// 1. Go to Workers -> admin-tasks -> Deployments
// 2. Select the new Version -> Rollout to 10%

// ============================================
// PART 7: MONITORING THE ROLLOUT
// ============================================
// Check for increases in 5xx errors specifically for the new Version ID.

// ============================================
// PART 8: EMERGENCY ROLLBACK
// ============================================
// Terminal: wrangler rollback
// This instantly points 100% of traffic to the previous stable ID.

// ============================================
// PART 9: TESTING CRONS LOCALLY
// ============================================
// Terminal: wrangler dev --test-scheduled
// Then: curl "http://localhost:8787/__scheduled?cron=0+0+*+*+*"

// ============================================
// PART 10: LOGGING SCHEDULER EVENTS
// ============================================
// Use ctx.waitUntil to ensure logs finish even if the handler returns.

The parts above demonstrate the combination of scheduled background work, immutable versioning for safety, and the code patterns required to handle different triggers within a single Worker.


Quick Reference

Cron Syntax Table

ExpressionMeaningExample
* * * * *Every minuteHigh frequency tasks
0 * * * *Every hourHourly report sync
0 0 * * *Every midnightDaily database cleanup
0 0 * * 1Every MondayWeekly newsletter prep
*/15 * * * *Every 15 minsWarm-up / Health checks

Deployment State Definitions

StateMeaning
ActiveReceiving 100% of traffic.
RolloutReceiving a partial % of traffic.
SupersededA newer version has replaced it.
Rolled BackManually set to inactive after a failure.

Wrangler Deployment Commands

CommandAction
wrangler deployCreate and activate a new version.
wrangler rollbackRevert to the last active version.
wrangler versions listShow history of immutable versions.
wrangler dev --test-scheduledLocal testing for Cron Triggers.

Best Practices

✅ Do This:

// Use event.cron to differentiate between multiple schedules
if (event.cron === "0 0 * * *") { ... }                        // ✅

// Wrap cron logic in try/catch to prevent silent failures
try { await cleanup(); } catch (e) { logError(e); }            // ✅

// Perform rollouts gradually for major architectural changes
// (e.g., 1% -> 10% -> 50% -> 100%)                            // ✅

// Version your API endpoints to prevent version skew issues
app.get("/v2/users", ...);                                     // ✅

❌ Don’t Do This:

// Don't assume a Cron Trigger has a Request object
const url = request.url; // ❌ (request is undefined in scheduled)

// Don't use crons for tasks requiring sub-minute precision
// (Minimum interval is 1 minute)                             // ❌

// Don't rollback without investigating the root cause
// (The bug might be in the database, not the code)           // ❌

// Don't forget ctx.waitUntil() for background logging in crons
logToExternalService(data); // ❌ (Might be killed early)

Common Pitfalls

PitfallWhy It HappensFix
Cron didn’t runInvalid cron syntax or Free plan limitValidate syntax; check Worker limits
request is undefinedAccessing HTTP data inside a Cron handlerCheck the trigger type before accessing request
Version Skew errorsAssets out of sync with Worker logicUse backward-compatible APIs or versioned assets
Rollback failsDependent resources (D1/KV) were migratedEnsure database changes are backward compatible
Silent Cron failuresNo HTTP response to show errorsUse an external logging service or Tail logs

Real-World Examples

1. Daily DB Cleanup

await env.DB.prepare("DELETE FROM logs WHERE created < ?").bind(oneWeekAgo).run();

2. Weekly Report Generator

const data = await env.DB.prepare("SELECT * FROM sales").all();
await sendEmail(data);

3. 5% Canary Deployment

User initiates rollout via Dashboard to monitor for new 404 errors.

4. Instant Rollback

CLI command wrangler rollback issued after a spike in 500 errors.

5. Cache Warming

Cron runs every 15 mins to hit heavy endpoints and keep KV/D1 warm.

6. Currency Exchange Sync

Worker fetches latest rates from an API and updates KV every hour.

7. Session Invalidation

Cron deletes all rows in KV marked as expired: true.

8. Health Check

Cron pings an origin server and updates a Status Page.

9. Version Header Logic

Worker checks X-Deployed-Version to route to legacy logic.

10. Local Cron Testing

Using __scheduled URL in wrangler dev to trigger logic manually.


Visual

Gradual Rollout Traffic Split

┌───────────────────────────────────────────────────────────┐
│  TRAFFIC STEERING (Edge Level)                            │
│                                                           │
│  User Request ───► [ Cloudflare Edge ]                    │
│                           │                               │
│             ┌─────────────┴─────────────┐                 │
│             ▼                           ▼                 │
│      [ Version 101 ]             [ Version 102 ]          │
│       (Stable - 90%)              (Canary - 10%)          │
│                                                           │
│  * Sticky: User stays on V102 if their first hit was V102 │
└───────────────────────────────────────────────────────────┘

Version Skew Conflict

┌───────────────────────────────────────────────────────────┐
│  VERSION SKEW SCENARIO                                    │
│                                                           │
│  1. Browser loads UI (V1) ─────┐                          │
│                                │ (Conflict!)              │
│  2. Worker Deploys (V2)        │                          │
│                                │                          │
│  3. UI (V1) calls API ─────────┴──► Worker (V2)           │
│                                                           │
│  * Result: UI expects V1 JSON, but gets V2 JSON.          │
│  * Solution: API Versioning (/api/v1 vs /api/v2)          │
└───────────────────────────────────────────────────────────┘

Cron Trigger Execution

┌───────────────────────────────────────────────────────────┐
│  SCHEDULED EVENT FLOW                                     │
│                                                           │
│  [ Cloudflare Scheduler ]                                 │
│          │                                                │
│  (Trigger: 0 0 * * *) ───► [ Worker Instance ]            │
│                                     │                     │
│  ┌──────────────────────────────────┴──────────────────┐  │
│  │ export default {                                    │  │
│  │   async scheduled(event, env, ctx) {                │  │
│  │     // No 'request' object here                     │  │
│  │     await doLogic();                                │  │
│  │   }                                                 │  │
│  │ }                                                   │  │
│  └─────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────┘

Summary

ItemValue
Deployment ModelImmutable Versions
Rollback SpeedGlobal / Seconds
Traffic SplittingPercentage-based
Background JobsCron Triggers
Min Cron Interval1 Minute
Skew PreventionAPI Versioning
Local Testingwrangler dev --test-scheduled
Primary Handlerscheduled(event, env, ctx)

Key takeaways:

  • Workers are immutable. Every deployment creates a permanent version that can be reverted to instantly, making the “rollback” a routing update rather than a code revert.
  • Gradual deployments reduce risk. By splitting traffic between versions, you can validate new features on a small subset of users before committing globally.
  • Version Skew is the “Silent Killer”. Always consider how old frontend code will interact with new backend logic during a transition period.
  • Cron Triggers automate the edge. They provide a serverless way to run maintenance, syncing, and reporting tasks without needing an external trigger or server.
  • The scheduled handler is unique. It lacks the Request and Response objects of the fetch handler, focusing purely on execution logic and environment bindings.

Remember: Safety in the edge comes from controlled transitions and automated maintenance. Use gradual deployments for every major change, keep a clear rollback path, and offload non-user tasks to Cron Triggers to ensure your application remains clean and efficient.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!