Guides

Your First Workflow


A workflow is defined using language-specific decorators or macros and receives a workflow context (ctx) that provides all the durable operations. The context is how you tell Orcher "this is a step that should be journaled."

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
// Define a workflow with the #[workflow] macro
5
#[workflow(
6
name = "greet_user",
7
version = "1.0.0",
8
description = "Greet a user by name"
9
)]
10
pub async fn greet_user(
11
ctx: WorkflowContext,
12
name: String,
13
) -> Result<String> {
14
// Step 1: Format greeting (type-safe task reference, automatically journaled)
15
let greeting: String = ctx
16
.execute_task(format_greeting, name.clone())
17
.await?;
18
19
// Step 2: Log the greeting (automatically journaled)
20
ctx.execute_task(log_greeting, greeting.clone()).await?;
21
22
// Return result
23
Ok(greeting)
24
}
25
26
// Task: Format greeting
27
#[task(
28
name = "format_greeting",
29
description = "Format a greeting message"
30
)]
31
pub async fn format_greeting(_ctx: TaskContext, name: String) -> Result<String> {
32
Ok(format!("Hello, {}!", name))
33
}
34
35
// Task: Log greeting
36
#[task(
37
name = "log_greeting",
38
description = "Log the greeting message"
39
)]
40
pub async fn log_greeting(_ctx: TaskContext, message: String) -> Result<()> {
41
println!("Greeting: {}", message);
42
Ok(())
43
}

Start the workflow:

1
use orcher::prelude::*;
2
3
#[tokio::main(flavor = "current_thread")]
4
async fn main() -> Result<()> {
5
let client = Client::connect("http://localhost:50051").await?;
6
7
let handle = client
8
.start_workflow("greet_user", "Alice".to_string())
9
.await?;
10
11
let result: String = handle.result().await?;
12
println!("Result: {}", result);
13
14
Ok(())
15
}

In this example, greet_user is the workflow and format_greeting / log_greeting are tasks. The workflow orchestrates the tasks in sequence. Each execute_task call is a journaled step — if the workflow crashes after formatting the greeting but before logging it, the replay will skip the formatting step (using the journaled result) and only execute the logging step.


How Workflows Work

The Execution Model

When your workflow code calls ctx.execute_task() (or any other context method), the following happens under the hood:

  1. Journal check — The system checks whether this step has already been executed by looking up the step's sequence number in the journal. Each context call in your workflow gets a deterministic sequence number based on its position in the execution flow.

  2. First execution — If the step is not in the journal, the task is dispatched to a worker, executed, and the result is written to the journal in PostgreSQL. The workflow then receives the result and continues.

  3. Replay — If the step is already in the journal (because the workflow is being replayed after a crash), the journaled result is returned immediately without executing the task again. From your workflow code's perspective, the call looks identical — it awaits and gets back the same result.

This is the key insight: your workflow function runs from the beginning every time, but completed steps are fast-forwarded using journaled results. The function itself is the source of truth for the execution order; the journal is the source of truth for the results.

Journaling in Action

Here's what happens when a payment workflow executes, crashes, and recovers:

First ExecutionPayment Workflow
1charge_cardStripe API→ "ch_123"✓
2reserve_inventoryDB Update→ "ok"✓
3send_confirmationCRASH before execution✗
ReplayNew worker picks up
1charge_cardcached → "ch_123"↺
2reserve_inventorycached → "ok"↺
3send_confirmationExecute fresh✓

Notice that charge_card is not called a second time. On replay the customer is not charged again: the charge ran during the first execution, and its journaled result (ch_123) is returned instead of calling the API. This is how Orcher avoids repeating completed work on replay. If a task fails before its result is recorded, it will be retried — so make external calls idempotent.


Workflow Context

The WorkflowContext (called ctx by convention) is the interface between your workflow code and the Orcher runtime. Every method on the context represents a durable operation — one that is journaled and safe to replay. You should never perform side effects (API calls, database writes, file I/O) directly in workflow code. Instead, execute them through the context.

Orcher provides two ways to execute work inside a workflow: execute_task for distributed, registered tasks and execute for inline, one-off operations. Both are journaled and replay-safe, but they differ in how and where the work runs.

execute_task — Distributed Task Execution

execute_task is the primary way workflows interact with the outside world. It references a registered task — a function decorated with @task (Python), #[task] (Rust), or @Task (TypeScript) — and schedules it for distributed execution via a task queue.

When you call execute_task:

  1. The workflow emits a ScheduleTask command and suspends
  2. The task is placed on a task queue and picked up by a task worker (which may be a different process or machine)
  3. The worker executes the task function and records the result
  4. The workflow is re-dispatched, replays to the suspension point, and receives the result

This distributed model means tasks scale independently from workflows. You can run 10 workflow workers and 100 task workers, or vice versa.

execute_task also supports rich configuration: retry policies, timeouts, and heartbeat monitoring — all defined at the task level.

Type-Safe Task References

