Skip to content
tako
Esc
↑↓navigate↵open⌘Jpreview
On this page

Workflows

Build durable background workflows with typed payloads, checkpointed steps, retries, sleeps, signals, and scale-to-zero execution.

Tako workflows run background work next to your app without a separate queue service. A workflow can retry after failures, remember completed steps, sleep without holding a worker open, wait for an external signal, run on a cron schedule, and let its worker process scale to zero when idle.

Code tabs cover JavaScript/TypeScript and Go where their workflow APIs correspond. JavaScript uses tako.sh; the Go worker SDK is the separate github.com/tako-sh/tako/sdk/go module, not the root Go HTTP SDK. The Rust SDK does not currently provide workflow authoring or worker APIs. JavaScript, the root Go HTTP SDK, and Rust can enqueue a JavaScript-owned network workflow by qualified string address. Shared runtime semantics apply to both supported worker SDKs; option tables below describe the JavaScript API unless stated otherwise.

Vocabulary

Term Meaning
Workflow A named handler discovered from a JS module or registered by a Go worker.
Run One execution of a workflow with its own payload, run ID, attempts, and status.
Step A named, checkpointed operation inside a run, created with ctx.run.
Worker A separate process that claims and executes workflow runs.

Run statuses are pending, running, succeeded, cancelled, and dead. A run may return to pending while waiting for a retry, sleep, or signal.

Define A Workflow

For JavaScript, create a module under <app_root>/workflows/ and default-export defineWorkflow. For Go, register the handler in the worker process before RunWorker:

// src/workflows/fulfill-order.ts
import { defineWorkflow } from "tako.sh";

type FulfillOrderPayload = {
  orderId: string;
};

export default defineWorkflow<FulfillOrderPayload>("fulfill-order", {
  retries: 4,
  handler: async (payload, ctx) => {
    const order = await ctx.run("load-order", () => db.orders.find(payload.orderId));

    await ctx.run("charge", () =>
      payments.charge({
        orderId: order.id,
        amount: order.total,
        idempotencyKey: `${ctx.runId}:charge`,
      }),
    );

    await ctx.run("send-receipt", () => mailer.send(order.email));
  },
});
// cmd/worker/main.go
package main

import (
    "context"
    "encoding/json"
    "log"

    workflow "github.com/tako-sh/tako/sdk/go"
)

func main() {
    workflow.RegisterWorkflow("fulfill-order", func(ctx *workflow.WorkflowContext, raw json.RawMessage) error {
        var payload struct { OrderID string `json:"orderId"` }
        if err := json.Unmarshal(raw, &payload); err != nil {
            return ctx.Fail(err)
        }
        return ctx.Step.Run("fulfill", nil, func() (any, error) {
            // Your helper must use the stable key to deduplicate external effects.
            return nil, fulfillOrder(payload.OrderID, ctx.RunID+":fulfill")
        })
    }, workflow.WithMaxAttempts(5))
    if err := workflow.RunWorker(context.Background()); err != nil {
        log.Fatal(err)
    }
}

The Go fulfillOrder helper is app-owned. Install the Go worker module with go get github.com/tako-sh/tako/sdk/go, build a worker binary, and configure its command in [workflows].run when needed. WithMaxAttempts(5) counts all attempts; JavaScript retries: 4 counts retries after the first attempt.

Both SDKs store the attempt budget on the run when it is enqueued, and the worker honors the stored value. Go’s Enqueue stores the WithMaxAttempts budget only in a process that registered the workflow; from another binary, pass EnqueueOpts.MaxAttempts. Runs created by a cron schedule get the workflow’s own budget, retries or WithMaxAttempts, which the worker registers with the schedule when it starts.

The payload type flows into .enqueue(payload), so callers get normal TypeScript checking without a generated workflow registry. The workflow name must be unique within the app. Using the filename stem as the name keeps discovery and logs easy to follow.

Useful definition options include:

