Durable Objects & Durable Workflows Guide
Veko 1.0 includes a zero-dependency Durable Objects (lib/durable/object.vk) and Durable Workflows (lib/durable/workflow.vk) library layered directly over lib/db/kv.vk's CRC-32-verified Write-Ahead Log (WAL). Every state transition, alarm, inbox message, step checkpoint, signal, and saga compensation is committed atomically in db/kv batches and survives process restarts and crashes cleanly.
1. Architecture Over lib/db/kv.vk
Crash-Safe Durable Objects & Replay-Safe Workflows over db/kv
Single-writer transactional actors, memoized step checkpoints, external signals, and LIFO saga compensations.
Both abstractions share one single embedded db/kv file (or separate stores per service) using clean, lexicographically sorted key prefixes:
| Key Prefix | Owner | Stored Payload (codec/vbin) |
|---|---|---|
do/<ns>/<id>/meta |
durable/object |
Version counter, timestamps, inbox sequence counter, active alarm deadline |
do/<ns>/<id>/kv/<field> |
durable/object |
Individual durable state fields |
do/<ns>/<id>/inbox/<seq> |
durable/object |
Monotonic FIFO mailbox messages (with attempt counters & visibility deadlines) |
do_alarm/<ns>/<id> |
durable/object |
Indexed durable alarm schedule for O(k) poll-due-alarms |
do_dlq/<ns>/<id>/<seq> |
durable/object |
Poison-message Dead-Letter Queue (list-dead-letters) |
wf/<id>/meta |
durable/workflow |
Run status (.running, .waiting, .completed, .failed, .compensated), wake deadlines, worker lease |
wf/<id>/step/<name> |
durable/workflow |
Memoized step result, retry attempt count, backoff deadline, or durable timer |
wf/<id>/event/<name> |
durable/workflow |
External signal payload delivered via send-event |
wf/<id>/comp/<seq> |
durable/workflow |
LIFO saga compensation journal entries |
wf/<id>/log/<seq> |
durable/workflow |
Chronological execution audit trail |
wf_dlq/<id> |
durable/workflow |
Dead-Letter Queue entry for exhausted workflows (requeue-dead-letter) |
2. Durable Objects (lib/durable/object.vk)
A Durable Object is a named, single-writer, versioned stateful actor ((namespace, id)). All mutations commit atomically alongside the object's version counter.
Transactional Actor Turns (mutate) with Automatic Rollback
use [d = durable, dobj = durable/object]
mut db = d/open-store 'state.vkkv'
mut acct = d/object mut db 'account' 'acct-001'
_ = dobj/put-fields mut db mut acct { owner = 'Alice', balance = 500 }
// Atomic turn: succeeds and increments acct.version in one WAL batch
bal = dobj/mutate mut db mut acct fn [st] [
cur = as-i64 (map/get/or st 'balance' [ 0 ])
if cur < 120 [ return (err 'insufficient funds') ]
mut next = st
map/set mut next 'balance' (cur - 120)
{ state = next, result = (cur - 120) }
]
If the handler returns err, zero keys are written and acct.version stays untouched.
Durable Alarms, Batch Enqueue & Transactional process-inbox with DLQ
Alarms and inbox messages are persisted in the WAL so they survive restarts. Use enqueue-batch for single-fsync multi-message writes, mutate-cas for optimistic compare-and-swap version checks across concurrent handles, and process-inbox (InboxOpts) to commit handler state updates and message deletion in one atomic WAL batch—automatically backing off failed messages and routing poison messages exceeding max_attempts into do_dlq/<ns>/<id>/<seq>:
use [d = durable, dobj = durable/object]
_ = dobj/set-alarm mut db mut acct 30s 'billing-reconcile'
_ = dobj/enqueue-batch mut db mut acct [
{ kind = 'credit', payload = 250 }
{ kind = 'debit', payload = 75 }
]
stats = dobj/process-inbox mut db mut acct (dobj/InboxOpts {
max_messages = 32
max_attempts = 3
base_backoff = 100ms
}) fn [st msg] [
bal0 = as-i64 (map/get/or st 'balance' [ 0 ])
delta = if msg.kind == 'credit' [ as-i64 msg.payload ] else [ 0 - (as-i64 msg.payload) ]
if (bal0 + delta) < 0 [ return (err 'overdraft') ]
mut next = st
map/set mut next 'balance' (bal0 + delta)
next
]
due = dobj/poll-due-alarms mut db 'account'
dlqs = dobj/list-dead-letters db acct
3. Durable Workflows (lib/durable/workflow.vk)
A Durable Workflow executes multi-step business logic with exact-once step memoization: if the process crashes halfway through a workflow and replays from the top, already-completed steps return their persisted checkpoints from db/kv without re-executing side effects.
Memoized Steps, Retries, Signals, Timers & LIFO Sagas
use [d = durable, wf = durable/workflow]
mut db = d/open-store 'workflows.vkkv'
mut run = d/workflow mut db 'ord-77' 'fulfill-order' { sku = 'VEKO-PRO', qty = 2 }
// 1. Memoized step: runs once, replays from db/kv on restart
res_id = wf/step mut db mut run 'reserve-inventory' fn [] [
'res-901'
]
// 2. Durable retry with backoff & persisted attempt count
quote = wf/step-with-retry mut db mut run 'fetch-quote' 3 100ms fn [attempt] [
if attempt < 2 [ return (err 'transient carrier timeout') ]
{ carrier = 'fastpost', cents = 1299 }
]
// 3. Suspend waiting for an external webhook signal
sig = wf/wait-event mut db mut run 'payment-confirmed'
if not sig.ready [
// Workflow is durably parked in .waiting until `wf/send-event` arrives
return .ok
]
// 4. Durable timer that survives restarts
if not (wf/sleep-until mut db mut run 'cooling-window' 5s) [
return .ok
]
_ = wf/complete mut db mut run { reservation = res_id, receipt = sig.payload.receipt }
LIFO Saga Compensations, Batch Steps, Worker Leases & Workflow DLQ
Register compensating actions as forward steps succeed. If a downstream step fails permanently, call wf/run-compensations to unwind in strict reverse (LIFO) order:
_ = wf/record-compensation mut db mut run 'release-inventory' res_id
_ = wf/record-compensation mut db mut run 'void-payment' auth_id
// On unrecoverable failure:
n = wf/run-compensations mut db mut run fn [comp_name data] [
println (str/join ['undo ' comp_name ': ' (mold data)] '')
.ok
]
For high-throughput distributed workers:
wf/step-policy& Dead-Letter Queue (wf_dlq/*): Configurewf/RetryPolicy { max_attempts, base_backoff, max_backoff, backoff_factor, dead_letter = true }so non-parked steps persist exponential backoff deadlines (status = .waiting, zero thread blocking!) and move exhausted runs towf_dlq/<id>. Inspect viawf/list-dead-letters dband replay after fixing an upstream outage viawf/requeue-dead-letter mut db 'ord-77'.wf/step-batch: Executes and checkpoints multiple deterministic sub-steps in a single WALfsynccommit (wf/step-batch mut db mut run [['validate' fn [] [...]] ['enrich' fn [] [...]]]).wf/wait-event-timeout: Parks a workflow awaiting an external webhook signal up to a durable deadline (wf/wait-event-timeout mut db mut run 'approval' 24h), returning{ ready = false, timed_out = true }if the deadline elapses first.- Distributed Worker Leases (
poll-runnable&claim-run): Multiple worker processes poll ready workflows whose sleep/retry timers or signals have matured (wf/poll-runnable db 16) and acquire time-bounded leases (wf/claim-run mut db run_id 'worker-01' 30s) before resuming execution.
Run the end-to-end crash-and-replay demonstration in examples/32_durable_objects_and_workflows.vk:
veko run examples/32_durable_objects_and_workflows.vk
veko run --native examples/32_durable_objects_and_workflows.vk