Pattern Detection with Correlated Events
Some event-driven scenarios require correlating multiple events that arrive over time — detecting fraud by matching a password change followed by a large transfer within 10 minutes, or identifying abandoned carts by checking if a checkout event doesn't follow an add-to-cart within 30 minutes. Orcher models this with event gates that wait for correlated events with timeouts.
How it works
A first event starts a workflow that opens a gate for the correlated second event, with a deadline. The powerful part is that one primitive — wait_for_event_with_timeout — detects two opposite things depending on which branch you treat as the signal: an event arriving inside the window, or an event failing to.
password change → wait 10 min for large_transfer. Event arrives → flag & lock. Timeout → clear.
add-to-cart → wait 30 min for checkout. Event arrives → do nothing. Timeout → send reminder.
The workflow itself is the correlation state. A fraud detector parked on its gate for ten minutes is the record that this user is being watched — there's no separate "pending patterns" table to maintain, scan, or expire.
Example: fraud and abandoned-cart detectors
1import {2 Workflow,3 Tasks,4 Task,5 WorkflowContext,6 createTaskRefs,7} from '@orcher/sdk';89@Tasks()10class FraudTasks {11 @Task()12 async flagSuspiciousActivity(input: SuspiciousActivity): Promise<void> {13 await fraudService.flag(input);14 }1516 @Task()17 async lockAccount(userId: string): Promise<void> {18 await authService.lockAccount(userId);19 }2021 @Task()22 async notifySecurityTeam(alert: SecurityAlert): Promise<void> {23 await alerting.notifySecurity(alert);24 }2526 @Task()27 async sendAbandonedCartEmail(input: AbandonedCartEmail): Promise<void> {28 await emailClient.sendAbandonedCart(input);29 }30}3132const tasks = createTaskRefs(FraudTasks);3334// Fraud detection: password change + large transfer = suspicious35@Workflow({ name: 'fraud_pattern_detector', version: '1.0.0' })36class FraudPatternDetector {37 async run(38 ctx: WorkflowContext,39 trigger: PasswordChangeEvent,40 ): Promise<FraudCheckResult> {41 // Wait up to 10 minutes for a large transfer after password change42 try {43 const event = await ctx.waitForEventWithTimeout<TransferEvent>(44 'large_transfer',45 10 * 60 * 1000, // 10 minutes46 );4748 if (event.amount > 5000) {49 // Suspicious pattern detected50 await ctx.executeTask(tasks.flagSuspiciousActivity, {51 userId: trigger.userId,52 pattern: 'password_change_then_large_transfer',53 transferAmount: event.amount,54 });55 await ctx.executeTask(tasks.lockAccount, trigger.userId);56 await ctx.executeTask(tasks.notifySecurityTeam, {57 userId: trigger.userId,58 severity: 'high',59 details: `$${event.amount.toFixed(2)} transfer within 10min of password change`,60 });61 return FraudCheckResult.flagged();62 }63 } catch {64 // Timeout — no suspicious pattern65 }6667 return FraudCheckResult.clear();68 }69}7071// Abandoned cart detection: add-to-cart without checkout within 30min72@Workflow({ name: 'abandoned_cart_detector', version: '1.0.0' })73class AbandonedCartDetector {74 async run(75 ctx: WorkflowContext,76 cartEvent: AddToCartEvent,77 ): Promise<void> {78 try {79 // Wait 30 minutes for a checkout event80 await ctx.waitForEventWithTimeout<CheckoutEvent>(81 'checkout_completed',82 30 * 60 * 1000, // 30 minutes83 );84 } catch {85 // No checkout within 30 minutes — send reminder86 await ctx.executeTask(tasks.sendAbandonedCartEmail, {87 userId: cartEvent.userId,88 items: cartEvent.items,89 });90 }91 }92}The key insight is that the workflow waits for the correlated event rather than polling for it. While waiting, it consumes zero compute. If the correlated event never arrives, the timeout fires and triggers the appropriate action (lock account, send reminder). This pattern scales to millions of concurrent correlation windows because each waiting workflow is just a row in PostgreSQL.
Presence or absence, side by side
The two detectors are mirror images. Seeing them side by side is the clearest way to internalize when to act on the event and when to act on its absence:
Design notes
- Route the second event to the right instance. The
large_transferevent has to reach this user's detector, not another's. Address it by the workflow/execution ID keyed on the user — the same per-instance delivery as event gates, covered in Events & Signals. - The window is state you don't have to store. Traditional absence-detection needs a scheduled job scanning a table for "carts with no checkout." Here the parked workflow is the pending state and the durable timer is the scan — nothing to poll, nothing to expire manually.
- Filter inside the branch, not just on delivery. The fraud detector waits for any
large_transferbut only flags whenamount > 5000. Keep the predicate in the workflow so the rule is journaled and versioned with the code, not buried in whatever emits the event. - Correlate more than two events by nesting gates. A three-step pattern (login → password change → transfer) is just another
wait_for_event_with_timeoutafter the first fires — an escalation ladder like the one in event gates, where each rung tightens the deadline.