Skip to content
AnswerWell geo Documentation

Research · 6 min read · Answerwell

Agent State Persistence, WebSocket Sync, and Connection Control

How Cloudflare Agents persist state in SQLite, sync it over WebSocket with useAgent and AgentClient, and restrict updates with readonly and protocol hooks.

This page summarizes Cloudflare Agents documentation on store and sync state: server-side setState(), SQLite persistence, and real-time updates to browsers through useAgent and AgentClient. It also covers readonly connections and protocol message controls for specialized clients.

Agent state: what persists and how it syncs

Section titled “Agent state: what persists and how it syncs”

Agent state is persistent, synchronized, bidirectional, and stored per agent instance in embedded SQLite. The framework recommends this.setState() rather than mutating this.state directly.

Agents provide built-in state management with automatic persistence and real-time synchronization across all connected clients.

— Cloudflare, Store and sync state

Property Meaning
Persistent Survives restarts, deploys, and hibernation (SQLite)
Synchronized Changes broadcast to connected WebSocket clients
Bidirectional Server and clients can update state
Instance-scoped Each name is a separate instance (e.g. CounterAgent:user-123 vs user-456)

Persistent state — State survives restarts, deploys, and hibernation. It is stored in SQLite
Real-time sync — All clients connected to the same agent receive state updates instantly
Hibernation — When no clients are connected, the agent hibernates (no cost). It wakes on the next request

— Cloudflare, Quick start

State vs props: Store and sync state distinguishes state (persisted, synced) from props (one-time initialization via getAgentByName or routeAgentRequest).

initialState, this.state, and setState() on the server

Section titled “initialState, this.state, and setState() on the server”

define defaults with initialState. The this.state getter lazy-loads from storage; for a new instance it uses initialState, for an existing instance it loads SQLite. If initialState is omitted, this.state can be undefined until you call setState().

this.state is a getter that lazily loads state from storage (SQL). State is persisted across Durable Object evictions when it is updated with this.setState(), which automatically serializes the state and writes it back to storage.

— Cloudflare, Agent class internals

setState() persists, broadcasts (except connections that opted out of protocol state frames), and triggers onStateChanged(). State must be JSON-serializable (no functions, classes, or circular references); use ISO strings for dates. See Store and sync state for state vs this.sql (keep state small; store large history in SQL).

onStateChanged, validateStateChange, and the source argument

Section titled “onStateChanged, validateStateChange, and the source argument”

Override onStateChanged(state, source) for notifications after a change. Use source === "server" to avoid reacting to your own server writes or infinite loops.

onStateChanged() is not intended for validation; it is a notification hook and should not block broadcasts. Use validateStateChange() for validation.

— Cloudflare, Store and sync state

validateStateChange() runs before persistence and broadcast, must be synchronous, and can reject or transform updates (return false or throw; rejections can surface to clients as CF_AGENT_STATE_ERROR). See Agents SDK workflows integration and Store and sync state.

On the server, onStateChanged is the preferred name; onStateUpdate is deprecated with a console warning (Agents SDK v0.4.0).

WebSocket clients: useAgent and AgentClient connection path

Section titled “WebSocket clients: useAgent and AgentClient connection path”

Browsers connect over WebSocket. Class names map to kebab-case URLs such as /agents/research-agent/user-123 (Build a Durable AI Agent, Client SDK).

Client Use case
useAgent React: reconnection, state, stub RPC
AgentClient Vanilla JS/TS
agentFetch HTTP when WebSocket is not needed

useAgent connects to your agent via WebSocket
onStateUpdate fires whenever the agent’s state changes
agent.stub.methodName() calls methods marked with @callable() on your agent

— Cloudflare, Add to existing project

Typical flow when a user clicks a control: client RPC → server method → setState() → SQLite → broadcast → client onStateUpdate or reactive agent.state (Add to existing project, Quick start).

Reading and pushing state from the browser

Section titled “Reading and pushing state from the browser”

Both clients expose a state property (undefined until the first server state message). In React, agent.state is reactive; you can still use onStateUpdate(state, source) where source is "server" or "client".

Both useAgent (React) and AgentClient (vanilla JS) now expose a state property that reflects the current agent state.

— Cloudflare, Agents SDK v0.8.0

Client setState() sends over WebSocket, runs server onStateChanged, broadcasts, and fires your callback with source: "client" (Client SDK).

Use optional chaining (agent.state?.field) until state is populated. For auth on connect, pass query (static or async); tokens are re-fetched on reconnect when using async query (Cross-domain authentication, Client SDK).

  • agent: class name → URL segment (ChatAgent → chat-agent).
  • name: instance id; defaults to "default".
  • Shared rooms, per-user agents, and basePath / onIdentity patterns are described in Routing.

Set static options.sendIdentityOnConnect: false on the server if instance names are sensitive (Routing, Agent class internals).

Protocol messages (cf_agent_state) vs custom WebSocket traffic

Section titled “Protocol messages (cf_agent_state) vs custom WebSocket traffic”

On connect, the framework may send JSON protocol frames: cf_agent_identity, cf_agent_state, cf_agent_mcp_servers. The Client SDK consumes these automatically; binary-only or minimal clients may not.

On every new connection, the Agent sends three protocol messages… For most web clients this is fine — the Client SDK and useAgent hook consume these messages automatically.

— Cloudflare, Protocol messages

Override shouldSendProtocolMessages(connection, ctx) and return false to suppress protocol frames for that connection (e.g. Sec-WebSocket-Protocol: mqtt). RPC, onMessage, and this.broadcast() still work (Protocol messages, WebSockets).

State is stored in the cf_agents_state SQL table. State messages are sent with type: "cf_agent_state" (both from the client and the server).

— Cloudflare, Agent class internals

Use isConnectionProtocolEnabled(connection) to check status; the flag is set at connect and survives hibernation (Protocol messages).

Readonly connections: view-only clients without mutating state

Section titled “Readonly connections: view-only clients without mutating state”

Readonly mode blocks client setState() and any @callable() that calls this.setState() internally. Observers still receive state broadcasts and may call non-mutating RPC.

When a connection is marked as readonly… It cannot call this.setState() — neither via client-side setState() nor via a @callable() method that calls this.setState() internally.

— Cloudflare, Readonly connections

Hook / API Role
shouldConnectionBeReadonly Decide at connect (e.g. query.mode === "view")
setConnectionReadonly Toggle at runtime (spectator ↔ player)
isConnectionReadonly Inspect current flag
Client onStateUpdateError Handles blocked client setState() and validation rejection

Readonly is per connection, not per user identity; combine with token checks in onConnect (Cross-domain authentication, Readonly connections).

Common mistakes when state does not persist or clients stay stale

Section titled “Common mistakes when state does not persist or clients stay stale”

Quick start and Add to existing project list the usual fixes:

  • Call this.setState(), not in-place mutation of this.state.
  • Register the agent class in new_sqlite_classes in migrations.
  • Use the same instance name on client and server.
  • Wire onStateUpdate / read agent.state in the UI.
  • Confirm the WebSocket is open (browser developer tools).

On hibernation, only this.state, connection.state, and this.sql persist—not ordinary class fields (WebSockets).

For AI chat UIs, pair useAgent with useAgentChat or WebSocketChatTransport for non-React stacks (Chat agents). Chat message persistence is separate from generic agent state; extend AIChatAgent for conversational apps (Agent class).

  1. Open your app, connect with useAgent or AgentClient using the intended agent and name, and in browser developer tools confirm the WebSocket to /agents/{agent-name}/{instance-name} is 101 Switching Protocols (Build a Durable AI Agent).

  2. Trigger a server update via a @callable() method and verify all tabs on the same instance receive the same state (Quick start).

  3. Call client setState() and confirm the server persists after refresh or reconnect (Store and sync state).

  4. If using view-only mode, connect with readonly query params and confirm writes fail with onStateUpdateError or RPC errors as documented in Readonly connections.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your setup, email yimasynthetic@gmail.com with the page URL and the exact statement you think is wrong or unclear.