Workers

Long-running processes that execute actions and consume streams — with automatic registration, heartbeats, health monitoring, lease management, graceful drain, and per-process metrics. SDKs for Go, Python, JavaScript, and Zig.

Workers are long-running processes that connect to Flo and execute tasks. There are two kinds:

  • Action workers — take action tasks (long-polling), execute a handler, and report results. Used for durable task processing with retries and leases.
  • Stream workers — consume records from a stream via consumer groups, process each record, and auto-ack or nack. Used for continuous event processing.

Both worker types register themselves in the worker registry, send periodic heartbeats, report load metrics, and support graceful drain. The server marks a worker silent for 90 seconds unhealthy, and removes one silent for 10 minutes.

Worker Types

TypePurposeTask SourceCompletion
ActionDurable task executionaction_await long-pollExplicit complete / fail
StreamContinuous event processinggroup_read on streamAuto-ack on success, auto-nack on error

Both types share the same registration, heartbeat, drain, and health-monitoring infrastructure.

Lifecycle

Register ──▸ Heartbeat loop ──▸ Process tasks ──▸ Drain ──▸ Deregister
   │              │                   │              │           │
   │         every 30s           await/poll      sticky      cleanup
   │         reports load        execute         no new       remove
   │              │              complete/fail    tasks        record
   ▼              ▼                   ▼              ▼           ▼
 active        active            active/idle    draining    (removed)

1. Register

The worker announces itself to the server with:

FieldDescription
worker_idUnique identifier (auto-generated from hostname + random hex if not provided)
worker_typeaction (0) or stream (1)
max_concurrencyMaximum parallel tasks: the worker's concurrency (default 10; Zig 1)
processesList of action names or stream/group pairs this worker handles
metadataOptional JSON string (labels, version, environment)
machine_idOptional host identifier for grouping workers on the same machine

Re-registering the same worker ID replaces the previous registration.

A registration past a limit is refused bad_request, with ran = no, and the reason says which:

LimitReason
More than 1024 processesout_of_range
A process name longer than 4096 bytes, processes too long to list together, or a machine id longer than 255 bytesfield_too_long

The SDKs don't check these themselves; the server's refusal comes back as the error.

2. Heartbeat

Workers send a heartbeat every 30 seconds: fixed in Go and Python, set with heartbeatIntervalMs in JS and heartbeat_interval_ms in Zig. The heartbeat carries the worker's current_load (number of in-flight tasks). The server responds with the worker's current status — if the server returns draining, the SDK stops accepting new tasks.

If a worker misses heartbeats for 90 seconds, the server marks it unhealthy and gives it no work; after 10 minutes of silence it removes it. Both are set in [workers].

Halted shards

If the worker's shard is halted, its registration, group join and polls are refused with reason shard_halted. Those calls are safe to repeat, so every SDK's workers keep trying instead of failing: from 100 ms apart up to 30 seconds apart, logging a warning with the halt reason each time. They resume by themselves once the shard is repaired, and stop or drain ends the wait. A worker started during a halt comes up the same way.

3. Process

Action workers long-poll with action_await and receive a task: one delivery of a run, leased to the worker (run id, delivery, action name, input, attempt number, lease). They execute the registered handler, touching the task if it runs long, then call complete (with result bytes) or fail (with an error message and a retry flag), naming the delivery. A report for a delivery the run has moved on from is refused as stale.

Stream workers call group_read on a consumer group, receive a batch of records, process each one through the handler, and auto-ack on success or auto-nack on error.

4. Drain

Drain is a graceful shutdown mechanism. When a worker is drained:

  • The server sets its status to draining (sticky — it never reverts to active)
  • Subsequent heartbeats return draining so the SDK knows to stop polling
  • In-flight tasks continue to completion
  • No new tasks are dispatched to the worker
  • Once all active tasks finish, the worker deregisters

Drain can be initiated by the worker itself or externally via CLI/API.

5. Deregister

Removes the worker from the registry entirely. SDKs call deregister automatically on shutdown (in defer / finally blocks).

Worker Status

StatusValueDescription
active0Healthy, processing or ready for tasks
idle1Connected, no current tasks
draining2Finishing current work, accepting nothing new
unhealthy3No heartbeat for 90+ seconds; given no work

Status transitions:

                    ┌── heartbeat ──┐
                    ▼               │
  register ──▸ active ◀────────────┘
                 │
                 ├── drain ──▸ draining ──▸ deregister
                 │
                 └── 90s no heartbeat ──▸ unhealthy
                                              │
                                              └── heartbeat or register ──▸ active
 
  any status, 10 min since the last heartbeat ──▸ (removed)

Action Workers

Action workers poll for tasks, execute handlers, and report outcomes. All four SDKs provide a high-level ActionWorker that handles registration, heartbeats, concurrency control, and drain automatically.

Quick Start

package main
 
import (
    "context"
    "log"
    "os/signal"
    "syscall"
 
    flo "github.com/floruntime/flo-go"
)
 
func main() {
    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()
 
    client := flo.NewClient("localhost:9000", flo.WithNamespace("myapp"))
    if err := client.Connect(); err != nil {
        log.Fatal(err)
    }
    defer client.Close()
 
    w, err := client.NewActionWorker(flo.ActionWorkerOptions{
        Concurrency: 10,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer w.Close()
 
    w.MustRegisterAction("process-order", func(actx *flo.ActionContext) (interface{}, error) {
        var order map[string]interface{}
        if err := actx.Into(&order); err != nil {
            return nil, err
        }
        // Process the order...
        return map[string]string{"status": "done"}, nil
    }, nil)
 
    w.MustRegisterAction("send-email", func(actx *flo.ActionContext) (interface{}, error) {
        // Send the email...
        return []byte(`{"status":"sent"}`), nil
    }, nil)
 
    // Blocks until context is cancelled or drain completes
    w.Start(ctx)
}

Each SDK's register call also takes the action's options (its lease and attempts), and registers the action with the server: Go and Zig at once, JavaScript and Python when the worker starts. Registering replaces the action's settings, so the last registration wins. See Actions.

ActionContext

Every action handler receives an ActionContext with helpers for parsing input and formatting output:

MethodDescription
json() / Into()Deserialise the input payload from JSON
toBytes() / Bytes()Serialise a result value to JSON bytes
result(outcome, value) / Result()Complete with a named outcome
touch() / Touch()Keep the task's lease (see below); returns when the lease runs out, in Unix ms
taskId / task_id / TaskID()The task's id, run:deliveries:term:index:action (not in Zig)
runId / run_id / RunID()The run's id
actionName / action_name / ActionName()The action that was invoked
attempt / Attempt()The run's failures so far, plus one

The full list per SDK is on the Actions page.

Lease Extension

A task is leased to its worker for the action's timeout. A handler that runs longer must touch it, or the run is taken back and run again elsewhere. A touch takes no length: with half the lease or less left, the lease runs a full lease from now; with more left, nothing changes. So touch at least every half lease. A touch for a run that has moved on fails as a stale report.

w.MustRegisterAction("generate-report", func(actx *flo.ActionContext) (interface{}, error) {
    for i := 0; i < totalSteps; i++ {
        processStep(i)
        if _, err := actx.Touch(); err != nil {
            return nil, err // the run moved on, or the touch was lost
        }
    }
    return result, nil
}, nil)

Touching often is cheap: a touch with more than half the lease left writes nothing. Or turn on auto-touch (AutoTouch in Go, autoTouch in JavaScript, auto_touch in Python and Zig), and the worker touches each task on a timer while its handler runs: every sixth of the lease in Go, every quarter in JavaScript and Python, every third in Zig. It is off by default.

Error Handling and Retries

When a handler returns an error, the SDK fails the task with retry: true. While the run has attempts left (the action's max_attempts, the first included), it is ready again at once for another attempt; on its last attempt it fails for good. Specific errors change the behaviour:

ConditionReportNotes
Handler returns or throws an errorFail, retryThe run is ready again at once while attempts are left
NonRetryableError / NewNonRetryableErrorf / error.NonRetryable (Zig)Fail, no retryThe run fails now
Handler panics (Go)Fail, no retryThe SDK recovers the panic
Handler runs past the worker's handler time limitFail, no retryActionTimeout (Go), actionTimeoutMs (JavaScript), action_timeout (Python), 5 minutes by default; Zig has none
Worker stops while the handler runs (Go: its context is cancelled; Python: it is cancelled)Handed backNo failure is counted; the run is ready again for another worker
Handler runs past its lease without touchingNoneThe lease runs out: a failed attempt, and the run is delivered again. The late report is refused as stale

On stop, the JavaScript, Python and Zig workers let running handlers finish and send their results; Go's Stop cancels the handlers' context.

NonRetryableError

Use NonRetryableError when the task has definitively failed and retrying would be pointless (invalid input, business rule violations, permanent service rejections). The run is marked failed at once, whatever attempts it has left. In Zig, return error.NonRetryable.

import { NonRetryableError } from "@floruntime/node";
 
worker.action("validate-order", async (ctx) => {
  const { orderId, amount } = ctx.json<{ orderId?: string; amount?: number }>();
 
  if (!orderId) {
    throw new NonRetryableError("missing orderId");
  }
  if ((amount ?? 0) > 2000) {
    throw new NonRetryableError(`order amount $${amount} exceeds $2000 limit`);
  }
  return ctx.toBytes({ valid: true, orderId });
});

When a workflow step handler throws NonRetryableError, the workflow run is routed through the failure transition without waiting for retries.

Named Outcomes

By default, a returning handler produces the success outcome. To route a workflow down a specific named transition branch, use ctx.result(outcomeName, data). This is used for outcome-based routing — where the same step can branch to different next steps depending on the business decision.

import { ActionResult } from "@floruntime/node";
 
worker.action("review-order", async (ctx): Promise<ActionResult> => {
  const { orderId, amount } = ctx.json<{ orderId: string; amount: number }>();
 
  if (amount < 100) {
    // Workflow follows "approved" transition
    return ctx.result("approved", { orderId, decision: "auto-approved" });
  } else if (amount >= 500) {
    // Workflow follows "rejected" transition
    return ctx.result("rejected", { orderId, reason: "amount too high" });
  } else {
    // Workflow follows "needs_review" transition
    return ctx.result("needs_review", { orderId, note: "manual review required" });
  }
});

The workflow YAML declares the named outcome transitions:

start:
  run: "@actions/review-order"
  transitions:
    approved: fulfill          # ctx.result("approved") → go to fulfill step
    rejected: notify_rejection # ctx.result("rejected") → go to notify_rejection
    needs_review: manual_review
    failure: flo.Failed

The concurrency setting controls how many tasks a worker processes in parallel:

SDKMechanismDefault
GoGoroutines behind a semaphore channel10
Pythonasyncio tasks with semaphore10
JavaScriptPromise concurrency with semaphore10
ZigOne polling loop; above 1, a thread per slot, each with its own connection1

The worker reports its current_load (number of in-flight tasks) in each heartbeat, and the worker list shows it. Tasks aren't routed by it.

Stream Workers

Stream workers consume records from a stream via consumer groups. They automatically join the group on start, poll for batches, execute the handler for each record, and ack/nack based on the outcome.

Quick Start

client := flo.NewClient("localhost:9000", flo.WithNamespace("myapp"))
client.Connect()
defer client.Close()
 
sw, _ := client.NewStreamWorker(flo.StreamWorkerOptions{
    Stream:      "events",
    Group:       "processors",
    Concurrency: 5,
    BatchSize:   10,
}, func(sctx *flo.StreamContext) error {
    var event map[string]interface{}
    sctx.Into(&event)
    fmt.Printf("Processing event: %v\n", event)
    return nil // auto-ack
})
defer sw.Close()
 
sw.Start(ctx) // blocks until context cancelled or drain

StreamContext

MethodDescription
json() / Into()Deserialise the record payload from JSON
payload() / Payload()Raw record payload bytes
streamId / StreamID()The record's stream ID (timestamp + sequence)
headers() / Headers()Record headers (key-value map)
stream / Stream()Stream name
group / Group()Consumer group name
consumer / Consumer()Consumer name within the group
namespace / Namespace()Namespace

Ack / Nack Behaviour

Handler ResultRecord ActionEffect
Returns normallyAuto-ackRecord is marked as consumed
Returns error / throwsAuto-nackRecord is redelivered to the group
Panics (Go)Auto-nackPanic is recovered, record is redelivered

Stream Worker Configuration

OptionDefaultDescription
stream(required)Stream to consume from
group"default"Consumer group name
consumer(auto: worker_id)Consumer name within the group
worker_id(auto: hostname-hex)Unique worker identifier
concurrency10 (Zig: 1)Maximum parallel record handlers
batch_size10Records to read per poll
block_ms30,000Blocking read timeout (ms)
message_timeout5 minutesMaximum time for a handler to process one record
machine_id(auto: hostname)Host identifier for dashboard grouping
metadata—Optional JSON metadata

Worker Registry

The worker registry is a per-shard in-memory table that tracks all connected workers. It is separate from the action dispatch system — its role is observability and health monitoring, not task routing.

What the Registry Tracks

Each WorkerRecord stores:

FieldTypeDescription
worker_idstringUnique identifier
worker_typeaction / streamWhat kind of tasks this worker processes
statusenumactive, idle, draining, unhealthy
namespacestringNamespace the worker belongs to
max_concurrencyu32Maximum parallel tasks
current_loadu32In-flight tasks, as the worker last reported in a heartbeat; 0 once unhealthy
tasks_completedu64Lifetime completed count
tasks_failedu64Lifetime failed count
registered_attimestampWhen the worker first registered
last_heartbeattimestampLast heartbeat received
machine_idstring?Host identifier for grouping
metadataJSON?Arbitrary key-value data
processesarrayPer-action or per-stream tracking (see below)

Listing Workers

The worker list pages through a namespace's workers in id order, up to 1024 a page. Give it an action name to list only the workers that run that action: Action on Go's WorkerListOptions, action in the JavaScript, Python and Zig options. Left empty, it lists every worker.

Process Tracking

Each worker registers a list of processes — the specific actions or stream/group pairs it handles. The server tracks per-process metrics:

FieldDescription
nameAction name (e.g. "process-order") or stream/group (e.g. "events/processors")
kindaction (0) or stream_consumer (1)
run_countSuccessful executions
fail_countFailed executions
last_run_atTimestamp of last execution

Health Monitoring

Each shard checks its workers once a second. A worker that hasn't sent a heartbeat in heartbeat_timeout_ms (90 seconds) is marked unhealthy: its action_await is refused with reason worker_unhealthy until it sends a heartbeat or registers again, either of which makes it active. An await it parked earlier is refused the same way when a run arrives for it, or times out empty if none does. A worker silent for remove_after_ms (10 minutes since its last heartbeat, whatever its status, draining included) is removed, so workers that died without deregistering don't pile up. After that its heartbeats are answered worker not found, and it must register again to be listed, labelled or drained. A draining worker's action_await is refused with reason worker_draining.

A worker that never registered can still await tasks; it has no labels and can't be drained.

Limits

  • Maximum 10,000 workers per shard
  • Heartbeat timeout: 90 seconds; removal after 10 minutes (both in [workers])
  • Default heartbeat interval: 30 seconds (SDK-side)

Configuration Reference

Action Worker Options

OptionGoPythonJSZigDefault
Worker IDWorkerIDworker_idworkerIdworker_idhostname-random
Machine IDMachineIDmachine_idmachineIdmachine_idhostname
ConcurrencyConcurrencyconcurrencyconcurrencyconcurrency10 (Zig: 1)
Action timeoutActionTimeoutaction_timeoutactionTimeoutMsaction_timeout_ms5 min
Block timeoutBlockMSblock_msblockMsblock_ms30,000 ms

Stream Worker Options

OptionGoPythonJSZigDefault
StreamStreamstreamstreamstream(required)
GroupGroupgroupgroupgroup"default"
ConsumerConsumerconsumerconsumerconsumerworker_id
Worker IDWorkerIDworker_idworkerIdworker_idhostname-random
ConcurrencyConcurrencyconcurrencyconcurrencyconcurrency10 (Zig: 1)
Batch sizeBatchSizebatch_sizebatchSizebatch_size10
Block timeoutBlockMSblock_msblockMsblock_ms30,000 ms
Message timeoutMessageTimeout———5 min
  • Actions — Register and invoke durable task types
  • Streams — Append-only ordered log with consumer groups
  • Workflows — Multi-step orchestration using actions as steps
  • Stream Processing — Declarative stream processing jobs