Local Development

Workflow Development


Learn how to develop workflows with Orcher's SDK. Workflows are the core abstraction in Orcher - they define the orchestration logic that coordinates tasks, manages state, and handles failures automatically.

Choose Your SDK

Prerequisites: • Rust 1.70 or later • Orcher SDK: orcher = "2.0" • Local Orcher server running


What is a Workflow?

A workflow is a durable function that orchestrates multiple steps (tasks) with automatic journaling. If a workflow crashes, it resumes exactly where it left off without re-executing completed steps.

Key characteristics:

• Durable - Survives crashes and restarts • Deterministic - Same inputs produce same outputs • Journaled - Every step is automatically recorded • Typed - Full compile-time type safety • Composable - Can call other workflows as children

1
use orcher::prelude::*;
2
3
#[workflow(
4
name = "payment_workflow",
5
version = "1.0.0",
6
description = "Process payment with durable execution"
7
)]
8
async fn payment_workflow(
9
ctx: WorkflowContext,
10
input: PaymentInput,
11
) -> orcher::Result<PaymentOutput> {
12
// Step 1: Charge card (automatically journaled)
13
let charge: ChargeResult = ctx
14
.execute_task("charge_card", (input.amount, input.card_token.clone()))
15
.await?;
16
17
// Step 2: Reserve inventory (automatically journaled)
18
let inventory: InventoryResult = ctx
19
.execute_task("reserve_inventory", input.order_id.clone())
20
.await?;
21
22
// Step 3: Send confirmation (automatically journaled)
23
let notification: NotificationResult = ctx
24
.execute_task(
25
"send_confirmation_email",
26
(input.customer_email.clone(), charge.charge_id.clone()),
27
)
28
.await?;
29
30
Ok(PaymentOutput::new(
31
input.order_id,
32
charge.charge_id,
33
inventory.reserved,
34
notification.sent,
35
"completed".to_string(),
36
))
37
}

Creating Your First Workflow

1. Define the Workflow

Create a workflow using the #[workflow] attribute macro:

1
use orcher::prelude::*;
2
use serde::{Deserialize, Serialize};
3
4
#[derive(Debug, Serialize, Deserialize)]
5
pub struct GreetingInput {
6
pub name: String,
7
}
8
9
#[derive(Debug, Serialize, Deserialize)]
10
pub struct GreetingOutput {
11
pub message: String,
12
}
13
14
#[workflow(
15
name = "greet_workflow",
16
version = "1.0.0",
17
description = "Simple greeting workflow"
18
)]
19
async fn greet_workflow(
20
ctx: WorkflowContext,
21
input: GreetingInput,
22
) -> orcher::Result<GreetingOutput> {
23
let message = format!("Hello, {}!", input.name);
24
25
Ok(GreetingOutput { message })
26
}

Workflow Attributes:

• name - Unique workflow identifier (defaults to function name) • version - Semantic version for tracking changes • description - Human-readable description for docs • namespace - Optional namespace for organization • timeout - Maximum execution time (e.g., timeout = "1h")

2. Register the Workflow

Register your workflow with a worker:

1
use orcher::prelude::*;
2
3
#[tokio::main]
4
async fn main() -> orcher::Result<()> {
5
// Create worker with automatic handler registration
6
let worker = WorkerBuilder::new()
7
.task_queue("my-task-queue")
8
.server_url("http://localhost:50051")
9
.build()
10
.await?;
11
12
// Workflows and tasks are automatically registered via #[workflow] and #[task] macros
13
14
// Start processing
15
worker.run().await
16
}

3. Execute the Workflow

Execute workflows using the client API:

1
use orcher::prelude::*;
2
3
let client = Client::connect("http://localhost:50051").await?;
4
5
let options = StartWorkflowOptions {
6
task_queue: "my-task-queue".to_string(),
7
..Default::default()
8
};
9
10
let handle = client
11
.start_workflow_with_options("greet_workflow", input, options)
12
.await?;
13
14
// Wait for result
15
let output: GreetingOutput = handle.result().await?;
16
println!("Result: {}", output.message); // "Hello, Alice!"

