Sub topic 7
How a rule is evaluated: windows, aggregation and batch versus real time
This chapter assumes you know what a scenario and its parameters are, and that you can read basic Python. It covers how a monitoring engine runs a rule against transaction data and decides when to create an alert.
The evaluation steps
A scenario is evaluated in the same order every time:
- Select the transactions the rule cares about, for example cash deposits between the
floorandceilingparameters. - Group them by an entity, usually the customer or account.
- Aggregate over a lookback window: count, sum, average, or distinct counterparties.
- Compare the result with a threshold such as
min_count. - Emit an alert record if the condition holds.
Lookback windows
A lookback window defines how far back the rule looks from a given moment. A 7-day window means a deposit on 2 March and one on 10 March never count together.
There are two common window styles:
- Rolling (sliding) window. The window moves with each transaction. The structuring function from the spine uses this style: it advances a
startindex until every transaction left in the window is withinlookback_daysof the current one. - Fixed (calendar) window. The rule counts per calendar day, week, or month. It is simpler and cheaper to compute, but it can miss activity that straddles a boundary. Three deposits on Sunday and Monday fall into two different weeks and may never reach the count.
Rolling windows catch more of this boundary behavior. Fixed windows are easier to explain to auditors and to reproduce.
Aggregation
Aggregation turns many transactions into one number that can be compared with a threshold. Common choices are count, total amount, maximum, and number of distinct counterparties. The grouping key matters as much as the function. Grouping by account misses a customer who splits deposits across three accounts. Grouping by customer, or by a household or related-party link, catches it. Choosing the key is a design decision, and the data you have (see the data inputs chapter) limits it.
Batch evaluation
In batch mode, the engine runs on a schedule, usually nightly. It loads the day's transactions plus enough history to fill the window, runs each scenario, and writes alerts. The structuring_alerts function in the spine is batch-shaped: it receives a full list, sorts it, and returns all alerts.
Batch is simple to build and test, and it makes full re-runs possible. A re-run reproduces the same alerts on the same data, which is useful when you test a new threshold. The cost is delay. An alert appears hours after the transaction.
Near-real-time evaluation
In near-real-time mode, the engine evaluates each transaction as it arrives. It keeps state per customer, such as the recent transactions inside the window, and updates it incrementally.
from collections import defaultdict, deque
from datetime import datetime, timedelta
class StreamingStructuring:
"""Evaluate the structuring rule one transaction at a time."""
def __init__(self, params):
self.params = params
self.window = timedelta(days=params["lookback_days"])
self.recent = defaultdict(deque) # customer_id -> deque of transactions
self.alerted = set()
def on_transaction(self, t):
p = self.params
if t["type"] != "cash_deposit" or not (p["floor"] <= t["amount"] < p["ceiling"]):
return None
queue = self.recent[t["customer_id"]]
queue.append(t)
while t["timestamp"] - queue[0]["timestamp"] > self.window:
queue.popleft()
if len(queue) >= p["min_count"] and t["customer_id"] not in self.alerted:
self.alerted.add(t["customer_id"])
return {
"customer_id": t["customer_id"],
"txn_count": len(queue),
"total_amount": sum(x["amount"] for x in queue),
"triggered_at": t["timestamp"],
}
return None
params = {"lookback_days": 7, "min_count": 3, "floor": 8000, "ceiling": 10000}
engine = StreamingStructuring(params)
feed = [
{"customer_id": "C1", "type": "cash_deposit", "amount": 9500, "timestamp": datetime(2026, 3, 2, 10, 0)},
{"customer_id": "C1", "type": "cash_deposit", "amount": 9200, "timestamp": datetime(2026, 3, 3, 15, 30)},
{"customer_id": "C1", "type": "cash_deposit", "amount": 9800, "timestamp": datetime(2026, 3, 5, 9, 15)},
]
for txn in feed:
result = engine.on_transaction(txn)
if result:
print(result["customer_id"], result["txn_count"], result["total_amount"], result["triggered_at"])
# C1 3 28500 2026-03-05 09:15:00The alert fires on the third deposit, not at the next nightly run. The alerted set plays the role of break in the batch version. Without it, the rule would create a new alert on every later qualifying deposit.
Trade-offs
| Concern | Batch | Near real time |
|---|---|---|
| Alert delay | Hours | Seconds to minutes |
| Complexity | Low | Higher: state, restarts, ordering |
| Re-running history | Easy | Needs replay of the event log |
| Late or out-of-order data | Handled by reloading the window | Can corrupt window state |
| Best for | Behavior over days or weeks | Cases where a hold or block must happen before settlement |
Common errors
- Window boundaries. Using
>=where the rule says "more than" shifts which transactions count. Check inclusive and exclusive ends. - Time zones. A deposit at 23:30 local time may fall on the next day in UTC and move out of a daily window.
- Duplicate alerts. Each run or each event can re-trigger the same pattern unless the engine remembers what it already alerted on.
- Late data. A transaction that posts after the batch ran is missed unless the next run reloads enough history.
Exercise
A rule alerts on 3 or more qualifying deposits in a 7-day rolling window. A customer deposits on Monday, Tuesday, and the next Monday at 9:00 on each of those days. Does the rule fire, and what changes if the window is a fixed calendar week (Monday to Sunday)?
Show answer
With the rolling window, the next Monday's deposit is exactly 7 days after the first. The code only drops transactions older than 7 days (a gap greater than the window), so all three count and the rule fires. With a fixed calendar week, the first two deposits fall in one week and the third falls in the next, so no week holds three and the rule does not fire. This shows how fixed windows can miss activity across a boundary.