Option Meaning
retries Retries after the first run attempt. The default is 2, for three total attempts.
backoff Run-level retry timing with optional base and max values in milliseconds.
worker JavaScript worker group; omitted means the default lane.
schedule Five-field Unix cron in UTC. "0 9 * * 1-5" runs at 09:00 Monday through Friday. Sunday is 0 or 7.
local Keep the workflow on per-server local storage in a multi-server environment.

Enqueue A Run

Import the workflow handle from server-side code and enqueue a JSON-serializable payload:

import fulfillOrder from "./workflows/fulfill-order";

const runId = await fulfillOrder.enqueue({ orderId: "ord_123" });
import (
    "context"
    workflow "github.com/tako-sh/tako/sdk/go"
)

func enqueueOrder(ctx context.Context, orderID string) (string, error) {
    result, err := workflow.Enqueue(ctx, "fulfill-order",
        map[string]string{"orderId": orderID}, workflow.EnqueueOpts{})
    if err != nil { return "", err }
    return result.ID, nil
}

You can enqueue from a request handler, another workflow, or a script running with Tako’s server runtime. Go producers also need the Tako internal socket, and container HTTP processes do not receive it in v0; see Container Workflows. Browser code cannot enqueue directly and throws TakoError("TAKO_UNAVAILABLE") if it reaches .enqueue().

Set options for a delayed run with a stable ID and seven total attempts:

await fulfillOrder.enqueue(
  { orderId: "ord_123" },
  {
    runAt: new Date(Date.now() + 60_000),
    retries: 6,
    id: "fulfill:ord_123",
  },
);
import (
    "context"
    "time"
    workflow "github.com/tako-sh/tako/sdk/go"
)

func enqueueDelayedOrder(ctx context.Context) (*workflow.EnqueueResult, error) {
    runAt := time.Now().Add(time.Minute)
    id := "fulfill:ord_123"
    maxAttempts := uint32(7)
    return workflow.Enqueue(ctx, "fulfill-order", map[string]string{"orderId": "ord_123"},
        workflow.EnqueueOpts{RunAt: &runAt, ID: &id, MaxAttempts: &maxAttempts})
}
Option Meaning
runAt Do not make the run eligible before this time. The default is now.
retries Override the workflow’s retry count for this run.
id Use this as the run ID. A retained run with the same ID, workflow, and payload is reused in any status.

.enqueue() returns the run ID, including the exact id you supply. Omit id to generate one and create a new run each time. IDs must contain 1–255 bytes and no NUL characters.

Go’s EnqueueOpts uses ID, RunAt, and MaxAttempts pointers. MaxAttempts counts the first attempt as well as retries. Enqueue returns an EnqueueResult with ID and Deduplicated.

IDs are unique within the app and environment, across workflow names. Repeating an ID with a different workflow or payload produces a conflict: JavaScript throws a TakoError with reason: "run_id_conflict", and Go returns an error matching workflow.ErrRunIDConflict with errors.Is. Concurrent enqueues with the same ID create one run. Existing runs keep their original schedule, retry budget, status, and completed steps; enqueue does not restart a succeeded, cancelled, or dead run.

Deleting a finished run’s history also frees its ID. A later enqueue with that ID creates a new run with no saved steps. Deduplication does not prevent a step’s external side effect from repeating after a crash; pass a stable idempotency key to the external service as well.

Return Results and Call Child Workflows

JavaScript workflow handlers can return JSON data. Tako saves the result when it marks the run succeeded; an absent return becomes null. Use await task.result(runId, { timeout: "30s" }) to retrieve it, or await task.run(payload) to enqueue and wait. Both imported defineWorkflow handles and workflow("app.name") network handles expose these methods. A wait timeout leaves the child running and its result retrievable by ID.

Go handlers keep the error return value and set the result with ctx.SetResult(value). The last call wins, a value that does not JSON-encode is rejected with an error, and a handler that never calls it completes with null. workflow.Result(ctx, name, runID) reads the current outcome once and returns nil for a missing run; poll pending and running runs with your own deadline:

// src/workflows/generate-report.ts
import { defineWorkflow } from "tako.sh";

export default defineWorkflow("generate-report", {
  handler: async (payload: { month: string }, ctx) => {
    const url = await ctx.run("render", () => renderReport(payload.month));
    return { url };
  },
});

