Durable functions (tier 2)
A durable function is a workflow written as an async function. It can run for seconds or for months, survive restarts and deploys, and pick up exactly where it left off, because the engine records everything the function does in the run's event history and rebuilds its state by replaying that history.
A first durable function
import { workflow, defineSignal, ApplicationError } from '@fluidgrids/workflows';
import { nodes as n } from '../.fluidgrids/nodes';
export const approve = defineSignal<{ by: string }>('approve');
export const refundOrder = workflow(
'refund-order',
{ signals: [approve] },
async (ctx, order: { id: string }) => {
const decision = await Promise.race([
ctx.signalReceived(approve),
ctx.sleep('2d').then(() => undefined),
]);
if (!decision) throw new ApplicationError('Not approved in time', { type: 'PERMANENT' });
const refund = await ctx.run(n.stripe.refund, {
args: { chargeId: order.id },
retry: { maxRetries: 5, retryDelay: 1000 },
});
return { refunded: refund.id, approvedBy: decision.by };
},
);
Push it with fluidgrids push, start a run with fluidgrids runs start refund-order --input '{"id":"ch_1"}', and approve it with fluidgrids signal <runId> approve --payload '{"by":"ana"}'.
How replay works
Each time something happens in a run (it starts, an activity finishes, a timer fires, a signal arrives) the engine runs a workflow task: it runs the function from the top, answers every call the function has already made with the result recorded in the history, and stops when the function asks for something new. The new requests (run this activity, start this timer) are recorded, and the engine carries them out.
This gives you a function that behaves as if it never stopped, as long as it is deterministic: given the same history, it must make the same calls in the same order.
The rules of workflow code
-
No direct side effects. Network calls, files, databases and email go through activities:
ctx.runfor a FluidGrids node. -
No real clock or randomness. Use
ctx.now(),ctx.random()andctx.uuid(). Inside workflow codeDate.now,Math.randomandcrypto.randomUUIDare replaced with deterministic versions, andfetch,setTimeout,process,fsand dynamicimportthrow aDeterminismViolation. -
No credentials. Workflow code never sees a secret. Activities resolve connections themselves.
ctx.varsgives you the workflow's non-secret variables. -
Pure dependencies only. A bundle may use pure-JavaScript ES modules such as zod, date-fns or lodash-es. Packages that need Node built-ins or native code fail the build, with the import named.
-
Your own code runs on your workers. A user activity on a self-hosted worker is the other way to reach the outside world.
Managed durable functions run in an isolated sandbox that has no network, clock or filesystem at all, so these rules are enforced, not just recommended.
The workflow context
| Call | Does |
|---|---|
ctx.run(operation, options) | Run a FluidGrids node operation as an activity. See Activities |
ctx.activity(declaration, options), ctx.localActivity(…) | Run a user activity on a self-hosted worker. See Self-hosted workers |
ctx.sleep(duration), ctx.condition(predicate, timeout) | Durable timers and waits. See Timers |
ctx.signalReceived(signal), ctx.onSignal(signal, handler) | Receive signals. See Signals |
ctx.handleQuery(query, handler), ctx.handleUpdate(update, handler, { validate }) | Answer queries and handle updates. See Run control |
ctx.upsertSearchAttributes(values) | Set the run's search attributes. See Search attributes |
ctx.child(workflow, options), ctx.startChild(…) | Start child runs. See Child runs |
ctx.patched(id), ctx.deprecatePatch(id) | Change running code safely. See Versioning |
ctx.now(), ctx.random(), ctx.uuid(), ctx.sideEffect(fn) | Deterministic values, recorded on first use |
ctx.cancellationScope(fn), ctx.nonCancellable(fn), ctx.onCancel(fn) | Cancellation that reaches activities, timers and children |
ctx.saga() | Register compensations and run them in reverse order |
ctx.setCurrentDetails(markdown) | A live status line on the run page |
ctx.continueAsNew(input) | Start a fresh history for the same workflow. See Limits |
ctx.info | The run id, workflow key, version, build id, history length and more |
ctx.log | Logs that are written once, not again on every replay |
Errors
Throw ApplicationError(message, { type, nonRetryable }) to fail the run with one of the FluidGrids error types (TIMEOUT, TRANSIENT, DEPENDENCY, AUTHORIZATION, VALIDATION, PERMANENT, UNKNOWN). The SDK's failure classes, such as ActivityFailure, ChildRunFailure, CancelledFailure and TimeoutFailure, also fail the run when they are not caught.
Any other exception, and any determinism violation, fails only the workflow task, not the run. The engine retries the task with a backoff, and the run page shows a determinism banner, so you can fix the code with a hotfix and the run continues where it stopped. List error classes in failureErrorTypes to fail the run instead.
Triggers
A durable function starts through the Trigger Manually (API) trigger unless it declares another one:
import { triggers, workflow } from '@fluidgrids/workflows';
export const nightlyReconcile = workflow(
'nightly-reconcile',
{ trigger: { operation: triggers.schedule, id: 'nightly' } },
async (ctx) => { /* … */ },
);
The declaration is a default for the first push. After that the workflow's trigger is owned by the definition, so an operator sets or changes the schedule's rules and policy on the canvas, and the next fluidgrids pull updates the code to match.
On the canvas
A pushed durable function appears as a workflow with a trigger and one Code workflow node. In a run, the History tab lists every event, grouped per activity, timer and child, and the Waiting at panel shows the line of code the function is waiting on. You can also drop the same function into any canvas workflow with a Code workflow node.
Durable functions can also be written in Python; see Durable functions in Python.