The starter uses WebSockets for notifications, not as a second database. A note is saved through an ordinary authenticated HTTP route. Its SQLite transaction increments a revision for the owner. Each running server observes that committed revision and tells the sockets subscribed by that owner. The browser then fetches the rendered notes page. The HTML remains the source of truth.
This distinction matters in an Express or Next.js app. A connection on one worker does not share a JavaScript Map with a connection on another worker. Broadcasting only to the process that handled the write loses updates. TradJS's route describes admission and socket callbacks; sqlite-zod-orm's shared-file change journal carries the committed signal between processes.
Declare an authenticated route#
Create app/api/notes/live/route.ts. The actual starter route begins with these definitions and notification functions:
import type { RouteWebSocket, WebSocketRoute } from "tradjs/server";
import { db, noteRevision, readSession, sessionUser } from "../../../../db";
type LiveSocket = RouteWebSocket & { data: { userId: number; token: string; revision: number } };
const sockets = new Map<number, Set<LiveSocket>>();
const OPEN = 1;
function valid(socket: LiveSocket) {
return sessionUser(socket.data.token)?.id === socket.data.userId;
}
function sendRevision(socket: LiveSocket, revision: number) {
if (socket.readyState !== OPEN) return;
if (!valid(socket)) {
socket.close(1008, "Session expired");
return;
}
// A journal callback can observe a newer revision than the individual
// commit it represents. Send each contiguous revision only once, so bursts
// remain lossless and the receiving browser can coalesce HTML fetches.
const previous = socket.data.revision;
if (revision <= previous) return;
for (let next = previous + 1; next <= revision; next++) {
if (socket.readyState !== OPEN) break;
// A nonpositive send result signals backpressure or a dropped frame.
// Do not buffer an unbounded queue. The browser resyncs from SQLite on its next connection.
if (socket.send(JSON.stringify({ type: "revision", revision: next })) <= 0) {
socket.close(1013, "Backpressure; resync on reconnect");
return;
}
socket.data.revision = next;
}
}
function notify(row: { userId: number; revision: number } | null) {
if (!row || !Number.isSafeInteger(row.userId)) return;
const group = sockets.get(row.userId);
if (!group) return;
// Always read the committed revision, not a possibly stale journal row.
const latest = noteRevision(row.userId);
for (const socket of group) sendRevision(socket, latest);
}
// Register once per server process, not once per connection. Both the insert
// and update paths are needed (a newly registered user starts with no row).
db.noteVersions.on("insert", notify);
db.noteVersions.on("update", notify);
// A revoked session must not keep receiving even if its socket remains open.
db.sessions.on("delete", () => {
for (const group of sockets.values())
for (const socket of group) if (!valid(socket)) socket.close(1008, "Session ended");
});
Source: templates/app/app/api/notes/live/route.ts, lines 10–58.
The socket type carries userId, the session token and the last revision delivered. The Map is in-process. It never claims to span servers. The database does span processes as long as they open the same SQLite file on the same host. The notify callback looks up sockets by authenticated user and reads the newest revision from the database rather than treating a potentially delayed journal event as current.
The exported route is the rest of the protocol. Its admission guard runs before a WebSocket is accepted:
export const websocket: WebSocketRoute = {
limits: {
// Authenticated user IDs, never a client-supplied query or frame value.
clientKey(_request, data) { return String(data.userId); },
maxConnectionsPerClient: 8,
// Native navigation can open multiple legitimate sockets in quick succession.
upgradesPerMinute: 120,
upgradeBurst: 20,
idleTimeoutSeconds: 180,
},
upgrade(request) {
const user = readSession(request);
if (!user) return new Response("Unauthorized", { status: 401, headers: { "Cache-Control": "no-store" } });
const token = (request.headers.get("cookie") ?? "").split(";")
.map(part => part.trim()).find(part => part.startsWith("session="))?.slice(8);
if (!token) return new Response("Unauthorized", { status: 401 });
return { userId: user.id, token, revision: -1 };
},
open(socket) {
const ws = socket as LiveSocket;
if (!valid(ws)) return ws.close(1008, "Unauthorized");
let group = sockets.get(ws.data.userId);
if (!group) sockets.set(ws.data.userId, group = new Set());
group.add(ws);
// This read AFTER adding the socket closes the subscribe/snapshot race:
// writes committed during the handshake are observed in at least one path.
const revision = noteRevision(ws.data.userId);
ws.data.revision = revision;
ws.send(JSON.stringify({ type: "revision", revision }));
},
message(socket, raw) {
// A resync request has no authority to choose a user or a revision.
if (String(raw) === "sync") {
const ws = socket as LiveSocket;
if (valid(ws)) ws.send(JSON.stringify({ type: "revision", revision: noteRevision(ws.data.userId) }));
else ws.close(1008, "Session ended");
}
},
close(socket) {
const ws = socket as LiveSocket;
const group = sockets.get(ws.data.userId);
if (!group) return;
group.delete(ws);
if (group.size === 0) sockets.delete(ws.data.userId);
},
};
/** Ordinary HTTP requests to a socket-only URL never expose data. */
export function GET() {
return new Response("WebSocket required", { status: 426, headers: { Upgrade: "websocket" } });
}
Source: templates/app/app/api/notes/live/route.ts, lines 60–110.
The framework checks the browser's Origin before it invokes upgrade. A foreign origin is denied by default. The guard then reads the session from an HttpOnly cookie and returns HTTP 401 if it cannot authenticate. Returning the object associates trusted data with the accepted socket. Returning a Response refuses the handshake. The browser cannot claim another userId through a query parameter or a message.
The route's clientKey identifies the authenticated account for limits. Counting by remote IP would group every customer behind one office proxy; counting by a client-supplied ID would be bypassable. The route uses its own per-user connection cap and upgrade bucket, while the remaining limits come from the framework defaults.
The open callback first adds the socket to the subscriber set and then reads the current revision. This ordering closes the gap in which a write could commit between reading a snapshot and subscribing. A new connection receives a revision snapshot even if the journal has already removed the corresponding event. The message callback accepts only sync and reads the revision for the socket's existing authenticated user. It does not accept a user ID in the frame. close removes the subscriber.
Commit the note and revision together#
The database schema and transaction helper contain the key contract:
export function noteRevision(userId: number) {
return measured("note revision", () => db.noteVersions.select().where({ userId }).first()?.revision ?? 0);
}
/** Change the note and its revision atomically. Never bump another user's revision. */
export function writeNote<T>(userId: number, change: () => T): T {
return db.transaction(() => {
const result = change();
measured("bump revision", () => {
const row = db.noteVersions.select().where({ userId }).first();
if (row) db.noteVersions.select().where({ userId }).updateAll({ revision: row.revision + 1 });
else db.noteVersions.insert({ userId, revision: 1 });
});
return result;
});
}
Source: templates/app/db.ts, lines 61–75.
The note route invokes that helper for a new note:
const note = writeNote(ctx.locals.user.id, () => db.notes.insert({ userId: ctx.locals.user!.id, text }));
return json ? Response.json({ note }, { status: 201 }) : redirect("/notes");
Source: templates/app/app/api/notes/route.ts, lines 25–26.
For edits and deletes, app/api/notes/[id]/route.ts calls ownedNote before writing. A note belonging to another account is treated like a missing note. The handler ignores any submitted ownership field and writes the revision for ctx.locals.user.id. The revision row is not an independent background job: when the note write rolls back, the revision increment rolls back with it.
pollInterval: 10 in db.ts configures the journal reader used by sqlite-zod-orm's table listeners. Each server process registers its noteVersions.on("insert") and on("update") callbacks when its route module loads. A revision for a new user creates a row; subsequent revisions update it. The journal is an ordered, bounded notification mechanism, not an archive of note contents or a durable replay queue. The starter's actual socket frames contain only {"type":"revision","revision":...}.
In the figure, process A handles tab A's POST. SQLite commits the note and the user's revision. The journal wakes the listener in process B, where tab B's authenticated socket is already subscribed. The listener reads the authoritative revision and sends a small frame. Tab B refetches /notes, receives new server HTML, and replaces the notes-results subtree. Neither process sends note text over the socket.
The starter load run used two tradjs start processes against one file, with 200 authenticated sockets and 2,000 committed writes. Every user received exactly their own 10 updates; aggregate server memory was 204 MiB before and 220 MiB after. This establishes the observed behavior for that workload, not a maximum connection count or a per-socket memory formula. The browser run completed 43 of 43 steps on the stated test machine.
Revisions recover missed notifications#
A client stores the revision from the rendered #notes-results element and separately tracks the newest requested revision. It ignores malformed numbers and any revision that does not advance the target. Receiving a higher revision starts an HTML fetch only when there is no active request. The HTML's data-revision determines which state was actually rendered.
} finally {
refreshing = false;
// An event arriving during the HTML request must not be discarded.
if (active && desired > revision && !controller.signal.aborted) {
// Avoid spinning if the server response precedes the change commit.
scheduleRefresh(refreshBackoff);
}
}
}
function revisionReceived(value: unknown) {
if (!active || typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) return;
desired = Math.max(desired, value);
void updateList();
}
Source: templates/app/app/notes/page.client.tsx, lines 61–75.
A frame can arrive during the fetch. The finally block schedules another attempt while desired remains above the revision in the DOM. The server captures the revision before listing notes, so a concurrent write may cause an extra refresh rather than stamping older HTML with a revision that claims it is newer. A focused edit form is not replaced while somebody is typing. focusout retries the pending refresh. Only #notes-results is replaced; the create form remains intact.
Reconnection is a snapshot operation rather than replay. The new socket receives the latest revision in open and the client also sends sync on onopen. Any intervening writes are folded into the current HTML fetch. If the browser was parked in the back/forward cache, pagehide disposed the socket and pageshow remounts it. The revision stored in the DOM is compared with the next snapshot. This recovers from an offline interval longer than the journal's retention window.
The route sends contiguous revision frames for a burst, but it does not queue them without limit. If send indicates backpressure, the socket is closed with 1013; a reconnect then catches up with the latest revision. Session revocation closes subscribed sockets with 1008. Authentication is checked again before sending; being admitted once does not grant indefinite access.
Connection limits and close codes#
The transport manager enforces the following defaults unless an individual route overrides them. The starter changes its per-client cap to 8, its upgrade rate to 120 per minute, its upgrade burst to 20 and its idle timeout to 180 seconds.
| Condition | Default | Result |
|---|---|---|
| Incoming payload | 64 KiB | Over limit: close 1009 |
| Active plus pending sockets per client | 16 | Extra upgrade: HTTP 429 |
| Active plus pending sockets per route | 512 | Extra upgrade: HTTP 503 |
| Messages per socket | 20/second, burst 5 | Empty token bucket: close 1008 |
| No inbound message | 60 seconds | Idle close 1001 |
| Outbound buffered data | 256 KiB | Over limit: close 1013 |
| Upgrades per client and route | 30/minute, burst 5 | Empty token bucket: HTTP 429 |
Source: src/server/websocket-limits.ts and docs/websockets.md; boundary tests: tests/websocket-limits-matrix.test.ts. |
||
| An upgrade rejection happens before a socket exists, so it is an HTTP status, not a close frame. The token buckets replenish continuously, include pending handshakes in connection quotas and operate per process. An upstream rate limiter is needed for limits shared between processes or hosts. The close codes follow the protocol's meanings for policy, message size, going away and temporary overload (RFC 6455). |
Retry without a reconnect storm#
The starter's actual reconnect function is short:
/** Exponential reconnect backoff with bounded jitter; no timers or DOM required. */
export function websocketReconnectDelay(attempt: number, random: () => number = Math.random): number {
const step = Math.max(0, Math.floor(Number.isFinite(attempt) ? attempt : 0));
const ceiling = Math.min(30_000, 250 * 2 ** Math.min(step, 10));
const jitter = Math.min(1, Math.max(0, random()));
return Math.floor(ceiling * (0.5 + jitter * 0.5));
}
Source: templates/app/app/notes/reconnect-backoff.ts, lines 1–7.
The formula is floor(min(30000, 250 × 2^min(attempt,10)) × (0.5 + 0.5 × random)) milliseconds, with random clamped to the interval from zero to one. The first failed connection schedules another after 125–250 ms. After repeated failures the range reaches 15,000–30,000 ms. The count resets only after a socket stays healthy for 30,000 ms, not whenever a short-lived connection opens.