// Server-side caller: import generateReport from "./workflows/generate-report".
const report = await generateReport.result(runId, { timeout: "30s" });
// Inside a registered Go workflow handler.
var url string
if err := ctx.Step.Run("render", &url, func() (any, error) {
    return renderReport(payload.Month)
}); err != nil {
    return err
}
return ctx.SetResult(map[string]string{"url": url})

// Server-side caller with access to the Tako internal socket.
state, err := workflow.Result(ctx, "generate-report", runID)
if err != nil { return err }
if state != nil && state.Status == "succeeded" {
    var report struct { URL string `json:"url"` }
    err = json.Unmarshal(state.Result, &report)
}

renderReport is app-owned in both examples.

Within another JavaScript workflow, .run() checkpoints the child identity and terminal outcome. It defers the parent while the child is pending, releasing the worker slot without consuming a retry. Parent replay reuses the same child and cached result. Give calls stable step names, or preserve their call order within each named ctx.run scope. Use a stable enqueue ID for detached .enqueue() calls that can repeat. Retain child history long enough for parent retries: pruning a run also frees its ID.

See Network Primitives for typed examples, timeout/failure behavior, and Go/Rust result readers for JavaScript-owned workflows. Automatic durable child calls currently belong to the JavaScript SDK; the Go worker SDK has no .run() equivalent.

Durable Steps With ctx.run

ctx.run(name, fn) saves the function’s result. When the workflow is claimed again, a completed step with the same name returns its saved result instead of calling fn again. Keep step names stable for the lifetime of a workflow run, and keep returned values JSON serializable.

Step names must also be unique within a run. ctx.run, ctx.sleep, and ctx.waitFor (Go: ctx.Step.Run, Sleep, and WaitFor) share one namespace of saved steps, so give repeated work an index or ID in its name:

for (const item of order.items) {
  await ctx.run(`reserve:${item.sku}`, () => inventory.reserve(item));
}
// Inside a registered Go workflow handler.
for _, item := range order.Items {
    if err := ctx.Step.Run("reserve:"+item.SKU, nil, func() (any, error) {
        return nil, inventory.Reserve(item)
    }); err != nil {
        return err
    }
}

Using a name a second time in one execution of the handler does not return the first result: the call fails and the run becomes dead immediately, with an error that names the step. This is a programming error that another attempt cannot fix, so it does not spend the retry budget. A step completed by an earlier attempt still replays its saved result once per execution. A step whose body threw saved nothing, so the handler may catch the error and call the same name again.

The durability boundary is the saved result, not the side effect itself. If a worker stops after fn completes but before Tako saves the result, that step runs again on the next claim. Step bodies therefore have an at-least-once execution contract. Use provider idempotency keys, upserts, conditional writes, or another domain-specific guard for side effects.

Steps can retry independently before an error reaches the run-level retry policy:

await ctx.run("call-provider", callProvider, {
  retries: 2,
  backoff: { base: 500, max: 10_000 },
});
import (
    "time"
    workflow "github.com/tako-sh/tako/sdk/go"
)

func callProviderStep(ctx *workflow.WorkflowContext, callProvider func() (any, error)) error {
    opts := workflow.StepRunOpts{Retries: 2}
    opts.Backoff.Base = 500 * time.Millisecond
    opts.Backoff.Max = 10 * time.Second
    return ctx.Step.Run("call-provider", nil, callProvider, opts)
}

Step retries default to 0. Set JavaScript’s retry: false or Go’s StepRunOpts{NoRetry: true} when an error from that step is permanent and should move the run directly to dead. Go’s out argument (nil above) can be a pointer to receive the checkpointed result.

The workflow context also provides runId, workflowName, attempt, and a workflow-scoped logger. Each step callback receives the same run metadata plus stepName and a step-scoped logger.

Durable Sleep

Use a stable name and a duration in milliseconds:

await ctx.sleep("wait-before-reminder", 24 * 60 * 60 * 1000);
// Inside a registered Go workflow; import "time".
if err := ctx.Step.Sleep("wait-before-reminder", 24*time.Hour); err != nil {
    return err
}

