Skip to main content
Back to Community & Earn Hub

Cloudflare Workers + Durable Objects for Stateful MCP Servers: How to avoid WebSocket hibernation state loss on 10MB+ session graphs?

@ishaan_malhotra5 days ago 1477 views

We deployed our remote MCP server on Cloudflare Workers + Durable Objects (DO) using the WebSocket Hibernation API (this.ctx.acceptWebSocket(ws)).

The Hibernation & Storage Trap

While the agent is actively thinking for 20 seconds, Cloudflare hibernates the Durable Object to save billing—which wipes all in-memory JS Map variables when the next WebSocket message wakes the DO!

When we tried persisting the entire MCP session state via await this.ctx.storage.put("session", state) before hibernation:

  1. Once an agent's accumulated tool-call history and file diffs exceed 128 KiB, ctx.storage.put() throws RangeError: Value exceeds 128 KiB limit.
  2. Rehydrating megabytes of JSON on every single WebSocket ping adds noticeable wake-up latency.

How do you architect Durable Object persistence for large stateful MCP sessions (10MB+) while still benefiting from WebSocket hibernation?

1 Answers

Community Answers

@priya_sharma Accepted Answer5 days ago

Durable Object KV storage (ctx.storage.put) has a strict 128 KiB per-value limit, and hibernated WebSockets wipe JS heap variables on wake. The clean production solution in 2026 is DO SQLite Storage (this.ctx.storage.sql) paired with ws.serializeAttachment() for lightweight connection metadata.


1. Use ws.serializeAttachment() for Connection Identity

Never reload 10MB of session history just to identify which client sent a ping. Store small metadata (sessionId, userId, scopes) directly on the hibernated WebSocket attachment (survives hibernation with zero SQL read!):

typescript
// On WebSocket connect:
this.ctx.acceptWebSocket(server);
server.serializeAttachment({ sessionId, userId, lastSeq: 0 });

// On wake inside webSocketMessage(ws, message):
const meta = ws.deserializeAttachment() as { sessionId: string; userId: string };

2. Store Large Tool Trajectories in Durable Object SQLite (ctx.storage.sql)

Enable SQLite-backed Durable Objects (new_sqlite_classes in wrangler.toml), which gives each DO up to 10 GB of co-located, zero-network-latency SQLite storage and removes the 128 KiB JSON blob bottleneck:

typescript
export class McpSessionDO extends DurableObject {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.ctx.storage.sql.exec(`
      CREATE TABLE IF NOT EXISTS tool_events (
        seq INTEGER PRIMARY KEY AUTOINCREMENT,
        tool_name TEXT NOT NULL,
        payload_json TEXT NOT NULL,
        created_at INTEGER NOT NULL
      );
    `);
  }

  async appendToolEvent(toolName: string, payload: unknown) {
    // Store individual events instead of rewriting one giant 10MB JSON blob!
    this.ctx.storage.sql.exec(
      `INSERT INTO tool_events (tool_name, payload_json, created_at) VALUES (?, ?, ?)`,
      toolName,
      JSON.stringify(payload),
      Date.now()
    );
  }

  async getRecentWindow(limit: number = 20) {
    return this.ctx.storage.sql
      .exec(`SELECT seq, tool_name, payload_json FROM tool_events ORDER BY seq DESC LIMIT ?`, limit)
      .toArray()
      .reverse();
  }
}

Why This Solves Both Problems:

  • Zero 128 KiB Crashes: Each tool event is a single SQLite row; total session state scales cleanly to 10MB–1GB+.
  • Sub-Millisecond Wakeup: On hibernation wake, you query only LIMIT 20 recent events instead of deserializing the entire session history.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.