skip to content

A Durable Object releases 15-minute ticket holds from its alarm() handler, yet some holds were released twice and others never; how do setAlarm() and alarm retries explain it?

level: seniorimportance: must knowfreq 45%

answer

  1. one alarm per object
  2. a later call replaces the time
  3. at-least-once delivery
  4. six retries, then silence
  5. store the schedule, reschedule

basics

~20 s

Each Durable Object has a single alarm, so a setAlarm() per hold overwrites earlier wake-ups. alarm() runs at least once and retries a throw only 6 times with backoff, so the handler must be idempotent and reschedule itself.

solid answer

~50 s

`ctx.storage.setAlarm(time)` sets the object's only alarm, and calling it again replaces the earlier time. Code that set an alarm for each new hold kept pushing the wake-up later, and earlier holds never expired on time. Delivery is **at least once**. If `alarm()` throws, it is retried with exponential backoff starting at 2 seconds, up to 6 retries, and each retry runs the whole handler again, so anything a failed attempt already did can happen twice. After the last retry the alarm is dropped until someone calls `setAlarm()` again. The fix: keep every hold's expiry in a table, set the alarm to the earliest one, and in `alarm()` delete everything already expired (harmless to repeat), then set the alarm to the next expiry. Catch failures yourself and reschedule, and never call `setAlarm()` unconditionally in the constructor.

code

javascript · 46 lines
javascript
import { DurableObject } from "cloudflare:workers";

const HOLD_MS = 15 * 60 * 1000;

