Realtime
Look up the realtime handler, scoped tokens, browser client, type helpers, errors, and wire limits.
This page lists the exact behavior of @runlane/realtime. To set it up, start with the realtime guides.
Imports
| Import from | Use in | Main exports |
|---|---|---|
@runlane/realtime | Server code | createRunlaneRealtime, and the types RunlaneRealtime, RunlaneRealtimeOptions, RunlaneRealtimeAuthorize, RunlaneRealtimeTokenOptions, CreateRealtimeTokenOptions, and RunlaneRealtimeSource. Also re-exports RunlaneError, ErrorCode, RunReadPermission, RunAccessGrant, and VerifiedRunToken. |
@runlane/realtime/client | Browsers and Node.js 22.18 or later | createRunlaneClient, RunlaneError, ErrorCode, RunSubscriptionEventType, RunStreamRecordType, the client types, and the frontend type helpers |
@runlane/contracts/realtime | Both | Shared schemas, enums, and types, plus realtimeDefaults |
The client needs a browser with Fetch response streaming, or Node.js 22.18 or later.
Server entry
createRunlaneRealtime(options) returns a RunlaneRealtime:
| Member | Type |
|---|---|
handle | (request: Request) => Promise<Response> |
createToken | (options: CreateRealtimeTokenOptions) => Promise<string> |
import { createRunlaneRealtime } from '@runlane/realtime'
export const realtime = createRunlaneRealtime({
runlane,
authorize,
tokens: { audience: 'web', keyId: 'v1', key, verifyKeys: { v0: previousKey } },
})
export const GET = realtime.handleOptions
| Option | Meaning |
|---|---|
runlane | Required. A RunlaneRealtimeSource. A core runtime works. |
authorize | Your access check. See authorize. |
tokens | Token signing settings. See token options. |
telemetry, onTelemetryError | Optional. See telemetry. |
You must set authorize, tokens, or both:
authorizealone suits same-origin session cookies.tokensalone suits bearer tokens from a frontend on another origin.- Both check the token and your current policy on every connection.
Setting neither throws at construction. The message shows both fixes. Unknown options, or an authorize that is not a function, throw configuration_invalid. All of these checks run before the first request.
RunlaneRealtimeSource is a structural interface. It needs environment, runs.get(), runs.subscribe(), and runs.readStream(). It can also expose lane.runSignal, which wakes named stream readers sooner. A core runtime has all of these.
The handler starts no worker. A runtime that does not mount it does no extra storage reads or writes and needs no extra indexes.
Routes
The handler serves two routes. It matches the end of the path, so any prefix works without rewriting the URL. For example, mount it at /api/progress.
| Route | Response body |
|---|---|
GET /runs/:id/events | A run snapshot, then status, metadata, and permitted stream events |
GET /runs/:id/streams/:name | Saved records for one stream, then new records and attempt closes |
- URI-encode run IDs and stream names.
- Other methods return
405withAllow: GET. Unknown routes return404. - Send a resume cursor in
Last-Event-IDor theafterquery parameter. Sending two different cursors returns400. - The events route also accepts
streams=none. It sends no stream records, whatever the grant allows. The client sends it forsubscribe(runId, { streams: false }). Any other value, a repeated parameter, orstreamson a stream route returns400. - Any other query parameter returns
400. - A cursor is tied to one reader kind, environment, run, and retained run instance. It grants no access.
- Run IDs and stream names cannot be
.or.., because URL parsing removes those path segments. Their schemas reject them with a clear message. Generated run IDs always work.
Authorization
authorize
RunlaneRealtimeAuthorize is the type of the authorize option. It equals NonNullable<RunlaneRealtimeOptions['authorize']>. Use it to type a policy that lives in its own module.
type RunlaneRealtimeAuthorize = (input: {
request: Request
runId: RunId
token?: VerifiedRunToken
}) => RunAccessGrant | undefined | Promise<RunAccessGrant | undefined>- It runs on every connection. It runs after token checks and before any run data is read.
- Return a grant to allow access. Return
undefinedto deny it. - If it throws, the reader gets a safe
500response.
Grants
import { RunReadPermission, type RunAccessGrant } from '@runlane/contracts/realtime'
const progressGrant: RunAccessGrant = {
permissions: [RunReadPermission.Status, RunReadPermission.Meta, RunReadPermission.Streams],
streams: ['answer'],
}| Permission | Sends |
|---|---|
Status | Run snapshots and status changes |
Meta | Metadata patches. Snapshot metadata also needs Status. |
Output | output and failure inside permitted snapshots and status changes |
Streams | Stream records, limited to streams when you set it |
Name rules:
- Leaving out
streamsallows every name, but only with theStreamspermission. streams: []allows no names.- A request for a stream name outside the grant gets
403.
How grants combine:
| Setup | Effective grant |
|---|---|
authorize only | The grant that authorize returns |
tokens only | The verified token's grant. A request without a token is denied. |
| Both | The overlap of both: shared permissions and shared names. A token never adds access. |
With both set, a request without a token uses the authorize grant alone.
What the browser receives
The handler passes the allowed stream names to core runs.subscribe(runId, { streams }). With streams=none, it passes streams: false. Core never reads names outside that list, and they never enter the cursor. Payload, output, and metadata are stored on the run record, so the handler reads them with it. It then removes the fields the grant does not allow. Forbidden values are never sent.
A snapshot can contain only these fields:
- Always:
id,environment,taskId,status,counters.attempts,eventSequence,version,createdAt,updatedAt,startedAt, andfinishedAt. - With
Meta:meta. - With
Output:output, andfailurewith onlyname,code,message, andretryable.
The handler never sends failure stacks or failure metadata. It also never sends payloads, wait tokens, application keys, tags, queues, policies, source identity, leases, trace carriers, or hook state.
runRealtimeSnapshotSchema owns this list. The browser's RunSubscriptionEvent snapshot uses this restricted type. Core subscriptions still return the full run record. When the grant hides a status or metadata event, the handler sends a cursor-only checkpoint instead, so a reconnect still moves forward.
Scoped tokens
Token options
RunlaneRealtimeTokenOptions is { audience, keyId, key, verifyKeys? }.
| Field | Rules |
|---|---|
audience | Non-empty string. Tokens for another audience are rejected. |
keyId | 1 to 128 characters. Sent in the token header as kid. |
key | Web Crypto HMAC-SHA256 secret key, at least 256 bits, with sign and verify usage |
verifyKeys | Optional record of older keys by ID. Each needs verify usage. It cannot repeat the active keyId. |
Invalid options throw before the first request. At request time, an unknown key ID, a bad signature, or an expired token returns a safe 403.
Keep every key on the server. Keep old keys in verifyKeys until the tokens they signed expire.
createToken
realtime.createToken({ runId, grant?, expiresIn? }) returns a signed token for the runtime's environment.
| Option | Rules |
|---|---|
runId | Required. A plain string is fine. It is validated and branded. |
grant | Defaults to every RunReadPermission, with no stream-name limit |
expiresIn | Defaults to contractDefaults.realtime.tokenTTL. Whole seconds from 1s up to contractDefaults.realtime.maxTokenTTL. |
createToken takes no Request. It does not call authorize, and it does not check that the run exists. Your app must check the user's access before it mints a token, including in server actions and token refresh routes. When authorize is set, it still limits every connection that uses the token.
| Problem | Error |
|---|---|
| Invalid run ID or grant | validation_failed |
tokens not configured | configuration_invalid |
Invalid expiresIn | configuration_invalid |
The package has no token endpoint and no default access policy. See use tokens for routes you can copy.
Token format
- Tokens are compact JWS with canonical, unpadded base64url segments. The format still accepts tokens issued by earlier Runlane versions.
- The header is exactly
{ alg: 'HS256', typ: 'JWT', kid }. - The claims are a
VerifiedRunToken:{ environment, runId, grant, audience, issuedAt, expiresAt, version: 1 }. Times are whole Unix seconds. issuedAtcan be up tocontractDefaults.realtime.issuedAtLeewayahead of the server clock. Expiry has no leeway.- Verification rejects unknown fields, versions, algorithms, and key IDs. It also rejects bad signatures, issue times beyond the leeway, expired tokens, lifetimes that are too long, and mismatched scopes.
- The server reads tokens only from the
Authorization: Bearerheader. - A request with an invalid token gets
403. The handler does not fall back toauthorizewith cookies.
Browser client
createRunlaneClient({ baseUrl, refreshAccessToken?, fetch?, telemetry?, onTelemetryError? }) returns a RunlaneClient. You own its lifetime. One client can serve readers for many runs. Each reader keeps its own token.
baseUrl is the absolute http or https URL of the handler's mount. It cannot contain a user name, password, query, or fragment.
| Call | Returns |
|---|---|
client.subscribe<TTask = unknown>(runId, options?) | AsyncGenerator<RunSubscriptionEvent<TTask>, void> |
client.readStream<TTask = unknown, TName = RunStreamName<TTask>>(runId, name, options?) | AsyncGenerator<RunStreamRecord<RunStreamPart<TTask, TName>>, void> |
Reader options
RunlaneClientReadOptions is shared by both readers:
| Option | Meaning |
|---|---|
accessToken | Token for the first connection |
after | Resume cursor |
signal | AbortSignal. Aborting ends the iterator without an error. It does not cancel the run. |
onConnectionChange | (change: RealtimeConnectionChange) => void. See connection state. |
subscribe() takes RunlaneClientSubscribeOptions: the options above, plus streams?: false. Pass false to leave out stream records, for a connection that only needs status, metadata, and output. Omit it to get every stream the grant allows. readStream() does not take streams. An invalid streams value fails with validation_failed on the first next().
RunSubscribeOptions belongs to core and contracts. The client does not export it. The browser can only leave streams out; the grant chooses which names it may read.
Reader behavior:
- Wire timestamps are ISO strings. The client turns them into
Dateobjects. - Saved stream records arrive before the terminal status.
- A terminal status, or the server's
endevent, ends the reader normally. - A failed task is data, not a client error.
readStream()both catches up and follows. Do not pass it asubscribe()cursor.
refreshAccessToken
refreshAccessToken({ runId, signal }) returns a token string, or a promise of one. Its argument type is RunTokenRequest, exported from @runlane/realtime/client: { readonly runId: RunId; readonly signal: AbortSignal }. Pass signal to your token request.
Token rule
- The first connection uses the reader's
accessToken. If there is none and a refresher is set, the client calls the refresher first. With neither, the client sends noAuthorizationheader, so same-origin cookies can authorize the request. - Network drops, normal connection rotation, retryable SSE errors,
429, and retryable5xxresponses reconnect with the current token. They do not call the refresher. - A
403with codeaccess_deniedcalls the refresher once, then reconnects with the new token. A second403in a row, or a403with no refresher, ends the reader withaccess_denied. A successful connection resets this allowance. - If the refresher throws a plain error, the client treats it as a retryable
disconnectederror that keeps the cause. It uses the normal backoff and failure budget. A thrownRunlaneErrorwithretryable: truedoes the same. Any otherRunlaneErrorends the reader at once. - Aborting stops waiting for a refresh. The client ignores a late result and observes a late rejection. It never opens a connection with a late token.
Input checks
| Problem | When | Error |
|---|---|---|
Unknown client option, or a refreshAccessToken or fetch that is not a function | createRunlaneClient() | configuration_invalid |
Invalid baseUrl | createRunlaneClient() | configuration_invalid, with the validation error as cause |
| Invalid run ID or stream name | First next() | validation_failed, with the validation error as cause |
Invalid after cursor | First next() | run_cursor_invalid, with the validation error as cause |
Reader input is checked on the first next(). That happens before any token request, network call, or connection notification.
Reconnects
The client uses Fetch streaming, because the browser's EventSource cannot send a bearer header. It rejects redirects.
- Disconnects,
429, and retryable5xxresponses reconnect after a growing delay with random jitter.reconnect.backoffuses the existing retry backoff shape, including fixed and exponential backoff. Backoff durations and every permitted retry delay must fit the Node timer platform limit of 2,147,483,647 ms. Unlimited exponential retries requiremaxDelay. The default is exponential, from250msup to10s, owned bycontractDefaults.realtime.reconnect. - Each reconnect resumes from the last delivered cursor. The server checks access again.
- Token route failures also count as reconnect failures.
- Retries continue until caller abort by default (
reconnect.maxRetries: 'unlimited'). Set a non-negative integer to allow that many retries after the initial request; zero disables retries. On reaching a finite limit, the reader fails with a non-retryabledisconnectederror. Itsmeta.cursorholds the last delivered cursor. Itscauseis the last retryable failure, including nested causes such as a token callback error. A plain end of the response body adds no cause. - Cursor progress, or a connection that stays open for one heartbeat interval, resets the failure count.
These do not retry: 400 responses, invalid cursors, missing or pruned runs, and malformed wire data. A 403 follows the token rule.
Connection state
RealtimeConnectionChange and its enums live in @runlane/contracts/realtime. Notifications stay in the client and are never sent over the wire. Both readers accept the same callback.
RealtimeConnectionState | When and fields |
|---|---|
Connecting | Before each connection attempt |
Open | After a streaming response passes header checks |
Reconnecting | attempt counts tries in a row, starting at 1. It resets when a connection opens. delayMs is the jittered wait before the next try, in milliseconds. |
Closed | reason is RealtimeConnectionCloseReason.Completed, Aborted, or Failed. Failed also has error, a RunlaneError that keeps an unexpected failure as its cause. |
- Each change fires once, in order, and never after the reader ends.
- A run that ends in failure still closes with
Completed, because its result was delivered. - If the callback throws, it gets no more notifications and the reader ends. A thrown
RunlaneErroris kept. Any other value becomesinternal_errorwith the value ascause. This holds even during a retryable failure; the client does not retry it.
Errors
Realtime and React failures all use RunlaneError and ErrorCode. Both @runlane/realtime and @runlane/realtime/client export them. instanceof RunlaneError works even when a bundle holds two copies of the contracts package.
| Code | HTTP | Meaning |
|---|---|---|
access_denied | 403 | Denied by authorize, a token check, or a stream-name limit |
validation_failed | 400 | Bad request input or grant. Also used when the source throws ConfigurationInvalid or ValidationFailed. |
run_cursor_invalid | 400 | The cursor does not match this reader, or is malformed |
run_not_found | 404 | The authorized run is missing or pruned |
internal_error | 500 | Unexpected failure. The response is safe; the original stays in cause on the server. |
event_too_large | — | One event is over the size limit. Sent as an SSE error. It does not retry. |
wire_invalid | — | The client received malformed data |
disconnected | — | The connection was lost. The server sends a retryable one when it shuts down. The client throws a final one only when a configured finite retry limit is reached. |
configuration_invalid | — | Invalid handler, client, or hook options. Thrown in your code, never sent over the wire. |
Before response headers are sent, an error is JSON: { error: { code, message, retryable, cursor? } }. After headers, the same safe error arrives as an SSE error event, and the connection closes.
On the client, a RunlaneError has code, retryable, and an optional checkpoint in meta.cursor. Wire decoding requires message and retryable, and accepts only codes the handler can send. The client maps the wire cursor to meta.cursor.
To throw one yourself, for example from refreshAccessToken:
import { ErrorCode, RunlaneError } from '@runlane/realtime/client'
throw new RunlaneError({
code: ErrorCode.AccessDenied,
message: 'Run access denied.',
})The options type, RunlaneErrorOptions, belongs to @runlane/contracts. It accepts { code, message?, retryable?, meta?, cause? }. message defaults to code, and retryable defaults to false. Set retryable: true yourself for temporary failures. Use cause to keep the original internal error. Never show cause to users. These defaults do not apply to wire decoding.
This package never logs tokens or application bodies.
Frontend type helpers
RunTypes, RunOutput, RunMeta, RunStreams, RunStreamName, and RunStreamPart are types only. Import them from @runlane/contracts/realtime, @runlane/realtime/client, or @runlane/react. They add no runtime code.
import type { RunOutput, RunStreamPart, RunTypes } from '@runlane/realtime/client'
import type { writeAnswer } from './tasks/write-answer'
type Output = RunOutput<typeof writeAnswer>
type AnswerPart = RunStreamPart<typeof writeAnswer, 'answer'>
type Answer = RunTypes<{
output: { parts: number }
meta: { progress: number }
streams: { answer: string; tokens: number }
}>
type Part = RunStreamPart<Answer> // string | number| Helper | Result |
|---|---|
RunOutput<TTask> | The output schema's input type (the stored handler return), or the declared output. Falls back to JsonValue | undefined. |
RunMeta<TTask> | The declared metadata type, or JsonObject for a core task |
RunStreams<TTask> | A map from each declared name to its parsed part type |
RunStreamName<TTask> | A union of the declared names |
RunStreamPart<TTask, TName> | The parsed part type for that name. Without TName, a union across all names. Undeclared names are type errors. |
With no type argument, output is JsonValue | undefined, metadata is JsonObject, streams are Record<string, JsonValue>, names are string, and parts are JsonValue.
How the readers use them:
subscribe<TTask>types snapshot and status output asRunOutput<TTask>, and snapshot metadata asRunMeta<TTask>. Both stay optional, because a grant can leave them out.readStream<TTask, TName>types each chunk'svalueasRunStreamPart<TTask, TName>. It also limitsnameto declared names.- With only
TTask, the name type defaults to the union of names. With several part types, pass the name as the second type argument to get an exact type.
Rules:
- Output uses the schema's input type. Core validates the handler's return value, but stores and sends it unchanged. If an output schema turns a string into an object, the browser still gets the string.
- Parts use the schema's output type, because writers store parsed parts.
- No browser validation. These types do not check values. The server validates output and parts when they are written.
RunTypesdescribes the JSON the server sends, in optionaloutput,meta, andstreamskeys. Interfaces and type aliases both work, with no index signature. It does not check that the types are valid JSON. Leaving outstreamsmeans the task has no stream names.
To get these types in another repo, see frontend types.
Wire format and limits
Responses use text/event-stream and Cache-Control: no-store. They send heartbeat comments and id: <cursor> lines. This follows the HTML server-sent events standard, with the Fetch and Streams standards. Tokens use Web Crypto HMAC.
| SSE event | Data |
|---|---|
snapshot, status, meta, stream | On the events route, the subscription event with its cursor |
stream | On a stream route, { cursor?, record } |
checkpoint, end | {} |
error | { code, message, retryable, cursor? } |
Stream pages
- A stream route reads
contractDefaults.pagination.defaultLimitrecords per page. Only the last record of a page carriescursorand the SSEid. Earlier records leave the last checkpoint unchanged. - After a disconnect, at most one page can be sent again. Within one reader, the client skips record IDs it already delivered, so each record reaches your code once. It only remembers records since the last checkpoint.
- A new reader started from an older cursor can repeat records after that cursor.
Connection lifetime
- A connection ends at its token's expiry or after
contractDefaults.realtime.connectionDuration, whichever comes first. The client reconnects. - On runtime shutdown, the handler sends a retryable error with the last delivered cursor. The client reconnects and can resume on another server.
Size limits
contractDefaults.realtime.maxEventBytesisstorage.maxRecordBytesplus room for the cursor and SSE envelope.maxBufferedBytesis at least that large.- Limits count real UTF-8 bytes after JSON escaping.
- Every run output, metadata value, and stream part that storage accepts fits in one event. One event over the limit fails with non-retryable
event_too_large. Reconnecting cannot fix it. - One network read can hold several events. The client limits each event on its own, including comments, IDs, and unknown fields. It rejects invalid UTF-8.
- An SSE
idcarries over to later events that have none. An emptyidclears it. A parsediddoes not move the resume cursor until your code receives that event's record.
Backpressure
The server reads only as fast as the client consumes. A paused reader pauses the source. A stream route keeps one page in memory. It waits for run hints only while idle, and otherwise polls every contractDefaults.streams.pollInterval. It sends checkpoints only when the cursor it checked has changed.
Read all shared limits from contractDefaults.realtime, or from realtimeDefaults in browser code. See defaults for the values.
Proxies and CORS
- Turn off proxy caching. Allow streaming and request cancellation. Keep idle timeouts longer than
contractDefaults.realtime.heartbeatInterval. - The handler sends
X-Accel-Buffering: no, which nginx follows. If a proxy or CDN ignores or strips it, turn off buffering for the route. In nginx, addproxy_buffering off;to thatlocation. - The handler adds no CORS headers, and never a wildcard. Your app owns CORS, including
OPTIONSpreflight responses and headers on error responses. Allow only your origin, theGETmethod, and theAuthorizationandLast-Event-IDheaders. See allow another origin for a working adapter. - The browser hides CORS failures behind a network error.
onConnectionChangethen reportsReconnectingwith a growingattempt. A redirectingbaseUrlalso looks like a network failure, because the client rejects redirects. - Use HTTPS in production.
Telemetry
Pass telemetry to the handler or the client to record:
- read and subscribe spans;
- connection duration and reconnects;
- authorization denials and
authorizeexceptions; - token rejections.
Access logs hold only the operation and a short, fixed reason. Token rejection reasons are: malformed data, header, unknown key, invalid key, signature, claims, audience, future issue time, expiry, and lifetime. They never include tokens, user values, run IDs, cursors, or stream names. See the signal list.