Cloudflare Durable Objects tutorial

By

Updated

Tagged: Cloudflare

Learn Cloudflare Durable Objects step by step using TypeScript, RPC methods, named instances, and each object's embedded SQLite database.

Durable Objects are one of the most useful parts of Cloudflare Workers, and they’re much easier to grasp by building something than by reading through a list of APIs.

We’ll build a small counter. The counter itself isn’t the point; it’s just small enough to stay out of the way while we look at what makes Durable Objects different:

  • every object has a stable identity
  • every object runs in one place at a time
  • every object has private persistent storage
  • requests for the same object can coordinate safely
  • different objects work independently

By the end, you’ll know how to create, call, test, and deploy a Durable Object, and you’ll have a clear sense of when to reach for one.

This tutorial uses Cloudflare’s managed service. If you’re interested in a self-hosted implementation of the same APIs, check out how celld runs Workers on your own infrastructure.

Why Durable Objects exist

A normal Worker is stateless. It takes a request, runs your code, and returns a response, and the next request might hit a completely different instance in another location. That works great when requests are independent, but things get tricky the moment several requests need to agree on shared state.

Picture two requests trying to increment the same counter at once. Both read 10, both add one, and both write back 11, so one of those increments gets lost. The same race shows up all over real applications:

  • two people reserving the last seat
  • two players making a move at the same time
  • several users editing the same document
  • hundreds of clients sending messages into one chat room
  • multiple requests updating the same rate limit

A Durable Object solves this by giving that shared state a single owner. Cloudflare routes every request for the same object to the same logical instance, which can keep temporary state in memory and persist data in its own embedded SQLite database.

The easiest way to picture a Durable Object is as a small named server with private storage. Instead of running one big server for your whole application, you create lots of small objects, one per room, document, game, user, device, tenant, or whatever unit needs to coordinate its own state.

Create the project

Make sure you have a Cloudflare account and Node.js installed. If you’re new to Workers, my free Cloudflare Workers course walks through the runtime, Wrangler, bindings, storage, testing, and deployment in a complete project.

Start by creating a new project:

npm create cloudflare@latest -- durable-objects-tutorial

When the prompts appear, pick these options:

  • Hello World example
  • Worker + Durable Objects
  • TypeScript
  • Yes for Git
  • No for the first deployment

Then move into the new folder:

cd durable-objects-tutorial

The template installs Wrangler 4 (the current major version) directly in the project, so npm run dev and the npx wrangler commands we run later will all use that local copy.

We’ll only touch two files in this project:

durable-objects-tutorial/
├── src/
│   └── index.ts
└── wrangler.jsonc

Inside src/index.ts, you have both a normal Worker and a Durable Object class. The Worker handles incoming public HTTP requests, picks the right object, and calls it, while the Durable Object class owns the state.

Configure the Durable Object

Open wrangler.jsonc and replace its contents with this configuration:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "durable-objects-tutorial",
  "main": "src/index.ts",
  "compatibility_date": "2026-08-13",
  "durable_objects": {
    "bindings": [
      {
        "name": "COUNTERS",
        "class_name": "Counter"
      }
    ]
  },
  "exports": {
    "Counter": {
      "type": "durable-object",
      "storage": "sqlite"
    }
  }
}

The durable_objects.bindings entry exposes a namespace called COUNTERS to our Worker, and the exports entry tells Cloudflare to provision the Counter class with SQLite storage.

If you’ve read older tutorials, you might have seen a migrations array with new_sqlite_classes. Cloudflare treats that as the legacy flow now; new projects use exports, and you shouldn’t mix the two in the same Worker.

Create your first Durable Object class

Open src/index.ts and start with a minimal Counter class:

import { DurableObject } from 'cloudflare:workers'

interface Env {
  COUNTERS: DurableObjectNamespace<Counter>
}

export class Counter extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env)
  }
}

Every Durable Object is a class that extends DurableObject. Inside the constructor, ctx gives you access to the object’s state and storage, while env holds its bindings. The Env interface describes the COUNTERS binding we just defined in wrangler.jsonc.