| Failed attempt, zero-based | Minimum delay | Maximum delay |
|---|---|---|
| 0 | 125 ms | 250 ms |
| 1 | 250 ms | 500 ms |
| 2 | 500 ms | 1,000 ms |
| 3 | 1,000 ms | 2,000 ms |
| 4 | 2,000 ms | 4,000 ms |
| 5 | 4,000 ms | 8,000 ms |
| 6 | 8,000 ms | 16,000 ms |
| 7 and later | 15,000 ms | 30,000 ms |
Computed from templates/app/app/notes/reconnect-backoff.ts; the Python arithmetic is in FACTS.md. |
||
| There is a separate connection timeout of 1,500 ms. A socket that never opens is closed rather than leaving polling disabled indefinitely. The code does not promise that a connection will succeed by any scheduled retry; the delay controls pressure on the unavailable service. |
Poll when the socket is absent#
A WebSocket is an enhancement to a page that already works through standard GET and POST. When a socket errors or closes, the client immediately starts fetching the small version endpoint, then polls it every 600 ms while disconnected. On a successful WebSocket open it stops the fallback. The endpoint is authenticated and returns only the current revision:
import type { RouteContext } from "tradjs/server";
import { noteRevision, type AppLocals } from "../../../../db";
export function GET(_req: Request, ctx: RouteContext<AppLocals>) {
if (!ctx.locals.user) return Response.json({ error: "Unauthorized" }, { status: 401, headers: { "Cache-Control": "no-store" } });
return Response.json({ revision: noteRevision(ctx.locals.user.id) }, { headers: { "Cache-Control": "no-store" } });
}
Source: templates/app/app/api/notes/version/route.ts, lines 1–7.
An unauthorized poll returns 401; the mount disposes itself. A revision increase calls the same HTML refresh path used by socket frames. If WebSocket does not exist in the environment, polling remains the transport. If the WebSocket returns, the app does not combine socket frames with unnecessary periodic version requests.
To exercise the path, initialize the starter, log in from two tabs, and edit a note. For a cross-process check, run two production listeners from the same generated app directory on different ports and point a tab at each. Both listeners must use the identical SQLite database path. Disconnect one tab's socket, change notes through the other process and reconnect. Its first new revision snapshot must cause the list to catch up. Check network traffic: only revision numbers travel in socket frames, while the note text comes from an authenticated HTML response.
Do not copy a SQLite file to another host and expect the journal to synchronize it. SQLite WAL coordination requires the processes to share the same host and database file (SQLite WAL). For multiple hosts, replace the shared-file notification design with an explicit distributed change service and a database topology designed for that deployment.