Workflow Context API

The WorkflowContext provides methods for durable operations. All operations through the context are automatically journaled.

Execute Tasks

Orcher provides two ways to execute durable steps that are automatically journaled and replay-protected:

Method 1: ctx.execute() - Inline Closures

Use for one-off operations specific to a single workflow:

1
#[workflow]
2
async fn order_workflow(ctx: WorkflowContext, order: Order) -> orcher::Result<Receipt> {
3
// Inline closure - code lives in the workflow
4
let payment = ctx
5
.execute("charge_card", || async move {
6
// One-off logic here
7
let client = StripeClient::new();
8
client.charge(order.amount, order.card_token.clone()).await
9
})
10
.await?;
11
12
// Another inline operation
13
let inventory = ctx
14
.execute("reserve_inventory", || async move {
15
let db = Database::connect().await?;
16
db.reserve_items(order.items.clone()).await
17
})
18
.await?;
19
20
Ok(Receipt { payment, inventory })
21
}

Advantages: • Quick to write - no separate task definition needed • Good for workflow-specific logic • Keeps related code together • Perfect for prototyping

When to use: • One-off operations not reused elsewhere • Workflow-specific business logic • Simple external API calls • Rapid prototyping

Method 2: ctx.execute_task() - Registered Tasks

Use for reusable operations shared across workflows:

1
// Define task once (in tasks/ module)
2
#[task(
3
name = "charge_card",
4
description = "Charge credit card via Stripe",
5
retry = 3
6
)]
7
async fn charge_card(ctx: TaskContext, input: (f64, String)) -> Result<ChargeResult> {
8
let (amount, card_token) = input;
9
let client = StripeClient::new();
10
client.charge(amount, card_token).await
11
}
12
13
// Use in multiple workflows
14
#[workflow]
15
async fn order_workflow(ctx: WorkflowContext, order: Order) -> orcher::Result<Receipt> {
16
// Call registered task by name
17
let payment = ctx
18
.execute_task("charge_card", (order.amount, order.card_token.clone()))
19
.await?;
20
21
// Another registered task
22
let inventory = ctx
23
.execute_task("reserve_inventory", order.items.clone())
24
.await?;
25
26
Ok(Receipt { payment, inventory })
27
}
28
29
#[workflow]
30
async fn subscription_workflow(ctx: WorkflowContext, sub: Subscription) -> orcher::Result<()> {
31
// Same task, different workflow!
32
let payment = ctx
33
.execute_task("charge_card", (sub.amount, sub.card_token.clone()))
34
.await?;
35
36
Ok(())
37
}

Advantages: • Reusable across multiple workflows • Centralized retry and timeout configuration • Easier to test in isolation • Better separation of concerns • Can be versioned independently

When to use: • Shared operations across workflows • Complex logic that needs testing • Operations with specific retry policies • Third-party integrations • Team-shared functionality

Comparison Example

1
// Inline - repeated code
2
#[workflow]
3
async fn workflow_a(ctx: WorkflowContext, input: Input) -> orcher::Result<Output> {
4
let email = ctx.execute("send_email", || async move {
5
EmailClient::new().send(input.to, input.subject, input.body).await
6
}).await?;
7
Ok(Output { email })
8
}
9
10
#[workflow]
11
async fn workflow_b(ctx: WorkflowContext, input: Input) -> orcher::Result<Output> {
12
// Same code duplicated!
13
let email = ctx.execute("send_email", || async move {
14
EmailClient::new().send(input.to, input.subject, input.body).await
15
}).await?;
16
Ok(Output { email })
17
}
18
19
// Registered task - reused
20
#[task(name = "send_email", retry = 3)]
21
async fn send_email(ctx: TaskContext, input: EmailRequest) -> Result<EmailResult> {
22
EmailClient::new().send(input.to, input.subject, input.body).await
23
}
24
25
#[workflow]
26
async fn workflow_a(ctx: WorkflowContext, input: Input) -> orcher::Result<Output> {
27
let email = ctx.execute_task("send_email", input.email_request).await?;
28
Ok(Output { email })
29
}
30
31
#[workflow]
32
async fn workflow_b(ctx: WorkflowContext, input: Input) -> orcher::Result<Output> {
33
let email = ctx.execute_task("send_email", input.email_request).await?;
34
Ok(Output { email })
35
}

