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
| Type | Purpose | Task Source | Completion |
|---|---|---|---|
| Action | Durable task execution | action_await long-poll | Explicit complete / fail |
| Stream | Continuous event processing | group_read on stream | Auto-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:
| Field | Description |
|---|---|
| worker_id | Unique identifier (auto-generated from hostname + random hex if not provided) |
| worker_type | action (0) or stream (1) |
| max_concurrency | Maximum parallel tasks: the worker's concurrency (default 10; Zig 1) |
| processes | List of action names or stream/group pairs this worker handles |
| metadata | Optional JSON string (labels, version, environment) |
| machine_id | Optional 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:
| Limit | Reason |
|---|---|
| More than 1024 processes | out_of_range |
| A process name longer than 4096 bytes, processes too long to list together, or a machine id longer than 255 bytes | field_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 toactive) - Subsequent heartbeats return
drainingso 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
| Status | Value | Description |
|---|---|---|
active | 0 | Healthy, processing or ready for tasks |
idle | 1 | Connected, no current tasks |
draining | 2 | Finishing current work, accepting nothing new |
unhealthy | 3 | No 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:
| Method | Description |
|---|---|
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:
| Condition | Report | Notes |
|---|---|---|
| Handler returns or throws an error | Fail, retry | The run is ready again at once while attempts are left |
NonRetryableError / NewNonRetryableErrorf / error.NonRetryable (Zig) | Fail, no retry | The run fails now |
| Handler panics (Go) | Fail, no retry | The SDK recovers the panic |
| Handler runs past the worker's handler time limit | Fail, no retry | ActionTimeout (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 back | No failure is counted; the run is ready again for another worker |
| Handler runs past its lease without touching | None | The 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:
| SDK | Mechanism | Default |
|---|---|---|
| Go | Goroutines behind a semaphore channel | 10 |
| Python | asyncio tasks with semaphore | 10 |
| JavaScript | Promise concurrency with semaphore | 10 |
| Zig | One polling loop; above 1, a thread per slot, each with its own connection | 1 |
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 drainStreamContext
| Method | Description |
|---|---|
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 Result | Record Action | Effect |
|---|---|---|
| Returns normally | Auto-ack | Record is marked as consumed |
| Returns error / throws | Auto-nack | Record is redelivered to the group |
| Panics (Go) | Auto-nack | Panic is recovered, record is redelivered |
Stream Worker Configuration
| Option | Default | Description |
|---|---|---|
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 |
concurrency | 10 (Zig: 1) | Maximum parallel record handlers |
batch_size | 10 | Records to read per poll |
block_ms | 30,000 | Blocking read timeout (ms) |
message_timeout | 5 minutes | Maximum 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:
| Field | Type | Description |
|---|---|---|
worker_id | string | Unique identifier |
worker_type | action / stream | What kind of tasks this worker processes |
status | enum | active, idle, draining, unhealthy |
namespace | string | Namespace the worker belongs to |
max_concurrency | u32 | Maximum parallel tasks |
current_load | u32 | In-flight tasks, as the worker last reported in a heartbeat; 0 once unhealthy |
tasks_completed | u64 | Lifetime completed count |
tasks_failed | u64 | Lifetime failed count |
registered_at | timestamp | When the worker first registered |
last_heartbeat | timestamp | Last heartbeat received |
machine_id | string? | Host identifier for grouping |
metadata | JSON? | Arbitrary key-value data |
processes | array | Per-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:
| Field | Description |
|---|---|
name | Action name (e.g. "process-order") or stream/group (e.g. "events/processors") |
kind | action (0) or stream_consumer (1) |
run_count | Successful executions |
fail_count | Failed executions |
last_run_at | Timestamp 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
| Option | Go | Python | JS | Zig | Default |
|---|---|---|---|---|---|
| Worker ID | WorkerID | worker_id | workerId | worker_id | hostname-random |
| Machine ID | MachineID | machine_id | machineId | machine_id | hostname |
| Concurrency | Concurrency | concurrency | concurrency | concurrency | 10 (Zig: 1) |
| Action timeout | ActionTimeout | action_timeout | actionTimeoutMs | action_timeout_ms | 5 min |
| Block timeout | BlockMS | block_ms | blockMs | block_ms | 30,000 ms |
Stream Worker Options
| Option | Go | Python | JS | Zig | Default |
|---|---|---|---|---|---|
| Stream | Stream | stream | stream | stream | (required) |
| Group | Group | group | group | group | "default" |
| Consumer | Consumer | consumer | consumer | consumer | worker_id |
| Worker ID | WorkerID | worker_id | workerId | worker_id | hostname-random |
| Concurrency | Concurrency | concurrency | concurrency | concurrency | 10 (Zig: 1) |
| Batch size | BatchSize | batch_size | batchSize | batch_size | 10 |
| Block timeout | BlockMS | block_ms | blockMs | block_ms | 30,000 ms |
| Message timeout | MessageTimeout | — | — | — | 5 min |
Related
- 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