Right now the class doesn’t store anything, so let’s add its SQLite table next.

Create the SQLite table

Every new Durable Object comes with its own embedded SQLite database. Update the constructor so it sets up a single-row table starting at 0:

export class Counter extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env)

    this.ctx.storage.sql.exec(`
      CREATE TABLE IF NOT EXISTS counter (
        id INTEGER PRIMARY KEY CHECK (id = 1),
        value INTEGER NOT NULL
      );

      INSERT OR IGNORE INTO counter (id, value)
      VALUES (1, 0);
    `)
  }
}

Keep in mind that this constructor can run more than once. When an object sits idle, Cloudflare can evict the class instance from memory and construct a fresh one the next time a request comes in, while the SQLite data stays intact. Using CREATE TABLE IF NOT EXISTS and INSERT OR IGNORE makes this setup safe to repeat whenever the instance wakes up.

Also notice that sql.exec() is synchronous, so you don’t await your SQL queries here.

Add methods to read and change the value

Workers talk to Durable Objects through RPC methods, which means any public method you put on the class can be called directly from a stub.

Start by adding a method that reads the current value:

async getValue(): Promise<number> {
  const row = this.ctx.storage.sql
    .exec<{ value: number }>(
      'SELECT value FROM counter WHERE id = 1',
    )
    .one()

  return row.value
}

Because sql.exec() returns a cursor and we expect exactly one row back, we call .one() on it.

Next, add a method to increment the counter:

async increment(amount = 1): Promise<number> {
  const row = this.ctx.storage.sql
    .exec<{ value: number }>(
      `UPDATE counter
       SET value = value + ?
       WHERE id = 1
       RETURNING value`,
      amount,
    )
    .one()

  return row.value
}

The ? placeholder binds to the second argument of sql.exec(), keeping the value safely separate from the SQL string.

Finally, add a reset method:

async reset(): Promise<number> {
  this.ctx.storage.sql.exec(
    'UPDATE counter SET value = 0 WHERE id = 1',
  )

  return 0
}

They look like regular TypeScript methods, and Cloudflare handles turning their arguments and return values into RPC messages behind the scenes.

Call the object from the Worker

Durable Objects don’t take public Internet traffic directly. Your Worker receives the HTTP request, chooses which object should handle it, and calls it through the binding.

Add the Worker handler right below the Counter class:

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url)
    const name = url.searchParams.get('name') ?? 'default'
    const counter = env.COUNTERS.getByName(name)

    if (request.method === 'POST' && url.pathname === '/increment') {
      const value = await counter.increment()
      return Response.json({ name, value })
    }

    if (request.method === 'POST' && url.pathname === '/reset') {
      const value = await counter.reset()
      return Response.json({ name, value })
    }

    if (request.method === 'GET' && url.pathname === '/') {
      const value = await counter.getValue()
      return Response.json({ name, value })
    }

    return Response.json({ error: 'Not found' }, { status: 404 })
  },
} satisfies ExportedHandler<Env>

The key line in that handler is how we look up the object:

const counter = env.COUNTERS.getByName(name)

Calling getByName('page-views') always points to the same logical object inside the COUNTERS namespace, while getByName('downloads') points to a separate one. What you get back is a stub, a client for that single Durable Object. When you call counter.increment(), Cloudflare sends an RPC call over to it. Because that object might be running in another location, you always await those RPC calls.

Run it locally

Start the local dev server with Wrangler:

npm run dev

Wrangler normally listens at http://localhost:8787. Once it’s running, read the default counter:

curl http://localhost:8787/

You’ll get this response:

{
  "name": "default",
  "value": 0
}

Now increment it:

curl -X POST http://localhost:8787/increment

The counter goes up to 1:

{
  "name": "default",
  "value": 1
}

Run the same command again and you’ll see 2. If you stop the dev server, start it back up, and read the counter, you’ll still see 2, because Wrangler keeps local Durable Object storage across restarts.

Names create different objects

Now try passing a name in the request, and run this command twice:

curl -X POST \
  'http://localhost:8787/increment?name=page-views'

Then create a second counter with a different name:

