Quick revision
The short answer
Decide by the latency each rule needs: rules that must block a payment belong in an in-line service or a stream processor that answers in milliseconds, while reports and slow-moving risk signals can stay in batch SQL. Over five years, aim for one shared rule definition that runs in both streaming and batch (for example Flink SQL with MATCH_RECOGNIZE or a rules DSL), keep event data and labels in your own store whatever engine you buy, and govern rules with versioning, backtesting and measured false positives.
What to remember
In this answer, we classified consecutive-event rules by the latency of the action they drive, saw that window functions cover simple sequences while MATCH_RECOGNIZE expresses real patterns in engines that support it, argued for one rule definition that runs in streaming and batch, kept our event data and labels whatever we buy, and governed rules through versioning, backtesting, shadow mode and false positive reviews with the business.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Decide by the latency each rule needs: rules that must block a payment belong in an in-line service or a stream processor that answers in milliseconds, while reports and slow-moving risk signals can stay in batch SQL. Over five years, aim for one shared rule definition that runs in both streaming and batch (for example Flink SQL with MATCH_RECOGNIZE or a rules DSL), keep event data and labels in your own store whatever engine you buy, and govern rules with versioning, backtesting and measured false positives.
Why this question is asked
Rules like three failed payments followed by a success from a new device are pattern rules over ordered events, and they tend to grow organically: an analyst writes an hourly SQL job, a platform team adds a stream processor, a vendor engine arrives with a new contract. After a few years the same rule exists in three places and they disagree. Interviewers ask this at senior levels because there is no single right engine; the answer shows whether we can reason from requirements, cost and risk rather than from tool preference. In this answer, we will classify rules by the latency they need, look at what SQL can and cannot express for consecutive events, see why one shared definition matters, weigh build against buy, and finish with how to govern and backtest rules.
1Start From What Each Rule Must Do
Every fraud or alerting rule exists to trigger an action, and the action decides how fast the rule must be. If the action is declining a card payment, the decision must arrive inside the payment request, typically within 50 to 200 milliseconds. If the action is a case for an analyst to review tomorrow, an hourly batch is plenty. If the action is a weekly risk report, a nightly job is fine.
So the first step is an inventory: list the rules, and for each one record the action, the latency it needs, who owns it and how often it fires. In most companies this inventory alone reveals that a minority of rules truly need real time, and that several rules are duplicates with slightly different thresholds.
| Action | Latency needed | Natural home |
|---|---|---|
| Block or challenge a payment | under 200 ms | In-line service or stream state |
| Alert an analyst or freeze an account | seconds to minutes | Stream processor (Flink, Kafka Streams) |
| Daily risk review queue | hours | Batch SQL on the warehouse |
| Monthly reporting to regulators | days | Batch SQL, versioned and audited |
2What SQL Can Express for Consecutive Events
Simple consecutive rules fit window functions. Three failed payments in a row is LAG(status, 1) and LAG(status, 2) per account in time order. But the rule in the question is a pattern, three failures followed by a success with a condition on the success, and those become hard to read with LAG alone.
The SQL standard has a feature built for this: MATCH_RECOGNIZE, row pattern matching. We describe the rows with names and a regular expression over them. It is supported by Oracle, Snowflake, Trino and Flink SQL, but not by PostgreSQL or MySQL, so check your engines before standardising on it.
Notice that is_new_device is a column we must compute first, by enriching each event with whether the device was seen before for that account. That enrichment is often the hardest part of the rule, and it needs state: a lookup table in batch, keyed state in a stream processor.
3One Rule Definition, Two Execution Modes
The most expensive failure in this area is two implementations of the same rule that disagree: the hourly SQL flags 1,200 accounts and the stream flags 950, and nobody knows which is right. The fix is to define each rule once and run that definition in both modes. Flink SQL is attractive here because the same query, including MATCH_RECOGNIZE, can run on a Kafka stream and on a bounded historical table. A rules DSL compiled to both a streaming and a batch engine is the other common option.
The reason this matters beyond tidiness is testing. A rule we can run on last year's events in batch is a rule we can backtest before it blocks a single real payment.
- Rule definitionsversioned SQL or DSL, owned per rule
- Streaming runtimeFlink on Kafka for real-time decisions
- Batch runtimesame definitions on historical tables
- Event and label storeour own data, kept regardless of vendor
- Feedbackconfirmed fraud and false positives from analysts
5 layers, from the top down. Step through them one at a time.
4Build Versus Buy
Vendor fraud engines bring things we cannot easily build: models trained on data across many merchants, device fingerprinting and consortium signals. For a mid-sized company, that can catch more fraud in the first year than an internal team would. The costs are lock-in, per-transaction pricing that grows with volume, and explainability: when a regulator or a customer asks why a payment was blocked, we must be able to answer.
A balanced position is to buy the signals and keep the decisions and the data. We send events to the vendor and use its score as one input, but our own event store keeps every event, decision and label, so we can switch vendors, retrain or backtest without asking anyone for our own history.
5Governing and Backtesting Rules
Rules are code that changes money flows, so they deserve the same discipline as code. Each rule has a version, an owner in the business and an engineering owner. A new rule or threshold change runs first against historical data, then in shadow mode, where it computes decisions but does not act, and only then goes live, ideally on a small share of traffic.
- Write the rule as a versioned definition
- Backtest on 6 to 12 months of eventscompare flags with known fraud labels
- Precision and false positives acceptable?Yesgo to shadow modeNotune or drop the rule
- Shadow mode for 1 to 2 weeksdecisions logged, not enforced
- Enable for a share of trafficthen for everyone
- Review monthly with the business owner
6 steps in order. Play them, or step through them one at a time.
We measure precision, the share of flagged cases that were truly fraud, and the false positive rate together with the business owners, because a rule that blocks 2 percent of good customers to catch a little more fraud can lose more revenue than it saves.
6Follow-up questions
How would you backtest a new rule?
Run the rule's definition in batch over a long stretch of historical events, for example the last twelve months, in event time order and with the enrichment as it would have been known at the time, so we do not use information from the future. Join the flags to the confirmed fraud labels and chargebacks, and compute how many fraud cases it would have caught, how many good customers it would have flagged, and the money involved. Compare against the current rules to see the incremental value, then confirm with a shadow run on live traffic, because historical data hides changes in customer behaviour.
Why not put every rule in the stream processor to be safe?
Streaming state, exactly-once processing and on-call support are expensive, and rules that only feed a daily report gain nothing from them. Keeping slow rules in batch SQL is cheaper and easier for analysts to change. The shared definition lets a rule move to streaming later if its action changes.
What if our main database is PostgreSQL, which lacks MATCH_RECOGNIZE?
Simple patterns still work with LAG and the gaps and islands technique, and that is fine for batch reports. For complex patterns we would run them in an engine that supports row pattern matching, such as Flink SQL or the warehouse, fed from PostgreSQL by change data capture, rather than writing hard-to-test SQL.
7Conclusion
In this answer, we classified consecutive-event rules by the latency of the action they drive, saw that window functions cover simple sequences while MATCH_RECOGNIZE expresses real patterns in engines that support it, argued for one rule definition that runs in streaming and batch, kept our event data and labels whatever we buy, and governed rules through versioning, backtesting, shadow mode and false positive reviews with the business.
Open with
I would not decide by engine but by what each rule has to do. First I would inventory the rules with their action, owner and required latency. Rules that block a payment need an answer in well under a second, so they live in the payment path or in a stream processor with keyed state.
Then, if they want more
Rules that feed analyst queues can run every few minutes in streaming or hourly in batch, and reporting rules stay in batch SQL.
For expressing the logic, simple sequences work with LAG and window functions, while real patterns like three failures followed by a success from a new device are what MATCH_RECOGNIZE is for; Flink SQL, Snowflake, Trino and Oracle support it, PostgreSQL and MySQL do not.
My main goal over five years would be one definition per rule that runs in both streaming and batch, for example in Flink SQL or a rules DSL, because two implementations always drift and because batch execution of the same definition is how we backtest.
On vendors, I would buy signals such as device intelligence and consortium scores, but keep all events, decisions and labels in our own store so we stay free to switch and can explain decisions.
Finally, rules get versions and owners, are backtested on historical data, run in shadow mode before enforcement, and are reviewed with the business on precision and false positives.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Fraud and alerting rules in your company are written as SQL over event tables, for...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/adb058f89a/