Ir al contenido
Español

WebsocketClientActor

Esta página aún no está disponible en tu idioma.

WebsocketClientActor opens a client-side WebSocket connection to a remote endpoint. Inbound frames are decoded into typed messages you handle in onMessage; outbound messages are encoded and sent (buffered while disconnected, resent after reconnect). For accepting incoming WS connections (server side), see server WebSocket.

import { match } from 'ts-pattern';
import { WebsocketClientActor, WebsocketClientOptions, websocketSend } from 'actor-ts/http';
type ClientMessage = { kind: 'ping'; n: number };
type ServerMessage = { kind: 'pong'; n: number } | { kind: 'event'; data: unknown };
class Feed extends WebsocketClientActor<ClientMessage, ServerMessage> {
constructor() {
const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>().withUrl('ws://localhost:8080/ws');
super(webSocketClientOptions);
}
override onConnected(): void {
this.send({ kind: 'ping', n: 1 });
}
onMessage(message: ServerMessage): void {
// decoded server message
match(message)
.with({ kind: 'pong' }, (m) => this.onPong(m))
.exhaustive();
}
private onPong(message: PongMessage): void {
this.log.info(`pong ${message.n}`);
}
}
const feed = system.spawn(Feed, 'feed');

The two type parameters read from the client’s point of view: TOut = the messages this client sends, TIn = the decoded server messages it receives.

WebsocketClientActor extends the shared BrokerActor base, so it inherits reconnect-with-backoff, the outbound buffer across reconnects, and a circuit breaker around the connect — off until you name one.

The constructor takes Partial<WebsocketClientOptionsType<TOut, TIn>>. Only url is required; everything else has a default.

interface WebsocketClientOptionsType<TOut, TIn> extends BrokerCommonOptionsType {
url: string; // required — ws:// or wss://
protocols?: string | string[]; // subprotocols
codec?: WebsocketCodec<TOut, TIn>; // default jsonCodec()
maxFrameBytes?: number; // default 1 MiB; oversize inbound closes with 1009
onInvalidMessage?: 'drop' | 'hook' | 'disconnect'; // default 'drop'
pingIntervalMs?: number; // keepalive interval; default off, payload from keepAliveFrame()
idleTimeoutMs?: number; // read-idle deadline; default 0 (off)
connectTimeoutMs?: number; // connect deadline; default 0 (off)
inboundHighWaterMark?: number; // pause the socket at this many queued inbound frames; default off
inboundLowWaterMark?: number; // resume at this many; default a quarter of the high-water mark
}

Because the settings extend BrokerCommonOptionsType, the reconnect block ({ initialDelayMs, maxDelayMs, factor, maxAttempts, randomFactor }), outboundBuffer and circuitBreaker — a breaker id, whose numbers live under actor-ts.circuit-breaker.<id> — all apply; see the BrokerActor base for their semantics, the breaker’s under Circuit breaker.

Inside the actor, this.send(message) encodes the message via the codec and enqueues it; while disconnected the message is buffered and resent after reconnect. Inbound frames are decoded and delivered to onMessage.

class Chat extends WebsocketClientActor<ClientMessage, ServerMessage> {
constructor() {
const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>().withUrl('wss://chat.example.com/ws');
super(webSocketClientOptions);
}
override onConnected(): void {
this.send({ kind: 'setName', name: 'alice' }); // encode + enqueue → true
}
onMessage(message: ServerMessage): void {
// one call per decoded server frame, in frame order
}
}

send(message: TOut): boolean returns whether the message was accepted (it can be rejected if the outbound buffer is full). For a raw frame — bypassing the codec — use sendRaw(frame: WebsocketFrame): boolean.

Other actors don’t call send directly; they push a typed send through the ref with the websocketSend helper:

import { websocketSend } from 'actor-ts/http';
feed.tell(websocketSend({ kind: 'ping', n: 42 }));

onMessage(message: TIn) is abstract — you must implement it. The rest are optional overrides:

HookWhen
onConnected()The connection is (re)established. Good place for a handshake / re-subscribe.
onDisconnected(cause?: Error)The connection dropped; cause is set on error-driven drops.
onInvalidMessage(error: WebsocketDecodeError)A frame failed to decode (only when onInvalidMessage: 'hook').
onSelfMessage(message: TSelf)Handle the optional third type parameter — messages the actor sends to itself — and anything else told to its ref that none of its own kinds matched, a remote node’s body included. Default: a warn naming the message’s class (never its payload), then this.unhandled(message) — a dead letter naming this actor, counted in actor_unhandled_total{class}.
onTerminated(signal: Terminated)An actor you context.watched stopped. Inherited from BrokerActor.