Mixing Both Approaches

You can freely mix both approaches in the same workflow:

1
#[workflow]
2
async fn hybrid_workflow(ctx: WorkflowContext, order: Order) -> orcher::Result<Receipt> {
3
// Use registered task for common operations
4
let payment = ctx
5
.execute_task("charge_card", (order.amount, order.card_token))
6
.await?;
7
8
// Use inline for one-off logic
9
let fraud_check = ctx
10
.execute("check_fraud_score", || async move {
11
// Custom logic specific to this workflow
12
let score = fraud_service::analyze(order.clone()).await?;
13
if score > 0.8 {
14
return Err(anyhow::anyhow!("High fraud risk"));
15
}
16
Ok(score)
17
})
18
.await?;
19
20
// Use registered task again
21
let inventory = ctx
22
.execute_task("reserve_inventory", order.items)
23
.await?;
24
25
Ok(Receipt { payment, fraud_check, inventory })
26
}

Timers and Delays

Add durable delays to your workflows:

1
use std::time::Duration;
2
3
#[workflow]
4
async fn reminder_workflow(ctx: WorkflowContext, input: ReminderInput) -> orcher::Result<()> {
5
// Wait 1 hour (survives crashes!)
6
ctx.sleep(Duration::from_secs(3600)).await?;
7
8
// Send reminder
9
ctx.execute_task("send_reminder", (input.email, input.message)).await?;
10
11
Ok(())
12
}

Key points:

• Timers are durable - they survive worker restarts • The workflow resumes exactly when the timer expires • Multiple timers can run in parallel

Event Gates

Wait for external events (human-in-the-loop, external system notifications):

1
#[workflow]
2
async fn approval_workflow(
3
ctx: WorkflowContext,
4
request: ApprovalRequest,
5
) -> orcher::Result<ApprovalResult> {
6
// Request approval
7
ctx.execute_task("notify_manager", request.manager_email.clone()).await?;
8
9
// Wait for the approval event with a 24h deadline.
10
// Returns Ok(None) if no event arrives before the timeout.
11
let approval = ctx
12
.wait_for_event_with_timeout::<Approval>("manager_approval", Duration::from_secs(86400))
13
.await?;
14
15
// Process approval if it arrived before the deadline
16
match approval {
17
Some(approval) if approval.approved => {
18
ctx.execute_task("process_request", request.clone()).await?;
19
Ok(ApprovalResult { approved: true })
20
}
21
_ => Ok(ApprovalResult { approved: false }),
22
}
23
}

Sending events from the client:

1
// From another service or UI — events are delivered through a workflow handle
2
let handle = client.get_workflow_handle(workflow_id).await?;
3
handle.send_event("manager_approval", Approval {
4
approved: true,
5
comment: "Looks good!".to_string(),
6
}).await?;

Child Workflows

Compose workflows by calling other workflows:

1
#[workflow]
2
async fn parent_workflow(
3
ctx: WorkflowContext,
4
order: Order,
5
) -> orcher::Result<OrderResult> {
6
// Execute child workflows in parallel
7
let (payment, inventory, shipping) = tokio::join!(
8
ctx.execute_child_workflow("payment_workflow", order.payment_info.clone()),
9
ctx.execute_child_workflow("inventory_workflow", order.items.clone()),
10
ctx.execute_child_workflow("shipping_workflow", order.address.clone()),
11
);
12
13
Ok(OrderResult {
14
payment: payment?,
15
inventory: inventory?,
16
shipping: shipping?,
17
})
18
}

Benefits:

• Isolate concerns (each workflow handles one domain) • Reuse workflows across different parents • Parallel execution for better performance • Independent failure handling


Task Execution Patterns

