I made a Durable Object alarm handler fail seven times in a row on a local runtime. The attempts ran at +0, 2.3, 6.7, 16.2, 34.3, 68.2 and 147.5 seconds, and then stopped. The lease it was supposed to expire stayed in the table, overdue.
That is what the alarms documentation says will happen: an object has one alarm, alarms run at least once, and a failing handler is retried only a limited number of times. If an object owns things that must be cleaned up when they expire (leases, sessions, reservations), the handler has to be written with those three facts in mind. This post builds a small expiry handler that survives all three and shows what it did when I ran it.
TL;DR
- One alarm.
setAlarmreplaces the alarm that is set. With many expirations, keep the list in a table and set the alarm to the earliest one. - At least once. If the handler throws after doing external work, it runs again from the start. The work must tolerate a repeat.
- Retries are bounded. Up to 6 retries; after that the alarm is gone and overdue rows stay where they are.
- Re-arm on wake-up. A constructor that sets the alarm when rows exist and no alarm is set brings a stalled expiry back on the next request.
- All results are from local workerd. I did not run this on Cloudflare’s network.
What the documentation says
Key points from the alarms documentation:
- Each Durable Object can have one alarm at a time. Calling
setAlarm()when one is set overrides it. - Alarms have guaranteed at-least-once execution and are retried automatically if
alarm()throws, with exponential backoff starting at 2 seconds, up to 6 retries. This applies only to the most recentsetAlarm(). - The handler receives
retryCountandisRetry. Only onealarm()runs at a time per object. If the object terminates unexpectedly,alarm()may run again from the start on another machine. - Inside
alarm(),getAlarm()returnsnullunlesssetAlarm()was called after the handler started. - When an object wakes up, the constructor runs before
alarm(). The docs warn that callingsetAlarm()unconditionally in the constructor can interfere with an existing alarm, so check first. - For retries beyond the built-in ones, the docs suggest catching exceptions in
alarm()and rescheduling yourself.
According to the storage API page, alarms usually start within milliseconds but can be delayed by up to a minute during maintenance or failover.
A minimal implementation
The whole object is about 35 lines. Here it is in the order it runs.
export class LeaseLedger extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
this.sql = ctx.storage.sql;
this.sql.exec(`CREATE TABLE IF NOT EXISTS leases (id TEXT PRIMARY KEY, expire_at INTEGER NOT NULL)`);
this.sql.exec(`CREATE INDEX IF NOT EXISTS leases_by_expiry ON leases (expire_at)`);
ctx.blockConcurrencyWhile(() => this.ensureAlarm()); // (1)
}
(1) Every time the object is created (first request, after eviction, after a restart), it checks that an alarm is set. blockConcurrencyWhile holds other events until it finishes, so no request reaches a half-initialized object.
async ensureAlarm() {
const next = this.sql.exec(`SELECT MIN(expire_at) AS t FROM leases`).one().t; // (2)
if (next === null) return;
const current = await this.ctx.storage.getAlarm();
if (current === null || next < current) await this.ctx.storage.setAlarm(next); // (3)
}
(2) The table is the source of truth, and the alarm time is derived from it. (3) The alarm only moves earlier, never later, and is left alone if it is already right. This is the check the docs ask for. The function gives the same result however often it runs, so it is safe to call from the constructor, grant and alarm.
async grant(id, ttlMs) {
this.sql.exec(`INSERT OR REPLACE INTO leases (id, expire_at) VALUES (?, ?)`, id, Date.now() + ttlMs);
await this.ensureAlarm();
}
Granting a lease is one insert plus ensureAlarm. If the new lease expires before the current alarm, the alarm moves earlier.
async alarm() {
const due = this.sql.exec(`SELECT id FROM leases WHERE expire_at <= ? ORDER BY expire_at LIMIT 100`, Date.now()).toArray(); // (4)
for (const { id } of due) {
await this.revoke(id); // (5)
this.sql.exec(`DELETE FROM leases WHERE id = ?`, id); // (6)
}
await this.ensureAlarm(); // (7)
}
async revoke(_id) { /* the external effect */ }
}
(4) Do not trust how many times you were called; read what is due now. toArray() reads the whole result before the first await. (5) and (6): the order matters. Effect first, then delete the row. If the process dies between them, the row survives and the next run repeats the effect. The reverse order loses the effect on a crash. Under at-least-once, you choose duplicates over losses and make duplicates harmless. (7) Set the alarm for the next expiry, or for rows beyond the LIMIT. Inside the handler getAlarm() is null, so ensureAlarm simply sets it.
What workerd did
These are the results of running the steps in “Run it on workerd” below, with wrangler 4.148.0 (local workerd, compatibility date 2026-09-01) and Node.js 22.23.3.
(a) Normal path. Leases with 300 ms and 1500 ms lifetimes. The alarm fired once for each, the second 1.2 s after the first. The table ended up empty and alarm was null.
(b) Crash after the effect. revoke throws once after recording its call. The first attempt ran the effect and failed before the DELETE. Two to three seconds later it was retried with retryCount=1, ran the effect again, and deleted the row. The effect ran twice for one lease.
(c) The alarm only moves earlier. Leases of 5 s, 60 s and 1 s, granted in that order. After the first, alarm was the 5 s lease’s expire_at; after the second, it was unchanged; after the third, it was the 1 s lease’s expire_at.
(d) Exhausting the retries. The handler throws 7 times. The attempts ran at the times in the opening paragraph, with retryCount 0 to 6. After the seventh, the lease stayed in the table, overdue.
By the time of the final status request, the object had been evicted. So that request ran the constructor, which found an overdue row and no alarm and set the alarm again (the output shows alarm as a future time). That is the recovery path. In a separate run where I kept wrangler running, that alarm fired right away, the lease was removed, and calls became 8.
Making the effect tolerate a repeat
This design makes repeats rare, not impossible. Give the effect one of these shapes:
- Naturally idempotent: “revoke credential X” or “set status to expired” gives the same result when run twice.
- Keyed: for a call such as send, charge or create, pass the lease
idas the key so the other side can recognize a repeat.
The effect is a stub in the test, so this section describes the shape; I did not test it end to end.
Run it on workerd
Three files are enough. src/ledger.js is the four snippets above joined in order, with one import at the top:
import { DurableObject } from "cloudflare:workers";
// then the LeaseLedger class from above, unchanged
wrangler.jsonc:
{
"name": "alarm-lab",
"main": "src/index.js",
"compatibility_date": "2026-09-01",
"durable_objects": { "bindings": [{ "name": "LEDGER", "class_name": "LabLedger" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["LabLedger"] }]
}
src/index.js is the test subclass. The URL path picks the object, so each experiment gets a fresh one.
import { LeaseLedger } from "./ledger.js";
// Test subclass: logs each attempt, counts revoke calls, throws on demand.
export class LabLedger extends LeaseLedger {
async alarm(info) {
const log = (await this.ctx.storage.get("log")) ?? [];
log.push({ t: Date.now(), retry: info?.retryCount ?? 0 });
await this.ctx.storage.put("log", log);
return super.alarm();
}
async revoke(id) {
const calls = ((await this.ctx.storage.get("calls")) ?? 0) + 1;
await this.ctx.storage.put("calls", calls);
const fail = (await this.ctx.storage.get("fail")) ?? 0;
if (fail > 0) {
await this.ctx.storage.put("fail", fail - 1);
throw new Error(`injected failure for ${id}`);
}
}
async fetch(req) {
const q = new URL(req.url).searchParams;
if (q.has("fail")) await this.ctx.storage.put("fail", Number(q.get("fail")));
if (q.has("id")) await this.grant(q.get("id"), Number(q.get("ttl")));
return Response.json({
leases: this.sql.exec(`SELECT id, expire_at FROM leases`).toArray(),
alarm: await this.ctx.storage.getAlarm(),
calls: (await this.ctx.storage.get("calls")) ?? 0,
log: (await this.ctx.storage.get("log")) ?? [],
});
}
}
export default {
fetch(req, env) {
const name = new URL(req.url).pathname.slice(1) || "demo";
return env.LEDGER.get(env.LEDGER.idFromName(name)).fetch(req);
},
};
Setup (needs Node.js 22):
mkdir alarm-lab && cd alarm-lab && npm init -y > /dev/null
npm i -D wrangler@4.148.0
# place wrangler.jsonc, src/ledger.js, src/index.js here
Save the following as run.sh and run bash run.sh in a terminal. It takes about three minutes.
trap 'kill 0' EXIT # stop wrangler when the script ends
c() { curl -s "localhost:8799/$1"; echo; }
npx wrangler dev --port 8799 --persist-to ./state > dev.log 2>&1 &
until curl -s localhost:8799/ping > /dev/null; do sleep 1; done
# (a) normal path
c "a?id=x&ttl=300"; c "a?id=y&ttl=1500"
sleep 3; c a
# (b) crash after the effect
c "b?fail=1&id=x&ttl=200"; sleep 4; c b
# (c) alarm only moves earlier
c "c?id=x&ttl=5000"
c "c?id=y&ttl=60000"
c "c?id=z&ttl=1000"
# (d) exhaust the retries: about 2.5 minutes
c "d?fail=7&id=x&ttl=100"; sleep 170; c d
Ways an alarm handler stops silently
- Treating the alarm as the data. Symptom: two expirations, one alarm; the later
setAlarmreplaces the earlier one and one expiry is lost. Fix: keep expirations in a table and set the alarm to the minimum. - Assuming a failing handler is retried forever. Symptom: after an outage or a bug lasting a few minutes, overdue rows sit unprocessed with no error. Fix: re-arm on wake-up as above, and add a periodic job that touches objects with overdue work from outside.
- One permanently failing row blocking the rest. Symptom: because rows are read
ORDER BY expire_at, the same row comes first every time, throws, and the rows after it never run. Fix: keep a per-row attempt count and move or mark rows that exceed a limit so they are skipped. I did not test this version. - Setting the alarm unconditionally in the constructor. Symptom: every wake-up pushes the alarm later and some expirations run late. Fix: read
getAlarm()and only move it earlier. This follows the docs’ warning; I did not reproduce the bad version. - Deleting the row before the effect. Symptom: a crash loses the effect permanently. Fix: effect first, delete second, and make the effect repeat-safe.
- Acting on the alarm itself instead of querying due rows. Symptom: when the alarm comes early, late or twice, the handler does nothing or handles the wrong rows. Fix: query
expire_at <= nowevery time; then early or duplicate runs are harmless. - Expecting
getAlarm()insidealarm()to show the old alarm. Symptom: a re-arm decision is based onnull. Fix: inside the handler,getAlarm()isnullunless you set a new one.
When an alarm fits
Use this shape when one object owns many time-based obligations and “eventually, at least once, up to about a minute late” is acceptable. The table plus alarm is small and lives entirely in the object’s own storage.
Do not use it for work that must run at an exact moment, or for cleanup nobody would notice missing unless you also add the outside check. If the effect cannot be made repeat-safe, an alarm is the wrong tool.
What an alarm promises
An alarm promises to call you, not to finish your work. Keep the work in a table, re-check it on every wake-up, and write the effect so that being called twice costs nothing.