curl -X POST \
  'http://localhost:8787/increment?name=downloads'

Now read both counters back:

curl 'http://localhost:8787/?name=page-views'
curl 'http://localhost:8787/?name=downloads'

You’ll get 2 for page-views and 1 for downloads. Instead of two rows in one shared database, those are two separate Durable Objects, each with its own class instance and its own SQLite database:

COUNTERS namespace
├── page-views object
│   └── private SQLite database
└── downloads object
    └── private SQLite database

This is how Durable Objects scale: instead of pushing all your traffic through a single global object, you split your app along independent units of coordination.

Choose the object boundary

The name you pass to getByName() sets your object boundary, and it’s the most important design choice you’ll make when building with Durable Objects. Here are a few natural boundaries:

const room = env.CHAT_ROOMS.getByName(roomId)
const game = env.GAMES.getByName(gameId)
const document = env.DOCUMENTS.getByName(documentId)
const limiter = env.RATE_LIMITERS.getByName(userId)

With names like those, every room, game, document, or user gets its own object. Requests with the same name meet at the same instance, while requests for different names run in parallel without waiting on each other.

Unless your whole app genuinely needs a single global coordinator, avoid doing this:

const object = env.OBJECTS.getByName('global')

A single global object turns into a bottleneck fast, and it lumps unrelated state into the same storage and failure boundary.

My advice is to finish this sentence:

There must be exactly one owner for each ________.

Whatever fills that blank is usually the name you want for your Durable Object.

Why concurrent increments are safe

Let’s test concurrency by firing 20 increments at the same counter at once:

seq 1 20 | xargs -P20 -I{} \
  curl -s -X POST \
  'http://localhost:8787/increment?name=concurrent'

Now check the result:

curl 'http://localhost:8787/?name=concurrent'

You’ll see 20. Every request for concurrent landed on the same logical object, and the SQL update updated the row atomically inside its local SQLite database.

Under the hood, Durable Objects also use input and output gates around storage operations. An input gate stops another event from observing storage while protected storage work is in progress, and an output gate makes sure the object doesn’t confirm a response until its writes are durable. Because of that, you normally don’t need to write manual locks around local Durable Object storage.

That protection only covers local storage, though, and doesn’t automatically make every asynchronous operation atomic.

Be careful with external I/O

While your code waits on non-storage I/O, JavaScript is free to handle another incoming request. Look at what happens in this snippet:

async updateFromAnotherService() {
  const before = await this.getValue()

  const response = await fetch('https://api.flaviocopes.com/value')
  const { amount } = await response.json<{ amount: number }>()

  this.ctx.storage.sql.exec(
    'UPDATE counter SET value = ? WHERE id = 1',
    before + amount,
  )
}

While fetch() is in flight, another request can easily change the counter, leaving before stale by the time the external call returns.

Don’t assume you’re holding a lock across fetch(), R2, KV, or any other external service. Persist whatever state you need before making the call, and verify it again once the call comes back. You might be tempted to wrap it in blockConcurrencyWhile(), which pauses all incoming events, but that’s meant for short initialization and storage migrations, not slow network calls.

Memory is not durable

You can store properties directly on your Durable Object class, like this:

private requestsSinceStart = 0

Reading a property from memory is fast, but it won’t stick around forever. When an object goes idle, Cloudflare can evict it from memory; the next request spins up a fresh class instance, and requestsSinceStart resets to 0. Your SQLite data survives that eviction without a hitch.

Use in-memory properties for caches and active connections, and write any state you can’t afford to lose to this.ctx.storage before you return success. That’s why the name refers to the object’s identity and stored state rather than the JavaScript instance in memory.

The complete code

Here’s the complete src/index.ts file with everything put together:

import { DurableObject } from 'cloudflare:workers'

interface Env {
  COUNTERS: DurableObjectNamespace<Counter>
}

