// Engineering notes

Durable Object alarms instead of background jobs

Published · ·Last updated ·

EOXLABS replaces most per-entity background jobs with Durable Object alarms. An alarm wakes one object at a scheduled time, runs at least once, and retries when the handler throws. The schedule lives in the same object as the data the job acts on, so there is no scheduler fleet, no broker and no machine whose crontab everyone forgot.

What goes wrong with process-model background jobs?

Three patterns cover most of the background work in a process-model system.

  • The cron box. One machine runs a crontab that sweeps every tenant. It is a single point of failure, its run time grows with the customer count, and a missed run is silent.
  • The worker queue. A broker plus a pool of worker processes. It scales, but it is a second distributed system to operate, and each job reaches its data from wherever the worker happens to run.
  • setTimeout in a long-lived process. The timer exists only in memory. A deploy, a crash or a scale-down loses it, and nobody finds out until a customer asks why the reminder never arrived.

The shared flaw is that the schedule lives apart from the data. A Durable Object alarm removes the gap: the object that owns a tenant's state also owns that tenant's timer.

What do Durable Object alarms guarantee?

We checked each row against Cloudflare's documentation on the date this note was published.

PropertyBehavior
Alarms per objectOne at a time; calling setAlarm() while one is pending overrides it
DeliveryAt least once
RetriesOn an uncaught exception, exponential backoff starting at 2 seconds, up to 6 retries
ConcurrencyOnly one alarm() runs at a time per object
Wall timeA maximum of 15 minutes per alarm invocation
RepetitionNone; the handler must call setAlarm() again (rules of Durable Objects)
BillingEach invocation is billed as a request; on SQLite-backed objects each setAlarm() is billed as one row written

Two details matter in practice. Retries apply only to the most recent setAlarm() call. And Cloudflare recommends catching exceptions inside alarm() and scheduling the next alarm yourself, because a long outage or an unfixed bug can exhaust the platform's retries.

How do you run many jobs on one alarm?

One alarm per object means the object keeps its own schedule and arms the alarm for the earliest due job. We keep the schedule in the object's SQLite storage.

import { DurableObject } from "cloudflare:workers";

type Job = { id: string; kind: string; payload: string; run_at: number; attempts: number };

export class TenantScheduler extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS jobs (
      id TEXT PRIMARY KEY, kind TEXT NOT NULL, payload TEXT NOT NULL,
      run_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0)`);
  }

  async schedule(id: string, kind: string, payload: unknown, runAt: number) {
    this.ctx.storage.sql.exec(
      `INSERT INTO jobs (id, kind, payload, run_at) VALUES (?, ?, ?, ?)
       ON CONFLICT(id) DO UPDATE SET payload = excluded.payload, run_at = excluded.run_at`,
      id, kind, JSON.stringify(payload), runAt);
    await this.arm();
  }

  async alarm() {
    const due = this.ctx.storage.sql
      .exec<Job>(`SELECT * FROM jobs WHERE run_at <= ? ORDER BY run_at LIMIT 50`, Date.now())
      .toArray();
    for (const job of due) {
      try {
        await this.run(job); // may run more than once: must be idempotent
        this.ctx.storage.sql.exec(`DELETE FROM jobs WHERE id = ? AND run_at = ?`, job.id, job.run_at);
      } catch {
        const backoff = Math.min(1000 * 2 ** job.attempts, 3_600_000);
        this.ctx.storage.sql.exec(
          `UPDATE jobs SET attempts = attempts + 1, run_at = ? WHERE id = ? AND run_at = ?`,
          Date.now() + backoff, job.id, job.run_at);
      }
    }
    await this.arm();
  }

  private async arm() {
    const { next } = this.ctx.storage.sql
      .exec<{ next: number | null }>(`SELECT MIN(run_at) AS next FROM jobs`).one();
    if (next === null) await this.ctx.storage.deleteAlarm();
    else await this.ctx.storage.setAlarm(next);
  }

  private async run(job: Job) {
    // Call the provider, passing job.id as the idempotency key.
  }
}

A Worker schedules work over RPC with env.SCHEDULER.getByName(tenantId).schedule(...). Three choices in that code are deliberate.

The AND run_at = ? guards matter because await this.run(job) lets other events into the object. If schedule() moves a job while it is running, the conditional DELETE leaves the new schedule alone instead of erasing it.

Per-job errors are caught and rescheduled with our own backoff, so the platform's six retries are reserved for failures we didn't anticipate, such as a storage error. A production version also caps attempts and moves exhausted jobs to a failure table someone reads.

LIMIT 50 bounds the work per invocation so it stays well inside the 15-minute wall time. If more jobs are due, arm() sets an alarm at or before Date.now(), which the SQLite storage API schedules "for asynchronous execution in the immediate future", and the next batch follows.

How do you make an alarm handler idempotent?

The handler is at-least-once at two levels. The platform can deliver an alarm more than once, and our own code has a crash window between the side effect and the DELETE. So every job must tolerate a second run.

  • Give every job a stable ID and pass it to external APIs as an idempotency key, so a payment or email provider rejects the duplicate.
  • Make local state changes conditional, as the run_at guard does, rather than blind overwrites.
  • Record the outcome in the same object before any follow-up work, so a rerun can see what already happened.

Cloudflare's own guidance for Queues takes the same line: give each message a unique ID and use it as a primary key or idempotency key to de-duplicate.

When do Queues, Workflows or Cron Triggers fit better?

Alarms are the default for per-entity timing. They are the wrong tool for several jobs.

  1. Use an alarm when the work belongs to one entity and so does the schedule: renewing one connection's token, a reminder for one user, a retention purge for one tenant, a debounce.
  2. Use Queues when producers vastly outnumber entities and you want batching, consumer concurrency and a dead-letter queue. By default a consumer gets batches of up to 10 messages and 3 retries, and messages can be delayed by up to 24 hours.
  3. Use Workflows when one process has many steps over minutes or weeks, waits on outside events, and each step should retry on its own. A step that completed does not run again, and a step's return value can persist up to 1 MiB.
  4. Use a Cron Trigger for a fixed global schedule that isn't about any one entity, such as a nightly export. Cloudflare notes that changes to Cron Triggers can take up to 15 minutes to propagate.
  5. Don't use setTimeout inside a Durable Object for anything that must happen. A pending timer prevents hibernation and is lost when the object leaves memory.

The same placement logic runs through our note on edge-native and edge-deployed systems: the timer should live where the state lives.

What would we do differently?

We'd never wake objects on a short fixed interval to "check for work". Cloudflare warns that each alarm invocation incurs cost, and a poll loop across thousands of objects turns an idle system into a busy one. Arm the alarm for the next real due time, or not at all.

We'd add a small index from the first day, a row per tenant in D1 with the next due time and the job count, so operators can answer "what is scheduled?" without waking every object. Each alarm belongs to one object, and we'd rather query one table than ask every object in turn.

And we'd keep setAlarm() out of constructors unless it first checks getAlarm(). Cloudflare's alarm reference warns that an unconditional call in the constructor can interfere with an alarm that was already set.

Alarms pair naturally with WebSocket hibernation for real-time inboxes: the same object that holds a user's connections can prune its own message history on a schedule. More on the platform is on our Durable Objects stack page, on the legacy-to-edge migration capability, and across our engineering notes.

— DL

→

Related

+

More engineering notes

Have a system that can’t go dark?

Start a project →