In a Cloudflare Durable Object, what does ctx.blockConcurrencyWhile() guard, and why call it in the constructor rather than around every request?
answer
- holds every other event back
- even across awaited I/O
- schema setup before first request
- throw or 30 seconds resets
- throughput collapses per request
basics
~20 sctx.blockConcurrencyWhile(callback) stops every other event reaching the object until the async callback settles, even across awaits. That suits one-time setup in the constructor, such as creating tables; wrapping each request serialises all traffic and caps throughput.
solid answer
~50 s`ctx.blockConcurrencyWhile()` runs an async callback and delivers no other event to the object (requests, RPC calls, alarms) until that callback's promise settles, even if the callback awaits I/O in between. Its natural home is the constructor: create tables, run schema migrations or load state there, and no request ever sees a half-initialised object. Two failure rules come with it: if the callback throws, the object is terminated and reset, and if it runs longer than 30 seconds, the object is reset too. Around every request it is the wrong tool. It turns the object into a strict queue, so a 5 ms critical section caps it near 200 requests per second, and synchronous `ctx.storage.sql.exec()` work is already atomic without it. Holding it across a `fetch()` is the classic anti-pattern, a lock held across slow I/O.
code
javascript · 29 linesimport { DurableObject } from "cloudflare:workers";
export class TicketEvent extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS holds (
seat TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
expires_at INTEGER NOT NULL
)`);
this.capacity = (await ctx.storage.get("capacity")) ?? 100;
});
}
seatsLeft() {
const { taken } = this.ctx.storage.sql
.exec("SELECT COUNT(*) AS taken FROM holds")
.one();
return this.capacity - taken;
}
}
export default {
async fetch(request, env) {
const stub = env.TICKETS.getByName("gig-1");
return Response.json({ seatsLeft: await stub.seatsLeft() });
},
};go deeper
Recall that blockConcurrencyWhile() delays all other events until its callback finishes, and that it is normally called in the constructor to set up tables.
Explain what is blocked and what is not, why setup must be idempotent because the constructor reruns, and the two reset rules: a thrown error and the 30-second timeout.
Show the throughput cost of per-request use, why synchronous SQL and transactionSync() already give atomicity, and the alternatives to holding it across a fetch().
Treat it as a team rule: allowed in constructors for schema setup, reviewed anywhere else, because one misplaced call turns a busy object into a single-file queue.
## What it blocks A Durable Object handles events one at a time, but JavaScript code that `await`s something other than its own storage (a `fetch()`, a timer, a call to another service) gives the runtime a chance to deliver the next event before the first one finishes. **`ctx.blockConcurrencyWhile(callback)`** closes that gap for one stretch of code: - it runs `callback`, which returns a Promise; - until that Promise settles, **no other event is delivered** to the object: no incoming request, no RPC call, no alarm; - events started by the callback itself (its own `fetch()` or storage calls) proceed normally; - once it settles, the queued events are delivered in order, and the method resolves to the callback's result. It guards **ordering and initialisation**, not durability. Making writes durable before a reply leaves is the output gate's job, which needs no help from this method. ## The constructor pattern The documented use is setup that must finish before the first request: 1. In the constructor, call `ctx.blockConcurrencyWhile(async () => { ... })`. 2. Inside, run `CREATE TABLE IF NOT EXISTS` statements or a small migration step, and load any values you want to cache in fields. 3. Requests that arrive during setup wait in line instead of running against missing tables. The constructor runs every time the object starts: on first use, after eviction, after a reset and after a deploy. So the setup must be **idempotent**, which `IF NOT EXISTS` and a migrations table make easy. Durable Object SQLite storage does not support `PRAGMA user_version`, so the schema version lives in a table you create. ## Failure behaviour - **The callback throws**: the object is terminated and reset, so it cannot stay stuck half-initialised; the next event runs the constructor again. Wrap the body in `try...catch` if you would rather continue in a degraded state. - **The callback takes longer than 30 seconds**: the runtime treats it as a likely deadlock and resets the object. - **The callback is slow but finishes**: every queued request waits that long, so keep it to local storage work. ## Why not around every request | Approach | Blocks other events? | Typical use | | --- | --- | --- | | Plain synchronous `ctx.storage.sql.exec()` calls | No yield, so nothing interleaves | Normal request handling | | `ctx.storage.transactionSync()` | No yield; adds rollback on throw | Several statements that must commit together | | `ctx.blockConcurrencyWhile()` | Yes, for the whole callback | Constructor setup and migrations | Wrapping each booking in `blockConcurrencyWhile()` makes the object a strict single-file queue. If each critical section takes about 5 ms, that object tops out near **200 requests per second**, however light the rest of the work is. It also buys nothing for synchronous SQL, which cannot be interrupted anyway. And if the callback awaits a `fetch()`, every other caller waits for that remote service: the equivalent of holding a lock across network I/O. ## Reading the code example In the example the constructor creates the `holds` table and then **awaits** `ctx.storage.get("capacity")`. Without `blockConcurrencyWhile()`, a request could arrive between the constructor returning and that read completing, and `seatsLeft()` would subtract from an undefined capacity. Inside the callback, nothing reaches `seatsLeft()` until both steps are done, so the method can read `this.capacity` without checking it. If the stored capacity were missing, the `?? 100` default would apply; a real system would rather fail loudly than invent a venue size. It is just as important to know what the method does **not** do: - it does not extend the CPU limit or the 30-second callback window; - it does not make writes durable sooner or later; - it does not affect any other object, even of the same class. ## When it does belong outside the constructor Rarely, a request must make an external async call and cannot tolerate the object's state changing while it waits. Before reaching for `blockConcurrencyWhile()` there, consider: - recording the intent in storage first (a hold marked pending), then calling out, then updating it; - a **check-and-set** after the await: re-read a version or status and write only if it is unchanged; - moving the external call to an alarm, so it runs off the request path. Use the method when ordering truly cannot be achieved any other way, and keep the callback short.
- Does a synchronous ctx.storage.sql.exec() in a request handler need blockConcurrencyWhile() to be atomic?No. Synchronous SQL never yields, so no other event can run between the statements, and writes made without an intervening `await` are committed together as one implicit transaction. Use `ctx.storage.transactionSync()` when you also want a thrown error to roll the statements back.
- The constructor's setup sometimes fails on a bad row; how do you stop it resetting the object on every start?Catch inside the callback. An exception that escapes `blockConcurrencyWhile()` terminates and resets the object, and the next event reruns the constructor and fails the same way. A `try...catch` that logs the bad row and marks the object degraded in a field lets requests get a clear error instead of a reset loop.
- Does blockConcurrencyWhile() hold back events for other objects of the same class?No. It blocks events for the one instance whose `ctx` you called it on. Other objects of the class, each with its own name and storage, keep running independently.
A shop keeps its shutter down while staff stock the shelves before opening, and customers queue outside. Pulling the shutter down again whenever a clerk phones a supplier mid-sale would leave the whole queue waiting on that one call.
- blockConcurrencyWhile() is required around every storage write to make it atomic.
- Other requests keep running while a blockConcurrencyWhile() callback awaits a fetch().
- If the blockConcurrencyWhile() callback throws, the object carries on uninitialised.
- blockConcurrencyWhile() locks every Durable Object of the class.
- Holding blockConcurrencyWhile() across a slow external call is a cheap way to avoid races.