Channels
Define SSE and WebSocket channels with typed messages, authorization, replay recovery, and SQLite or shared Postgres storage.
Tako Channels are broadcast streams for live app events over SSE or WebSocket. Channels are durable by default: Tako stores each message before fanout and retains a bounded replay window. Set ephemeral: true for memory-only live delivery on one server or across native network servers.
JavaScript and Go can register channel definitions. JavaScript additionally provides local server-side publication and can close a stream. JavaScript, Go, and Rust can publish to a JavaScript-owned network channel. Rust currently has no general Channels registration API; its Presence and Stores registries are separate capabilities. Browser and React examples below use the JavaScript client with any supported backend definition.
tako dev authorizes channel subscriptions and connections the same way production does: it wakes the app if needed, validates params against the app’s definition, and runs the auth callback, so a denied client is rejected locally with the same status or WebSocket close code. Params select separate streams, but they are not access control: authorization must check that the caller may use the requested params.
Choose Broadcast Semantics
Channels are pub-sub, not work queues. Every authorized subscriber to a channel stream reads the same messages and, for durable channels, keeps an independent replay cursor. A message is not claimed, acknowledged, or removed when one subscriber receives it.
Use a channel for live dashboards, chat delivery, presence updates, notifications, and collaborative updates. Use a workflow when work should be claimed and executed with retries instead of broadcast to every subscriber.
For automatic online membership, typing status, and cursor metadata, use Presence with definePresence and usePresence from tako.sh/react.
For backend data that stays synchronized with the UI, use Stores with defineStore and useStore. Stores add authorized reads, scoped invalidation, reconnect catch-up, and optional offline caching on top of channels.
Every delivered message has this wire shape:
type ChannelMessage<T> = {
id: string; // replay cursor for durable channels; "" for ephemeral events
channel: string; // exact wire channel name
type: string; // application-defined message type
data: T;
};
Define A Channel
In JavaScript, put one default export in each <app_root>/channels/*.ts file. The first argument to defineChannel is the explicit wire name and is the source of truth for the public route; it does not have to match the file name. Use .$messageTypes<M>() to declare the payload for each message type without changing runtime behavior. In Go, register the same wire name before starting tako.ListenAndServe:
// <app_root>/channels/site-events.ts
import { defineChannel } from "tako.sh";
import { readSession } from "../lib/auth";
type SiteMessages = {
notification: { id: string; text: string };
presence: { online: number };
};
export default defineChannel("site-events", {
auth: {
async verify({ header }) {
const session = await readSession(header);
if (!session) return false;
return { subject: session.userId };
},
},
transport: "ws",
}).$messageTypes<SiteMessages>();import "tako.sh"
func registerSiteEvents() {
tako.Channels.Register("site-events", tako.ChannelDefinition{
Auth: &tako.ChannelAuthScheme{HeaderName: "authorization"},
Verify: func(input tako.VerifyInput) tako.ChannelAuthDecision {
userID, ok := readSession(input.Header)
if !ok { return tako.RejectChannel() }
return tako.AllowChannel(tako.ChannelGrant{Subject: userID})
},
Transport: tako.ChannelTransportWS,
})
}readSession is application-owned authentication code. The JavaScript helper receives a parsed header; the Go helper above accepts *tako.ChannelHeaderValue and returns the verified user ID and a success flag. Go’s SDK serves discovery and authorization through ListenAndServe; it does not provide the JavaScript handle or browser-client methods.
Use Memory-Only Channels
Set ephemeral: true when only current subscribers need an event, such as live progress or transient telemetry. Omit it or set it to false for durable delivery.
import { defineChannel } from "tako.sh";
export default defineChannel("live-progress", {
ephemeral: true,
// Add transport: "ws" to enable browser publishing.
});import "tako.sh"
tako.Channels.Register("live-progress", tako.ChannelDefinition{
ChannelLifecycleConfig: tako.ChannelLifecycleConfig{Ephemeral: true},
})Ephemeral publishing and receiving use memory, including event identity and duplicate detection; they do not read or write the channel database per event. On native networks, the originating broker sends events to its local subscribers and connected server peers, which deliver to their own subscribers without forwarding them again. A server with no local subscribers still forwards events to its peers.
Messages published without reachable subscribers, during disconnects, or before a server restart can be lost. Reconnection does not replay them. Each active stream has a bounded 64-message buffer; slow subscribers skip evicted events, and the buffer is released when the last subscriber disconnects. Native peer and proxy-notification queues have separate ephemeral capacity (64 messages and 2 MiB per receiver, also subject to a shared ephemeral byte budget); when full, they drop new ephemeral events without disconnecting the peer or invalidating durable replay. Actual shared-connection failures still trigger the normal recovery path.
Ephemeral messages have id: ""; SSE frames omit the id field. Reconnects start with live events and do not resume from a replay cursor. Authorization, params, SSE/WebSocket transport, keepalives, and connection lifetime still apply. Setting replayWindowMs together with ephemeral: true is rejected; in Go, leave ReplayWindowMs at its zero value.
Ephemeral channels support local development, single-server production, and native network servers without a postgres_url credential. Shared Postgres deployments still reject ephemeral publishing and subscriptions; a shared database alone does not provide the native live transport. A channel can be durable or ephemeral independently of other channels in the app. Use Presence for membership and current typing/cursor metadata.
A successful ephemeral publish means the local broker accepted the event for best-effort fanout; it does not acknowledge receipt by every server or browser. A lost acknowledgement leaves acceptance uncertain, so retries can create another event. Events keep their originating broker’s order while its incarnation is active, but concurrent publishers on different servers have no shared total order. Internal eventId values use a fresh random origin when the in-memory publisher is recreated; duplicate detection is bounded and does not survive a restart. Applications must tolerate missing events and repeats. Fetch authoritative state or use expiry for updates that must eventually converge: a browser can remain connected while its server loses a peer, and not every dropped event produces a recovery callback.
To verify, connect two clients (on different native servers when using a network) and publish an event. Both should receive it. Disconnect one client or a server peer, publish another event, then reconnect: the missed event must not replay, and the next live event should arrive. Check that an overloaded ephemeral receiver does not reset an unrelated durable subscription.
Understand Channel Params
JavaScript’s paramsSchema is a TypeBox schema for typed params. Go’s ParamsSchema accepts JSON Schema as json.RawMessage. Tako validates the values before authorization and passes them to the verifier.
Params select the stream. A channel stream is identified by the channel name and its validated params, so chat({ roomId: "one" }) and chat({ roomId: "two" }) have separate messages, replay history, cursors, and subscribers. A publish reaches only subscribers bound to the same params. A channel without a params schema, or bound with no params, has one stream.
Params choose a stream; they do not grant access to it. Anyone who can send a request can name any params, so auth.verify must check that the caller may use the requested params, for example that the user belongs to the room:
// <app_root>/channels/chat.ts
import { defineChannel } from "tako.sh";
import { canJoinRoom, readSession } from "../lib/auth";
type ChatMessages = { message: { text: string } };
export default defineChannel("chat", {
paramsSchema: (t) => t.Object({ roomId: t.String({ minLength: 1 }) }),
auth: {
async verify({ header, params }) {
const session = await readSession(header);
if (!session || !(await canJoinRoom(session.userId, params.roomId))) return false;
return { subject: session.userId };
},
},
}).$messageTypes<ChatMessages>();import (
"encoding/json"
"tako.sh"
)
func registerChat() {
tako.Channels.Register("chat", tako.ChannelDefinition{
ParamsSchema: json.RawMessage(`{
"type":"object",
"properties":{"roomId":{"type":"string","minLength":1}},
"required":["roomId"],
"additionalProperties":false
}`),
Auth: &tako.ChannelAuthScheme{HeaderName: "authorization"},
Verify: func(input tako.VerifyInput) tako.ChannelAuthDecision {
var params struct { RoomID string `json:"roomId"` }
if json.Unmarshal(input.Params, ¶ms) != nil {
return tako.RejectChannel()
}
userID, ok := readSession(input.Header)
if !ok || !canJoinRoom(userID, params.RoomID) {
return tako.RejectChannel()
}
return tako.AllowChannel(tako.ChannelGrant{Subject: userID})
},
})
}readSession and canJoinRoom are app-owned. The Go registration uses the default SSE transport.
In JavaScript, parameterized exports are callable and unparameterized exports are already bound handles. Publish and subscribe with the same params to use the same stream:
import chat from "../channels/chat";
import siteEvents from "../channels/site-events";
await chat({ roomId: "one" }).publish({ type: "message", data: { text: "hello" } });
await siteEvents.publish({ type: "presence", data: { online: 42 } });
Params are flat string, number, or boolean values. Browsers send them as query values, and Tako converts each one by the type the schema declares for that property: integer, number, and boolean properties become numbers or booleans, and every other value stays a string. Key order does not matter, undefined and null values are omitted, and 1 and 1.0 name the same stream. A JavaScript handle from defineChannel publishes with the same conversion: for an integer param page, both { page: 2 } and { page: "2" } publish to the stream a subscriber with ?page=2 reads. The JavaScript SDK rejects nested objects and arrays when a channel is defined or bound; in Go, declare only scalar property types in ParamsSchema.
A JavaScript number cannot carry every integer exactly, and a value that rounds would select one stream when subscribing and another when publishing. So an integer param must be a safe integer (at most 2^53 - 1 in magnitude, including bigint values) and a number param must be finite; the JavaScript SDK throws when such a handle is bound, subscribes, connects, publishes, or closes. Declare large identifiers, such as snowflake ids or 64-bit database keys, as string params. The server rejects a publish or close whose params contain an explicit null; leave a param out to leave it unset.
When the server knows the publishing build’s definition, it rejects a publish whose params do not match the schema instead of starting a stream nobody reads.
A params schema is one object schema with every param under its top-level properties: in JavaScript a single t.Object({ ... }), with t.Composite([...]) to combine object schemas. Combinators and references that declare params (t.Intersect, t.Union, t.Ref of objects, or allOf, anyOf, oneOf, not, if/then/else, dependentSchemas whose subschemas, at any depth, name a param under properties that the top-level properties does not declare, or use patternProperties, additionalProperties other than false, $ref, or $dynamicRef, and a top-level $ref) hide the params from the top level, so defineChannel, definePresence, and Go’s Channels.Register and RegisterPresence reject them, and the server answers a subscribe or publish on such a channel with an invalid-schema error (500, logged) instead of treating its params as unknown; it also logs a warning for each such channel when it first loads a build’s channels. A top-level combinator that only adds constraints over the declared params is fine, for example oneOf: [{ required: ["userId"] }, { required: ["teamId"] }] to require exactly one of two params (in JavaScript, pass it as an option: t.Object({ ... }, { oneOf: [...] })). Its subschemas may use properties over declared params too, for example if: { properties: { kind: { const: "team" } } }, then: { required: ["teamId"] }, or oneOf branches told apart by a const on a declared param. Combinators inside one property’s own schema are fine too.
Only declared params exist. A param the schema does not list under properties is rejected with 400 (before authorization, so it never starts a stream), unless the schema explicitly sets additionalProperties: true. A channel without a params schema accepts no params. The JavaScript, Go, and Rust definitions emit additionalProperties: false for you; set additionalProperties: true only when every extra param should select its own stream.
from and last_message_id are reserved query names on channel routes (where a reader starts and the WebSocket replay cursor), so no param can use them. JavaScript’s defineChannel and Go’s Channels.Register reject a params schema that declares either name, and the server rejects publish or close params that name them.
Keep connection context that must not split the stream out of params. A client version, locale, or feature flag passed as a param would give each value its own stream. Send such context in a header or the auth credential instead, and read it in auth.verify.
Each distinct params binding is a separate stream with its own retention. Durable messages expire after replayWindowMs as usual. Once a stream retains no messages and has been idle for longer than its maxConnectionLifetimeMs plus one minute, Tako releases its bookkeeping, so streams for many short-lived params do not accumulate. A released stream starts again at the store’s current position; cursors from its earlier life reset like expired history. An app keeps at most 100,000 streams; beyond that, starting a new parameterized stream fails with a logged error, while existing streams and channels without params keep working.
Authorize And Choose A Transport
Omit auth or set it to false for a public channel. Otherwise, auth.verify receives the validated params, exact channel, requested operation, and any configured header or cookie. Production subscribe and connect requests pass "subscribe" or "connect" as the operation. The callback must return:
falseto deny access.trueto allow access without an identity.{ subject: "user-id" }to allow access with a stable identity.
headerName defaults to authorization. Set headerName: false with cookieName for cookie-only auth. Cookie-authenticated WebSockets require an Origin matching the application’s public scheme, host, and port; cross-origin or missing-origin handshakes are rejected. Nonbrowser clients using cookies must also send this header. Browser clients can pass authorization: token; Tako sends Authorization: Bearer <token> for SSE and includes the token in each shared WebSocket subscription. Dedicated WebSockets use a tako.auth first frame when header credentials are needed. The SDK handles these envelopes; application code calls connect() and send().
The transport option chooses the live transport:
| Need | Definition | Browser API |
|---|---|---|
| Server-to-browser updates | Omit transport; the channel uses receive-only SSE |
subscribe() |
| Browser-to-server messages | Set transport: "ws" |
connect() / send() |
Both the channel definition and the authorization response must allow WebSocket transport. An SSE-only definition cannot be joined over shared or dedicated WS.
WebSocket application messages are { type, data }; the shared client wraps them in a subscription-specific send command. The proxy stores and broadcasts the application message to the stream selected by that subscription’s params. Channels do not run application callbacks for incoming messages. Once the server closed the stream, a client message is not stored: the subscription ends with close code 4200, and connect().send() and useChannel’s send throw after that close.
Publish From The Server
The JavaScript SDK provides server-side publishing. Import the channel definition, bind the params of the stream to publish to, and publish a typed event:
import siteEvents from "../channels/site-events";
const published = await siteEvents.publish({
type: "presence",
data: { online: 42 },
});
publish() requires the Tako server runtime and returns the published ChannelMessage. It reaches only subscribers bound to the same params, so a parameterized channel publishes with chat({ roomId }).publish(...). Browser code does not call it. An SSE browser only receives events, while a WebSocket browser sends { type, data } through its connection.
close() ends a durable stream for good: await chat({ roomId }).close(). Subscribers receive every earlier message and then the end of the stream, and later publishes to it fail with a TakoError whose reason is "channel_closed". Params the channel’s schema rejects fail with reason: "channel_params_invalid", and a channel the deployed build does not define with reason: "channel_unknown". See Stream A Reply That Survives A Refresh. Go has no server-side publish or close; Go apps can register a definition and serve its authorization, and can publish to a JavaScript-owned network channel but not close one.
Consume In The Browser
Use the browser-safe tako.sh/client entry point outside React. Pass the exact wire name, "ws" for a WebSocket channel, and the channel params:
import { Channel, type ChannelMessage } from "tako.sh/client";
const events = new Channel("site-events", "ws");
const connection = events.connect({ authorization: token });
(connection.raw as EventTarget).addEventListener("message", (event) => {
const message = JSON.parse((event as MessageEvent<string>).data) as ChannelMessage;
console.log(message.type, message.data);
});
For an SSE channel, omit the transport and call subscribe():
const room = new Channel("chat", undefined, { roomId: "one" });
const subscription = room.subscribe({ authorization: token });
React apps can use useChannel from tako.sh/react. SSE is the default; set transport: "ws" to receive a send function. Pass params, such as params: { roomId }, to select a stream; changing them reconnects to the other stream:
import { useChannel } from "tako.sh/react";
function LiveStatus({ token }: { token: string }) {
const { messages, status, send } = useChannel("site-events", {
transport: "ws",
authorization: token,
});
return (
<button
disabled={status !== "open"}
onClick={() => send({ type: "presence", data: { online: 42 } })}
>
Send presence event ({messages.length} received)
</button>
);
}
Shared WebSocket Ownership
WebSocket channels and Presence share one physical WebSocket per origin, credential set, and transport configuration within each browser tab. Every logical subscription has its own authorization, params, replay cursor, and lifetime. SSE subscriptions and Store notifications remain independent HTTP streams.
The shared WebSocket endpoint is /_tako/channels/ws; topics and params travel in subscription messages. Dedicated WebSockets use /_tako/channels/ws/<name>, while each SSE subscription uses /_tako/channels/sse/<name>. Store notifications also use the SSE namespace. SSE URLs reject WebSocket upgrades, and WS URLs require them.
These transport-specific paths replace the old /_tako/channels/<name> routes. Protocol v0 has no compatibility aliases: upgrade the server and browser SDK together, and update any handwritten transport URLs. The dedicated WS option is supported; the old unnamespaced URLs are not.
The page owns its logical subscription. Call the socket handle’s close() or abort its signal when leaving; React hooks do this on unmount. Unsubscribing removes that page’s presence even while a layout’s other subscriptions stay connected. Presence leases cover lost cleanup after crashes or suspended tabs. Membership does not prove that a user is actively looking at a page.
For WebSocket useChannel and usePresence, an aborted signal stops the active subscription and cancels pending retries. An already-aborted signal opens no connection. The hook exposes the abort reason in error; pass a new signal to restart it. This applies to shared and dedicated WS.
connect().raw is a logical EventTarget with open, message, error, and close events. Use the handle’s send() and close() methods. The physical connection closes when its last subscription is released. A rejected or terminally closed subscription leaves its siblings connected. A physical connection failure affects all subscriptions; React hooks reconnect independently with their own cursors. Lower-level connect() callers own reconnection.
Use connection: "dedicated" on connect(), useChannel({ transport: "ws" }), or usePresence() for a separate WebSocket. configureChannels({ connection: "dedicated" }) changes the WebSocket default. Calling configureChannels closes existing pooled connections and starts a new pool with the new configuration. These settings do not change SSE.
Cookies belong to the physical WebSocket handshake. After login, logout, or switching accounts, call resetChannelConnections() from tako.sh/client after the session response updates cookies and before opening new subscriptions. Browsers hide HttpOnly cookie changes from JavaScript, so this reset must be part of the application’s auth flow. It closes all shared subscriptions with code 1012; React hooks reconnect with fresh cookies, while low-level connect() callers must reconnect. Also clear any application state belonging to the previous user. If your auth integration cannot perform this reset, use dedicated connections so each new subscription gets a fresh handshake.
import { resetChannelConnections } from "tako.sh/client";
// After your application's successful login/logout response sets cookies:
resetChannelConnections();
For header auth, configureChannels({ token: () => currentToken }) supplies a token to each subscription regardless of its declared auth.headerName. A value supplied explicitly for that declared header takes precedence. Reset shared connections when the authenticated session changes, including when an existing token resolver starts returning another user’s token.
A shared connection permits 32 subscriptions and 64 KiB client command frames, including their envelope. If the local pool is full, connect() throws; React hooks expose the error and retry with backoff, so they can join after another subscription releases a slot. Complete delivered events may contain up to 1 MiB of serialized UTF-8. Larger events close only that subscription with code 1009; stream AI output as incremental application events. The transport splits eligible events into small fragments, delivers only complete events, and discards unfinished fragments on disconnect. Replay therefore resumes after the last complete event.
Client publishing throws before sending an unserializable payload, an oversized command, or a command that would make the outgoing buffer exceed 1 MiB. These local send failures leave sibling subscriptions connected. The server bounds its output queue and stops stalled writes after 10 seconds. If a subscription’s terminal message cannot enter that queue, the server closes the physical socket with retryable code 1012 so clients can recover. Shared replay reads one record at a time; no timer-based batching is enabled.
Verify Shared Subscriptions
- With
tako dev, mount a layout’s WS channel and a page’s Presence hook using the same credentials. The browser’s Network panel should show one connection to/_tako/channels/ws. - Leave the page while keeping the layout mounted. From another client, verify that the page’s presence member disappears and the layout still receives events. Leaving the last subscription should close the physical socket.
- Abort a hook’s signal and trigger an online/reconnect event. It must stay stopped until given a new signal. An SSE subscription should keep its own request under
/_tako/channels/sse/<name>throughout. - Switch accounts through your auth flow and call
resetChannelConnections()after the new cookies are set. Confirm a fresh handshake and that subscriptions authorize as the new user. Clear the previous user’s application state too.
Recover After Disconnects
For durable channels, each publish is inserted before delivery. replayWindowMs defaults to 10 minutes. A reconnect can replay retained events after a network interruption or a restart when the reconnect reaches storage that still has that history. Replay is a bounded delivery window, not automatic state failover.
Replay cleanup runs every second, including when no clients are connected. Channel definitions carry their lifecycle settings with server-side publishes, so retention applies before the first subscription. A committed publish immediately notifies subscribers using the same store. Native SQLite brokers deliver notifications over the private transport. Shared Postgres stores also poll for commits from other processes or servers every 100 ms. Database reads run outside the async request workers.
Local replay uses SQLite WAL with synchronous=NORMAL: committed messages survive an application process crash, but recent commits can be lost after a host crash or power failure. Replay is a short delivery buffer; keep canonical history in the app database as described below.
- SSE resumes with
Last-Event-ID;subscribe({ lastEventId })sets an initial cursor. The built-in fetch-based reader reconnects after routine disconnects and carries its latest message ID forward.close()or an abortsignalstops it. HTTP401,403, and404are terminal and reachonError. connect({ lastMessageId })resumes a WebSocket subscription after that cursor. The shared protocol sends it as the subscription’scursor; dedicated WS useslast_message_id.useChanneltracks the latest complete message’s ID and reconnects with bounded backoff and jitter. A lower-levelconnect()call returns one logical subscription by default, so non-React code owns its reconnection.- With no cursor, Tako starts at the latest retained message and then follows live traffic. A fresh subscription does not recover all missed events. Pass
from: "start"tosubscribe(),connect(), oruseChannelto replay every message the stream still retains first. The SDK sendsfromin a shared subscription command, orfrom=startin the SSE/dedicated WS query. An explicit cursor wins overfrom, and reconnects resume by cursor rather than from the start again. If retention already dropped the beginning, the reader gets what is retained, without a reset. Ephemeral streams retain nothing, sofrom: "start"reads live messages only.
An expired SSE cursor produces HTTP 410 Gone. A running SSE stream can also send the internal tako.reset control event. The built-in reader consumes either signal, clears its cursor, and reconnects without exposing a reset as an application message. The React hook handles WebSocket close code 4410 with reason replay-too-old the same way.
A reader that asked for from: "start" reconnects from the start after such a reset: it has no cursor left, so it re-reads the whole retained stream, which is the right recovery for a reader that wants the full stream. onRecovery("history-expired") (and onResync) then means: discard local state built from earlier messages, because the stream replays from its start. Message ids can change across a reset (a replay reset on SQLite issues new ones), so do not match replayed messages to earlier ones by id. useChannel keeps its messages buffer across the reset; call clear() in onResync so the replayed messages do not follow the old ones.
A closed stream ends with a terminal signal after its last message: the SSE control event tako.close (with the marker’s ID) followed by the end of the response, or WebSocket close code 4200 with reason stream-closed. The signal is final. The built-in SSE reader, subscribe() with a custom eventSourceFactory (it calls the EventSource’s close(), so the browser does not reconnect), and useChannel stop without reconnecting and call onClose once; useChannel reports closed: true and status: "closed". connect() calls onClose on code 4200; its caller must not reconnect. tako.close never reaches onMessage or the messages buffer. tako.reset, close code 4410, a 1000 connection expired close, and an SSE response that ends without tako.close stay reconnectable.
Routine reconnects and expired history do not populate useChannel.error or invoke the built-in SSE subscription’s onError. The hook reports status: "connecting" until the connection opens again. Optional onRecovery(reason) receives "reconnecting" or "history-expired" outside the message stream. Authorization failures and malformed application messages still need error handling.
Reload custom channel state
The SDK restores the transport. Your application must restore any state that depends on missing events. With React, use the optional onResync callback to reload authoritative state when history expires:
import { useChannel } from "tako.sh/react";
export function LiveUpdates({
token,
reloadState,
}: {
token: string;
reloadState: () => Promise<void>;
}) {
const { status, error } = useChannel("site-events", {
transport: "ws",
authorization: token,
onResync: async () => {
await reloadState();
},
});
if (error) return <p>Updates are unavailable.</p>;
return <p>{status === "open" ? "Live" : "Reconnecting"}</p>;
}
reloadState is app-owned code that fetches a current snapshot from the app’s authenticated API and replaces the view’s state. It must handle events that arrive during the fetch, for example through application revisions or another read after invalidation. onResync does not run for every ordinary reconnect.
For a non-React SSE client, use onRecovery to start the same reload:
import { Channel } from "tako.sh/client";
export function subscribeUpdates(reloadState: () => Promise<void>) {
const room = new Channel("chat", undefined, { roomId: "one" });
return room.subscribe({
onRecovery: async (reason) => {
if (reason === "history-expired") await reloadState();
},
});
}
Both callbacks are optional and can be async. Reconnection does not await them. The built-in SSE reader and useChannel catch and log callback failures without stopping recovery. Handle reload failures in your application’s data UI. useChannel keeps its existing message buffer until clear(), unmount, or a change of connection identity; treat the reloaded snapshot as authoritative rather than assuming the buffer contains complete history.
If you supply a custom eventSourceFactory, that factory owns transport errors, cursor reset, and recovery callbacks; subscribe() only closes it on tako.close. Lower-level connect() callers handle close code 4410 by dropping the expired cursor, reloading state, and opening another subscription; on code 4200, stop. Custom transports do not acquire the built-in reader’s recovery behavior.
A client written without the JavaScript SDK can use dedicated SSE/WS endpoints: add from=start to the query, resume with Last-Event-ID or last_message_id, and treat tako.close or WS close code 4200 as final. A custom shared WS client instead needs subscription commands, per-subscription cursors and closure, and fragment assembly. Follow the shared wire protocol, rather than sending dedicated tako.auth or application frames to the shared endpoint.
Stores implement snapshot reloads for backend data, so they do not need a custom channel resync callback.
Deploy Replay Storage
Replay storage is a deployment choice for durable channels; application publish and subscribe code stays the same. Ephemeral channels use memory-only delivery in every environment and do not use the replay backends below.
| Deployment | Replay storage and delivery |
|---|---|
| Local development | In-memory for the current dev daemon process |
| One production server | Tako-managed SQLite (channels.sqlite) by default |
| Native network servers | Bounded SQLite replay replication and fanout over native private transport; Postgres can remain the shared replay backend |
| Explicit Postgres backend | Shared schema tako_channels, keyed by deployed app id; supported on one or multiple servers |
Native brokers exchange events only with trusted active server peers. Replay has byte and event-count limits; membership changes, transport gaps, or expired history can require a reset. The JavaScript SDK keeps reset messages out of business handlers and resumes subscriptions. Custom channels must reload authoritative application state through their recovery callback; stores reload their authorized snapshot. Reconnect does not recover missing business records by itself.
Native environments selected with [envs.<env>].network can use SQLite for durable channel replay, presence, and store notifications across servers. No Postgres credential is required for those capabilities. If postgres_url is configured, Tako keeps using it; invalid or unreadable credentials fail deployment rather than silently switching backends.
To select shared Postgres explicitly:
tako credentials set postgres_url --env production
This is an encrypted provider credential, not a tako.toml field or an app secret. Set it for the selected environment, then deploy to apply the backend. Existing installations using the removed external-VPN enrollment flow need re-enrollment.
Native replication is a bounded delivery mechanism. It does not replicate an application’s database or move durable workflow execution state. Keep workflow storage configured independently, and test recovery by reloading current state after a gap.
Keep Canonical History In Your App Database
The replay store is a short delivery buffer, not permanent product history. Chat messages, document operations, audit events, and anything else that must remain queryable should be committed to your app database before publishing the corresponding channel event.
const saved = await db.notifications.create({ userId, text });
await siteEvents.publish({
type: "notification",
data: saved,
});
For canonical writes, use a normal authenticated app endpoint to commit the record, then publish the resulting channel event from server-side code. Treat browser-sent WebSocket frames as transient live signals. The app database remains the source of truth; channel replay only closes short delivery gaps.
Stream A Reply That Survives A Refresh
A long-running reply, such as LLM output, can stream through a channel so that a page refresh resumes it. A workflow appends the text to a stream for one reply and closes the stream when it finishes. The browser reads that stream from its start, rebuilds the text, and stops at the end. The proxy serves readers from Tako’s replay store, so once a subscription is authorized the app and its worker can go back to sleep while clients keep reading. Authorizing a new subscription, or reauthorizing after maxConnectionLifetimeMs, still calls the app’s auth.verify.
This pattern needs server-side publish() and close(), which only the JavaScript SDK provides. A Go app can register the same definition, but it cannot produce or close the stream.
Define a channel with one stream per reply. Authorization must check that the caller may read that reply:
// <app_root>/channels/reply.ts
import { defineChannel } from "tako.sh";
import { canReadReply, readSession } from "../lib/auth";
// `content` is the whole text so far, so a replayed or repeated message never duplicates text.
type ReplyMessages = {
progress: { content: string };
done: { content: string };
};
export default defineChannel("reply", {
paramsSchema: (t) => t.Object({ replyId: t.String({ minLength: 1 }) }),
// Keep finished replies re-readable for an hour.
replayWindowMs: 60 * 60 * 1000,
auth: {
async verify({ header, params }) {
const session = await readSession(header);
if (!session || !(await canReadReply(session.userId, params.replyId))) return false;
return { subject: session.userId };
},
},
}).$messageTypes<ReplyMessages>();
The workflow publishes chunks, saves the finished text to the app database, and closes the stream on success and on failure, so readers are never left waiting:
// <app_root>/workflows/write-reply.ts
import { defineWorkflow } from "tako.sh";
import reply from "../channels/reply";
import { db } from "../lib/db";
import { streamCompletion } from "../lib/llm";
export default defineWorkflow<{ replyId: string; prompt: string }>("write-reply", {
handler: async ({ replyId, prompt }, ctx) => {
const stream = reply({ replyId });
try {
const content = await ctx.run(
"generate",
async () => {
let content = "";
let flushedAt = Date.now();
for await (const token of streamCompletion(prompt)) {
content += token;
// Each publish is a durable write: send a chunk every 250 ms, not every token.
if (Date.now() - flushedAt >= 250) {
await stream.publish({ type: "progress", data: { content } });
flushedAt = Date.now();
}
}
await stream.publish({ type: "done", data: { content } });
return content;
},
{ retries: 2 },
);
await ctx.run("save", () => db.replies.complete(replyId, content), { retries: 3 });
} catch (error) {
await ctx.run("mark-failed", () => db.replies.fail(replyId));
await stream.close();
// A retried run could not publish to the closed stream, so the failure is final.
ctx.fail(error instanceof Error ? error : String(error));
}
await stream.close();
},
});
db, canReadReply, readSession, and streamCompletion are app-owned. The request that starts a reply creates its database row with status "streaming", then enqueues the run with the reply ID as the run ID, so a repeated request does not start a second run: await writeReply.enqueue({ replyId, prompt }, { id: replyId }).
The component reads from the start, shows the latest content, and stops at closed:
import { useChannel } from "tako.sh/react";
type Reply = { id: string; status: "streaming" | "complete" | "failed"; content: string };
export function ReplyText({ reply, token }: { reply: Reply; token: string }) {
// The app database is canonical: only stream replies it has not finished.
if (reply.status === "complete") return <p>{reply.content}</p>;
if (reply.status === "failed") return <p>The reply could not be finished.</p>;
return <LiveReply replyId={reply.id} token={token} />;
}
function LiveReply({ replyId, token }: { replyId: string; token: string }) {
const { messages, closed, error } = useChannel<{ content: string }>("reply", {
params: { replyId },
authorization: token,
from: "start",
});
const last = messages.at(-1);
if (error) return <p>The reply is unavailable.</p>;
if (closed && last?.type !== "done") return <p>The reply could not be finished.</p>;
return <p aria-busy={!closed}>{last?.data.content ?? "Thinking…"}</p>;
}
After a refresh, from: "start" replays the retained messages. If the stream is still open, the hook then follows live messages and resumes by cursor across reconnects; if the workflow already closed it, the hook replays and reports closed without reconnecting.
Keep these limits in mind:
- Each publish is a durable write. It is inserted into the replay store and fanned out before the next one. Batch tokens into chunks by time or size.
- Retention bounds re-reading. A closed stream stays closed, and its messages stay readable, for as long as
replayWindowMsretains them. After that, a new subscriber withfrom: "start"gets nothing and, because the marker is gone too, keeps waiting. That is why the component above renders finished replies from the app database, as described in Keep Canonical History In Your App Database, and subscribes only while the database says the reply is streaming. Choose a replay window longer than your longest reply. - Make repeats harmless. A step can run again after a failure or a worker restart, and a reader can see a message twice across a replay. Because every message carries the cumulative
content, a repeated or restarted step replaces the visible text rather than appending duplicates, and expired early chunks lose nothing. If chunks must be deltas, give each a sequence number and let the client keep one entry per number. - Close only when nothing follows. Publishing to a closed stream fails, so close after the last attempt that could publish. Step retries above run inside
ctx.run, andctx.failstops run-level retries after the stream is closed. Closing twice is safe, so a replayedclose()succeeds. - Ephemeral channels cannot be closed.
close()on an ephemeral channel throws, and it throws in the browser. - Publish and close from one place. A close is ordered after the publishes the same server made before it. With native multi-server replication, a publish from another server that races the close may be dropped on servers that already have the marker, so every server ends at the close with nothing after it. Shared Postgres orders publishes and closes in one store and never drops one. Peers keep a replicated stream, and its close, for the same
replayWindowMsas the server it came from, timed from when that server stored each message. Once a closed stream reopens on one server (its close expired there), the publishes made there reopen it on every other server too, even one that has not yet removed its copy of the close.
Verify
Connect two authorized clients and confirm both receive the same published event. Confirm that a denied client is rejected, and reconnect with a retained replay cursor. Then reconnect after expiry and confirm the SDK resumes, the application reloads authoritative state, and no reset message reaches business handlers. Test an async reload failure and stop a reconnecting subscription with close(). For a closed stream, subscribe with from: "start" and confirm that every message arrives, then closed, with no reconnect, and that a publish after close() fails. On multiple servers, publish through one and subscribe through another using the configured native or shared Postgres transport. Local development keeps replay in memory on one daemon, so a successful local connection does not verify durable storage or cross-server fanout.