onReceive and onCommand are sealed — the base classes dispatch to the hooks above; do not override them. A Terminated from a watch of your own arrives at onTerminated, not at onSelfMessage.

The codec turns TOut messages into wire frames and wire frames back into TIn messages. The default is jsonCodec():

import { jsonCodec } from 'actor-ts/http';
new Feed(); // uses jsonCodec() — text frames <-> JSON
// With runtime validation (zod etc.):
class Validated extends WebsocketClientActor<ClientMessage, ServerMessage> {
constructor() {
const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>()
.withUrl('wss://...')
.withCodec(jsonCodec<ClientMessage, ServerMessage>({
validate: (value: unknown): ServerMessage => ServerMessageSchema.parse(value),
}));
super(
webSocketClientOptions,
);
}
onMessage(message: ServerMessage): void { /* already validated */ }
}

For binary protocols, rawCodec() is the escape hatch — TOut = TIn = WebsocketFrame, so you handle raw text/binary frames yourself:

import { match } from 'ts-pattern';
import { rawCodec, type WebsocketFrame } from 'actor-ts/http';
class Binary extends WebsocketClientActor<WebsocketFrame, WebsocketFrame> {
constructor() {
const webSocketClientOptions = WebsocketClientOptions.create<WebsocketFrame, WebsocketFrame>()
.withUrl('wss://...')
.withCodec(rawCodec());
super(webSocketClientOptions);
}
onMessage(frame: WebsocketFrame): void {
match(frame)
.with({ kind: 'binary' }, (f) => this.onBinary(f))
.otherwise(() => {});
}
private onBinary(frame: BinaryFrame): void {
this.handleBytes(frame.data); // Uint8Array
}
}

A WebsocketFrame is { kind: 'text'; data: string } or { kind: 'binary'; data: Uint8Array }. Decode failures throw a WebsocketDecodeError; the inbound frame-size cap (maxFrameBytes) is enforced on the raw frame before decode.

data is a plain Uint8Array on every runtime. The client sets the socket’s binaryType to 'arraybuffer' when it dials, because the runtimes disagree about the default — Bun hands over a Node Buffer, Node and Deno hand over a Blob — and a Blob yields its bytes only asynchronously, which the inbound path cannot afford: awaiting it would move the maxFrameBytes check behind a microtask and stop guaranteeing that frames reach onMessage in arrival order. Two consequences worth knowing. The bytes are always the frame’s own, never a window into a pooled buffer, so frame.data.buffer is safe to hand on. And the value is a Uint8Array and not a Buffer even on Bun, so reach for Buffer.from(frame.data) if you want toString('hex') and friends.

An oversize frame closes the connection with code 1009 (“Message Too Big”) and starts the usual reconnect, rather than being dropped in place. Be clear about what that does and does not buy you: it does not stop the allocation. Unlike the server backends, the client has no transport cap to push the limit down to — no supported runtime’s native WebSocket honours a payload limit passed to its constructor, so by the time maxFrameBytes is checked the runtime has already reassembled the frame on the heap. What closing buys is that the peer cannot spend that heap again on the same socket: without it, one connection could be made to repeat the allocation for every frame it felt like sending. Another round now costs the peer a full reconnect — and only that. A connect that succeeds resets the reconnect backoff and counts as a success for a circuit breaker, so neither slows a peer that accepts every connect and then sends an oversize frame: the client is back on it every initialDelayMs or so. See Capping untrusted input.