Sleeps shorter than 30 seconds run inline. Longer sleeps park the run until its wake time so the worker can process other work or exit. Sleeping does not consume the run’s retry budget, and the wake time survives worker and server restarts.

Wait For A Signal

ctx.waitFor (JavaScript) or ctx.Step.WaitFor (Go) parks a run until matching server-side code sends a signal. With a timeout, a missing signal becomes null in JavaScript or a nil pointer result in Go:

const decision = await ctx.waitFor<{ approved: boolean; by: string }>(
  `approval:order-${payload.orderId}`,
  { timeout: 7 * 24 * 60 * 60 * 1000 },
);

if (decision === null) {
  ctx.bail("approval timed out");
}
import (
    "time"
    workflow "github.com/tako-sh/tako/sdk/go"
)

type ApprovalDecision struct {
    Approved bool   `json:"approved"`
    By       string `json:"by"`
}

func waitForApproval(ctx *workflow.WorkflowContext, orderID string) error {
    var decision *ApprovalDecision
    if err := ctx.Step.WaitFor("approval:order-"+orderID, &decision, 7*24*time.Hour); err != nil {
        return err
    }
    if decision == nil { return ctx.Bail("approval timed out") }
    if !decision.Approved { return ctx.Bail("approval rejected") }
    return nil
}

Call the Go helper from the registered handler and return its error so the worker can park or cancel the run. Its event name is also the durable step name; keep it stable across retries.

Send the signal from a request handler, webhook, script, or another workflow:

import { signal } from "tako.sh";

const woken = await signal(`approval:order-${orderId}`, {
  approved: true,
  by: userId,
});
import (
    "context"
    workflow "github.com/tako-sh/tako/sdk/go"
)

func approveOrder(ctx context.Context, orderID, userID string) (uint64, error) {
    return workflow.Signal(ctx, "approval:order-"+orderID,
        map[string]any{"approved": true, "by": userID})
}

signal wakes every run waiting on that event name and returns the number of runs woken. Like enqueue, it is server-only and throws TakoError("TAKO_UNAVAILABLE") without an installed Tako runtime. Waiting and resuming do not consume retry attempts. Completed steps before the wait remain checkpointed.

Finish, Bail, Fail, Or Retry

Handler outcome Run result
Return normally succeeded.
Throw a regular error Retry while attempts remain, then become dead.
ctx.bail(reason?) cancelled immediately, with no retry.
ctx.fail(error) dead immediately, with no retry.
Reuse a step name in one run dead immediately, with no retry.
Worker lost during the attempt Retry while attempts remain, then become dead.
Long ctx.sleep or ctx.waitFor Return to pending without spending the retry budget.

Run retries use exponential backoff with 20% jitter. The default delay starts at one second and is capped at one hour. retries: 4 means four retries after the first attempt, for five total attempts.

A worker that is killed mid-run (out of memory, SIGKILL, a host crash) or stops renewing its lease cannot report a failure. Tako reclaims the run when its lease expires, 60 seconds after the last heartbeat. The lost attempt counts against the retry budget: with attempts left, the run returns to pending immediately and resumes from its saved steps; on its last attempt it becomes dead with the error worker lost; retry budget exhausted. A handler that reliably kills its worker therefore stops after its budget instead of restarting forever.

Go handlers return nil for success, an ordinary error for retry, ctx.Bail(reason) for cancellation, or ctx.Fail(err) for permanent failure. Return errors from ctx.Step operations so the worker can park or retry the run.

Use ctx.bail when the work is no longer needed, such as a rejected or expired approval. Use ctx.fail for a permanent error that another attempt cannot fix. To finish successfully before the bottom of a handler, return normally.

Workflow and step lifecycle logs appear in the normal Tako log stream. Use ctx.logger and the logger passed to ctx.run for messages that carry the run and step context.

Scale To Zero

When a workflow runtime starts, Tako launches one worker to register schedules, even with an empty queue. The worker exits after its idle window. Enqueue, cron, a signal, a due retry or sleep, and reclaimed work can wake workers again.

