Sessions
A session runs a series of tasks on the same worker. Use one when a task leaves something behind in its worker that the next task needs: a file on local disk, a model loaded into memory, an open connection.
Creating a Session
Define the tasks as usual:
1// Worker-local state the tasks share: it exists only in the process that set it.2const downloads = new Map<string, string>();34export const download = task({5 name: 'download',6 execute: async (_ctx: TaskContext, url: string): Promise<string> => {7 const path = `/tmp/${encodeURIComponent(url)}`;8 // Download url to path here.9 downloads.set(url, path);10 return path;11 },12});1314export const transcode = task({15 name: 'transcode',16 execute: async (_ctx: TaskContext, path: string): Promise<string> => {17 // Read the local file at path, write the output beside it.18 return `${path}.mp4`;19 },20});2122export const upload = task({23 name: 'upload',24 execute: async (_ctx: TaskContext, path: string): Promise<string> => {25 // Upload the local file at path here.26 return `https://cdn.example.com/${encodeURIComponent(path)}`;27 },28});Then call ctx.createSession() in the workflow and run the tasks through the session:
1export type TranscodeResult = { ok: true; location: string } | { ok: false; error: string };23export const transcodeVideo = workflow({4 name: 'transcodeVideo',5 run: async (ctx: WorkflowContext, url: string): Promise<TranscodeResult> => {6 // A worker with a free session slot takes the session; its tasks all run there.7 const session = await ctx.createSession();8 try {9 const path = await session.executeTask(download, url);10 const output = await session.executeTask(transcode, path);11 const location = await session.executeTask(upload, output);12 session.complete(); // release the worker's slot13 return { ok: true, location };14 } catch (err) {15 // Waiting for a task is not a failure: leave the session open.16 if (isWorkflowSuspension(err)) throw err;17 // A real failure. Release the slot and report it in the result: a workflow18 // that throws sends nothing else from that activation, complete() included.19 session.complete();20 return { ok: false, error: err instanceof Error ? err.message : String(err) };21 }22 },23});session.executeTask() takes the same typed references as ctx.executeTask(), and sends the
task to a queue that only the session's worker polls. It takes no per-call options.
Releasing the Slot
Each worker hosts at most 10 sessions at once. session.complete() frees the session's slot on
its worker; nothing else does, short of the worker shutting down. So:
- Call
complete()on every path that ends the session, success and failure alike. - Don't call it in
finallyor before re-throwing a suspension. Waiting for a task throws a suspension (see handling failures), and completing then would close the session while its tasks are still to come. - Don't throw after
complete(). A workflow that throws fails, and nothing else it did in that run of its code is sent to the engine,complete()included. Report the failure in the workflow's result instead, as the sample does.
How It Works
ctx.createSession()schedules an internal session-creation task on the workflow's queue.- A worker picks it up and takes one of its session slots. If it has none free, the creation task fails, and is retried like any task, possibly on another worker.
- That worker starts polling a queue of its own,
{queue}__session__{id}, and the workflow receives the queue's name. session.executeTask()sends each task to that queue, so only that worker runs them.session.complete()schedules an internal task on that queue, which frees the slot and stops the worker polling it.
On replay the session comes from the journal; it is not created again.
Limitations
- A session lives and dies with its worker. If the worker stops while one of the session's tasks is running, that task times out (its heartbeat timeout, a minute by default) and the engine fails it and every other task on the session's queue as lost, so the workflow sees the failure and can open a new session. A task only waiting on the queue is caught by its own queue timeout, which by default is none.
- Two session options are not enforced.
createSession()acceptsmaxConcurrentTasksandheartbeatInterval, but the worker does not apply them;creationTimeoutandexecutionTimeoutare applied. - No migration. Worker-local state (files, models, connections) is not moved anywhere.
- One worker. All of a session's tasks run on one worker; for work that can run anywhere, use ordinary tasks.
- The slot count is fixed at 10 per worker; it is not a worker option.