The close is accompanied by one warning line. It names the connection by a redacted label (wss://feed.example.com/ws/orders) rather than by url: the userinfo and the query string are stripped, since a WebSocket endpoint is commonly authenticated with a ?token=…, and the path is kept because it is what tells two connections to the same host apart. A URL with an @ past its host — in a path such as /rooms/@general, or in a query token — is labelled wss://*** instead: the same bytes could be a password, and the host behind the @ would then be the wrong one. The same masking is available to your own code as redactedUrlLabel.

An unexpected disconnect is handled by the BrokerActor lifecycle:

  • The actor transitions to disconnected and fires BrokerDisconnected on the event stream.
  • The reconnect cycle starts, with exponential backoff per the reconnect settings (initialDelayMs, maxDelayMs, factor, maxAttempts) — jittered by randomFactor (default ±20 %) so a fleet does not reconnect in lockstep.
  • After a successful re-connect, onConnected() runs and BrokerConnected fires.

Outbound messages sent while disconnected are buffered per the outbound-buffer policy and resent after reconnect.

There is no circuit breaker until circuitBreaker names one, and maxAttempts defaults to Infinity, so on its own a dead endpoint is retried forever, on the backoff above. Name a breaker and, after max-failures failed connects in a row, the client stops dialling for the breaker’s window and then sends a single probe. Clients that share the id make at most one attempt each per window, and one probe answers for all of them only while a failing connect is short against the spread of their wake-ups — a connect that hangs is still in flight when the next client wakes, and that one probes too (see Circuit breaker). It still retries for as long as maxAttempts allows; the breaker spaces the attempts out, it does not end them.

pingIntervalMs runs a keepalive timer so an intermediate proxy or load balancer does not close the connection for being idle. What that timer sends is yours to supply — override keepAliveFrame():

class KeepAlive extends WebsocketClientActor<ClientMessage, ServerMessage> {
constructor() {
const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>()
.withUrl('wss://...')
.withPingIntervalMs(30_000)
.withIdleTimeoutMs(90_000);
super(webSocketClientOptions);
}
protected override keepAliveFrame(): WebsocketFrame {
return { kind: 'text', data: JSON.stringify({ kind: 'heartbeat' }) };
}
onMessage(message: ServerMessage): void {}
}

The frame bypasses the codec — encode it yourself. The framework ships no default frame on purpose: bytes it invented would be an unannounced message in your protocol, and a peer that closes on an unknown message would be severed by its own keepalive.

A keepalive is written straight to the live socket, never through the outbound buffer. It is not sendRaw() under a different name, and the difference shows up exactly when the connection is in trouble. A tick that finds no live connection sends nothing at all: it is not buffered while disconnected, not replayed after the reconnect, and never takes a slot that an application message was holding. Replaying a heartbeat would be a keepalive for a connection that no longer exists, sent against a period that has already elapsed — and on a full buffer it would evict a real message to say so. A frame you do want resent belongs in sendRaw(), which promises the opposite.

Without the override the timer may have nothing to send. It falls back to the runtime’s native WebSocket.ping(), and that is a protocol-level control frame which exists on Bun only — the WHATWG WebSocket that Node and Deno ship has no ping() method at all. On those two runtimes an un-overridden hook can send nothing, so the client starts no timer and logs one warning at connect time instead (#751). A timer that provably sends nothing is worse than no timer: it is the thing that convinces you the connection is being kept warm.

Only an application-level frame reaches a proxy that inspects payload rather than frames, and only an application-level frame counts against the peer’s own read deadline — a protocol-level pong is not delivered to the message listener on any supported runtime.

Pair it with idleTimeoutMs (next section). A keepalive stops a proxy closing an idle connection; only the read deadline notices one that was dropped anyway.

Detecting a connection that was silently dropped

Section titled “Detecting a connection that was silently dropped”

A ping keeps a proxy from closing the connection. It does not tell you when one was dropped anyway — an expired NAT entry, a load balancer that forgot the flow, a peer killed with SIGKILL. Neither side is notified, so close and error never fire, onDisconnected never runs, and the actor reports connected while every send goes nowhere.

idleTimeoutMs is the deadline that ends that state:

const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>()
.withUrl('wss://realtime.example.com/feed')
.withIdleTimeoutMs(90_000) // no inbound frame for 90 s → reconnect
.withConnectTimeoutMs(10_000); // handshake stalled for 10 s → fail the attempt

On expiry the socket is closed, onDisconnected runs with an idle timeout cause, and the ordinary reconnect cycle starts — the same path an observed close takes.

It counts application messages, not pongs. A protocol-level pong is not delivered as a message event on any supported runtime, so pingIntervalMs does not refresh this deadline. Size idleTimeoutMs against the server’s own heartbeat interval, not against your ping interval; below that, the deadline severs healthy connections in a loop. Off by default for exactly that reason.

connectTimeoutMs covers the other end: the handshake settles only on open or error, so a server that accepts the TCP connection and never completes the upgrade holds the actor in connecting indefinitely.

Everything on this page called backpressure so far governs the outbound direction: the send buffer, maxBufferedBytes, the BackpressurePolicy. On the receive side the client has, by default, no flow control at all — every frame is decoded and handed to the mailbox the instant it arrives. A peer that publishes faster than onMessage drains has nowhere to push back to, and a bounded mailbox then drops decoded application messages, which is the wrong thing to lose.

An inbound high-water mark pauses the socket instead, so TCP does the pushing back:

const webSocketClientOptions = WebsocketClientOptions.create<ClientMessage, ServerMessage>()
.withUrl('wss://realtime.example.com/feed')
.withInboundHighWaterMark(256) // frames queued in the mailbox before pause()
.withInboundLowWaterMark(64); // resume() once the backlog is down to this

The count is decoded frames waiting in the mailbox — handed to the actor and not yet handed to onMessage. At the high-water mark the socket is paused; once the backlog has drained to the low-water mark it is resumed. The low-water mark defaults to a quarter of the high one, and resuming at the first free slot is deliberately not the default: it would flap the socket between paused and reading once per frame.

Bun only, in practice. pause() and resume() exist on Bun 1.4.1+‘s client WebSocket and on neither Node’s nor Deno’s WHATWG one. The actor probes the socket rather than the runtime name; where the pair is absent it keeps the behaviour above and says so once at connect time, because a limit that looks applied and is not is worse than none.

websocket_client_inbound_paused_seconds_total accumulates the time the socket spent paused, so the condition is observable rather than inferred from a stall on the far side.

Client defaults can be set under actor-ts.io.broker.websocket:

actor-ts.io.broker.websocket {
url = "wss://realtime.example.com/feed"
protocols = ["my-proto-v1"]
ping-interval = 30s
idle-timeout = 90s
connect-timeout = 10s
max-frame-bytes = 1M
inbound-high-water-mark = 256 # pause the socket at this many queued inbound frames (Bun 1.4.1+)
inbound-low-water-mark = 64 # resume once the backlog is down to this many
on-invalid-message = "drop" # drop | hook | disconnect
reconnect { initial-delay = 500ms, max-delay = 30s, factor = 2.0, random-factor = 0.2 } // max-attempts omitted = unlimited (the default)
circuit-breaker = "realtime-feed" // a breaker id; none when unset (the default)
outbound-buffer = 1000 // messages held while disconnected; 0 = fail-fast
}
actor-ts.circuit-breaker.realtime-feed { max-failures = 5, reset-timeout = 30s }

Precedence follows the broker convention: constructor argument > HOCON > built-in defaults.

A few notes on that block.

Every leaf is the kebab-case of its option with the unit suffix dropped, so the three intervals are durations and max-frame-bytes is a size. The camelCase spellings these leaves had before — pingIntervalMs, maxFrameBytes and the rest — are refused with a ConfigError that names the new key, rather than ignored: the frame cap in particular would otherwise fall back to its default with nothing said. The client is a broker actor, so the refusal comes when it starts, in its preStart — not at ActorSystem.create.

circuit-breaker holds a breaker’s id, not its settings: those go under actor-ts.circuit-breaker.<id>, as on the last line, over the defaults every breaker shares. A block in its place — the old circuit-breaker { failure-threshold, reset }, or the breaker’s own leaves written under the client’s root — is refused at start, naming the id shape.

on-invalid-message has a namesake on the server side, actor-ts.http.websocket.on-invalid-message, and its value list is not the same one — it offers close where the client offers disconnect, so the two cannot be copied across.

codec has no config key at all: it is a pair of functions, and a function cannot come from a config file.

Three primary fits:

  1. Subscribing to real-time data feeds — stock tickers, crypto exchanges, social-media streams.
  2. Outbound WebSocket clients to third-party services (Slack RTM, streaming LLM APIs, IoT vendor APIs).
  3. Custom WS-based protocols layered on top — use rawCodec() for binary wire formats.

For server-side WebSocket (accepting client connections), use the server WebSocket page.

  • I/O overview — the bigger picture.
  • Server WebSocket — the websocket() directive + WebsocketServerActor.
  • SSE — server-sent events as a one-way streaming alternative.
  • BrokerActor base — the shared reconnect / buffer / circuit-breaker lifecycle.