Getting Started

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.

The Same Gate, Two Opposite Signals
Presence · fraud
The event is the alert

password change → wait 10 min for large_transfer. Event arrives → flag & lock. Timeout → clear.

Absence · abandoned cart
The timeout is the alert

add-to-cart → wait 30 min for checkout. Event arrives → do nothing. Timeout → send reminder.

Detecting "something didn't happen" is normally the hard case — here it's just the timeout branch.

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

1
import {
2
Workflow,
3
Tasks,
4
Task,
5
WorkflowContext,
6
createTaskRefs,
7
} from '@orcher/sdk';
8
9
@Tasks()
10
class FraudTasks {
11
@Task()
12
async flagSuspiciousActivity(input: SuspiciousActivity): Promise<void> {
13
await fraudService.flag(input);
14
}
15
16
@Task()
17
async lockAccount(userId: string): Promise<void> {
18
await authService.lockAccount(userId);
19
}
20
21
@Task()
22
async notifySecurityTeam(alert: SecurityAlert): Promise<void> {
23
await alerting.notifySecurity(alert);
24
}
25
26
@Task()
27
async sendAbandonedCartEmail(input: AbandonedCartEmail): Promise<void> {
28
await emailClient.sendAbandonedCart(input);
29
}
30
}
31
32
const tasks = createTaskRefs(FraudTasks);
33
34
// Fraud detection: password change + large transfer = suspicious
35
@Workflow({ name: 'fraud_pattern_detector', version: '1.0.0' })
36
class 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 change
42
try {
43
const event = await ctx.waitForEventWithTimeout<TransferEvent>(
44
'large_transfer',
45
10 * 60 * 1000, // 10 minutes
46
);
47
48
if (event.amount > 5000) {
49
// Suspicious pattern detected
50
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 pattern
65
}
66
67
return FraudCheckResult.clear();
68
}
69
}
70
71
// Abandoned cart detection: add-to-cart without checkout within 30min
72
@Workflow({ name: 'abandoned_cart_detector', version: '1.0.0' })
73
class AbandonedCartDetector {
74
async run(
75
ctx: WorkflowContext,
76
cartEvent: AddToCartEvent,
77
): Promise<void> {
78
try {
79
// Wait 30 minutes for a checkout event
80
await ctx.waitForEventWithTimeout<CheckoutEvent>(
81
'checkout_completed',
82
30 * 60 * 1000, // 30 minutes
83
);
84
} catch {
85
// No checkout within 30 minutes — send reminder
86
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:

Same Window, Inverted Verdict
1
trigger eventpassword change · add-to-cart
⏸
wait_for_event_with_timeoutthe correlation window opens
✓
event arrives in windowfraud → FLAG · cart → do nothing
⏱
window expires, no eventfraud → clear · cart → REMIND
Uppercase is the alert path — presence for fraud, absence for the cart.

Design notes

  • Route the second event to the right instance. The large_transfer event 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_transfer but only flags when amount > 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_timeout after the first fires — an escalation ladder like the one in event gates, where each rung tightens the deadline.

Next Steps