export class Counter extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env)

    this.ctx.storage.sql.exec(`
      CREATE TABLE IF NOT EXISTS counter (
        id INTEGER PRIMARY KEY CHECK (id = 1),
        value INTEGER NOT NULL
      );

      INSERT OR IGNORE INTO counter (id, value)
      VALUES (1, 0);
    `)
  }

  async getValue(): Promise<number> {
    const row = this.ctx.storage.sql
      .exec<{ value: number }>(
        'SELECT value FROM counter WHERE id = 1',
      )
      .one()

    return row.value
  }

  async increment(amount = 1): Promise<number> {
    const row = this.ctx.storage.sql
      .exec<{ value: number }>(
        `UPDATE counter
         SET value = value + ?
         WHERE id = 1
         RETURNING value`,
        amount,
      )
      .one()

    return row.value
  }

  async reset(): Promise<number> {
    this.ctx.storage.sql.exec(
      'UPDATE counter SET value = 0 WHERE id = 1',
    )

    return 0
  }
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url)
    const name = url.searchParams.get('name') ?? 'default'
    const counter = env.COUNTERS.getByName(name)

    if (request.method === 'POST' && url.pathname === '/increment') {
      const value = await counter.increment()
      return Response.json({ name, value })
    }

    if (request.method === 'POST' && url.pathname === '/reset') {
      const value = await counter.reset()
      return Response.json({ name, value })
    }

    if (request.method === 'GET' && url.pathname === '/') {
      const value = await counter.getValue()
      return Response.json({ name, value })
    }

    return Response.json({ error: 'Not found' }, { status: 404 })
  },
} satisfies ExportedHandler<Env>

Even though this counter is small, it walks through the full Durable Objects request path you’ll use in much larger apps:

  1. The Worker receives an HTTP request.
  2. getByName() selects one object.
  3. The Worker calls a public RPC method on the stub.
  4. The object reads from or writes to its private SQLite database.
  5. The RPC result comes back to the Worker.
  6. The Worker returns the HTTP response.

Deploy the Worker

To push this live, log in to your Cloudflare account first:

npx wrangler login

Then deploy the project:

npx wrangler deploy

Wrangler prints your workers.dev URL once the deploy finishes. Give the live Worker a quick test:

curl -X POST \
  'https://durable-objects-tutorial.YOUR-SUBDOMAIN.workers.dev/increment?name=page-views'

That first deployment provisions the Counter namespace you declared in exports, and future deployments will keep that namespace and all of its stored data intact.

One thing to watch out for later: deleting or renaming a Durable Object class can move or remove stored data, so check Cloudflare’s Durable Object class exports documentation before making lifecycle changes to a class that’s already deployed.

Where to go next

So far our object handles RPC calls and keeps its state in SQLite. Two more features plug right into the same model once you need them.

WebSockets

A single object can own all the live WebSocket connections for a chat room, a game, or a collaborative document. With the Hibernatable WebSockets API, Cloudflare can evict the JavaScript instance from memory while clients stay connected and wake it back up as soon as a message arrives. You still partition by name, so one room name maps to one room object and all of its connections.

Alarms

Each Durable Object can also schedule a single alarm to wake itself up at a future time, which comes in handy for expiring sessions, retrying failed work, closing an inactive room, or processing the next scheduled item. Calling setAlarm() again replaces the existing alarm, so if your app needs multiple scheduled items, store them in SQLite and point the alarm at whichever one is due next.

When I would use Durable Objects

Reach for a Durable Object when your app needs a single authoritative owner for each independent piece of state. It’s a natural fit for things like:

  • a chat room with connected users
  • a multiplayer game or lobby
  • a collaborative document
  • a per-user rate limiter
  • a device session
  • an inventory or booking boundary
  • a long-lived AI agent

Skip them for static content, large files, general analytics, or independent requests. Cloudflare already gives you better tools for those:

  • a plain Worker for stateless request handling
  • D1 for relational data you need to query across many entities
  • KV for globally read configuration or cached values
  • R2 for files and large objects

If you’re not sure which option fits your case, my free Cloudflare storage chooser can help you decide.

Once you think of a Durable Object as one unit that brings code, identity, storage, and coordination together, rather than just another database, the rest of the API makes a lot more sense. Check the official Cloudflare Durable Objects documentation for the complete API and more examples.

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: