Skip to content
Back to Cloud Services

Cloudflare WebSockets at the Edge

Bidirectional WebSocket connections from Workers with Hibernatable Sockets for cheap persistent connections.

CloudflareIntermediate

Why

Workers support WebSocket server with Hibernatable Sockets — connections persist without billing for idle time, only messages cost CPU. A 10k-connection chat app costs ~$5/mo vs $200+ on a VPS.

Cloudflare's network spans 330+ cities in 125+ countries, serving 20% of all internet traffic. Workers have 0ms cold starts (isolate-based) and the free tier covers 100k requests/day.

When

Use for chat, live dashboards, collaborative editing, and notifications. Avoid for binary protocols needing >1MB frames or millions of concurrent connections (use Durable Objects sharding).

How

1. Accept upgrade — const [client, server] = Object.values(new WebSocketPair()); ctx.acceptWebSocket(server) 2. Return client — new Response(null, { status: 101, webSocket: client }) 3. Hibernatable — use acceptWebSocket (not adoptWebSocket) for free idle 4. Handlers — webSocketMessage(ws, msg), webSocketClose(ws), webSocketError(ws) 5. Broadcast — ctx.getWebSockets().forEach(ws => ws.send(data)) 6. Tag sockets — ctx.acceptWebSocket(server, ["room:42"]) for filtered broadcast 7. Durable Objects — for room-scoped state, route WS to DO instance

Example

export default { async fetch(request: Request, env: Env): Promise<Response> { if (request.headers.get("Upgrade") !== "websocket") { return new Response("Expected WS", { status: 426 }); } const pair = new WebSocketPair(); const [client, server] = Object.values(pair); env.ctx.acceptWebSocket(server); // hibernatable return new Response(null, { status: 101, webSocket: client }); }, async webSocketMessage(ws: WebSocket, msg: string) { // broadcast to all connected clients for (const peer of this.ctx.getWebSockets()) { peer.send(`echo: ${msg}`); } }, async webSocketClose(ws: WebSocket) { console.log("client disconnected"); }, };

Common Problems

  • ⚠1MB message size limit — large payloads must be chunked across multiple messages
  • ⚠getWebSockets() returns all in Worker — for room-scoped, use tags or Durable Objects
  • ⚠No ws.ping() — Workers don't expose ping/pong, rely on app-level heartbeats

Best Practices

  • ✓Use Hibernatable Sockets (acceptWebSocket) — idle connections free, 10x cheaper
  • ✓Tag sockets by room/user — getWebSockets(tag) filters broadcast efficiently
  • ✓Send heartbeats every 30s — proxies/CDNs drop idle WS after 60-100s

FAQ

What is Cloudflare WebSockets at the Edge and what problem does it solve?

Bidirectional WebSocket connections from Workers with Hibernatable Sockets for cheap persistent connections. It lets developers deploy, store, and scale without self-managing infrastructure — a core reference for cloud service selection.

How do I get started with Cloudflare WebSockets at the Edge in 5 minutes?

Two steps to run it: (1) Accept upgrade — const [client, server] = Object.values(new WebSocketPair()); ctx.acceptWebSocket(server); (2) Return client — new Response(null, { status: 101, webSocket: client }). Validate on the free tier first, then wire into production.

What is the #1 pitfall with Cloudflare WebSockets at the Edge?

The most frequent issue is: 1MB message size limit — large payloads must be chunked across multiple messages. Run a pre-launch checklist item by item, and add policy/config scanning in CI.

What are the best practices for Cloudflare WebSockets at the Edge?

Best practices for Cloudflare WebSockets at the Edge include: Use Hibernatable Sockets (acceptWebSocket) — idle connections free, 10x cheaper; Tag sockets by room/user — getWebSockets(tag) filters broadcast efficiently; Send heartbeats every 30s — proxies/CDNs drop idle WS after 60-100s. The first one — "Use Hibernatable Sockets (acceptWebSocket) — idle connections free, 10x cheaper" — should be a team default baked into your IaC templates.

How do I control cost and avoid bill surprises with Cloudflare WebSockets at the Edge?

Three ways to prevent overspend: (1) tag every resource with env/team and enable billing alarms; (2) set budget thresholds to trigger Slack/email alerts; (3) review idle resources in Cost Explorer regularly and clean them up. Most Cloudflare WebSockets at the Edge options offer a free tier — validate within free quota before scaling.