Guides

Replay Safety Rules


To ensure correct replay behavior, workflows must be deterministic — the same inputs must always produce the same control flow. Any operation that could return a different result on replay must be wrapped in a journaled step.

Safe Operations (Deterministic)

These operations are safe inside workflow code because they produce the same result on every replay. Pure computation, conditional logic on deterministic data, and journaled SDK calls (execute_task, sleep) are all replay-safe.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[task]
5
pub async fn process_order(_ctx: TaskContext, total: f64) -> Result<String> {
6
// ...
7
}
8
9
#[task]
10
pub async fn apply_vip_discount(_ctx: TaskContext, total: f64) -> Result<()> {
11
// ...
12
}
13
14
#[workflow]
15
pub async fn safe_workflow(
16
ctx: WorkflowContext,
17
input: OrderInput,
18
) -> Result<String> {
19
// SAFE: Pure computation (same result every time)
20
let total = input.quantity as f64 * input.price;
21
22
// SAFE: Task execution (journaled — result cached on replay)
23
let result: String = ctx
24
.execute_task(process_order, total)
25
.await?;
26
27
// SAFE: Sleep (journaled — timer recorded in journal)
28
ctx.sleep(Duration::from_secs(60)).await?;
29
30
// SAFE: Conditional on deterministic data
31
if total > 1000.0 {
32
ctx.execute_task(apply_vip_discount, total).await?;
33
}
34
35
Ok(result)
36
}

Unsafe Operations (Non-Deterministic)

These operations break replay because they can return different results each time. Direct API calls, reading the current time, generating random values, and accessing environment variables must always be wrapped inside a journaled task — never called directly in workflow code.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[task]
5
pub async fn get_current_time(_ctx: TaskContext) -> Result<u64> {
6
Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())
7
}
8
9
#[task]
10
pub async fn fetch_api_data(_ctx: TaskContext, url: String) -> Result<ApiResponse> {
11
let resp = reqwest::get(&url).await?.json().await?;
12
Ok(resp)
13
}
14
15
#[workflow]
16
pub async fn example_workflow(ctx: WorkflowContext, input: OrderInput) -> Result<String> {
17
// UNSAFE: Current time differs on replay
18
// let now = SystemTime::now();
19
20
// UNSAFE: Random values differ on replay
21
// let random_id = rand::thread_rng().gen::<u32>();
22
23
// UNSAFE: Direct API call (not journaled — will re-execute on replay)
24
// let response = reqwest::get("https://api.example.com").await?;
25
26
// CORRECT: Wrap non-deterministic operations in tasks
27
let current_time: u64 = ctx.execute_task(get_current_time, ()).await?;
28
let api_data: ApiResponse = ctx.execute_task(fetch_api_data, url).await?;
29
30
// Or use ctx.execute() for inline journaled closures
31
let timestamp: u64 = ctx.execute("get_timestamp", || async {
32
Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())
33
}).await?;
34
35
Ok("result".to_string())
36
}

Rule of Thumb: Any operation that could produce different results on replay must be wrapped in ctx.execute() or ctx.execute_task().


Viewing the Journal

Since the journal is stored in standard PostgreSQL tables, you can query it directly using SQL. This is useful for debugging workflow executions, auditing step results, and understanding the timeline of events.

SQL Query

You can query the journal directly from PostgreSQL:

1
-- View all journal entries for a workflow execution
2
SELECT
3
event_id,
4
event_type,
5
timestamp,
6
payload
7
FROM workflow_execution_journal
8
WHERE
9
workflow_id = 'order-processing-abc123'
10
AND execution_id = 'exec_xyz789'
11
ORDER BY event_id ASC;
12
13
-- View only step completions
14
SELECT
15
event_id,
16
payload->>'step_name' AS step_name,
17
payload->'result' AS result,
18
timestamp
19
FROM workflow_execution_journal
20
WHERE
21
workflow_id = 'order-processing-abc123'
22
AND event_type = 'StepCompleted'
23
ORDER BY event_id;
24
25
-- View step-level idempotency cache
26
SELECT
27
step_name,
28
step_type,
29
status,
30
result,
31
execution_attempt,
32
duration_ms,
33
created_at
34
FROM execution_log
35
WHERE workflow_id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::uuid
36
ORDER BY created_at;
37
38
-- View workflow timeline with step durations
39
SELECT
40
event_id,
41
event_type,
42
timestamp,
43
timestamp - LAG(timestamp) OVER (ORDER BY event_id) AS duration
44
FROM workflow_execution_journal
45
WHERE workflow_id = 'order-processing-abc123'
46
ORDER BY event_id;

Practical Examples

Example 1: API Call with Automatic Idempotency

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
/// Task: Charge credit card via Stripe
5
#[task(retry = 3)]
6
pub async fn charge_card(
7
_ctx: TaskContext,
8
input: PaymentInput,
9
) -> Result<ChargeResult> {
10
let charge = stripe::Charge::create(
11
&stripe_client,
12
ChargeParams {
13
amount: input.amount,
14
currency: "usd",
15
source: input.card_token,
16
idempotency_key: Some(format!("order_{}", input.order_id)),
17
}
18
).await?;
19
20
Ok(ChargeResult {
21
charge_id: charge.id,
22
amount: charge.amount,
23
})
24
}
25
26
/// Workflow: Process payment
27
#[workflow]
28
pub async fn process_payment(
29
ctx: WorkflowContext,
30
input: PaymentInput,
31
) -> Result<PaymentResult> {
32
// Once its result is journaled, replay never runs this again
33
// Even if workflow crashes and replays multiple times
34
let charge: ChargeResult = ctx
35
.execute_task(charge_card, input)
36
.await?;
37
38
Ok(PaymentResult {
39
charge_id: charge.charge_id,
40
success: true,
41
})
42
}

Example 2: Multi-Step Saga with Replay

Scenario · e-commerce order processing
First execution
1 · Validate Order → journal { valid: true }
2 · Charge Payment → journal { charge_id: "ch_123" }
3 · Reserve Inventory → journal { reserved: true }
💥 Crash
Replay after crash
1 · Validate Order — cache HIT, skip
2 · Charge Payment — cache HIT, skip
3 · Reserve Inventory — cache HIT, skip
4 · Arrange Shipment — cache MISS, execute (new)
5 · Send Confirmation — cache MISS, execute (new)
Payment charged once · inventory reserved once · workflow completes successfully

Next Steps