Production starts one scale-to-zero lane per JavaScript worker group; Go and container workers use a single lane. Workflows with worker: "email" run in a process that only claims that group. The config parser also accepts worker counts, concurrency, and per-server overrides; those values are not applied yet.

JavaScript and Go workers honor the runtime-provided lane concurrency (currently 500). Go workers stop claiming on cancellation and wait for active handlers to finish, continuing their lease heartbeats while draining. Concurrency is a worker setting; defineWorkflow does not expose per-workflow concurrency or handler timeouts.

The workflow process runs separately from HTTP instances. Heavy workflow dependencies do not have to occupy every request-serving process, while the worker still receives the app’s runtime variables, secrets, storage bindings, and structured logs.

If a worker exits with an error before it can claim any work, Tako stops the immediate respawn loop and makes the next enqueue fail with the startup error. Fixing the worker lets the next successful claim restore normal operation.

Storage And Multiple Servers

On one server, Tako stores durable workflow state locally. Runs belong to the deployed app and environment, not to one worker process or release, so a worker restart or rolling deploy does not discard progress.

Local workflow transactions synchronize the SQLite write-ahead log before acknowledging changes, including enqueues and saved steps. Acknowledged state survives a process or host crash when the filesystem and storage device honor synchronization requests. This does not protect against loss of the disk or server; configure backups for recovery. External step side effects still have the at-least-once contract described above.

Each claim receives a distinct ownership identifier. After a lease is reclaimed, a delayed earlier attempt cannot heartbeat, save a step, or change the new attempt’s run state, even when the same process claims the run again. This protects workflow state; external side effects still need application-level idempotency.

With shared Postgres storage, leases are written, renewed, and checked against the database clock rather than each server’s own clock. Servers whose clocks disagree therefore cannot reclaim a run another server’s worker still holds, or leave a lost worker’s run stranded. Due times (runAt, sleep and wait deadlines, cron boundaries) still follow the clock of the server or worker that set them, so keep server clocks synchronized.

Tako keeps finished runs for at least 184 days by default, covering six calendar months, then removes them and their saved steps in small batches. The age is measured from completion, so long sleeps and waits do not shorten a run’s history. Cleanup is best effort while the workflow runtime is active; stopped or retired stores can keep older rows until the runtime starts again. To change the age or keep history indefinitely, set retention in tako.toml:

[workflows]
retention = "1d" # or "forever"

The setting applies to succeeded, cancelled, and dead runs. It does not delete pending or running runs. SQLite and Postgres can reuse freed database space even when the database file does not immediately shrink.

An environment deployed to multiple servers needs one of two explicit storage models:

Project shape Required setup
All workflows are global Set the environment’s postgres_url credential for shared workflow state.
Every JavaScript workflow is intentionally local Set local: true on every workflow to keep separate state on each server.
Local and global workflows are mixed Set postgres_url; the environment needs shared workflow state.
Go workflow worker on multiple servers Set postgres_url; Go workflows do not have the source-level local opt-out.

Configure shared storage with:

tako credentials set postgres_url --env production

postgres_url is a provider credential. Tako encrypts it and does not expose it to app code. The SDK API remains the same whether Tako selects local storage or Postgres.

With local: true, each server owns its own queue and cron schedule. A scheduled workflow runs once per server, and run IDs do not deduplicate across servers. Use this only for work that is intentionally server-local, such as cleaning local files or warming a regional cache.

Tako validates the multi-server storage choice before build and deploy work begins. See Deployment for environment setup and the CLI reference for provider credential commands.

Development And Deployment

tako dev discovers JavaScript and TypeScript workflows under <app_root>/workflows/. The dev daemon owns the durable state and runs workflows in a separate scale-to-zero worker. Worker output appears in the same log stream as the app. Workflow definition changes refresh the runtime.

The first worker registers the schedules and retry settings of every group. Removing the last schedule from a release with workflow support clears its registered schedules. On shared Postgres, an older release restarting after a rollout cannot overwrite the newer registration.

