惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

Flavio Copes

Workers Cache: a cache in front of your Cloudflare Worker Cloudflare Drop: drag a folder, get a live site Temporary Cloudflare accounts: agents can now deploy without signing up Moondream 3.1 on Workers AI: fast vision at the edge inferencecost.dev: what will AI inference cost you at 10k users? Sitebase: all the features your website needs, in one place StackPlan: figure out where to deploy your app, and what it How the Cloudflare Pages build cache works The Summer of Code How I generate an Open Graph image for every post New: 90 free tools for developers How I added search to my static site with Pagefind How to rebuild a Cloudflare site on a schedule Cloudflare Email Workers: run code when an email arrives Cloudflare Turnstile: stop bots without annoying CAPTCHAs Cloudflare Workers: secrets and environments Cloudflare Workers observability: logs and traces Cloudflare Analytics Engine: store and query metrics The AI Workshop (July 2026 cohort) Cloudflare Cron Triggers: run a Worker on a schedule Cloudflare Queues: run work in the background Cloudflare R2: object storage without egress fees Cloudflare KV: a key-value store for your Workers Cloudflare D1: a SQL database for your Workers Serving a website with Cloudflare Workers static assets Wrangler: the Cloudflare Workers command line tool Executor: one gateway to connect your AI agent to every tool Cloudflare Workers: your first serverless function Vercel eve: an open framework for building AI agents Flue: the open framework for building AI agents Val Town: write and deploy code in seconds A hands-on guide to The Agency, a collection of AI agents The AI Workshop (June 2026 cohort) The AI Workshop (May 2026 cohort) The AI Workshop (Apr 2026 cohort)
Cloudflare Durable Objects: state that lives in one place
Flavio Copes · 2026-06-27 · via Flavio Copes

By Flavio Copes

What Durable Objects are and how to use them, with their built-in SQLite storage. A simple counter and a rate limiter, explained from scratch.

~~~

This is the most powerful tool on the Cloudflare platform, and the one that takes a minute to click. Let me try to make it simple.

A Durable Object is a tiny server that exists once per name. It keeps its own memory, has its own little database, and handles one request at a time.

That last part is the magic. Because there’s only one of each, and it does one thing at a time, you never get two requests stepping on each other. No race conditions.

Think of a chat room. You want exactly one place that holds the messages and the list of who’s online. A Durable Object named after the room is that one place.

If you’re wondering whether you actually need a Durable Object instead of KV, D1 or R2, I built a free Cloudflare storage chooser that helps you pick.

Let’s build the simplest possible one: a counter.

A counter

A Durable Object is a class. It extends DurableObject, and it gets its own SQLite database through this.ctx.storage.sql:

import { DurableObject } from 'cloudflare:workers'

export class Counter extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env)
    this.ctx.storage.sql.exec(
      'create table if not exists counter (value integer)'
    )
  }

  async increment() {
    this.ctx.storage.sql.exec(
      'insert into counter (value) values (1)'
    )
    const { count } = this.ctx.storage.sql
      .exec('select count(*) as count from counter')
      .one()
    return count
  }
}

The constructor creates the table once. increment adds a row and returns the new total. This database belongs to this one object, and it survives restarts.

Wire it up

Declare the class in wrangler.jsonc, and tell Cloudflare it uses SQLite storage with a migration:

{
  "durable_objects": {
    "bindings": [
      { "name": "COUNTER", "class_name": "Counter" }
    ]
  },
  "migrations": [
    { "tag": "v1", "new_sqlite_classes": ["Counter"] }
  ]
}

Use it from a Worker

Here’s where the “once per name” idea shows up. You turn a name into an id, then get that object:

export default {
  async fetch(request, env) {
    const id = env.COUNTER.idFromName('global')
    const counter = env.COUNTER.get(id)

    const value = await counter.increment()

    return Response.json({ value })
  },
}

idFromName('global') always points to the same object. So everyone hitting this Worker talks to one shared counter, and it counts correctly even with lots of people at once.

Notice you call counter.increment() directly, like a normal method. Cloudflare routes the call to the object for you, wherever it lives.

If you used a different name, say a user id, you’d get a separate object per user, each with its own count. That’s the pattern: one object per thing you want to coordinate.

A real example: rate limiting

Counters are the toy version. A common real use is rate limiting, stopping someone from hammering your API.

One Durable Object per user, holding how many requests they’ve made recently:

import { DurableObject } from 'cloudflare:workers'

export class RateLimiter extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env)
    this.ctx.storage.sql.exec(
      'create table if not exists hits (at integer)'
    )
  }

  async check() {
    const now = Date.now()
    const windowStart = now - 60_000

    this.ctx.storage.sql.exec('delete from hits where at < ?', windowStart)
    this.ctx.storage.sql.exec('insert into hits (at) values (?)', now)

    const { count } = this.ctx.storage.sql
      .exec('select count(*) as count from hits')
      .one()

    return count <= 10
  }
}

check drops old hits, records the new one, and returns whether the user is under 10 requests per minute. Because each user has their own object handling one call at a time, the count is always right.

From the Worker:

const id = env.RATE_LIMITER.idFromName(userId)
const limiter = env.RATE_LIMITER.get(id)

if (!(await limiter.check())) {
  return new Response('Too many requests', { status: 429 })
}

When to use one

Reach for a Durable Object when you need one place to coordinate something: a chat room, a live document, a game lobby, a counter, a rate limiter.

When the data is just rows you query, use D1. When it’s “one authoritative thing that many requests touch at once,” that’s a Durable Object. The full reference is in the Durable Objects docs.

~~~

Related posts about cloudflare: