Actions

Durable task execution — register named action types and run them on external workers in Go, Python, JavaScript, Zig, or any language that speaks the wire protocol. Built-in retries, leases, labels, and stale-report fencing.

Actions are named, durable task types. You register an action once, then invoke it on demand — Flo handles dispatch, retries and lease management.

Action handlers run in user-hosted workers — long-lived processes (in Go, Python, JS, Zig, or any language that speaks the wire protocol) that pull tasks from Flo and report results. Flo owns the runs, their delivery, retries and leases; your worker owns the logic.

Every change to an action or a run (a registration, an invoke, a delivery to a worker, a complete, fail or touch, a lease running out) is an entry on the log of the shard that owns the action. Every replica applies the same entries, so every replica holds the same runs, and a report is checked against the run as the log has it.

┌──────────────┐                   ┌───────────────────────┐
│  Client      │                   │  Flo Server (Shard)   │
│              │  action invoke    │                       │
│  flo action  │ ─────────────────▸│  run: pending         │
│  invoke X    │  ◀─ run_id ───────┤                       │
└──────────────┘                   └──────────┬────────────┘
                                              │
┌──────────────┐   action await               │
│  Worker      │ ◄────────────────────────────┘
│  (Go/Py/JS)  │   task: one delivery of the run
│              │
│  handler()   │
│              │   complete(result), naming the delivery
│              │ ────────────────────────────▸ Flo
└──────────────┘

Quick Start

1. Register an action

flo action register send-email --owner platform-team --timeout 60000 --retries 3

--timeout is the action's lease in milliseconds, and --retries is the number of attempts a run gets in all, the first included. The CLI defaults are --timeout 30000 and --retries 0, which the server raises to 1: one attempt, no retry.

2. Invoke it

flo action invoke send-email '{"to":"alice@example.com","subject":"Welcome!"}'
# → Result: act-1a2b3c4d5e6f00-3

The printed id is the run's id.

3. Check status

flo action status act-1a2b3c4d5e6f00-3
# → Run: act-1a2b3c4d5e6f00-3
#   status: pending
#   created_at: 1773482400000
#   attempt: 0

Nothing happens until a worker takes the run: it stays pending until a worker awaits a task of its action, then goes running, then completed (or failed or timed_out).


Core Concepts

Action

A named task type, stored per namespace. Each action has:

FieldDefaultDescription
name—Unique within a namespace, at most 256 bytes, no NUL
owner—Who owns it, at most 256 bytes (--owner; the CLI sends cli when omitted)
timeout_ms300000The lease: how long a worker holds a run without completing, failing or touching it before the run is taken back. 5000 to 43200000 ms (12 h); 0 means 300000. See Leases and touch
max_attempts3Attempts a run gets, the first included; kept within 1 to 1000
version1One more on each re-registration

The defaults are the server's, for a registration that leaves the field out. Clients send their own: the CLI sends --timeout 30000 and --retries 0 (one attempt) unless told otherwise; the JavaScript, Python and Zig SDKs send a 30000 ms lease and 3 attempts; Go sends 0 (300000) and 3.

Registering an action again replaces its settings, so the last registration wins. Deleting an action stops its runs being handed out; they stay, and they are handed out again if the action is registered again.

Run

A single invocation of an action. Every invoke creates a run with a unique ID.

StatusDescription
pendingWaiting for a worker to take it, or for a retry delay to pass
runningA worker holds it
completedA worker completed it, with a result and optionally a named outcome
failedFailed for good: the worker failed it without retry, or its last attempt failed
timed_outIts last attempt's lease ran out without a report

Task

A task is one delivery of a run to one worker. A run delivered twice (after a failure, an expired lease or a hand-back) has two tasks, and only the latest can be reported on. A task carries:

FieldDescription
runThe run's id
namespaceThe run's namespace
deliveriesThe run's deliveries so far, this one included
term, indexWhere in the log the delivery was made
actionThe action the run invokes
created_at_msWhen the run was invoked, in Unix milliseconds
attemptThe run's failures so far, plus one
lease_msHow long the worker holds it without a touch
caller_run, caller_workflowThe workflow run that invoked it, if one did
inputThe run's input, as invoked

run, deliveries, term and index name the delivery. Every complete, fail or touch names them back, with the action and the worker's id. The CLI prints a task's id as run:deliveries:term:index:action, and its complete, fail and touch take that id.

Worker

A long-running process that takes tasks from Flo and executes them. Workers:

  • Register with Flo, declaring which actions they handle
  • Await tasks using long polling
  • Execute the handler, touching the task to keep its lease while it runs
  • Report completion or failure back to Flo

Workers can run anywhere — on the same machine, in a container, across the network. Several workers can handle the same action.


How Actions Run

Actions are executed by external worker processes that pull tasks from Flo over the wire — the model for:

  • Actions that call external APIs (payment gateways, email services)
  • Long-running tasks (report generation, media processing)
  • Logic that needs access to your infrastructure (databases, file systems)

The flow:

  1. Invoke creates a run in pending status
  2. A worker awaits (long poll) and receives a task: a delivery of the run, leased to that worker
  3. The worker runs the handler, touching the task if it runs long, and calls complete or fail
  4. Flo records the result, or makes the run ready again for another attempt

Worker Lifecycle

┌──────────┐   register    ┌──────────┐   await     ┌──────────┐
│  Init    │ ──────────▸   │  Idle    │ ──────────▸ │ Execute  │
│          │               │ (polling)│             │          │
└──────────┘               └──────┬───┘             └────┬─────┘
                                  │                      │
                            heartbeat (30s)         complete / fail
                                  │                      │
                                  ▼                      ▼
                           ┌──────────┐          ┌──────────┐
                           │ Draining │          │  Idle    │
                           └──────────┘          └──────────┘

Register

The worker announces itself and the actions it handles:

flo worker register worker-1 process-order send-email

Registration includes:

  • Worker ID — unique identifier (auto-generated if omitted)
  • Task types — list of action names this worker can execute
  • Max concurrency — how many tasks in parallel
  • Machine ID — for grouping workers on the same host
  • Metadata — a JSON object, which is also the worker's labels

Await (Long Poll)

Workers block-wait for tasks:

flo worker await process-order --worker-id worker-1 --block 30000
# → Task: act-1a2b3c4d5e6f00-3:1:2:41:process-order
#   Action: process-order
#   Attempt: 1
#   Payload: {"order_id":"A-1"}

An await names up to 64 actions, tried in order, and also takes tasks of the actions the worker registered. It waits up to --block milliseconds (at most 300000; 0 answers at once; the CLI's default is 5000) and answers with one task, or none.

An await may carry a request key (the Go, JavaScript and Python workers send one). Retrying an await with the same key gets the task the first try got, while its lease runs, so a lost answer doesn't leave a run held by nobody. A task whose await has nobody left to answer, because the client went away, is handed back at once, with no failure counted.

A draining worker's await is refused worker_draining, and an unhealthy one's worker_unhealthy until it heartbeats again.

Complete

Report success with the result:

flo worker complete act-1a2b3c4d5e6f00-3:1:2:41:process-order --worker-id worker-1 --result '{"status":"done"}'

--outcome names the outcome a workflow step follows; none is success.

Fail

Report failure:

# Retry: the run is ready again while it has attempts left
flo worker fail act-1a2b3c4d5e6f00-3:1:2:41:process-order --worker-id worker-1 --error "Temporary failure" --retry
 
# Without --retry the run fails for good
flo worker fail act-1a2b3c4d5e6f00-3:1:2:41:process-order --worker-id worker-1 --error "Invalid input"

A fail on the wire has more than the CLI shows:

FieldDefaultDescription
retrytrueRun it again while attempts are left; false fails the run now. The CLI sends false unless given --retry
abandonedfalseHand the run back untried: no failure is counted, so the next delivery has the same attempt
delay_ms0How long before the run is ready again, at most 86400000 (a day)
error""Why it failed

Touch

Keep the task's lease while the handler runs:

flo worker touch act-1a2b3c4d5e6f00-3:1:2:41:process-order --worker-id worker-1
# → Expires at: 1773482460000

See Leases and touch.

Heartbeat

Workers send periodic heartbeats (every 30 seconds in the SDKs) to report their current load and stay registered. If the server responds with a draining status, the worker should stop accepting new tasks and finish current ones.

Drain

Signal that the worker should finish current tasks but accept no new ones:

flo worker drain worker-1

Leases and touch

A delivered run is leased to its worker for the action's timeout_ms. If the worker neither completes, fails nor touches it before the lease runs out, the run is taken back: that counts as a failed attempt, and the run is ready again at once, or, on its last attempt, ends timed_out.

A touch keeps the lease. It takes no length:

  • With half the lease or less left, the lease runs a full lease from now.
  • With more than half left, nothing changes.

Either way it answers when the lease now runs out, in Unix milliseconds. So a handler that runs longer than the lease should touch at least every half lease. No delivery is held more than 12 hours from its delivery, however often it is touched; register a longer lease rather than touching a short one for hours.

A new leader takes over the leases its shard's log holds. It waits a little past a lease's deadline before ending it (30 seconds, or the lease if shorter), since a worker that touched the old leader in time may not have reached the new one yet.


Stale reports

A complete, fail or touch is accepted only for the run's live delivery, from the worker that holds it. Any other is refused with status conflict and reason stale_report, and it changes nothing. The message says why:

MessageMeaning
stale report: the lease expired and the run moved onThe lease ran out before this report
stale report: the run was delivered again sinceThe report names an earlier delivery
stale report: another worker holds this deliveryThe report comes from a worker that doesn't hold it
stale report: the run was completedThe run is already complete
stale report: the run was releasedThe delivery was already failed or handed back
stale report: the run isn't heldThe run isn't leased to anyone
stale report: the run was completed with another resultA second complete for the same delivery, with a different outcome or result

A complete or fail sent again after it applied, with the same content, answers ok. So a worker that loses the answer to a report can safely send it again. A report naming an action other than the run's is answered not_found.

The SDKs raise a stale report as its own error: IsStaleReport(err) in Go, StaleReportError in JavaScript and Python, error.StaleReport in Zig.


Labels

Actions can require specific worker capabilities using labels. When invoking an action with labels, only workers whose labels include every required one receive the run.

# A worker declares its labels when it registers
flo worker register gpu-worker-1 render-video --labels '{"gpu":true,"vram_gb":24}'
 
# Invoke with required labels
flo action invoke render-video '{"url":"..."}' --labels '{"gpu":true,"vram_gb":24}'

A worker with labels {"gpu":true, "vram_gb":24, "region":"us-east"} matches — it has all required keys with equal values. A worker with {"gpu":true, "vram_gb":16} does not match — vram_gb differs. A worker that registered no labels gets no run that requires some.

Label matching rules:

  • All keys in required must exist in worker labels
  • Values must be exactly equal (string, number, boolean or null)
  • Extra keys on the worker side are ignored
  • Nested objects and arrays never match

Invocation Options

OptionDefaultDescription
labels—Required worker labels, a JSON object; anything else is refused. A run goes to a worker whose labels include every one
namespacedefaultNamespace isolation

Invoke priority, delay and idempotency keys aren't supported yet: runs are taken in the order they were invoked, at once, and every invoke starts a new run (tracked in #181).

The input is at most 64 KiB.


Retry Behavior

A run gets the action's max_attempts attempts, the first included. An attempt is spent when its worker fails it, or when its lease runs out.

When a worker fails a run with retry (the SDK workers do, for a handler error):

  1. The failure is counted and the error recorded
  2. If attempts are left, the run is pending again after the fail's delay_ms (0 unless given), for the next worker that awaits it
  3. Otherwise the run is failed

A fail without retry makes the run failed at once. A fail with abandoned hands it back without counting a failure.

When a lease runs out, the failure is counted with the error lease expired; the run is ready again at once while attempts are left, and timed_out otherwise.

flo action status shows the attempt, the last error and the worker that holds or last held the run, for runs in any status.


Inspecting Actions

# Registered actions
flo action list
 
# An action's settings, its runs by status, and how long completed runs took
flo action info send-email
 
# Its runs
flo action runs send-email

action info shows the owner, version, lease and attempts, the runs waiting for a worker (counted up to 100,000), the runs running, completed, failed and timed out, and the mean, median, 95th percentile and longest time of completed runs, from a worker first taking the run to its completion. When the action's shard holds more than 10,000 of the namespace's runs, only the waiting count is given.


Namespace Isolation

Actions and runs are scoped to namespaces. The same action name can exist independently in different namespaces:

flo action register send-email --namespace prod
flo action register send-email --namespace staging
 
# These create separate runs in separate registries
flo action invoke send-email '{}' --namespace prod
flo action invoke send-email '{}' --namespace staging

Persistence

Action registrations and runs, with their deliveries, leases and results, are entries on the shard's log, applied the same way on every replica. A restarted node replays them, and a new leader picks up the runs and leases where the old one left them.

The worker registry is not on the log: after a restart, workers register again (the SDK workers do so by themselves when they reconnect) and resume polling.


SDK: Building Workers

The SDKs provide a high-level ActionWorker that handles registration, polling, concurrency, heartbeats, and reporting. You write handler functions.

Handler Signature

Every action handler receives an ActionContext and returns its result:

// Return []byte, an *ActionResult (a named outcome), or any value to marshal as JSON.
type ActionHandler func(actx *ActionContext) (result interface{}, err error)

ActionContext

The context passed to every handler:

GoJavaScriptPythonZig
Task id (run:deliveries:term:index:action)TaskID()taskIdtask_id—
Run idRunID()runIdrun_idrun_id
Action nameActionName()actionNameaction_nameaction_name
Input bytesInput()payload, input()payload, input()payload, input()
Attempt (failures so far, plus one)Attempt()attemptattemptattempt
Lease—leaseMstask.lease_mslease_ms
NamespaceNamespace()namespacenamespacenamespace
Calling workflow runCallerRunID()callerRunIdtask.caller_runcaller_run_id

Methods:

GoJavaScriptPythonZig
Parse the input as JSONInto(&v)json<T>()json(), into(cls)json(T)
Serialize a value to JSON bytesBytes(v)toBytes(v)to_bytes(v)toBytes(v)
Return a named outcomeResult(outcome, v)result(outcome, v)result(outcome, v)result(outcome, v)
Keep the lease; returns when it runs out, in Unix msTouch()touch()touch()touch()

Complete Examples

package main
 
import (
    "context"
    "fmt"
    "log"
    "os/signal"
    "syscall"
 
    flo "github.com/floruntime/flo-go"
)
 
type OrderRequest struct {
    OrderID string  `json:"order_id"`
    Amount  float64 `json:"amount"`
    Items   []Item  `json:"items"`
}
 
type Item struct {
    SKU      string `json:"sku"`
    Quantity int    `json:"quantity"`
}
 
func processOrder(actx *flo.ActionContext) (interface{}, error) {
    var req OrderRequest
    if err := actx.Into(&req); err != nil {
        return nil, flo.NewNonRetryableErrorf("invalid input: %v", err)
    }
 
    log.Printf("Processing order %s ($%.2f)", req.OrderID, req.Amount)
 
    for i, item := range req.Items {
        log.Printf("  Item %d/%d: %s", i+1, len(req.Items), item.SKU)
 
        // Keep the lease while the work runs long
        if _, err := actx.Touch(); err != nil {
            return nil, fmt.Errorf("lost the task: %w", err)
        }
    }
 
    return map[string]string{"order_id": req.OrderID, "status": "processed"}, nil
}
 
func sendEmail(actx *flo.ActionContext) (interface{}, error) {
    var input map[string]string
    if err := actx.Into(&input); err != nil {
        return nil, err
    }
    log.Printf("Sending email to %s", input["to"])
    return map[string]string{"status": "sent"}, nil
}
 
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()
 
    // nil registers the action with the server's defaults; pass
    // &flo.ActionRegisterOptions{...} to set its lease and attempts.
    w.MustRegisterAction("process-order", processOrder, &flo.ActionRegisterOptions{
        TimeoutMS:  flo.Uint32Ptr(60000),
        MaxRetries: flo.Uint32Ptr(3), // attempts in all
    })
    w.MustRegisterAction("send-email", sendEmail, nil)
 
    log.Println("Worker starting...")
    w.Start(ctx) // returns the context's error once it is cancelled
}