When upgrading a server, package the matching worker SDK. The server keeps existing schedules when a worker omits the release build from its registration.

tako deploy validates the storage model, packages workflow definitions with the app, and installs the workflow runtime for the release. A new release replaces the previous worker runtime after in-flight work drains. Removing the workflows directory in a later release retires the old workflow runtime. Durable runs remain scoped to the app and environment across releases.

Removing workflow support entirely stops that server’s cron ticker. Any servers still running the old release can keep firing the stored schedules. To stop schedules across shared Postgres while keeping older servers online, first deploy a workflow-enabled release with all schedules removed. Then deploy the HTTP-only release.

Use finite tako logs --env production --days 1 --json to inspect app and worker output with an agent; an attached terminal can follow it with --tail. See Operations for log inspection, Development for local runtime details, and Deployment for release behavior.

Inspect And Repair Runs

tako workflows reads and changes the runs of a deployed environment. It is not available for development; read the tako dev log stream locally.

Find runs that used up their retries:

tako workflows list --env production --status dead
tako workflows list --env production --name send-email --limit 100

The list shows each run’s attempts, when it finished or is next due, and the first line of its last error. Open one run to see where it stopped:

tako workflows show <run-id> --env production

show prints the payload, the saved steps oldest first with their completion time and result, any event waits, and the full stored error. The last saved step is the last checkpoint that succeeded; the error belongs to the code that runs after it. Large payloads and results are cut to a preview with their stored size, and only the 100 most recent steps are listed.

Fix the cause first, for example by deploying a corrected handler or restoring a dependency, then retry:

tako workflows retry <run-id> --env production

Retry accepts dead and cancelled runs. The run becomes pending, due now, with a fresh retry budget. Saved steps are kept, so completed steps return their saved results and the handler continues after its last checkpoint. Retrying without fixing the cause spends the new budget the same way.

Cancel work that is no longer wanted:

tako workflows cancel <run-id> --env production

Cancel accepts pending and running runs and removes their event waits. It asks for confirmation in a terminal; pass --yes in scripts. A pending run is cancelled immediately. A running handler is not interrupted: its worker loses the run, and the handler stops at its next checkpoint, such as the next step, sleep, or wait. Code between checkpoints keeps running until then, and side effects already started are not undone. The cancelled run is not reclaimed or retried unless you retry it.

With several servers and no postgres_url, each server keeps its own runs. list merges them and labels each run with its server. Run IDs are independent per server; when two servers hold the same ID, pass --server to choose one. With postgres_url, every server shares the same runs, which are listed once and changed once. See the CLI reference for every option and the JSON output.

Practical Rules

  • Keep workflow payloads and step results JSON serializable.
  • Give every step a stable name that is unique within the run. Changing a name creates a different checkpoint for existing runs; reusing one in the same execution fails the run.
  • Make side-effecting step bodies idempotent. ctx.run is durable but still at least once at the save boundary.
  • Supply id to deduplicate enqueues for the same business operation while its run history is retained.
  • Use ctx.bail for expected cancellation and ctx.fail for permanent failure.
  • To stream partial output, such as an LLM reply, to a browser that may refresh, publish chunks to a channel from a step and close the stream when the run finishes or fails; see Stream A Reply That Survives A Refresh.
  • Keep signal and .enqueue() in server-side code.
  • Use Postgres for global workflows across multiple servers. Use local: true only when once per server is intentional.

Verify

Enqueue a known payload, inspect the run/step logs, and check its application-side result. Force a retry in a test environment and confirm completed steps reuse saved results and external effects deduplicate. Test duplicate enqueue IDs, a signal or durable wait when used, and the intended shared-versus-per-server execution model.

Native network boundaries

Native channel replay and presence replication do not migrate durable workflow executions. Keep the workflow’s local or remote storage choice explicit. Draining a server pauses new workflow work and bounds cleanup of running work; inspect forced work and remaining workers before treating maintenance as complete. Resume restores persisted configuration on that server. It does not transfer a local queue, database, or volume to another host. See Native networks.

Last updated on

Was this page helpful?