Kest

Search

Search the documentation

Reliability

Durable workflows

Long processes written as ordinary code that survive crashes and restarts.

The problem

Some processes take days: charge the card, wait for the warehouse to approve, ship, wait three days, send a survey. If you keep that in a thread, a deploy or a crash loses it. If you build it from queues and status columns, the logic is scattered across handlers.

A durable workflow is that process written as one function. Kest records the result of every step, and when the process is interrupted (a crash, a deploy, a three-day sleep) it starts the function again from the top and skips the steps that already finished, using the recorded results.

Define and start one

Kest.run<AppModule> {
    import(WorkflowModule.forRoot {
        store = SqlWorkflowStore(datastore)                     // PostgreSQL or MySQL; survives restarts. The default is in memory.
 
        workflow("order") { ctx ->
            val payment = ctx.step("charge", retries = 3) { payments.charge(ctx.input["card"] as String) }   // runs once, result remembered
            ctx.waitForEvent("approved", timeout = Duration.ofDays(2)) ?: return@workflow "expired"          // parks, holds no thread
            ctx.step("ship") { shipping.create(payment) }
            ctx.sleep("survey-delay", Duration.ofDays(3))                                                    // parks for three days
            ctx.step("survey") { mail.send("survey", ctx.input["email"]) }
            "done"
        }
    })
}
 
val id = engine.start("order", mapOf("card" to "tok_1", "email" to "a@b.c"))     // returns at once with the run id
engine.signal(id, "approved")                                                    // from a controller, when the warehouse approves
engine.await(id).status                                                          // COMPLETED
engine.result(id)                                                                // "done" (throws WorkflowFailedException if it failed)

The one rule: the code between steps must be deterministic

Because the function is replayed from the top, anything outside a step runs again on every replay. So:

  • Do side effects (calling an API, writing to a database, sending mail) inside ctx.step(...). They run once; on replay the remembered result is returned.
  • Do not read the clock, random numbers or the environment outside a step: put them in one. val now = ctx.step("start") { Instant.now().toString() } gives the same value on every replay.
  • Step names must be unique within a workflow and stable: renaming a step while runs are in flight makes them redo it.
  • Step results are stored as JSON (maps, lists, strings, numbers, booleans), and you get the JSON form even on the first run, so the code behaves the same either way. Return ids and small data, not entities.

The pieces

ctx.step(name, retries, backoffMillis) { }run once and remember; on failure retry retries more times with a doubling wait, then fail the workflow
ctx.sleep(name, duration)park the run; no thread is held, so a million sleeping workflows are cheap
ctx.waitForEvent(name, timeout)park until engine.signal(runId, name, data); returns the data, or null on timeout
ctx.input, ctx.runIdthe start arguments and the run's id
engine.start(name, input, id)start a run; pass your own id to make starting idempotent (an order id)
engine.signal(id, event, data)wake a run waiting for event
engine.status(id) / runs()RUNNING, SLEEPING, WAITING, COMPLETED or FAILED, plus result or error

Crashes and several instances

A run is leased to one engine at a time (leaseMillis, 60 s). If that process dies, the lease expires and another instance picks the run up and replays it. Steps that completed are not repeated; the step that was running when the process died is repeated, so make steps idempotent (an idempotency key on the payment call).

WorkflowModule.forRoot {
    concurrency = 64        // runs executing at once in this process
    run = false             // this process only STARTS and signals workflows; a worker node executes them
}

A realistic example: onboarding

workflow("onboarding") { ctx ->
    val user = ctx.input["userId"] as String
    ctx.step("welcome-mail") { mail.send(user, "welcome") }
    ctx.sleep("day-2", Duration.ofDays(2))
    val used = ctx.step("check-usage") { usage.hasCreatedProject(user) }
    if (used != true) ctx.step("nudge") { mail.send(user, "need-help") }
    ctx.waitForEvent("upgraded", timeout = Duration.ofDays(14)) ?: ctx.step("downgrade-offer") { mail.send(user, "offer") }
}

Testing

Use the in-memory store and pass a controllable clock in the options, then move the clock forward and call engine.tick() to run what is due, without sleeping in the test.

When not to use it

For a task that takes seconds and can simply be retried, use a queue. Workflows are for processes with waiting and several steps that must not repeat.

Read more