Registered Tasks

Create reusable tasks that can be shared across workflows:

Define the task:

1
#[task(
2
name = "send_email",
3
description = "Send email via email service",
4
retry = 3
5
)]
6
async fn send_email(ctx: TaskContext, input: EmailRequest) -> Result<EmailResult> {
7
let client = EmailClient::new();
8
9
client.send(
10
&input.to,
11
&input.subject,
12
&input.body,
13
).await?;
14
15
Ok(EmailResult {
16
message_id: generate_id(),
17
sent_at: Utc::now(),
18
})
19
}

Tasks are automatically registered via the #[task] macro using inventory.

Use in workflows:

1
#[workflow]
2
async fn notification_workflow(
3
ctx: WorkflowContext,
4
user: User,
5
) -> orcher::Result<()> {
6
ctx.execute_task("send_email", EmailRequest {
7
to: user.email,
8
subject: "Welcome!".to_string(),
9
body: "Welcome to our platform!".to_string(),
10
}).await?;
11
12
Ok(())
13
}

Inline Closures

For one-off operations, use inline closures:

1
#[workflow]
2
async fn data_processing_workflow(
3
ctx: WorkflowContext,
4
data_id: String,
5
) -> orcher::Result<ProcessedData> {
6
// Inline closure for one-off operation
7
let raw_data = ctx
8
.execute("fetch_data", || async move {
9
let url = format!("https://api.example.com/data/{}", data_id);
10
reqwest::get(&url).await?.json().await
11
})
12
.await?;
13
14
// Another inline operation
15
let processed = ctx
16
.execute("transform_data", || async move {
17
transform_logic(&raw_data).await
18
})
19
.await?;
20
21
Ok(processed)
22
}

Use ctx.execute() (inline closures) when:

• The logic is specific to this workflow • You don't need to reuse it elsewhere • It's a simple operation (< 10 lines) • Quick one-off external API calls

Use ctx.execute_task() (registered tasks) when:

• The logic is shared across workflows • You need centralized retry configuration • The operation is complex • You want better testability and separation of concerns


Error Handling

Automatic Retries

Configure retry behavior for tasks:

1
#[task(
2
name = "unreliable_api_call",
3
description = "Call unreliable external API",
4
retry = 5
5
)]
6
async fn unreliable_api_call(ctx: TaskContext, input: Request) -> Result<Response> {
7
// This will retry up to 5 times
8
external_api::call(input).await
9
}

Retry configuration:

The retry = N shorthand caps the number of attempts. For full control, attach a RetryPolicy with max_attempts, initial_interval, max_interval, and backoff_coefficient. There is no separate strategy enum — the delay grows exponentially per backoff_coefficient (use 1.0 for a fixed delay).

Compensation (Saga Pattern)

Handle failures by undoing previous steps:

1
#[workflow]
2
async fn booking_workflow(
3
ctx: WorkflowContext,
4
booking: BookingRequest,
5
) -> orcher::Result<BookingResult> {
6
// Step 1: Reserve hotel
7
let hotel = ctx
8
.execute_task("reserve_hotel", booking.hotel_id.clone())
9
.await?;
10
11
// Step 2: Reserve flight
12
let flight_result = ctx
13
.execute_task("reserve_flight", booking.flight_id.clone())
14
.await;
15
16
// If flight fails, compensate by canceling hotel
17
if let Err(e) = flight_result {
18
ctx.execute_task("cancel_hotel", hotel.reservation_id.clone())
19
.await?;
20
21
return Err(e);
22
}
23
24
let flight = flight_result?;
25
26
Ok(BookingResult { hotel, flight })
27
}

State Management

Workflow State

Persist state across workflow executions:

