Guides

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):

1
ctx.execute<F, T>(
2
step_name: &str,
3
closure: F
4
) -> Result<T>
5
where
6
F: Future<Output = Result<T>>

Signature (TypeScript):

1
ctx.execute<TOutput>(
2
stepName: string,
3
closure: () => Promise<TOutput>
4
): Promise<TOutput>

How it works:

1
use orcher::prelude::*;
2
3
#[workflow(version = "1.0.0")]
4
async fn payment_workflow(
5
ctx: WorkflowContext,
6
order: Order,
7
) -> Result<Receipt> {
8
// Execute inline code with automatic journaling
9
let payment = ctx.execute("charge_card", || async {
10
// This code runs inside the workflow
11
// Result is automatically journaled to PostgreSQL
12
stripe::charge(order.amount, order.card).await
13
}).await?;
14
// ↑ Result written to execution_log table
15
// On crash/restart: replays instantly from journal (no duplicate charge!)
16
17
// Another durable step
18
let inventory = ctx.execute("reserve_inventory", || async {
19
inventory_service::reserve(order.items).await
20
}).await?;
21
22
// 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 point
26
27
Ok(Receipt::new(payment, inventory))
28
}

How Automatic Journaling Works:

First execution
1 · ctx.execute("charge_card", …) called
2 · check execution_log → no entry for (workflow_id, "charge_card")
3 · execute the closure → { charge_id: "ch_123", amount: 5000 }
4 · INSERT INTO execution_log … → status completed
5 · return result to the workflow
💥 Workflow crashes and restarts
1 · ctx.execute("charge_card", …) called again
2 · check execution_log → entry exists
3 · return cached result from the journal — closure not executed
4 · no duplicate Stripe charge
5 · workflow continues from the next step

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):

1
ctx.execute_task<T: IntoTaskName, I, O>(
2
task: T, // Type-safe task reference or &str
3
input: I
4
) -> Result<O>

Signature (TypeScript):

1
ctx.executeTask<I, O>(
2
taskRef: TaskReference<I, O>,
3
input: I
4
): Promise<O>

How it works:

1
use orcher::prelude::*;
2
3
// 1. Define a reusable task (registered globally)
4
#[task(name = "send_email")]
5
pub async fn send_email(
6
_ctx: TaskContext,
7
input: EmailInput,
8
) -> Result<EmailResult> {
9
let client = get_email_client();
10
let result = client.send(
11
&input.to,
12
&input.subject,
13
&input.body
14
).await?;
15
16
Ok(EmailResult {
17
message_id: result.id,
18
sent: true,
19
})
20
}
21
22
// 2. Execute the task using a type-safe reference in a workflow
23
#[workflow(name = "notify_user")]
24
pub async fn notify_user(
25
ctx: WorkflowContext,
26
email: String,
27
) -> Result<String> {
28
let input = EmailInput {
29
to: email,
30
subject: "Welcome".to_string(),
31
body: "Thanks for signing up".to_string(),
32
};
33
34
// Execute pre-defined task by reference
35
let result: EmailResult = ctx
36
.execute_task(send_email, input) // ← Function reference
37
.await?;
38
39
Ok(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()

Featurectx.execute()ctx.execute_task()
Code LocationInline in workflowSeparate task definition
Journaling✓ Automatic✓ Automatic
Replay Protection✓ Yes✓ Yes
Reusability✗ Single workflow only✓ Use across multiple workflows
Unit TestingDifficult (coupled to workflow)✓ Easy (independent function)
Cross-Language✗ No✓ Yes
Type Safety✓ Yes (inline code)✓ Full type-safe references
Best ForMost workflow stepsReusable 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]
2
async fn order_workflow(ctx: WorkflowContext, order: Order) -> Result<Receipt> {
3
// Use ctx.execute() for inline workflow-specific logic
4
let payment = ctx.execute("charge_card", || async {
5
stripe::charge(order.amount, order.card).await
6
}).await?;
7
8
// Use ctx.execute_task() for reusable, high-throughput operations
9
// (This task is reused across 5 different workflows)
10
let inventory = ctx.execute_task(reserve_inventory, order.items).await?;
11
12
// Use ctx.execute() for workflow-specific notification logic
13
let notification = ctx.execute("send_confirmation", || async {
14
email_service::send_order_confirmation(&order, &payment).await
15
}).await?;
16
17
Ok(Receipt::new(payment, inventory, notification))
18
}

Your First Task

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use serde::{Deserialize, Serialize};
4
5
#[task(
6
name = "send_email",
7
description = "Send email notification",
8
retry = 3
9
)]
10
pub async fn send_email(
11
_ctx: TaskContext,
12
input: EmailInput,
13
) -> Result<EmailResult> {
14
// Call external email API
15
let result = email_service::send(
16
&input.to,
17
&input.subject,
18
&input.body
19
).await?;
20
21
Ok(EmailResult {
22
message_id: result.id,
23
sent: true,
24
})
25
}
26
27
// Define input/output types
28
#[derive(Serialize, Deserialize)]
29
struct EmailInput {
30
to: String,
31
subject: String,
32
body: String,
33
}
34
35
#[derive(Serialize, Deserialize)]
36
struct EmailResult {
37
message_id: String,
38
sent: bool,
39
}

Use in a workflow:

1
#[workflow(name = "notify_user", version = "1.0.0")]
2
pub async fn notify_user(
3
ctx: WorkflowContext,
4
user_email: String,
5
) -> Result<String> {
6
let email_input = EmailInput {
7
to: user_email,
8
subject: "Welcome!".to_string(),
9
body: "Thanks for signing up.".to_string(),
10
};
11
12
let result: EmailResult = ctx
13
.execute_task(send_email, email_input)
14
.await?;
15
16
Ok(result.message_id)
17
}

Next Steps