Event Patterns
These patterns cover the most frequent real-world uses of events in production workflows: waiting for human decisions, receiving webhook callbacks from external services, and dynamically controlling long-running batch jobs.
Pattern 1: Human Approval
Wait for a human to approve or reject a document, order, or request. Set a timeout so the workflow doesn't block indefinitely — escalate or auto-resolve if no response arrives.
1#[task]2pub async fn submit_for_review(_ctx: TaskContext, doc_id: String) -> Result<()> { /* ... */ }34#[task]5pub async fn publish_document(_ctx: TaskContext, doc_id: String) -> Result<()> { /* ... */ }67#[task]8pub async fn notify_author(_ctx: TaskContext, args: (String, String)) -> Result<()> { /* ... */ }910#[task]11pub async fn escalate_review(_ctx: TaskContext, doc_id: String) -> Result<()> { /* ... */ }1213#[workflow]14pub async fn document_review(15 ctx: WorkflowContext,16 document_id: String,17) -> Result<String> {18 ctx.execute_task(submit_for_review, document_id.clone()).await?;19 ctx.set_state("status", &"under_review")?;2021 // Wait for reviewer decision (24 hour timeout)22 let decision: Option<ReviewDecision> = ctx23 .wait_for_event_with_timeout("review_decision", Duration::from_secs(86400))24 .await?;2526 match decision {27 Some(ReviewDecision { approved: true, .. }) => {28 ctx.execute_task(publish_document, document_id).await?;29 Ok("approved".to_string())30 }31 Some(ReviewDecision { approved: false, comments }) => {32 ctx.execute_task(notify_author, (document_id, comments)).await?;33 Ok("rejected".to_string())34 }35 None => {36 ctx.execute_task(escalate_review, document_id).await?;37 Ok("escalated".to_string())38 }39 }40}Pattern 2: Webhook Callback
Initiate an action with an external system (e.g., payment gateway), then wait for a webhook callback event. The webhook handler in your API sends the event to the waiting workflow.
1#[task]2pub async fn initiate_payment(_ctx: TaskContext, req: PaymentRequest) -> Result<String> { /* ... */ }34#[task]5pub async fn send_receipt(_ctx: TaskContext, tx_id: String) -> Result<()> { /* ... */ }67#[workflow]8pub async fn payment_processing(9 ctx: WorkflowContext,10 payment_request: PaymentRequest,11) -> Result<PaymentResult> {12 // Initiate payment with external gateway (returns transaction ID)13 let transaction_id: String = ctx14 .execute_task(initiate_payment, payment_request)15 .await?;1617 ctx.set_state("transaction_id", &transaction_id)?;18 ctx.set_state("status", &"pending")?;1920 // Wait for webhook callback from payment gateway (5 min timeout)21 let callback: PaymentCallback = ctx22 .wait_for_event_with_timeout("payment_callback", Duration::from_secs(300))23 .await?24 .ok_or_else(|| anyhow::anyhow!("Payment gateway timeout"))?;2526 match callback.status.as_str() {27 "success" => {28 ctx.set_state("status", &"completed")?;29 ctx.execute_task(send_receipt, transaction_id).await?;30 Ok(PaymentResult::Success(callback.transaction_id))31 }32 "failed" => {33 ctx.set_state("status", &"failed")?;34 Ok(PaymentResult::Failed(callback.error_message))35 }36 _ => Err(anyhow::anyhow!("Unknown payment status")),37 }38}Pattern 3: Dynamic Workflow Control
Use events to pause, resume, or cancel a running workflow from the outside. Each iteration checks for a control event with a very short timeout — if no event is pending, processing continues immediately.
1#[task]2pub async fn process_item(_ctx: TaskContext, item: Item) -> Result<()> { /* ... */ }34#[workflow]5pub async fn batch_processing(6 ctx: WorkflowContext,7 items: Vec<Item>,8) -> Result<BatchResult> {9 let mut processed = 0;1011 for item in items {12 // Non-blocking check for control events (100ms timeout)13 if let Some(control) = ctx14 .wait_for_event_with_timeout::<String>("control", Duration::from_millis(100))15 .await?16 {17 match control.as_str() {18 "pause" => {19 ctx.set_state("status", &"paused")?;20 // Block until resume event21 ctx.wait_for_event::<String>("control").await?;22 ctx.set_state("status", &"running")?;23 }24 "cancel" => {25 ctx.set_state("status", &"cancelled")?;26 return Ok(BatchResult { processed, cancelled: true });27 }28 _ => {} // Unknown control — continue29 }30 }3132 ctx.execute_task(process_item, item).await?;33 processed += 1;34 }3536 Ok(BatchResult { processed, cancelled: false })37}