A handler that returns an error fails the task with retry; a non-retryable error fails it for good. See Error Handling and Retries.

Worker Configuration

flo.ActionWorkerOptions{
    WorkerID:      "my-worker",       // auto-generated if empty
    MachineID:     "host-01",         // defaults to hostname
    Concurrency:   10,                // max parallel tasks (default 10)
    ActionTimeout: 5 * time.Minute,   // handler time limit (default 5 min)
    BlockMS:       30000,             // long-poll wait (0 = 30000, max 300000)
    AutoTouch:     true,              // touch every sixth of the lease (default off)
}

With auto-touch on, the worker touches each task on a timer while its handler runs, and stops when the task turns stale. Without it, a handler that runs past the lease without touching is taken back and run again elsewhere.


SDK: Invoking Actions

You don't need a worker to invoke actions — any client can register, invoke and check status:

client := flo.NewClient("localhost:9000")
if err := client.Connect(); err != nil {
    log.Fatal(err)
}
defer client.Close()
 
// Register
err := client.Action.Register("process-image", flo.ActionTypeUser, &flo.ActionRegisterOptions{
    TimeoutMS:  flo.Uint32Ptr(60000),
    MaxRetries: flo.Uint32Ptr(3), // attempts in all
})
 
// Invoke
result, err := client.Action.Invoke("process-image",
    []byte(`{"url":"https://example.com/img.jpg","width":800}`),
    nil,
)
fmt.Println("Run ID:", result.RunID)
 
// Poll for status
status, err := client.Action.Status(result.RunID, nil)
fmt.Printf("Status: %v, Output: %s, Outcome: %q\n", status.Status, status.Output, status.Outcome)
 
// Settings and run counts
info, err := client.Action.Info("process-image", nil)
fmt.Println("Waiting:", info.Ready)
 
// Delete
err = client.Action.Delete("process-image", nil)

Workflows Integration

Actions are the building blocks that Workflows compose. A workflow step references an action with the @actions/ prefix:

steps:
  charge:
    run: "@actions/charge-payment"
    retry:
      max_attempts: 3
      backoff: exponential
    transitions:
      success: ship
      failure: flo.Failed

When a workflow invokes an action, it parks in waiting until a worker completes or fails the run, then resumes with the result. A worker's named outcome picks the step's transition.

If the step's action isn't registered, the step waits for it to be, for up to the server's [workflows] missing_action_wait_ms (default 600000, ten minutes; 0 doesn't wait). If it still isn't registered by then, the step ends with the outcome target_not_found.


  • Workers — Worker registration, heartbeats, drain and error handling
  • Workflows — Compose actions into multi-step orchestrations
  • Stream Processing — Continuous data pipelines (different from actions)