Orcher strongly encourages type-safe task references across all SDKs. Instead of passing a string task name to execute_task, you pass a typed reference to the task itself. This gives you:

  • Compile-time / import-time validation — A misspelled task name is caught by the compiler (Rust) or at import time (TypeScript/Python), not at runtime in production.
  • Input/output type inference — The SDK knows what input a task expects and what output it returns. Pass the wrong shape and your IDE or compiler tells you immediately.
  • IDE support — Autocomplete, go-to-definition, and rename refactoring all work because task references are real code symbols, not opaque strings.
  • Zero runtime overhead — In Rust, the #[task] macro generates a zero-sized const that resolves to a &'static str at compile time. In TypeScript, createTaskRefs() is a type-level cast with no runtime cost. In Python, the decorated function itself carries metadata.

Each SDK implements this differently, but the principle is the same: reference the task, not its name.

In Rust, the #[task] macro generates a type-safe const with the same name as your function. You pass this const (not a string) to execute_task, so the compiler catches typos and enforces input/output types.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
// Define a registered task
5
#[task(name = "charge_card", timeout = 60, retry = 3)]
6
pub async fn charge_card(
7
_ctx: TaskContext,
8
amount: f64,
9
card_token: String,
10
) -> Result<ChargeResult> {
11
// This runs on a task worker (potentially a different machine)
12
stripe::Charge::create(&client, amount, &card_token).await
13
}
14
15
#[workflow(name = "process_payment", version = "1.0.0")]
16
pub async fn process_payment(
17
ctx: WorkflowContext,
18
input: PaymentInput,
19
) -> Result<PaymentOutput> {
20
// Type-safe task reference — compiler catches typos
21
let charge: ChargeResult = ctx
22
.execute_task(charge_card, (input.amount, input.card_token.clone()))
23
.await?;
24
25
// If workflow crashes here, charge_card won't be re-executed on replay
26
27
let inventory: InventoryResult = ctx
28
.execute_task(reserve_inventory, input.order_id.clone())
29
.await?;
30
31
Ok(PaymentOutput {
32
charge_id: charge.charge_id,
33
reserved: inventory.reserved,
34
})
35
}

execute — Inline Closure Execution

execute runs an inline closure (an anonymous function) directly in the workflow's process and journals the result. Unlike execute_task, there is no task queue, no distributed scheduling, and no separate worker. The closure executes immediately, its result is recorded, and on replay the journaled result is returned without re-executing the closure.

Use execute when:

  • You need a one-off operation that doesn't warrant defining a reusable registered task
  • You want to make an API call, database query, or computation replay-safe without the overhead of task scheduling
  • The operation is specific to this workflow and won't be reused elsewhere

execute takes two arguments: a step name (a string used as the journal key) and an async closure that returns the result. The step name must be unique within the workflow.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[workflow(name = "order_workflow", version = "1.0.0")]
5
pub async fn order_workflow(
6
ctx: WorkflowContext,
7
user_id: u64,
8
) -> Result<OrderSummary> {
9
// Inline closure — runs directly, no task queue
10
let user: User = ctx
11
.execute("fetch_user", move || async move {
12
// This runs in the workflow's process, not a task worker
13
let response = reqwest::get(format!("https://api.example.com/users/{}", user_id)).await?;
14
Ok(response.json().await?)
15
})
16
.await?;
17
18
// Another inline operation
19
let orders: Vec<Order> = ctx
20
.execute("fetch_orders", move || async move {
21
let response = reqwest::get(format!("https://api.example.com/users/{}/orders", user_id)).await?;
22
Ok(response.json().await?)
23
})
24
.await?;
25
26
// Pure computation — also safe to journal
27
let total: f64 = ctx
28
.execute("calculate_total", {
29
let orders = orders.clone();
30
move || async move {
31
Ok(orders.iter().map(|o| o.amount).sum())
32
}
33
})
34
.await?;
35
36
Ok(OrderSummary { user, orders, total })
37
}

Choosing Between execute_task and execute

Both methods are journaled and replay-safe. The difference is where and how the work runs:

execute_taskexecute
ExecutionDistributed — runs on a task worker via a task queueInline — runs directly in the workflow's process
Task definitionRequires a registered task (@task / #[task] / @Task)No registration — pass any async closure
Type safetyFull — typed task references enforce input/output types at compile timeManual — you choose the step name string and closure return type
Retry policiesConfigurable (max attempts, backoff, timeouts)None — closure exceptions propagate directly
ScalingTask workers scale independently from workflow workersScales with the workflow worker
ReusabilityTask can be called from multiple workflowsClosure is specific to this workflow
Best forAPI calls, database writes, long-running operations, reusable workOne-off queries, quick computations, workflow-specific operations

In practice, most workflows use a mix of both. Use execute_task for operations that need retry policies, independent scaling, or reuse across workflows. Use execute for one-off operations that are specific to a single workflow.

1
#[workflow(name = "process_order", version = "1.0.0")]
2
pub async fn process_order(ctx: WorkflowContext, order_id: String) -> Result<OrderResult> {
3
// execute: one-off lookup, specific to this workflow
4
let customer: Customer = ctx
5
.execute("lookup_customer", {
6
let oid = order_id.clone();
7
move || async move { db::find_customer_by_order(&oid).await }
8
})
9
.await?;
10
11
// execute_task: reusable operation with retry policy
12
let charge: ChargeResult = ctx
13
.execute_task(charge_card, (customer.payment_method, order_id.clone()))
14
.await?;
15
16
// execute: quick computation, no need for a registered task
17
let discount: f64 = ctx
18
.execute("apply_discount", {
19
let c = customer.clone();
20
move || async move { Ok(if c.is_premium { 0.10 } else { 0.0 }) }
21
})
22
.await?;
23
24
// execute_task: external API call with retry/timeout
25
ctx.execute_task(send_confirmation_email, (customer.email, charge.charge_id))
26
.await?;
27
28
Ok(OrderResult { charge_id: charge.charge_id, discount })
29
}

Execute Child Workflows

Workflows can start and wait on other workflows. This is called workflow composition and is how you break complex processes into smaller, reusable pieces. The parent workflow blocks until the child completes, and the child's result is journaled in the parent's journal. If the parent replays, the child's result is replayed from the journal — the child is not re-executed.

Child workflows run independently — they have their own journal, their own retry behavior, and can run on different workers. If the parent crashes, the child continues running. When the parent replays and reaches the child workflow step, it waits for the already-running child to complete (or replays the result if the child already finished).

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[workflow(
5
name = "parent_workflow",
6
version = "1.0.0"
7
)]
8
pub async fn parent_workflow(
9
ctx: WorkflowContext,
10
order_id: String,
11
) -> Result<String> {
12
// Execute child workflow and wait for result
13
let payment_result: PaymentOutput = ctx
14
.execute_child_workflow("process_payment", payment_input)
15
.await?;
16
17
let shipment_result: ShipmentOutput = ctx
18
.execute_child_workflow("arrange_shipment", shipment_input)
19
.await?;
20
21
Ok(format!("Order {} completed", order_id))
22
}

Durable Timers

ctx.sleep() pauses the workflow for a specified duration without holding any resources. Unlike thread::sleep or time.sleep, a durable timer survives server restarts. When you call ctx.sleep(1 hour), the workflow releases its worker, and the server schedules a timer in the database. An hour later, the timer fires and the workflow is re-dispatched to a worker to continue.

This makes durable timers suitable for delays of any length — minutes, hours, or days. The workflow consumes zero resources while waiting.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use std::time::Duration;
4
5
#[workflow(
6
name = "scheduled_reminder",
7
version = "1.0.0"
8
)]
9
pub async fn scheduled_reminder(
10
ctx: WorkflowContext,
11
delay_seconds: u64,
12
) -> Result<()> {
13
// Durable timer (survives restarts)
14
ctx.sleep(Duration::from_secs(delay_seconds)).await?;
15
16
// Send reminder after delay
17
ctx.execute_task(send_reminder, ()).await?;
18
19
Ok(())
20
}

Wait for Events

ctx.wait_for_event() pauses the workflow until an external event arrives or a timeout expires. This is how workflows implement human-in-the-loop patterns like approval flows, payment confirmations, or webhook callbacks.

Like durable sleep, waiting for an event releases the worker. The workflow is suspended — consuming no resources — until either the event is delivered (via the send_event API) or the timeout is reached.

Events are identified by name. When an external system calls send_event("approval", payload) targeting this workflow, the payload is written to the workflow's journal and the workflow is re-dispatched to a worker. On replay, the workflow fast-forwards to the wait_for_event call and returns the journaled payload immediately.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use std::time::Duration;
4
5
#[workflow(
6
name = "approval_workflow",
7
version = "1.0.0"
8
)]
9
pub async fn approval_workflow(
10
ctx: WorkflowContext,
11
request_id: String,
12
) -> Result<String> {
13
// Wait for approval event (max 24 hours)
14
let event: Option<ApprovalEvent> = ctx
15
.wait_for_event_with_timeout("approval", Duration::from_secs(86400))
16
.await?;
17
18
match event {
19
Some(e) if e.approved => {
20
ctx.execute_task(process_approval, request_id).await?;
21
Ok("Approved".to_string())
22
}
23
_ => Ok("Rejected".to_string()),
24
}
25
}

Send Events

Workflows can send events to other workflows. This enables workflow-to-workflow communication — for example, a payment workflow notifying an order workflow that payment succeeded. Sent events are journaled — on replay, the event is not re-sent, preventing duplicate notifications.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[workflow(
5
name = "order_workflow",
6
version = "1.0.0"
7
)]
8
pub async fn order_workflow(
9
ctx: WorkflowContext,
10
order_id: String,
11
notification_workflow_id: String,
12
) -> Result<()> {
13
// Process order
14
ctx.execute_task(process_order, order_id.clone()).await?;
15
16
// Send event to another workflow when complete
17
// The target workflow can receive this via wait_for_event("order_completed")
18
ctx.send_event(
19
&notification_workflow_id,
20
"order_completed",
21
serde_json::json!({ "order_id": order_id }),
22
).await?;
23
24
Ok(())
25
}

Next Steps