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, as covered in the earlier chapters on scenarios and thresholds. You should also read basic Python, including defaultdict and datetime. The chapter covers what the monitoring engine does with a scenario once the data is available. It looks at how the engine selects transactions, groups them, measures them over time, compares them with thresholds and decides when to run.
What evaluation means
A scenario is a definition. Evaluation is the act of applying that definition to data. For each customer, or each account or counterparty depending on the scenario, the engine answers one question: do the transactions in the relevant time span meet the conditions in the rule?
Most rules follow the same four steps:
- Filter. Keep only the transactions the rule cares about, such as cash deposits between 8,000 and 10,000.
- Group. Collect those transactions by the entity being monitored, usually the customer.
- Window. Look only at transactions inside a time span, called the lookback window.
- Aggregate and compare. Compute a count, sum or other measure over the window and compare it with a threshold.
If the comparison succeeds, the engine creates an alert record. Alert content is covered in the next chapter.
Lookback windows
The lookback window is the span of time a rule inspects. Parameters usually express it as a number of days, such as lookback_days = 7. There are two common designs.
- Rolling (sliding) window. The window ends at a transaction, or at the run time, and reaches back a fixed duration. Any 7 consecutive days can trigger the rule.
- Fixed (calendar) window. The window is a calendar day, week or month. All transactions in the same bucket are aggregated together.
The difference matters at boundaries. Suppose a customer deposits 9,500 on a Sunday night and 9,400 on a Monday morning. A weekly calendar window splits them into different weeks. A rolling window sees both. Rolling windows catch behavior that straddles boundaries, but they cost more to compute. Fixed windows are cheap and easy to explain, but a customer who knows the boundaries can stay under the rule by timing deposits around them.
Inclusive and exclusive edges
Every window has a boundary decision. A transaction exactly 7 days old is either in or out. The rule in the spine's first code example uses > in the condition current["timestamp"] - txns[start]["timestamp"] > window. A transaction exactly 7 days earlier therefore stays in the window. Document this choice, because validators and auditors will test it.
The amount range works the same way. In floor <= amount < ceiling, the floor is inclusive and the ceiling is exclusive. A deposit of exactly 10,000 is excluded, because the intent is to catch amounts just under the limit.
Aggregation
Aggregation turns many transactions into a few numbers that can be compared with thresholds. Common measures are:
- Count of transactions, as in "three or more deposits".
- Sum of amounts, as in "total above 25,000".
- Distinct count, such as the number of different counterparties or branches.
- Maximum or average, such as the largest single transfer.
- Ratios, such as cash in compared with cash out, or the customer's activity compared with their peer group.
A rule can combine several measures. A rapid-movement rule might require that funds in and funds out within 48 hours are within 10 percent of each other, and that the total is above a floor. Combining measures usually reduces false alerts, because each added condition narrows what fires.
The grouping key is also a design choice. Grouping by customer finds one person spreading activity over several accounts. Grouping by account is simpler but misses that pattern. Grouping by counterparty finds many customers paying the same recipient.
Walking through the structuring rule
This is the rule from the earlier scenario chapter, with the evaluation steps marked.
from collections import defaultdict
from datetime import timedelta
def structuring_alerts(transactions, params):
"""Alert when a customer makes several cash deposits just under a limit
inside a rolling window."""
window = timedelta(days=params["lookback_days"])
by_customer = defaultdict(list)
for t in transactions:
if t["type"] == "cash_deposit" and params["floor"] <= t["amount"] < params["ceiling"]:
by_customer[t["customer_id"]].append(t)
alerts = []
for customer_id, txns in by_customer.items():
txns.sort(key=lambda t: t["timestamp"])
start = 0
for end, current in enumerate(txns):
while current["timestamp"] - txns[start]["timestamp"] > window:
start += 1
hits = txns[start:end + 1]
if len(hits) >= params["min_count"]:
alerts.append({
"customer_id": customer_id,
"scenario": "structuring_cash",
"window_start": hits[0]["timestamp"],
"window_end": hits[-1]["timestamp"],
"txn_count": len(hits),
"total_amount": sum(t["amount"] for t in hits),
})
break # one alert per customer per run
return alertsThe function maps onto the four steps like this:
- Filter and group. The first loop keeps only qualifying cash deposits and files them under
customer_id. - Window. The
startandendindexes form a two-pointer sliding window over the sorted transactions.startonly moves forward, so each transaction is visited a bounded number of times. - Aggregate and compare.
hitsis the current window. Its length is the count, andsumgives the total. The comparison islen(hits) >= min_count. - Alert. The record stores the window boundaries, count and total, so an analyst can see why it fired.
Sorting is required. The two-pointer logic assumes transactions are in time order, and if they are not it silently gives wrong answers. The break means a customer receives at most one alert per run. That is a deliberate choice to limit duplicates, but it also means a customer with two separate bursts in one run gets only the first.
Batch evaluation
In batch mode, the engine runs on a schedule, commonly nightly. It loads all transactions that arrived since the last run, together with enough history to fill each rule's longest lookback. It then evaluates every scenario and writes alerts.
Batch has several practical features:
- A data cut-off. The run covers transactions up to a defined time, such as end of business day. Anything that arrives after the cut-off waits for the next run.
- Full history access. The engine can query weeks or months of data and join it to customer profiles and peer-group statistics.
- Different schedules per scenario. A structuring rule may run daily, while a rule with a 90-day window may run weekly or monthly.
- Reproducibility. Rerunning the same data with the same parameters produces the same alerts, which helps with testing and audit.
The cost is latency. A transaction made just after one run's cut-off can wait a day or more before any rule sees it.
Near-real-time evaluation
In near-real-time mode, the engine evaluates each transaction, or a small micro-batch, as it arrives. Instead of rereading history, it keeps a running state for each customer, such as a queue of recent qualifying deposits. Each new event updates that state and may trigger an alert at once.
from collections import defaultdict, deque
from datetime import datetime, timedelta
class StreamingStructuring:
"""Incremental version of the structuring rule. Events must arrive in time order."""
def __init__(self, params):
self.params = params
self.window = timedelta(days=params["lookback_days"])
self.recent = defaultdict(deque) # customer_id -> qualifying deposits in window
self.last_alert = {} # customer_id -> time of last alert
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"]:
return None
last = self.last_alert.get(t["customer_id"])
if last is not None and t["timestamp"] - last <= self.window:
return None # suppress repeat alerts while the same burst continues
self.last_alert[t["customer_id"]] = t["timestamp"]
return {
"customer_id": t["customer_id"],
"scenario": "structuring_cash",
"txn_count": len(queue),
"total_amount": sum(x["amount"] for x in queue),
}
params = {"lookback_days": 7, "min_count": 3, "floor": 8000, "ceiling": 10000}
engine = StreamingStructuring(params)
events = [
{"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)},
{"customer_id": "C1", "type": "cash_deposit", "amount": 9000, "timestamp": datetime(2026, 3, 6, 9, 0)},
]
for event in events:
alert = engine.on_transaction(event)
if alert:
print(alert["customer_id"], alert["txn_count"], alert["total_amount"])
# C1 3 28500The alert fires on the third deposit. The fourth deposit also meets the threshold, with four transactions in the window, but the cooldown suppresses it. Without that check, a streaming engine would alert on every new event in the burst. A batch engine avoids this problem with its one-alert-per-run rule.
Comparing the two modes
| Aspect | Batch | Near real time |
|---|---|---|
| Detection delay | Hours to a day or more | Seconds to minutes |
| Lookback cost | Re-queries history each run | Keeps state per customer |
| Late or out-of-order data | Handled by the next run | Needs explicit handling |
| Reproducibility | Easy to rerun | Harder, depends on event order |
| Duplicate control | One alert per run | Needs cooldown or state |
| Typical use | Pattern and behavior rules | Sanctions-style or high-urgency rules |
Many institutions use both. Pattern rules over long windows, peer-group comparisons and statistical models run in batch. A small set of high-urgency rules runs on the stream.
Edge cases to check
- Late-arriving transactions. A deposit posted two days after it happened falls outside a batch run's expected data. Decide whether the engine reprocesses affected windows or accepts the miss.
- Time zones. A deposit at 23:30 in one zone may be the next day in another. Use one consistent time basis for window math and record which one.
- Reversals and corrections. A canceled deposit should leave the count. Otherwise the rule fires on activity that did not stand.
- Duplicate records. Feed duplicates inflate counts and sums. Deduplicate before aggregating.
- Overlapping runs. If a window straddles two runs, the same pattern may match in both. Suppression logic must compare against alerts from earlier runs.
- Missing parameters. If a customer's segment has no parameter set, the rule should fail loudly or fall back to a documented default, not skip the customer silently.
Exercise
A weekly calendar-window rule alerts when a customer makes 3 or more qualifying cash deposits in the same Monday-to-Sunday week. A customer deposits just under the limit on Saturday, Sunday, Monday and Tuesday. Does the calendar rule alert? Would the 7-day rolling rule from this chapter alert? What does this show about the trade-off?
Show answer
The calendar rule does not alert. The Saturday and Sunday deposits fall in one week (2 deposits) and the Monday and Tuesday deposits in the next (2 deposits), so neither week reaches 3. The rolling rule alerts, because all four deposits fall inside one 7-day span and the count reaches 3 by the third deposit. This shows that fixed windows can miss activity that straddles a boundary, while rolling windows catch it at a higher computation cost.
Exercise
In the streaming example, what would happen on the fourth deposit if the cooldown check on last_alert were removed, and why does the batch version not need an equivalent check?
Show answer
The fourth deposit would produce a second alert, because the queue holds 4 deposits, which is at least min_count. Every further deposit in the burst would alert again. The batch version evaluates each customer once per run and stops at the first match through break, so it creates at most one alert per customer per run.