How WebSockets behave on Google Cloud Run: the request timeout that ends every connection, best-effort session affinity, concurrency and billing, and how to keep clients on different instances in sync, with a TypeScript chat service that reconnects without losing messages.

Cloud Run supports WebSockets with no extra setup, which is enough to deploy a chat or a live dashboard. Every connection still ends at the request timeout, clients land on different instances, and an instance with one open socket is billed the whole time.
This guide covers each of those limits with the numbers from Google's docs as of November 18, 2026, and the design that works around them: reconnect with a cursor and sync instances through a shared store. It ends with a TypeScript chat service on Encore that deploys to Cloud Run in your own GCP project.
The values are from Google's Using WebSockets page and the request timeout docs. The timeout is set per service with gcloud run services update chat --timeout=3600.
Cloud Run treats a WebSocket as one HTTP request, so the connection closes when the request timeout passes, even if both sides are healthy. Raising the timeout to 60 minutes reduces reconnects but does not remove them, and deploys and scale-in close connections too. The client therefore needs a reconnect loop with backoff, and the server needs a way to send what the client missed, which is a cursor such as the last message ID.
With session affinity enabled, Cloud Run tries to send a returning client to the same instance with a cookie, but a new connection can still land elsewhere when instances scale or restart. Anything a client expects after a reconnect, such as room history or unread counts, has to come from a store every instance can read.
Each instance accepts up to 1,000 concurrent requests, and each open WebSocket counts as one. A socket service mostly waits on the network, so raising --concurrency toward 1,000 fits more connections per instance and fewer instances overall. Google's docs state that an instance with any open WebSocket is considered active, so CPU stays allocated and the instance is billed at instance-based rates for as long as one client is connected.
Two clients in the same room can be connected to different instances, so a message received on instance A has to reach clients on instance B. Google suggests three options: write to a database and poll it, use Firestore real-time listeners, or use Redis Pub/Sub on Memorystore, where every instance subscribes to a channel. Polling is the simplest and adds no new service, and Redis gives the lowest latency at the cost of a Memorystore instance and a VPC connector.
Encore is a backend framework with built-in infrastructure for TypeScript and Go. A streaming API is declared with api.streamInOut, which runs over a WebSocket with typed messages and a typed handshake, and deploying to your GCP project runs the service on Cloud Run with a Cloud SQL database provisioned from the code. The GCP infrastructure docs describe what gets created.

Run in your terminal to get started locally.
The service below uses the database-polling option: messages are written to Postgres, each instance runs one poller per active room, and a reconnecting client passes after with the last seq it saw:
import { api, APIError, Query, StreamInOut } from "encore.dev/api";
import { getAuthData } from "~encore/auth";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import log from "encore.dev/log";
// Cloud SQL on GCP. Every instance reads new messages from here,
// so clients on different Cloud Run instances see the same room.
const db = new SQLDatabase("chat", { migrations: "./migrations" });
interface Handshake {
room: Query<string>;
// The last seq the client saw, sent again after a reconnect.
after?: Query<number>;
}
interface InMessage {
body: string;
}
interface OutMessage {
seq: number;
author: string;
body: string;
}
type Conn = StreamInOut<InMessage, OutMessage>;
// One poller per room per instance, shared by all its connections.
class Room {
conns = new Set<Conn>();
last = 0;
timer?: NodeJS.Timeout;
constructor(public name: string) {}
async start() {
const row = await db.queryRow<{ seq: number }>`
SELECT COALESCE(max(seq), 0)::int AS seq FROM messages WHERE room = ${this.name}`;
this.last = row?.seq ?? 0;
this.timer = setInterval(() => this.poll().catch((e) => log.error(e)), 500);
}
async poll() {
const rows = db.query<OutMessage>`
SELECT seq::int, author, body FROM messages
WHERE room = ${this.name} AND seq > ${this.last} ORDER BY seq`;
for await (const m of rows) {
this.last = m.seq;
for (const c of this.conns) c.send(m).catch(() => this.conns.delete(c));
}
}
stop() {
clearInterval(this.timer);
}
}
const rooms = new Map<string, Room>();
export const chat = api.streamInOut<Handshake, InMessage, OutMessage>(
{ expose: true, auth: true, path: "/chat" },
async (hs, stream) => {
const { userID } = getAuthData()!;
const member = await db.queryRow<{ room: string }>`
SELECT room FROM room_members WHERE room = ${hs.room} AND user_id = ${userID}`;
if (!member) throw APIError.permissionDenied("not a member of this room");
let room = rooms.get(hs.room);
if (!room) {
room = new Room(hs.room);
rooms.set(hs.room, room);
await room.start();
}
// Replay what the client missed while it was reconnecting.
if (hs.after !== undefined) {
const missed = db.query<OutMessage>`
SELECT seq::int, author, body FROM messages
WHERE room = ${hs.room} AND seq > ${hs.after} AND seq <= ${room.last}
ORDER BY seq`;
for await (const m of missed) await stream.send(m);
}
room.conns.add(stream);
try {
for await (const m of stream) {
if (m.body.length === 0 || m.body.length > 2000) continue;
await db.exec`
INSERT INTO messages (room, author, body) VALUES (${hs.room}, ${userID}, ${m.body})`;
}
} finally {
room.conns.delete(stream);
if (room.conns.size === 0) {
room.stop();
rooms.delete(hs.room);
}
}
},
);
The migration gives each message a sequence number and an index for the per-room query:
CREATE TABLE room_members (
room TEXT NOT NULL,
user_id TEXT NOT NULL,
PRIMARY KEY (room, user_id)
);
CREATE TABLE messages (
seq BIGSERIAL PRIMARY KEY,
room TEXT NOT NULL,
author TEXT NOT NULL,
body TEXT NOT NULL,
sent_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX messages_room_seq ON messages (room, seq);
The handler type-checks against encore.dev 1.58.8, and the queries were run against Postgres 17, where the poll and replay queries use the (room, seq) index. The databases docs cover migrations, and connecting your own cloud covers linking the GCP project. A coding agent that adds typing indicators or read receipts adds message types to the same handler, and the deploy keeps the database and service in sync.
Best fit: TypeScript teams adding chat, live updates or collaboration to a backend on GCP who want WebSockets on Cloud Run without wiring Cloud SQL and IAM by hand.
BIGSERIAL value is assigned at insert, and a transaction that commits later with a lower seq can be skipped by a poller that already moved past it. Re-reading a short window behind the cursor or assigning sequence numbers per room under a lock closes that gap.Yes. Cloud Run supports WebSockets with no extra configuration, and a WebSocket on Cloud Run is a long-running HTTP request, so it is subject to the service's request timeout, 5 minutes by default and up to 60 minutes. Clients must reconnect when the timeout closes the connection, and an instance with an open WebSocket is billed as active.
At most 60 minutes, the maximum request timeout for a Cloud Run service, and 5 minutes if you keep the default. Set the timeout to the longest connection you want and have the client reconnect, passing the ID of the last message it received so the server can replay what it missed.
No. An open connection stays on its instance, but Google's docs note that a new connection with session affinity enabled can still reach a different instance, even when session affinity is turned on. Any state that must survive a reconnect belongs in a shared store such as Cloud SQL, Firestore or Redis on Memorystore.
Use api.streamInOut in TypeScript, which runs over a WebSocket with typed incoming and outgoing messages and a typed handshake for query parameters. Encore deploys the service to Cloud Run in your GCP project and provisions the Cloud SQL database the handler uses to share messages across instances.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.