# Self-hosting Durable Objects with workerd

> Run a cluster of Durable Objects on your own machines with workerd, wrangler.jsonc, Docker, and one S3-compatible bucket.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2026-12-04 | Topics: [Cloudflare](https://flaviocopes.com/tags/cloudflare/) | Canonical: https://flaviocopes.com/self-host-durable-objects/

Cloudflare just merged the clustering ideas from [celld](https://flaviocopes.com/celld/) into [workerd](https://workerd.dev), the open-source runtime that powers Cloudflare Workers.

Back in August I wrote about [how celld runs Workers on your own infrastructure](https://flaviocopes.com/celld/) and [how workerd is built](https://flaviocopes.com/workerd/). At the time you had to choose between 2 trade-offs.

You could run `workerd`, which gave you real Workers compatibility, but you had to hand-write `config.capnp` files and you could not cluster Durable Objects (they were stuck on a single machine).

Or you could try `celld`, Ryan Dahl's separate Rust runtime that added bucket-backed Durable Object clustering, but had to reimplement Workers APIs from scratch.

In October Ryan Dahl and the Deno team joined Cloudflare, and now both pieces live in the same binary (`celld.dev` redirects to [workerd.dev](https://workerd.dev)).

I wanted to see how well this actually works in practice, so I installed `workerd`, wrote a small SQLite-backed Durable Object, spun up a 3-node cluster in Docker, measured read and write latency, and killed leaders on purpose to see failover in action.

## What is new in workerd

Three changes make self-hosting Workers much less painful than before:

- **Direct `wrangler.json` and `wrangler.jsonc` support.** You can run `npx workerd serve .` in a normal Workers project without touching Cap'n Proto configs. Support for `worker.config.json` (used by Cloudflare's newer `cf` CLI) is also planned next.
- **Official `cloudflare/workerd` Docker image.** It ships for Linux `x86-64` and `ARM64` at 266 MB and runs `workerd serve /app` out of the box.
- **Experimental bucket-backed Durable Object clustering.** Point multiple `workerd` processes at one R2, S3, or GCS bucket and they form a cluster with automatic request forwarding and leader failover.

Here's how the new setup compares to where things stood a few months ago:

| Capability | Earlier workerd | Standalone celld | Merged workerd (v1.20261202.1) |
| --- | --- | --- | --- |
| Config format | `config.capnp` | `wrangler.jsonc` | `wrangler.json` / `wrangler.jsonc` or `config.capnp` |
| Runtime compatibility | Full open-source Workers runtime | Partial Rust reimplementation | Full open-source Workers runtime |
| Official Docker image | Community builds | Yes | `cloudflare/workerd` (266 MB) |
| Multi-node Durable Objects | No | Yes (bucket-backed) | Yes, behind `--experimental` |
| Object store backends | None | S3 / R2 | S3, R2 (`s3://`), GCS (`gs://`) |

## Running one instance locally

Let's start with a single `workerd` instance on one machine, so we have a clean baseline before we add clustering.

If you're new to the programming model itself, my [Cloudflare Durable Objects tutorial](https://flaviocopes.com/cloudflare-durable-objects/) covers the basics first.

I created a small folder and installed `workerd` and `esbuild`:

```bash
mkdir visit-counter && cd visit-counter
npm init -y
npm install -D workerd esbuild
```

Next I wrote a small Durable Object called `VisitCounter` that stores every visit in its own embedded SQLite database (if you want a refresher on SQLite itself, grab my free [SQLite Handbook](https://flaviocopes.com/ebooks/sqlite-handbook/)).

Notice the `getInstanceId()` helper at the top. Each `workerd` process generates one short ID on its first request, so when we scale up to 3 nodes we can tell which machine received the HTTP request (`handledBy`) and which machine owns the Durable Object (`leader`).

```js
import { DurableObject } from 'cloudflare:workers'

let instanceId
function getInstanceId() {
  instanceId ??= crypto.randomUUID().slice(0, 8)
  return instanceId
}

export class VisitCounter extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env)
    this.ctx.storage.sql.exec(`
      CREATE TABLE IF NOT EXISTS visits (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        recorded_at TEXT NOT NULL
      )
    `)
  }

  record() {
    const now = new Date().toISOString()
    this.ctx.storage.sql.exec(
      'INSERT INTO visits (recorded_at) VALUES (?)',
      now,
    )
    const row = this.ctx.storage.sql
      .exec('SELECT COUNT(*) AS count FROM visits')
      .one()
    return {
      count: row.count,
      lastVisit: now,
      leader: getInstanceId(),
    }
  }

  stats() {
    const row = this.ctx.storage.sql
      .exec('SELECT COUNT(*) AS count, MAX(recorded_at) AS lastVisit FROM visits')
      .one()
    return {
      count: row.count,
      lastVisit: row.lastVisit,
      leader: getInstanceId(),
    }
  }
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url)
    const page = url.searchParams.get('page') ?? 'home'
    const id = ctx.exports.VisitCounter.idFromName(page)
    const stub = ctx.exports.VisitCounter.get(id)

    const data = request.method === 'POST'
      ? await stub.record()
      : await stub.stats()

    return Response.json({
      page,
      handledBy: getInstanceId(),
      ...data,
    })
  },
}
```

One small gotcha I hit right away: I originally called `crypto.randomUUID()` at the top level of the file, and `workerd` refused to start with `Disallowed operation called within global scope`.

Because it runs the real Workers runtime, the same startup restrictions apply.

So I moved the ID generation to be lazy, inside `getInstanceId()`, and it worked.

Now we add a minimal `wrangler.jsonc` next to `index.js`:

```jsonc
{
  "name": "visit-counter",
  "main": "index.js",
  "compatibility_date": "2026-01-01",
  "no_bundle": true,
  "exports": {
    "VisitCounter": {
      "type": "durable-object",
      "storage": "sqlite"
    }
  }
}
```

I set `"no_bundle": true` because `index.js` has no npm imports, and the official `cloudflare/workerd` Docker image does not include `esbuild`.

Using the `exports` map also allows the Worker to access `ctx.exports.VisitCounter` without having to write separate `durable_objects.bindings` and `migrations` arrays.

Start the server with:

```bash
npx workerd serve .
```

When I sent 2 `POST` requests for `pricing` and 1 for `about`, `workerd` created one SQLite database per Durable Object in `.wrangler/state/workerd/visit-counter-VisitCounter/`:

![Single-node workerd handling VisitCounter requests and creating separate SQLite files on disk](https://images.flaviocopes.com/self-host-durable-objects/single-node.webp?v=51f87ccd)

Stop the process with `Ctrl+C` and start it again, and the counts pick up right where they left off.

## Spinning up a 3-node cluster with Docker

Running on one machine is easy, so the real test is a multi-node cluster, where any node can receive a request, and any node can die.

In a `workerd` cluster, every node talks to the same object storage bucket ([Cloudflare R2](https://flaviocopes.com/cloudflare-r2/), Amazon S3, or Google Cloud Storage). There is no Raft daemon, no etcd, no separate database server.

The bucket coordinates everything using conditional writes (`If-None-Match: *` and `If-Match`):

```mermaid
flowchart LR
  accTitle: How a workerd cluster routes requests and syncs Durable Objects through one bucket
  accDescr: A client hits node 2, which forwards the call to node 1 as the object leader. Node 1 writes to local SQLite, uploads the WAL frame to the shared bucket, verifies leader.json, and then replies. If node 1 stops, another node claims leadership and restores the object from the bucket.

  Client["Client request"] --> N2["workerd node 2 (peer)"]
  N2 -->|"Forward RPC over port 7000"| N1["workerd node 1 (leader)"]
  N1 --> SQLite["Local SQLite"]
  N1 -->|"1. Upload WAL frame\n2. Verify leader.json"| Bucket["Shared R2 / S3 / GCS bucket"]
  Bucket -->|"Takeover after stop or\n20s lease expiry"| N3["workerd node 3"]
```

Before a node starts serving in cluster mode, it runs a built-in storage test against the bucket. It creates a probe object, tries a duplicate create, overwrites it, and tries a stale overwrite. If your S3 server does not respect conditional headers, `workerd` will refuse to start, instead of silently corrupting state later.

In production you would point the cluster at R2 or S3. To test everything locally on my laptop, I used a Docker Compose file with 3 `cloudflare/workerd` containers and a local S3-compatible container (`rustfs/rustfs`) that passed the conditional-write probe on the first try (my free [Docker Handbook](https://flaviocopes.com/ebooks/docker-handbook/) explains Docker Compose networking if you want the background).

```yaml
services:
  s3:
    image: rustfs/rustfs:latest
    container_name: workerd-do-s3
    environment:
      RUSTFS_ACCESS_KEY: workerdadmin
      RUSTFS_SECRET_KEY: workerdsecret123
      RUSTFS_ADDRESS: ":9000"
      RUSTFS_CONSOLE_ADDRESS: ":9001"
    ports:
      - "9000:9000"
    command: ["/data"]
    networks:
      cluster:
        ipv4_address: 172.29.0.10

  node1:
    image: cloudflare/workerd:latest
    container_name: workerd-do-node1
    depends_on: [s3]
    volumes:
      - ./app:/app:ro
    environment:
      AWS_ENDPOINT_URL: http://172.29.0.10:9000
      AWS_REGION: us-east-1
      AWS_ACCESS_KEY_ID: workerdadmin
      AWS_SECRET_ACCESS_KEY: workerdsecret123
      WORKERD_CLUSTER_BUCKET: s3://workerd-cluster/visits
      WORKERD_CLUSTER_KEY: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
    ports:
      - "8781:8787"
      - "7001:7000"
    command:
      - "--experimental"
      - "--data-dir=/tmp/workerd-data"
      - "--cluster-addr=0.0.0.0:7000"
      - "--cluster-advertise=172.29.0.11:7000"
    networks:
      cluster:
        ipv4_address: 172.29.0.11
```

`node2` and `node3` use the same block, with their own container IPs (`.12` and `.13` on that subnet) and host ports `8782`/`7002` and `8783`/`7003`.

Every node uses the same 32-byte `WORKERD_CLUSTER_KEY` (generate a real one with `openssl rand -hex 32`) and the same bucket prefix (`s3://workerd-cluster/visits`).

Every container binds `0.0.0.0:7000`, so passing `--cluster-advertise` tells the other nodes which private IP to use when forwarding RPC calls.

Once the containers started, every node answered `OK` on `GET /ready` on port `7000`.

Then I sent 3 `POST` requests for `page=pricing`, one to each node in turn:

![Three workerd cluster nodes forwarding requests for the same Durable Object to one leader](https://images.flaviocopes.com/self-host-durable-objects/cluster-routing.webp?v=b0c85aaa)

Look at `handledBy` and `leader` in those three responses:

- Node 1 (`bf002268`) got the first request, claimed leadership for `pricing`, and returned `count: 1`.
- Node 2 (`766fafe3`) got the second request, forwarded it to `bf002268`, and returned `count: 2` with `leader: "bf002268"`.
- Node 3 (`e6897231`) got the third request, forwarded it to `bf002268`, and returned `count: 3` with `leader: "bf002268"`.

When I listed the objects inside the bucket, I could see the entire cluster layout right there:

```text
visits/v1/do/aezEI_wP7xe0fykiuJfD-g/3d45351215ca624f9571f193ac81f8f15a34e8d90df74ef8548bc19e4cfee834/leader.json
visits/v1/do/aezEI_wP7xe0fykiuJfD-g/3d45351215ca624f9571f193ac81f8f15a34e8d90df74ef8548bc19e4cfee834/snapshot/ze/z9
visits/v1/nodes/4966205d0c58a522b32259d41cc6ed4e.json
visits/v1/nodes/895cd918ece426210031f408999f3ba7.json
visits/v1/nodes/be2b547e0f4d406be0ad19d71949c5aa.json
```

Each node writes its own lease file under `v1/nodes/`, and each Durable Object gets a `leader.json` file, in addition to its SQLite snapshots and WAL logs:

```json
{"node":"be2b547e0f4d406be0ad19d71949c5aa","epoch":1,"from":1}
```

## Testing graceful handoff and hard crashes

I tested both ways a leader can disappear.

First, I ran `docker stop workerd-do-node1`, which sends `SIGTERM`. On `SIGTERM`, `workerd` flips `/ready` to `503`, finishes in-flight requests, uploads any pending commits to the bucket, clears itself from `leader.json` and exits (the stop command finished in 5.29 seconds).

Immediately after `docker stop` returned, I sent a `POST` to node 2:

![Graceful SIGTERM failover moving leadership from node 1 to node 2 with no lost count](https://images.flaviocopes.com/self-host-durable-objects/cluster-failover.webp?v=3e5cb0b2)

Node 2 claimed leadership, restored the SQLite database from the bucket, incremented `count` to `4`, and answered in 63.8 ms.

Inside the bucket, `leader.json` moved straight to `"epoch": 2`.

Next I tested the ugly case: a hard crash with `docker kill workerd-do-node2` (`SIGKILL`), where the leader gets zero time to release its objects.

I immediately polled node 3 with `POST` requests until one succeeded:

```text
+ 0.26s: docker kill workerd-do-node2 (SIGKILL)
+ 3.35s (started + 0.26s): FAIL RemoteDisconnected: Remote end closed connection without response
+ 7.44s (started + 4.36s): FAIL RemoteDisconnected: Remote end closed connection without response
+11.53s (started + 8.44s): FAIL RemoteDisconnected: Remote end closed connection without response
+15.63s (started +12.53s): FAIL RemoteDisconnected: Remote end closed connection without response
+19.73s (started +16.63s): FAIL RemoteDisconnected: Remote end closed connection without response
+20.79s (started +20.73s): HTTP 200 {"page":"pricing","handledBy":"de1d0b55","count":5,"lastVisit":"2026-12-04T07:45:23.251Z","leader":"de1d0b55"}
```

That matched the documentation to the second. Node 2's lease lasted 20 seconds, so for those 20 seconds every request for `pricing` waited a few seconds and dropped, while node 3 respected the lease.

At +20.73 seconds the lease expired, node 3 took over in 60 ms, restored the database, incremented `count` to `5` and bumped `leader.json` to `"epoch": 3`, with all 5 writes intact.

## Measuring single-node vs. cluster latency

In cluster mode, `workerd` never acknowledges a write until the SQLite commit lands in the bucket and the node re-checks `leader.json`. Warm reads stay in local SQLite.

I ran 50 sequential requests against each path (after 5 warmup calls) to see how big that difference is on my machine, with local Docker S3 on the same host:

| Workload (50 sequential requests) | Median | p95 | Min | Max |
| --- | --- | --- | --- | --- |
| Single-node `GET` (local disk) | 0.30 ms | 0.37 ms | 0.25 ms | 0.43 ms |
| Single-node `POST` (local disk) | 0.43 ms | 0.61 ms | 0.37 ms | 0.84 ms |
| 3-node cluster `GET` to leader | 0.52 ms | 0.71 ms | 0.39 ms | 0.96 ms |
| 3-node cluster `GET` via peer | 0.62 ms | 0.80 ms | 0.49 ms | 0.87 ms |
| 3-node cluster `POST` to leader | 5.51 ms | 7.11 ms | 4.57 ms | 8.42 ms |
| 3-node cluster `POST` via peer | 6.64 ms | 7.80 ms | 5.09 ms | 8.12 ms |

Look at those numbers. Reads barely change at all (0.52 ms on the leader, 0.62 ms through a peer), because the object is already warm in memory and local SQLite.

Writes jump from 0.43 ms on local disk to 5.51 ms even against a local S3 container, because every write waits on the bucket upload plus the leader check. Against a real R2 or S3 bucket over the network, expect every durable write to pay that bucket round-trip.

## What works today and what does not

Before you plan a migration off managed Cloudflare, check [workerd's compatibility table](https://workerd.dev/docs/cloudflare-compat/) and [limitations page](https://workerd.dev/docs/limitations/).

Some gaps are big.

- **Supported today:** Workers, Durable Objects, and Facets are stable. D1, R2 bindings, Workflows, Static Assets, Cron Triggers, Dynamic Workers, Secrets Store secrets, and Rate Limiting work behind `--experimental`.
- **No cluster support yet for KV or Queues:** If your `wrangler.jsonc` declares `kv_namespaces` or `queues`, `workerd` refuses to start with `--cluster-addr`.
- **Not supported at all:** Workers AI, Vectorize, Hyperdrive, Browser Rendering, Images, Stream, Email Workers, Containers, and Pipelines.
- **Unencrypted peer traffic:** Cluster communication on port `7000` is plain TCP, so you need a private VPC, WireGuard, or Tailscale between machines.
- **No automatic rebalancing or WebSocket migration:** An object stays on the first node that activates it until that node stops, and open WebSockets close on failover so clients must reconnect.
- **Not a hardened multi-tenant sandbox:** Just like before, `workerd` isolates Workers at the V8 level, not well enough to run hostile untrusted user code without VMs around it.

Also watch your clocks. Every node checks its system time against the bucket and exits if they drift by more than 2 seconds, so you want NTP running on every machine.

## How I would use it

Most of my web projects stay on managed Cloudflare (my [Cloudflare Handbook](https://flaviocopes.com/ebooks/cloudflare-handbook/) covers the stack I rely on every day), because DNS, TLS, DDoS protection, global routing and zero server maintenance are hard to beat as a solo developer.

I would not self-host `workerd` for a static site like flaviocopes.com, a standard CRUD app that wants cross-table SQL queries in Postgres, or an app that already leans on Workers AI, Queues and Email Workers.

Where I would reach for a self-hosted `workerd` cluster is a specific kind of app: something stateful and naturally sharded by room, project, user, or agent session, that needs to live inside a private network, close to an existing database or GPU box, or on customer infrastructure where Cloudflare's managed network is off the table.

Even if you keep deploying everything to Cloudflare, having real bucket-backed Durable Object clustering inside the official Apache-2.0 `workerd` runtime changes the risk calculation. You can use Durable Objects without locking your app to a single host.

If you want to try it yourself, start with [workerd.dev](https://workerd.dev), spin up a single local instance with `npx workerd serve .`, and only add `--experimental` and a shared bucket once your app is actually ready to test failover.
