Tutorials
How to Self-Host Cloudflare Durable Objects Across Two Servers with workerd and R2
Cloudflare's experimental workerd clustering lets multiple servers share Durable Object state through an object storage bucket. Build a distributed counter, inspect object ownership, and test recovery after a server shuts down.
Imagine a small application that counts visits. It runs on two servers, and either server can receive an incoming request.
The implementation seems simple until both servers need to update the same counter.
Keeping the value in memory creates two independent counters. Saving it to a local SQLite database makes it persistent, but the databases still belong to separate machines.
A conventional solution would involve introducing a shared database or another service responsible for coordinating access to the state.
Cloudflare’s open-source runtime, workerd, now provides another approach.
In its December 3, 2026 changelog, Cloudflare announced experimental support for self-hosted Workers and Durable Objects running across multiple machines with shared object storage.
Several workerd instances can use the same Cloudflare R2 bucket, coordinate object ownership through conditional writes, and recover objects when a server becomes unavailable.
There is no separate consensus service to configure.
In this tutorial, we will build a small two-server cluster and use a persistent counter to examine how that architecture behaves.
What changes when workerd runs as a cluster?
A Durable Object represents an individually addressable instance with its own persistent state.
An application might create one object per user, document, shopping cart, or chat room.
Each object has a unique identity and an associated SQLite database.
When workerd operates independently, its Durable Objects can persist their state on local disk. Restarting the process does not necessarily destroy that state, but another machine cannot automatically take ownership of it.
Cluster mode changes where the authoritative state is stored and how ownership is coordinated.
Instead of two independent runtimes with unrelated databases, we have several runtimes participating in the same cluster.
Consider the following arrangement:
flowchart TD
Client["HTTP requests"] --> A["Server A - workerd"]
Client --> B["Server B - workerd"]
B -->|Forward object request| A
A --> DO["Counter - active owner"]
DO -->|Persist state| R2["Shared R2 bucket"]
B -.->|Recover state after failover| R2
In this example, Server A owns the counter.
Server B can accept HTTP requests, but requests targeting that particular Durable Object are forwarded to its current owner.
Another Durable Object could be owned by Server B at the same time.
Ownership is determined per object, not for the entire cluster.
This distinction becomes important as the application grows. Thousands of independently named objects can be distributed across multiple machines, while each object retains a single active owner.
1. Prepare two servers
For this tutorial, we will use two Linux machines connected through a private network.
| Setting | Server A | Server B |
|---|---|---|
| Private IP | 10.0.0.1 |
10.0.0.2 |
| HTTP port | 8787 |
8787 |
| Cluster port | 7000 |
7000 |
| Runtime | workerd | workerd |
| Persistent storage | Shared R2 bucket | Shared R2 bucket |
These IP addresses are examples. Replace them with addresses belonging to your own infrastructure.
Both machines need Node.js, npm, and access to the R2 S3-compatible API.
You will also need OpenSSL for generating a cluster key and curl for testing requests.
Install the same version of workerd on both machines:
mkdir durable-counter
cd durable-counter
npm init -y
npm install --save-exact [email protected]
This release is used throughout the tutorial.
Check the available cluster options:
npx workerd serve --help
Using an identical runtime version on both servers is particularly important at this stage.
Cloudflare warns that the experimental communication protocol may change between releases. Mixing versions during a rollout can therefore cause failures when instances communicate with one another.
Before proceeding, ensure that the servers can reach each other’s cluster port over the private network.
Do not expose port 7000 to the public internet.
2. Create the Durable Object
Create the following project structure on both machines:
durable-counter/
├── app/
│ ├── index.js
│ └── wrangler.json
├── package.json
└── package-lock.json
The application will provide three endpoints:
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /health |
Identify the responding runtime |
| GET | /count |
Read the current counter |
| POST | /increment |
Increase the counter |
Separating reads from writes makes the failover experiment easier to interpret.
Create app/index.js:
import { DurableObject } from "cloudflare:workers";
const instanceId = crypto.randomUUID();
export class Counter extends DurableObject {
fetch(request) {
const current =
this.ctx.storage.kv.get("count") ?? 0;
if (request.method === "GET") {
return Response.json({
count: current,
objectInstance: instanceId,
});
}
if (request.method === "POST") {
const next = current + 1;
this.ctx.storage.kv.put("count", next);
return Response.json({
count: next,
objectInstance: instanceId,
});
}
return new Response("Method not allowed", {
status: 405,
});
}
}
export default {
async fetch(request, env, ctx) {
const { pathname } = new URL(request.url);
if (pathname === "/health") {
return Response.json({
requestInstance: instanceId,
});
}
const validRequest =
(pathname === "/count" &&
request.method === "GET") ||
(pathname === "/increment" &&
request.method === "POST");
if (!validRequest) {
return new Response("Not found", {
status: 404,
});
}
const counter =
ctx.exports.Counter.getByName("global");
const response = await counter.fetch(request);
if (!response.ok) {
return response;
}
const result = await response.json();
return Response.json({
...result,
requestInstance: instanceId,
});
},
};
There are two identifiers in the response.
requestInstance identifies the Worker module instance that accepted the HTTP request.
objectInstance identifies the module instance in which the Durable Object handled the operation.
These randomly generated identifiers are diagnostic values, not persistent server identities. They can change when an isolate or runtime restarts.
They help us distinguish the execution paths during this experiment.
Why use a Durable Object for a counter?
Look at these three operations:
const current =
this.ctx.storage.kv.get("count") ?? 0;
const next = current + 1;
this.ctx.storage.kv.put("count", next);
If two independent servers performed this sequence against shared state without coordination, both could read the same initial value.
Suppose the counter contains 10.
Server A reads 10. Server B also reads 10. Both calculate 11, and both save it.
Two increments occurred, but the final value is 11.
Our Durable Object avoids this particular race because both requests are directed to the same active object. The read and write operations are synchronous, and the handler does not yield to another asynchronous operation between them.
The single-owner architecture is what allows us to keep this implementation small.
It should not be confused with a guarantee that every possible asynchronous read-modify-write sequence is automatically atomic.
3. Configure SQLite storage
Create app/wrangler.json:
{
"name": "durable-counter",
"main": "index.js",
"no_bundle": true,
"compatibility_date": "2026-10-01",
"exports": {
"Counter": {
"type": "durable-object",
"storage": "sqlite"
}
}
}
The exports configuration exposes the Counter class as a Durable Object backed by SQLite.
This allows the Worker to access it through:
ctx.exports.Counter.getByName("global");
Every request in our application targets the object named global.
If we used a different name, we would obtain a different Durable Object with its own state.
The no_bundle option is enabled because the application already consists of a JavaScript module and requires no additional bundling.
The configuration shown here follows the standalone project format supported by the current workerd runtime.
It should not be assumed that every configuration field supported by managed Cloudflare Workers is also supported by self-hosted workerd.
4. Create an R2 bucket for the cluster
Open the Cloudflare Dashboard and navigate to R2 object storage.
Create a new bucket:
workerd-cluster
Use a dedicated bucket for this experiment rather than one containing unrelated application files.
Next, create R2 API credentials with Object Read & Write permissions, restricted to this bucket.
Cloudflare will provide:
- Access Key ID
- Secret Access Key
- S3-compatible endpoint
For a standard R2 bucket, the endpoint follows this format:
https://ACCOUNT_ID.r2.cloudflarestorage.com
Jurisdiction-specific buckets may use a different endpoint. Copy the actual address from the dashboard.
The bucket does not need public access.
workerd communicates with it through authenticated S3-compatible requests.
There is also no need to create an R2 binding inside the Worker configuration.
The application interacts with Durable Object storage. The runtime itself is responsible for connecting that storage to the cluster’s bucket.
5. Generate and share the cluster key
The two servers need a shared cryptographic key for authenticating cluster communication.
Generate it once on a trusted machine:
openssl rand -hex 32
The command produces a hexadecimal representation of 32 random bytes.
Both servers must receive the same generated value.
Do not independently execute the command on each server and use the two different results.
That would give the instances different authentication keys.
For this tutorial, place the following environment configuration in a protected file outside the application repository.
For example, ~/.workerd-cluster.env:
export WORKERD_CLUSTER_KEY='YOUR_SHARED_CLUSTER_KEY'
export WORKERD_CLUSTER_BUCKET='s3://workerd-cluster/counters'
export AWS_ENDPOINT_URL='https://ACCOUNT_ID.r2.cloudflarestorage.com'
export AWS_REGION='auto'
export AWS_ACCESS_KEY_ID='YOUR_R2_ACCESS_KEY_ID'
export AWS_SECRET_ACCESS_KEY='YOUR_R2_SECRET_ACCESS_KEY'
Replace the placeholder values with the actual credentials.
Restrict access to the file:
chmod 600 ~/.workerd-cluster.env
Transfer the cluster key and credentials through a secure channel, or provision them through a secrets-management system.
The bucket and prefix must be identical on both machines.
Here, counters is the prefix reserved for this cluster’s data.
Using a different prefix creates a separate storage location rather than joining the existing cluster.
For managed deployments, workerd also supports file-based secret configuration, including WORKERD_CLUSTER_KEY_FILE and AWS_CREDENTIALS_FILE.
6. Start the two workerd instances
On Server A, load the environment:
source ~/.workerd-cluster.env
Then start the runtime:
npx workerd serve --experimental ./app \
--cluster-addr 10.0.0.1:7000
On Server B, load the corresponding environment and run:
npx workerd serve --experimental ./app \
--cluster-addr 10.0.0.2:7000
The configurations are almost identical.
Only the advertised cluster address differs.
The --experimental flag enables cluster functionality.
Once the instances start, check their readiness from a machine connected to the same private network:
curl -i http://10.0.0.1:7000/ready
curl -i http://10.0.0.2:7000/ready
A ready instance returns HTTP 200.
If either instance remains unavailable, check its startup logs, bucket permissions, private network connectivity, and environment variables before sending application requests.
A process running successfully is not necessarily a process that has successfully joined the cluster.
7. Check whether both servers share the same counter
First, identify the responding Worker instances:
curl http://10.0.0.1:8787/health
curl http://10.0.0.2:8787/health
Now increase the counter through Server A:
curl -fsS -X POST \
http://10.0.0.1:8787/increment
For a previously unused cluster, an illustrative response would be:
{
"count": 1,
"objectInstance": "instance-a",
"requestInstance": "instance-a"
}
Send the next request to Server B:
curl -fsS -X POST \
http://10.0.0.2:8787/increment
A possible response is:
{
"count": 2,
"objectInstance": "instance-a",
"requestInstance": "instance-b"
}
Notice what has changed.
The second request entered through another machine, but it reached the same Durable Object.
The counter did not restart from zero.
For a more useful test, alternate requests between the servers:
for i in 1 2 3; do
curl -fsS -X POST \
http://10.0.0.1:8787/increment
echo
curl -fsS -X POST \
http://10.0.0.2:8787/increment
echo
done
Assuming the counter started at zero and the previous two requests succeeded, the expected sequence is:
| Request | Entry server | Counter |
|---|---|---|
| 1 | A | 3 |
| 2 | B | 4 |
| 3 | A | 5 |
| 4 | B | 6 |
| 5 | A | 7 |
| 6 | B | 8 |
These are expected results, not captured output from a completed two-server experiment.
The important checks are that the values increase consistently and that object ownership remains stable while the owner is healthy.
The actual owner does not have to be Server A.
How does workerd coordinate ownership without a consensus service?
Cloudflare’s cluster implementation relies on conditional operations provided by the object store.
A conditional write allows a storage operation to succeed only when a specified condition remains true.
For example, a write may require that an existing object’s version still matches the version previously observed by the caller.
If another process modified that object in the meantime, the condition fails.
This gives distributed processes a way to coordinate ownership without relying on an additional service such as etcd.
R2 supports conditional S3-compatible write operations, making it suitable for this architecture.
When a Durable Object has an active owner, that ownership is maintained through a lease. Another instance can take responsibility for the object when ownership is released or its lease expires.
This does not mean that several SQLite processes independently write to the same database file over a network filesystem.
Each object has one active owner. The shared bucket stores its authoritative durable state, while the runtime maintains the local data necessary to execute the object.
8. Test graceful failover
Now we can examine what happens when the active owner stops.
Begin by reading the current value without modifying it:
curl -fsS http://10.0.0.2:8787/count
Record the returned count and object instance.
Determine which server currently owns the object using the diagnostic identifiers from the earlier requests.
Assuming Server A is the owner, connect to it and identify the actual workerd process:
pgrep -a -x workerd
After confirming the correct process ID, send it SIGTERM:
kill -TERM WORKERD_PID
Replace WORKERD_PID with the numeric process ID.
Do not use the literal placeholder.
According to the official documentation, SIGTERM initiates graceful shutdown and gives the instance an opportunity to hand off its Durable Objects. The default cluster handoff timeout is eight seconds.
The other instance can then take ownership.
sequenceDiagram
participant A as Server A
participant R2 as R2 bucket
participant B as Server B
participant C as Client
A->>R2: Persist counter state
Note over A: SIGTERM received
A->>R2: Release object ownership
C->>B: GET /count
B->>R2: Acquire ownership
B->>R2: Recover SQLite state
B-->>C: Return existing counter value
C->>B: POST /increment
B->>R2: Persist updated state
B-->>C: Return updated counter
This diagram represents the logical handoff, rather than the exact internal network protocol.
Once Server A has stopped, query Server B:
curl -fsS http://10.0.0.2:8787/count
If the previous value was 8, it should still be 8.
The next increment should return 9:
curl -fsS -X POST \
http://10.0.0.2:8787/increment
The value survives because Server B can recover the object’s persisted state from the bucket.
During the transition, individual requests may fail or experience additional latency. Graceful shutdown is not a guarantee of uninterrupted service for every request.
9. Compare graceful shutdown with an abrupt exit
Restart Server A and wait for it to become ready.
There are now two healthy instances again.
Repeat the ownership check, then stop the current owner using SIGINT instead of SIGTERM.
kill -INT WORKERD_PID
This corresponds to the immediate-exit behavior documented for Ctrl+C.
Unlike SIGTERM, it does not perform the same graceful object handoff.
The surviving instance may need to wait until the previous ownership lease expires, approximately twenty seconds under the documented defaults.
The difference is substantial:
| Shutdown method | Behavior |
|---|---|
SIGTERM |
Attempts graceful object handoff |
SIGINT |
Exits immediately; recovery may wait for lease expiration |
| Unexpected crash | Recovery depends on detecting lost ownership and lease expiration |
To observe recovery, periodically send a read-only request to the surviving server:
for i in $(seq 1 30); do
date -u +"%H:%M:%S"
curl --max-time 2 -sS -w "\nHTTP %{http_code}\n" \
http://10.0.0.2:8787/count || true
sleep 1
done
This example assumes Server B survived. Change the address if Server A is the remaining instance.
Record how long it takes before successful responses resume.
The lease duration should not be interpreted as a guaranteed maximum recovery time. Network conditions, storage availability, and runtime behavior can affect the result.
The read-only endpoint is useful because retrying it does not accidentally increment the counter.
10. Does failover guarantee that no data is lost?
Cloudflare documents that an acknowledged cluster write waits until its data has been uploaded to the object store.
That is an important durability property.
Suppose our application returns a successful response confirming that the counter reached 20. If the owner subsequently stops, the next instance should be able to recover the acknowledged state from the bucket.
But consider a slightly different situation.
The server increments the value and persists it successfully. Before the HTTP response reaches the client, the connection is interrupted.
From the client’s perspective, the request failed.
From the storage system’s perspective, the increment may already have completed.
If the client automatically retries the same POST request, the counter can increase again.
The durable storage guarantee does not eliminate this ambiguity.
For operations that must not execute twice, the application needs an idempotency strategy. One approach is to associate each operation with a unique request identifier and record processed identifiers alongside the relevant state.
For a visit counter, duplicate increments may be acceptable. For payment operations or inventory updates, they probably are not.
Failover and exactly-once execution are separate problems.
Why the example uses fetch instead of JavaScript RPC
Durable Objects also support JavaScript RPC methods.
A counter could expose a method such as:
increment() {
const count =
(this.ctx.storage.kv.get("count") ?? 0) + 1;
this.ctx.storage.kv.put("count", count);
return count;
}
The Worker would call it using:
const count = await counter.increment();
This is convenient, and it appears in the official workerd quick-start example.
However, Cloudflare’s Kubernetes sample deliberately uses stub.fetch() for requests that may encounter object movement.
Its documentation explains that a JavaScript RPC call reaching an instance during shutdown can fail with a retryable error. A subsequent call can discover the object’s new owner.
The HTTP-style fetch() path supports forwarding to the new owner during this transition.
That is why this tutorial uses fetch() for the failover experiment.
Neither approach removes the application’s responsibility to handle failures carefully.
Security limitations
Running the application on your own servers changes who is responsible for protecting it.
Cloudflare’s managed platform supplies security and operational infrastructure beyond the open-source runtime itself.
The experimental cluster requires particular attention to three areas.
Cluster traffic is not encrypted.
The shared key authenticates peer communication, but does not encrypt the traffic between instances.
Use a trusted private network, or an encrypted network overlay such as WireGuard. Restrict access to the cluster port so unrelated machines cannot reach it.
Bucket credentials are highly privileged.
The bucket stores more than ordinary application documents.
Cloudflare’s deployment documentation warns that someone with write access to the cluster bucket can publish code that the instances execute.
Treat those credentials accordingly. Do not share the bucket with untrusted applications or grant unnecessary write access.
workerd is not a hardened sandbox by itself.
Although the runtime provides isolation mechanisms, it does not include every additional security layer available on the managed Cloudflare platform.
Do not use this experimental setup to execute arbitrary untrusted customer code without additional isolation.
Our demonstration also exposes an unauthenticated increment endpoint. That is acceptable within an isolated test network, but not for a publicly accessible application.
Operational limitations
Moving from a single runtime to two instances improves resilience against the failure of an individual server.
It does not eliminate every dependency.
Both servers still depend on the shared bucket.
If that bucket becomes unavailable, adding another workerd instance does not restore access to persistent state.
There is also a latency consideration. Since acknowledged writes depend on object storage persistence, the connection between your servers and R2 affects write performance.
A counter updated thousands of times per second may behave differently from a document updated once every few minutes.
Measure the workload before assuming that object-storage-backed persistence will meet its latency requirements.
Storage operations can also incur R2 charges, independently of the cost of running your servers.
Finally, two servers do not automatically provide a highly available public HTTP endpoint.
A production-oriented architecture would need a separate load balancer or another mechanism for removing unavailable servers from incoming traffic.
The cluster readiness endpoint can help with that decision.
When does this architecture make sense?
The interesting property of Durable Objects is not necessarily that they replace a conventional database.
It is that they associate computation and persistent state with a particular identity.
A chat room can have its own object. So can a collaborative document or a connected device.
Requests concerning the same entity reach the object responsible for it, while unrelated entities can be handled elsewhere in the cluster.
For our demonstration, a single global counter is owned by one instance. Adding more machines improves its potential availability but does not make that individual counter execute concurrently across every machine.
If we instead create thousands of independent counters, each identified by a different name, the cluster can distribute their ownership.
That is a different scaling model from running several interchangeable application servers against one central relational database.
Neither architecture is universally preferable.
The choice depends on how naturally the application’s state can be divided into independently managed entities.
Cloudflare’s experimental clustering makes it possible to explore this model without deploying those objects to the managed Workers platform.
The application code remains relatively small. Most of the complexity lies in ownership coordination, persistence, network security, and recovery.
For now, the cluster should be treated as an experimental distributed runtime rather than a drop-in replacement for a mature production hosting platform.
External Sources used for this article
- Cloudflare — Self-host Workers and Durable Objects with workerd clustering, December 3, 2026
- workerd — Release v1.20261202.1
- workerd — Quick Start, Clustering and Security
- workerd — Official Kubernetes Cluster Example
- workerd — Official Cluster Counter Implementation
- Cloudflare R2 — S3-Compatible API Setup
- Cloudflare R2 — Authentication and Permissions
- Cloudflare R2 — S3 API Compatibility