1
#[derive(Serialize, Deserialize, Default)]
2
struct BatchState {
3
processed: usize,
4
total: usize,
5
failed: Vec<String>,
6
}
7
8
#[workflow]
9
async fn batch_processing_workflow(
10
ctx: WorkflowContext,
11
items: Vec<Item>,
12
) -> orcher::Result<BatchResult> {
13
let mut state = BatchState::default();
14
state.total = items.len();
15
16
for item in items {
17
match ctx.execute_task("process_item", item.clone()).await {
18
Ok(_) => state.processed += 1,
19
Err(_) => state.failed.push(item.id),
20
}
21
22
// State is automatically persisted by the context
23
}
24
25
Ok(BatchResult {
26
processed: state.processed,
27
failed: state.failed,
28
})
29
}

Queries

Query workflow state without side effects:

In the workflow:

1
#[workflow]
2
async fn long_running_workflow(
3
ctx: WorkflowContext,
4
input: Input,
5
) -> orcher::Result<Output> {
6
// Workflow logic with internal state tracking
7
let mut completed = 0;
8
let total = input.items.len();
9
10
for item in input.items {
11
ctx.execute_task("process_item", item).await?;
12
completed += 1;
13
}
14
15
Ok(Output { completed, total })
16
}

From the client:

1
let client = Client::connect("http://localhost:50051").await?;
2
3
// Get workflow status
4
let handle = client.get_workflow_handle(workflow_id).await?;
5
let status = handle.describe().await?;
6
7
println!("Workflow status: {:?}", status);

Best Practices

1. Keep Workflows Deterministic

Don't:

1
// Non-deterministic - uses system time directly
2
let timestamp = SystemTime::now();
3
4
// Non-deterministic - generates random values
5
let random_id = uuid::Uuid::new_v4();
6
7
// Non-deterministic - depends on external state
8
let user = database.get_user(id).await?;

Do:

1
// Use workflow context for deterministic time
2
let timestamp = ctx.time().now();
3
4
// Use workflow context for deterministic randomness
5
let random_id = ctx.rand().uuid();
6
7
// Wrap external calls in ctx.execute() or ctx.execute_task()
8
let user = ctx.execute("get_user", || async {
9
database.get_user(id).await
10
}).await?;

2. Design for Idempotency

Ensure tasks can be safely retried:

1
#[task]
2
async fn process_payment(ctx: TaskContext, payment: PaymentRequest) -> Result<PaymentResult> {
3
// Use idempotency key
4
let idempotency_key = format!("payment_{}", payment.order_id);
5
6
stripe::charge_with_idempotency_key(
7
payment.amount,
8
payment.card,
9
&idempotency_key,
10
).await
11
}

3. Use Descriptive Step Names

1
// Bad
2
ctx.execute("step1", || async { ... }).await?;
3
ctx.execute("step2", || async { ... }).await?;
4
5
// Good
6
ctx.execute("charge_customer_card", || async { ... }).await?;
7
ctx.execute("reserve_inventory_items", || async { ... }).await?;

4. Handle Failures Gracefully

1
#[workflow]
2
async fn resilient_workflow(ctx: WorkflowContext, input: Input) -> orcher::Result<Output> {
3
// Try primary service
4
let result = ctx.execute("primary_service", || async {
5
primary::process(input.clone()).await
6
}).await;
7
8
// Fallback to secondary service
9
let result = match result {
10
Ok(r) => r,
11
Err(_) => {
12
ctx.execute("secondary_service", || async {
13
secondary::process(input.clone()).await
14
}).await?
15
}
16
};
17
18
Ok(Output::from(result))
19
}

5. Version Your Workflows

1
// Version 1.0.0
2
#[workflow(version = "1.0.0")]
3
async fn order_workflow_v1(ctx: WorkflowContext, order: Order) -> Result<Receipt> {
4
// Original implementation
5
}
6
7
// Version 2.0.0 - Breaking changes
8
#[workflow(version = "2.0.0")]
9
async fn order_workflow_v2(ctx: WorkflowContext, order: OrderV2) -> Result<ReceiptV2> {
10
// New implementation with breaking changes
11
}

Examples

The quickstart repository has a complete, runnable workflow in Python, TypeScript and Rust.


Next Steps


Learn More

• Workflow Patterns - Advanced workflow patterns and best practices • API Reference - Complete workflow API documentation • Quickstart Repository - Runnable code samples