0Pricing
Edge Computing with Cloudflare Workers & Deno · レッスン

Durable Objectsとステートフルな協調処理

Durable Objectsを使い、ステートレスなエッジアーキテクチャに強い整合性を持つ単一インスタンスの状態管理と協調処理を追加します。

「Durable Objectsとステートフルな協調処理」はCoddyKit上の無料Edge Computing with Cloudflare Workers & Denoレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはEdge Computing with Cloudflare Workers & Deno学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

The Stateless Problem

Workers are stateless by design, each request may hit a different instance anywhere on Earth.

That is great for scale, but hard when you need:

  • A single source of truth
  • Coordination between many clients
  • Strong consistency, not eventual

Durable Objects solve exactly this.

What Is a Durable Object?

A Durable Object (DO) is a single, globally-addressable instance with its own private storage.

For a given object ID, all requests route to the same instance, giving you a consistent place to hold state.

Defining a Durable Object Class

A DO is a class with a fetch() method and access to persistent state.storage.

export class Counter {
  constructor(state, env) {
    this.state = state;
  }
  async fetch(request) {
    let count = (await this.state.storage.get('count')) || 0;
    count++;
    await this.state.storage.put('count', count);
    return new Response(String(count));
  }
}

Binding the Object

Declare the DO class as a binding in wrangler.toml and add a migration so Cloudflare knows about it.

[[durable_objects.bindings]]
name = "COUNTER"
class_name = "Counter"

[[migrations]]
tag = "v1"
new_classes = ["Counter"]

Getting an Object Stub

From a Worker, derive an ID then get a stub to talk to that specific instance.

const id = env.COUNTER.idFromName('global-counter');
const stub = env.COUNTER.get(id);
const res = await stub.fetch('https://do/increment');

idFromName vs newUniqueId

Two ways to get an ID:

  • idFromName('room-42') deterministic, same name always maps to the same object, ideal for named resources like chat rooms
  • newUniqueId() a brand-new unique object, ideal for per-session state

Strong Consistency Guarantee

Because every request for an ID hits the same instance and runs single-threaded, DO operations are strongly consistent, no race conditions on its own storage.

This makes DOs perfect for counters, locks, and leaderboards.

Coordinating Many Clients

A DO is a natural hub. Combined with WebSockets it can broadcast to all connected clients, the basis for collaborative apps and multiplayer rooms.

// Inside the DO: track sockets and fan out
this.sessions.forEach((ws) => ws.send(message));

Storage API Basics

state.storage is a transactional key-value store local to the object.

await this.state.storage.put('user:1', { name: 'Ada' });
const user = await this.state.storage.get('user:1');
await this.state.storage.delete('user:1');

Alarms for Scheduled Logic

Durable Objects support alarms, schedule the object to wake itself up later for cleanup or timeouts.

await this.state.storage.setAlarm(Date.now() + 60000);
// later, the runtime calls:
async alarm() {
  await this.cleanup();
}

When to Use Durable Objects

Reach for DOs when you need:

  • Coordination across requests or clients
  • Strong consistency on a single entity
  • Real-time rooms, locks, rate counters, or queues

For simple cached reads, KV is cheaper. Choose the right tool.

Quick Check

Which method gives you a deterministic Durable Object ID for a named resource like a chat room?

Recap

Durable Objects bring stateful coordination to the edge:

  • One globally-addressable instance per ID
  • Private transactional storage and alarms
  • Strong consistency and single-threaded execution
  • Use idFromName for named resources, newUniqueId for sessions

They are the missing piece for real-time, consistent, edge-native systems.

よくある質問

「Durable Objectsとステートフルな協調処理」レッスンは無料ですか?

はい。「Durable Objectsとステートフルな協調処理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Edge Computing with Cloudflare Workers & Denoコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。

「Durable Objectsとステートフルな協調処理」で何を学びますか?

Durable Objectsを使い、ステートレスなエッジアーキテクチャに強い整合性を持つ単一インスタンスの状態管理と協調処理を追加します。 ブラウザで直接実行するハンズオンコードでEdge Computing with Cloudflare Workers & Denoを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Edge Computing with Cloudflare Workers & Denoを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのEdge Computing with Cloudflare Workers & Denoは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「Durable Objectsとステートフルな協調処理」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このEdge Computing with Cloudflare Workers & Denoレッスンでコードを書いて実行できますか?

はい。すべてのEdge Computing with Cloudflare Workers & Denoレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. エッジでのマイクロサービス
  2. イベント駆動アーキテクチャ
  3. ジオロケーションとローカライゼーション
  4. Durable Objectsとステートフルな協調処理
← Edge Computing with Cloudflare Workers & Denoに戻る