export class TicketEvent extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env);
    ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS holds (
      seat TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      expires_at INTEGER NOT NULL
    )`);
  }

  async hold(seat, userId) {
    const expiresAt = Date.now() + HOLD_MS;
    this.ctx.storage.sql.exec(
      "INSERT INTO holds (seat, user_id, expires_at) VALUES (?, ?, ?)",
      seat, userId, expiresAt,
    );
    // One alarm per object: only move it if this hold expires first
    const current = await this.ctx.storage.getAlarm();
    if (current === null || expiresAt < current) {
      await this.ctx.storage.setAlarm(expiresAt);
    }
    return expiresAt;
  }

  async alarm(alarmInfo) {
    if (alarmInfo?.isRetry) console.log(`alarm retry ${alarmInfo.retryCount}`);
    // Safe to run twice: a second pass finds nothing left to delete
    this.ctx.storage.sql.exec("DELETE FROM holds WHERE expires_at <= ?", Date.now());
    const { next } = this.ctx.storage.sql
      .exec("SELECT MIN(expires_at) AS next FROM holds")
      .one();
    if (next !== null) await this.ctx.storage.setAlarm(next);
  }
}

export default {
  async fetch(request, env) {
    const stub = env.TICKETS.getByName("gig-1");
    const expiresAt = await stub.hold(new URL(request.url).searchParams.get("seat"), "u-1");
    return Response.json({ expiresAt });
  },
};

go deeper

for a junior

Recall that ctx.storage.setAlarm() schedules one wake-up per Durable Object and that the runtime then calls the object's alarm() handler.

for a middle

Explain that a new setAlarm() replaces the old one, the at-least-once delivery, the 2-second exponential backoff with 6 retries, and the retryCount and isRetry fields.

for a senior

Diagnose double and missing releases from retries and overwritten alarms, then show the schedule-in-a-table pattern, idempotent handling and self-rescheduling on failure.

for a principal

Judge when per-object alarms are the right scheduler for a team versus a shared job system, given one alarm per object and handlers that must tolerate repeats.

## One alarm per object A **Durable Object alarm** wakes the object at a chosen time and calls its `alarm()` handler, even if no request arrives. It is part of the storage API and follows the same rules as other storage writes: - `ctx.storage.setAlarm(time)` takes a `Date` or milliseconds since the epoch; a time in the past means "as soon as possible"; - each object has **one** alarm, and a second `setAlarm()` **replaces** the first; - `ctx.storage.getAlarm()` returns the scheduled time or `null`. While `alarm()` is running it returns `null` unless the handler has already set a new one; - `ctx.storage.deleteAlarm()` clears it; it does not cancel a handler that is already running. Alarms usually fire within a few milliseconds of the set time, but can be delayed by up to a minute during maintenance or failover. ## Delivery: at least once, with bounded retries - Only one `alarm()` runs at a time for a given object. - When `alarm()` throws, the runtime retries it with **exponential backoff from 2 seconds, up to 6 retries**. A handler that always throws therefore runs seven times in all, the first attempt plus six retries, with the gaps roughly doubling from about 2 seconds; after that `getAlarm()` returns `null`. - The optional `alarmInfo` argument carries `retryCount` and `isRetry`. - If the machine fails mid-handler, the alarm can run again from the beginning elsewhere. - Retries apply to the most recent `setAlarm()`; once they are exhausted, nothing runs until the next `setAlarm()` call. ## Why holds were released twice A retry runs the **whole handler from the top**. If the handler released holds and then threw while notifying the waiting list, the next attempt released the same holds again: duplicate "your seat is free" messages, or a seat handed to two people from the waiting list. At-least-once delivery means the handler must be **idempotent**: deleting expired rows is safe to repeat, while an external notification needs a recorded "notified" flag or a deduplication key. ## Why holds were never released Several distinct bugs end the same way: - **overwritten wake-ups**: `hold()` called `setAlarm(now + 15 min)` for every booking, so each new hold pushed the single alarm later and older holds outlived their 15 minutes; - **exhausted retries**: a downstream outage longer than the backoff window used up all 6 retries, and the alarm was dropped; - **constructor resets**: an unconditional `setAlarm()` in the constructor, which runs on every wake-up, moved the alarm each time the object restarted; - **a poison row**: a handler that throws on one malformed hold fails the same way on every retry, so all 6 retries are spent and no later expiry is processed until something calls `setAlarm()` again. ## A correct hold-expiry design 1. Store each hold with its `expires_at` in a table. 2. When adding a hold, read `getAlarm()` and call `setAlarm()` only if the alarm is unset or later than the new expiry. 3. In `alarm()`, delete every hold with `expires_at <= Date.now()` and handle notifications idempotently. 4. Set the alarm to the earliest remaining expiry, or leave it unset if none remain. 5. Wrap fragile work in `try...catch` and call `setAlarm(Date.now() + delay)` yourself, so an outage cannot exhaust the built-in retries. 6. If an `abort()` from the handler must not trigger a retry, call `ctx.abort()` with `{ retryAlarm: false }`. ## Reading the code example In the example, `hold()` inserts the row and then moves the alarm only if no alarm is set or the new hold expires sooner, so later bookings never postpone an earlier expiry. `alarm()` logs when it is running as a retry, deletes every hold whose time has passed, and then reads the earliest remaining `expires_at`. If one exists, it sets the alarm for that moment; if the table is empty, it leaves the alarm unset. Running the handler twice in a row is harmless: the second pass deletes nothing and sets the same next alarm. Any notification to the released holders would need a stored flag to keep that property. ## The alarm API at a glance | Call | Behaviour to remember | | --- | --- | | `setAlarm(time)` | replaces any existing alarm | | `getAlarm()` | `null` during a run unless reset | | `deleteAlarm()` | best-effort way to stop retries from inside `alarm()` | | `deleteAll()` | also deletes the alarm on compatibility dates from 2026-02-24 |

  • How do you keep a Durable Object's alarm work going through a downstream outage longer than its retries?
    Do not let the error escape. Catch it inside `alarm()`, record what is still pending in storage, call `ctx.storage.setAlarm(Date.now() + delay)` with your own backoff, and return normally. The runtime's 6 automatic retries then never run out, and the next run picks up the pending work.
  • Why must a Durable Object constructor check getAlarm() before calling setAlarm()?
    The constructor runs every time the object starts, including just before an `alarm()` delivery after it was evicted. An unconditional `setAlarm()` there replaces the time that was already scheduled, pushing expiries later on every wake-up. Read `getAlarm()` first and set an alarm only when none exists.
  • How do you remove a finished event's Durable Object entirely?
    Call `ctx.storage.deleteAll()`. On compatibility dates from 2026-02-24 it also deletes the pending alarm; on earlier dates call `ctx.storage.deleteAlarm()` as well. Deleting rows or dropping tables is not enough, because metadata can remain. An object whose storage is empty when it shuts down stops existing and is no longer billed for storage.

One alarm clock and a diary of appointments: set the clock for the earliest entry, and each time it rings, cross off everything due and set it for the next. Re-setting the clock for every new appointment only moves its single hand, and earlier appointments are missed.

  • setAlarm() adds another alarm, so each hold can schedule its own wake-up.
  • An alarm fires exactly once, so its handler need not be idempotent.
  • A throwing alarm() handler is retried until it eventually succeeds.
  • An unconditional setAlarm() in the constructor is harmless.
  • Two alarm() runs of one object can overlap, so the handler needs a lock.

Assumes a compatibility date on or after 2026-02-24, where ctx.storage.deleteAll() also deletes a pending alarm (the delete_all_deletes_alarm flag); earlier dates keep the alarm until deleteAlarm() is called.