Task Execution & First Task
Orcher provides two different APIs for executing work from workflows. Understanding the difference is crucial for writing correct workflows.
ctx.execute() - Inline Durable Execution with Automatic Journaling
Available in: Rust, TypeScript
The ctx.execute() API provides durable execution by automatically journaling the result of an inline async block or closure. This is the core primitive for building reliable workflows.
Signature (Rust):
1ctx.execute<F, T>(2 step_name: &str,3 closure: F4) -> Result<T>5where6 F: Future<Output = Result<T>>Signature (TypeScript):
1ctx.execute<TOutput>(2 stepName: string,3 closure: () => Promise<TOutput>4): Promise<TOutput>How it works:
1use orcher::prelude::*;23#[workflow(version = "1.0.0")]4async fn payment_workflow(5ctx: WorkflowContext,6order: Order,7) -> Result<Receipt> {8// Execute inline code with automatic journaling9let payment = ctx.execute("charge_card", || async {10 // This code runs inside the workflow11 // Result is automatically journaled to PostgreSQL12 stripe::charge(order.amount, order.card).await13}).await?;14// ↑ Result written to execution_log table15// On crash/restart: replays instantly from journal (no duplicate charge!)1617// Another durable step18let inventory = ctx.execute("reserve_inventory", || async {19 inventory_service::reserve(order.items).await20}).await?;2122// If workflow crashes here and restarts:23// 1. "charge_card" returns cached result from journal (no API call)24// 2. "reserve_inventory" returns cached result from journal (no API call)25// 3. Execution continues from this point2627Ok(Receipt::new(payment, inventory))28}How Automatic Journaling Works:
Benefits:
- Automatic Journaling — Every step is automatically saved to PostgreSQL
- Replay Protection — Completed steps never re-execute on workflow restart
- No Duplicate Operations — External APIs (Stripe, SendGrid) never called twice
- Fast Replay — Results cached in-memory, replays in <1ms
- Complete Audit Trail — Every step's input/output stored as JSONB
- Inline Code — Write workflow logic naturally without defining separate tasks
When to use:
- For most workflow steps (this is the primary API)
- When you want automatic durability and replay protection
- For inline API calls, database operations, or any code that should be journaled
- When you don't need to reuse the logic across multiple workflows
ctx.execute_task() - Pre-Defined Named Tasks
Available in: Rust, TypeScript (as ctx.executeTask())
The ctx.execute_task() API executes pre-defined tasks that are registered separately. Use this when you need reusable task functions.
Signature (Rust):
1ctx.execute_task<T: IntoTaskName, I, O>(2 task: T, // Type-safe task reference or &str3 input: I4) -> Result<O>Signature (TypeScript):
1ctx.executeTask<I, O>(2 taskRef: TaskReference<I, O>,3 input: I4): Promise<O>How it works:
1use orcher::prelude::*;23// 1. Define a reusable task (registered globally)4#[task(name = "send_email")]5pub async fn send_email(6_ctx: TaskContext,7input: EmailInput,8) -> Result<EmailResult> {9let client = get_email_client();10let result = client.send(11 &input.to,12 &input.subject,13 &input.body14).await?;1516Ok(EmailResult {17 message_id: result.id,18 sent: true,19})20}2122// 2. Execute the task using a type-safe reference in a workflow23#[workflow(name = "notify_user")]24pub async fn notify_user(25ctx: WorkflowContext,26email: String,27) -> Result<String> {28let input = EmailInput {29 to: email,30 subject: "Welcome".to_string(),31 body: "Thanks for signing up".to_string(),32};3334// Execute pre-defined task by reference35let result: EmailResult = ctx36 .execute_task(send_email, input) // ← Function reference37 .await?;3839Ok(result.message_id)40}Benefits:
- Reusable — Define once, use in multiple workflows
- Testable — Tasks can be unit tested independently
- Language Agnostic — Call Rust tasks from TypeScript workflows and vice versa
- Organized — Separate task definition from workflow orchestration logic
When to use:
- When you need to reuse the same logic across multiple workflows
- When you want to unit test task logic independently
- For cross-language task calls (Rust task from TypeScript workflow)
Comparison: ctx.execute() vs ctx.execute_task()
| Feature | ctx.execute() | ctx.execute_task() |
|---|---|---|
| Code Location | Inline in workflow | Separate task definition |
| Journaling | ✓ Automatic | ✓ Automatic |
| Replay Protection | ✓ Yes | ✓ Yes |
| Reusability | ✗ Single workflow only | ✓ Use across multiple workflows |
| Unit Testing | Difficult (coupled to workflow) | ✓ Easy (independent function) |
| Cross-Language | ✗ No | ✓ Yes |
| Type Safety | ✓ Yes (inline code) | ✓ Full type-safe references |
| Best For | Most workflow steps | Reusable tasks |
Which Should You Use?
Use ctx.execute() when:
- Writing most workflow steps (this is the primary API)
- You want inline code with automatic journaling
- The logic is specific to one workflow
Use ctx.execute_task() when:
- You need to reuse logic across multiple workflows
- You want to unit test task logic independently
- Calling tasks defined in a different language
Example: Combining Both APIs
1#[workflow]2async fn order_workflow(ctx: WorkflowContext, order: Order) -> Result<Receipt> {3 // Use ctx.execute() for inline workflow-specific logic4 let payment = ctx.execute("charge_card", || async {5 stripe::charge(order.amount, order.card).await6 }).await?;78 // Use ctx.execute_task() for reusable, high-throughput operations9 // (This task is reused across 5 different workflows)10 let inventory = ctx.execute_task(reserve_inventory, order.items).await?;1112 // Use ctx.execute() for workflow-specific notification logic13 let notification = ctx.execute("send_confirmation", || async {14 email_service::send_order_confirmation(&order, &payment).await15 }).await?;1617 Ok(Receipt::new(payment, inventory, notification))18}Your First Task
1use orcher::prelude::*;2use anyhow::Result;3use serde::{Deserialize, Serialize};45#[task(6name = "send_email",7description = "Send email notification",8retry = 39)]10pub async fn send_email(11_ctx: TaskContext,12input: EmailInput,13) -> Result<EmailResult> {14// Call external email API15let result = email_service::send(16 &input.to,17 &input.subject,18 &input.body19).await?;2021Ok(EmailResult {22 message_id: result.id,23 sent: true,24})25}2627// Define input/output types28#[derive(Serialize, Deserialize)]29struct EmailInput {30to: String,31subject: String,32body: String,33}3435#[derive(Serialize, Deserialize)]36struct EmailResult {37message_id: String,38sent: bool,39}Use in a workflow:
1#[workflow(name = "notify_user", version = "1.0.0")]2pub async fn notify_user(3ctx: WorkflowContext,4user_email: String,5) -> Result<String> {6let email_input = EmailInput {7 to: user_email,8 subject: "Welcome!".to_string(),9 body: "Thanks for signing up.".to_string(),10};1112let result: EmailResult = ctx13 .execute_task(send_email, email_input)14 .await?;1516Ok(result.message_id)17}