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."
1use orcher::prelude::*;2use anyhow::Result;34// Define a workflow with the #[workflow] macro5#[workflow(6 name = "greet_user",7 version = "1.0.0",8 description = "Greet a user by name"9)]10pub 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 = ctx16 .execute_task(format_greeting, name.clone())17 .await?;1819 // Step 2: Log the greeting (automatically journaled)20 ctx.execute_task(log_greeting, greeting.clone()).await?;2122 // Return result23 Ok(greeting)24}2526// Task: Format greeting27#[task(28 name = "format_greeting",29 description = "Format a greeting message"30)]31pub async fn format_greeting(_ctx: TaskContext, name: String) -> Result<String> {32 Ok(format!("Hello, {}!", name))33}3435// Task: Log greeting36#[task(37 name = "log_greeting",38 description = "Log the greeting message"39)]40pub async fn log_greeting(_ctx: TaskContext, message: String) -> Result<()> {41 println!("Greeting: {}", message);42 Ok(())43}Start the workflow:
1use orcher::prelude::*;23#[tokio::main(flavor = "current_thread")]4async fn main() -> Result<()> {5 let client = Client::connect("http://localhost:50051").await?;67 let handle = client8 .start_workflow("greet_user", "Alice".to_string())9 .await?;1011 let result: String = handle.result().await?;12 println!("Result: {}", result);1314 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:
-
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.
-
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.
-
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:
charge_cardStripe API→ "ch_123"✓reserve_inventoryDB Update→ "ok"✓send_confirmationCRASH before execution✗charge_cardcached → "ch_123"↺reserve_inventorycached → "ok"↺send_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:
- The workflow emits a
ScheduleTaskcommand and suspends - The task is placed on a task queue and picked up by a task worker (which may be a different process or machine)
- The worker executes the task function and records the result
- 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 strat 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.
1use orcher::prelude::*;2use anyhow::Result;34// Define a registered task5#[task(name = "charge_card", timeout = 60, retry = 3)]6pub 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).await13}1415#[workflow(name = "process_payment", version = "1.0.0")]16pub async fn process_payment(17 ctx: WorkflowContext,18 input: PaymentInput,19) -> Result<PaymentOutput> {20 // Type-safe task reference — compiler catches typos21 let charge: ChargeResult = ctx22 .execute_task(charge_card, (input.amount, input.card_token.clone()))23 .await?;2425 // If workflow crashes here, charge_card won't be re-executed on replay2627 let inventory: InventoryResult = ctx28 .execute_task(reserve_inventory, input.order_id.clone())29 .await?;3031 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.
1use orcher::prelude::*;2use anyhow::Result;34#[workflow(name = "order_workflow", version = "1.0.0")]5pub async fn order_workflow(6 ctx: WorkflowContext,7 user_id: u64,8) -> Result<OrderSummary> {9 // Inline closure — runs directly, no task queue10 let user: User = ctx11 .execute("fetch_user", move || async move {12 // This runs in the workflow's process, not a task worker13 let response = reqwest::get(format!("https://api.example.com/users/{}", user_id)).await?;14 Ok(response.json().await?)15 })16 .await?;1718 // Another inline operation19 let orders: Vec<Order> = ctx20 .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?;2526 // Pure computation — also safe to journal27 let total: f64 = ctx28 .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?;3536 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_task | execute | |
|---|---|---|
| Execution | Distributed — runs on a task worker via a task queue | Inline — runs directly in the workflow's process |
| Task definition | Requires a registered task (@task / #[task] / @Task) | No registration — pass any async closure |
| Type safety | Full — typed task references enforce input/output types at compile time | Manual — you choose the step name string and closure return type |
| Retry policies | Configurable (max attempts, backoff, timeouts) | None — closure exceptions propagate directly |
| Scaling | Task workers scale independently from workflow workers | Scales with the workflow worker |
| Reusability | Task can be called from multiple workflows | Closure is specific to this workflow |
| Best for | API calls, database writes, long-running operations, reusable work | One-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")]2pub async fn process_order(ctx: WorkflowContext, order_id: String) -> Result<OrderResult> {3 // execute: one-off lookup, specific to this workflow4 let customer: Customer = ctx5 .execute("lookup_customer", {6 let oid = order_id.clone();7 move || async move { db::find_customer_by_order(&oid).await }8 })9 .await?;1011 // execute_task: reusable operation with retry policy12 let charge: ChargeResult = ctx13 .execute_task(charge_card, (customer.payment_method, order_id.clone()))14 .await?;1516 // execute: quick computation, no need for a registered task17 let discount: f64 = ctx18 .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?;2324 // execute_task: external API call with retry/timeout25 ctx.execute_task(send_confirmation_email, (customer.email, charge.charge_id))26 .await?;2728 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).
1use orcher::prelude::*;2use anyhow::Result;34#[workflow(5 name = "parent_workflow",6 version = "1.0.0"7)]8pub async fn parent_workflow(9 ctx: WorkflowContext,10 order_id: String,11) -> Result<String> {12 // Execute child workflow and wait for result13 let payment_result: PaymentOutput = ctx14 .execute_child_workflow("process_payment", payment_input)15 .await?;1617 let shipment_result: ShipmentOutput = ctx18 .execute_child_workflow("arrange_shipment", shipment_input)19 .await?;2021 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.
1use orcher::prelude::*;2use anyhow::Result;3use std::time::Duration;45#[workflow(6 name = "scheduled_reminder",7 version = "1.0.0"8)]9pub 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?;1516 // Send reminder after delay17 ctx.execute_task(send_reminder, ()).await?;1819 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.
1use orcher::prelude::*;2use anyhow::Result;3use std::time::Duration;45#[workflow(6 name = "approval_workflow",7 version = "1.0.0"8)]9pub 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> = ctx15 .wait_for_event_with_timeout("approval", Duration::from_secs(86400))16 .await?;1718 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.
1use orcher::prelude::*;2use anyhow::Result;34#[workflow(5 name = "order_workflow",6 version = "1.0.0"7)]8pub async fn order_workflow(9 ctx: WorkflowContext,10 order_id: String,11 notification_workflow_id: String,12) -> Result<()> {13 // Process order14 ctx.execute_task(process_order, order_id.clone()).await?;1516 // Send event to another workflow when complete17 // The target workflow can receive this via wait_for_event("order_completed")18 ctx.send_event(19 ¬ification_workflow_id,20 "order_completed",21 serde_json::json!({ "order_id": order_id }),22 ).await?;2324 Ok(())25}