Evaluate the Ultra Tier Rollout and Build SQL Fraud Rules
Hard · Analytics & Experimentation · Data Analyst · Technical Screen
Prompt
You are a Data Analyst at a multi-product consumer fintech app where all warehouse timestamps are recorded in UTC. Only the three tables below exist in the analytics store:
users(user_id BIGINT PRIMARY KEY, create_date TIMESTAMP, country VARCHAR)— one row per customer with signup time and registered country.transactions(transaction_id BIGINT PRIMARY KEY, user_id BIGINT, product VARCHAR, amount_gbp DECIMAL(12,2), status VARCHAR, transaction_time TIMESTAMP)— one row per payment attempt or charge.activity(user_id BIGINT, product VARCHAR, event_type VARCHAR, event_time TIMESTAMP, ip_country VARCHAR)— one row per in-app event, including the geolocation country of the client IP.
Address both analytical design problems below using only these tables and columns.
Part 1: Evaluating the First Month of the Ultra Paid Plan
The company rolls out a premium paid membership tier named Ultra, but engineering has not created a standalone memberships table yet. You must reconstruct plan uptake and ongoing usage from the existing logs (for instance, records tagged with product = 'ultra' across transactions and activity).
Explain how you would judge whether Ultra's first 30 days succeeded and design the SQL reporting layer to support that readout:
- Select one primary success metric and complement it with supporting funnel, engagement, and guardrail metrics.
- Compare candidate denominators (total registered base, pre-launch active customers, newly acquired customers, offer viewers) and explain when each helps or misleads.
- Break performance down by customer registration country and account tenure.
- Show how to compute
UltraDAU / WAU / MAU, cumulative adoption, target-base penetration, and early post-signup retention in SQL. - Guard your conclusions against calendar seasonality, country composition shifts, and customer self-selection.
Part 2: SQL Rule Engine for Financial-Crime Triage
You are embedded with the Financial Crime operations group to build an interpretable SQL alerting pipeline that surfaces risky accounts or payments for human investigators.
Using strictly the three tables above, convert qualitative risk ideas into concrete, auditable SQL checks covering patterns such as:
- unusually high single-payment amounts,
- rapid bursts of payment attempts within brief rolling windows,
- repeated tiny card-testing / balance-probing attempts,
- sudden activity across many distinct products compared to prior habits,
- discrepancies between registered
countryand observedip_country.
Specify:
- the output schema for your alert log and analyst review queue,
- concrete rules, window definitions, and initial cutoffs,
- how multiple triggered rules roll up into an account-level risk score and prioritized queue,
- how to measure precision, recall, and false-positive cost over time without circular labels.
Scope & Expectations
- Explicit proxy design & data hygiene: State clear, testable SQL rules separating paid
Ultrasubscribers from window-shoppers, and call out edge cases such as refunds, payment declines, and free trials. - Rigorous metric & cohort SQL: Anchor the launch evaluation on a pre-committed, frozen-denominator metric, handle sliding active-user windows and right-censored retention cleanly, and control for Simpson's paradox and selection bias.
- Boundary-safe fraud detection SQL: Use true rolling time windows rather than fixed clock-minute buckets, guard string evidence against
NULLvalues, and combine rule weights so ordinary single anomalies (such as paying rent or travelling abroad) do not swamp investigators. - Unbiased operational evaluation: Explain how analyst dispositions measure precision while only independently surfaced fraud (chargebacks, victim reports, below-threshold audits) can measure recall honestly.
Step-by-step walkthrough
Infer Ultra adoption from raw transaction and activity logs
Because there is no dedicated subscription table, our first step is to define clear proxies (measurable stand-ins built from existing columns) for who saw Ultra, who paid for it, and who actively uses it:
User state Rule in existing tables Example row pattern ------------------ ----------------------------------------------------------------- --------------------------------------------- Paid subscriber >= 1 row in transactions with product = 'ultra', tx #91: ultra, 45.00 GBP, 'completed' status = 'completed', and amount_gbp > 0 (first row = start date) Prospect (unpaid) >= 1 row in activity with product = 'ultra', activity: ultra, 'view', no completed charge and 0 completed positive-amount Ultra charges Failed attempt >= 1 row in transactions with product = 'ultra' tx #92: ultra, 45.00 GBP, 'declined' and status = 'declined', with 0 completed Ultra charges Active Ultra user Paid subscriber who logs activity on product = 'ultra' activity on ultra after first_paid_at after their first completed Ultra chargeBefore building dashboards on this proxy, run three quick data checks: - Inspect fee amounts and statuses:
SELECT status, amount_gbp, COUNT(*) FROM transactions WHERE product = 'ultra' GROUP BY 1, 2;should cluster around a few fixed plan prices (monthly/annual tiers per country). Wide variation meansproduct = 'ultra'also tags perk purchases rather than only subscription fees. - Check refunds and free trials: Verify whether refunds are stored as negativeamount_gbpor a separatestatus, and whether a 30-day free trial delays the first charge past month 1 (if so, track trial starts via a specificevent_typeinactivity). - Exclude internal accounts: Filter out staff or QA test accounts if identifiable.All SQL below uses PostgreSQL dialect with UTC timestamps fixed in a
paramsCTE (Common Table Expression — a named temporary query block introduced withWITH):-- Build one summary row per user who interacted with or paid for Ultra after launch. CREATE TABLE ultra_users AS WITH params AS ( SELECT TIMESTAMP '2026-03-02 00:00' AS launch_ts ), ultra_events AS ( -- Earliest interaction and total interaction count on Ultra after launch. SELECT a.user_id, MIN(a.event_time) AS first_ultra_event_at, COUNT(*) AS ultra_events FROM activity a CROSS JOIN params p WHERE a.product = 'ultra' AND a.event_time >= p.launch_ts GROUP BY a.user_id ), ultra_charges AS ( -- Earliest completed positive fee charge = paid subscription start timestamp. SELECT t.user_id, MIN(t.transaction_time) AS first_paid_at, COUNT(*) AS paid_charges, SUM(t.amount_gbp) AS fees_gbp FROM transactions t CROSS JOIN params p WHERE t.product = 'ultra' AND t.status = 'completed' AND t.amount_gbp > 0 AND t.transaction_time >= p.launch_ts GROUP BY t.user_id ) SELECT COALESCE(e.user_id, c.user_id) AS user_id, e.first_ultra_event_at, c.first_paid_at, -- NULL means unpaid prospect COALESCE(c.paid_charges, 0) AS paid_charges, COALESCE(c.fees_gbp, 0) AS fees_gbp FROM ultra_events e FULL OUTER JOIN ultra_charges c ON c.user_id = e.user_id;Define one primary success metric and supporting guardrails
A launch evaluation needs one primary metric agreed upon before launch day so teams cannot cherry-pick whichever number looks best afterward.
Primary metric: Day-30 paid penetration of the pre-launch active base.
Pre-launch active base = users with >= 1 completed transaction or activity event in [launch_ts - 30 days, launch_ts) <-- frozen before launch! Day-30 paid penetration = (active-base users with >= 1 completed Ultra charge in [launch_ts, launch_ts + 30 days)) / (total users in pre-launch active base)Why this is the strongest primary metric: - Measures real willingness to pay: Views and clicks reflect curiosity; a completed positive fee proves the plan is worth its price and maps directly to subscription revenue (
penetration × base × price). - Normalized as a rate: Unlike a raw subscriber count, a percentage compares cleanly across countries of very different sizes. - Frozen denominator: Fixing the denominator before launch guarantees that an email reactivation campaign during month 1 cannot artificially shrink or bloat the denominator.Pair the primary metric with supporting metrics (to explain how we got the number) and guardrail metrics (health checks that must not get worse): - Volume & revenue: Total paid subscribers (including new sign-ups and reactivated dormant users) and gross Ultra fee revenue in GBP. - Conversion funnel: Unique users who viewed Ultra -> clicked -> attempted payment -> completed payment, plus median days from first view to first charge. - Engagement & early retention: Ultra DAU, WAU, MAU, stickiness (
DAU / MAU, how many days per month the typical monthly user engages), and Week-1/2/3 post-purchase Ultra activity retention. - Payment health: Charge decline rate =declined / (completed + declined)on positive Ultra fee attempts. - Guardrails: Non-Ultra product usage and revenue (checking for cannibalization), overall app active users, and the Fincrime suspicious-alert rate among new Ultra subscribers (checking for perk abuse).Compare denominators and segment by country and tenure
The exact same subscriber count tells four very different stories depending on the denominator. Suppose before launch the platform has
1,000,000registered users (400,000active in the prior 30 days),50,000new users join during launch month, and60,000users view the Ultra screen. Suppose6,000users pay for Ultra (5,200from the pre-launch active base,500reactivated dormant users, and300brand-new users):Denominator choice Calculation Rate When to use & key trade-off -------------------------- --------------------- ------- ----------------------------------------------------------- All registered users 6,000 / 1,050,000 0.57% Diluted by old, dead accounts; penalizes mature markets. Pre-launch active base 5,200 / 400,000 1.30% Best primary metric: reachable audience, fixed pre-launch. New sign-ups in month 1 300 / 50,000 0.60% Measures Ultra as an acquisition hook; small, noisy sample. Users who viewed Ultra 6,000 / 60,000 10.00% Measures paywall conversion, not reach (self-selected).Always headline the active-base rate (
1.30%) and report the other three as named funnel/acquisition diagnostics.Next, break penetration down by country (pricing, local perks, and marketing differ by market) and user tenure (time between
users.create_dateandlaunch_ts, separating brand-new explorers from loyal multi-year customers). In PostgreSQL,GROUP BY ROLLUP (country, tenure)computes every(country, tenure)cell, per-country subtotals, and the overall grand total in one pass:WITH params AS ( SELECT TIMESTAMP '2026-03-02 00:00' AS launch_ts ), active_base AS ( -- Users active in the 30 days strictly before launch (UNION deduplicates user_id). SELECT t.user_id FROM transactions t CROSS JOIN params p WHERE t.status = 'completed' AND t.transaction_time >= p.launch_ts - INTERVAL '30 days' AND t.transaction_time < p.launch_ts UNION SELECT a.user_id FROM activity a CROSS JOIN params p WHERE a.event_time >= p.launch_ts - INTERVAL '30 days' AND a.event_time < p.launch_ts ), subscribers AS ( SELECT DISTINCT t.user_id FROM transactions t CROSS JOIN params p WHERE t.product = 'ultra' AND t.status = 'completed' AND t.amount_gbp > 0 AND t.transaction_time >= p.launch_ts AND t.transaction_time < p.launch_ts + INTERVAL '30 days' ), segmented_base AS ( SELECT b.user_id, COALESCE(u.country, 'unknown') AS country, CASE WHEN u.create_date > p.launch_ts - INTERVAL '90 days' THEN '1_under_3m' WHEN u.create_date > p.launch_ts - INTERVAL '365 days' THEN '2_3m_to_12m' WHEN u.create_date > p.launch_ts - INTERVAL '1095 days' THEN '3_1y_to_3y' ELSE '4_over_3y' END AS tenure_bucket, CASE WHEN s.user_id IS NOT NULL THEN 1 ELSE 0 END AS is_subscriber FROM active_base b JOIN users u ON u.user_id = b.user_id CROSS JOIN params p LEFT JOIN subscribers s ON s.user_id = b.user_id ) SELECT country, tenure_bucket, COUNT(*) AS base_users, SUM(is_subscriber) AS subscribers, ROUND(100.0 * SUM(is_subscriber) / NULLIF(COUNT(*), 0), 2) AS penetration_pct FROM segmented_base GROUP BY ROLLUP (country, tenure_bucket) ORDER BY country, tenure_bucket;Always display
base_usersalongsidepenetration_pct: a tiny segment with2subscribers out of200users (1.00%) has an exact 95% confidence interval of roughly0.1%to3.6%, which is too wide to rank countries reliably.Measure Ultra DAU/WAU/MAU, adoption, and right-censored retention
State exact operational definitions before writing SQL: - Ultra DAU / WAU / MAU on day
d: Distinct users with an Ultraactivityevent or completed positive Ultratransactionsrow on dayd(DAU), during[d - 6, d](7-day WAU), or during[d - 29, d](30-day MAU). Split this into paid subscribers vs prospects so window-shopping traffic is not mistaken for subscriber usage. - Adoption vs penetration: Cumulative paid subscribers up to dayd(adoption) and that count divided by the frozen active base (penetration).PostgreSQL does not allow
COUNT(DISTINCT user_id) OVER (...)for sliding windows. Instead, generate a daily calendar table and join each dayc.dto user-days within the trailing 30 days:WITH params AS ( SELECT DATE '2026-03-02' AS launch_day, DATE '2026-03-31' AS last_day ), ultra_user_days AS ( -- Deduplicated (user_id, UTC date) pairs with any Ultra usage or paid fee. SELECT a.user_id, CAST(a.event_time AS DATE) AS d FROM activity a CROSS JOIN params p WHERE a.product = 'ultra' AND a.event_time >= p.launch_day UNION SELECT t.user_id, CAST(t.transaction_time AS DATE) AS d FROM transactions t CROSS JOIN params p WHERE t.product = 'ultra' AND t.status = 'completed' AND t.amount_gbp > 0 AND t.transaction_time >= p.launch_day ), calendar AS ( SELECT CAST(g AS DATE) AS d FROM params p, generate_series(p.launch_day, p.last_day, INTERVAL '1 day') AS g ) SELECT c.d, COUNT(DISTINCT CASE WHEN u.d = c.d THEN u.user_id END) AS ultra_dau, COUNT(DISTINCT CASE WHEN u.d > c.d - 7 THEN u.user_id END) AS ultra_wau, COUNT(DISTINCT u.user_id) AS ultra_mau FROM calendar c LEFT JOIN ultra_user_days u ON u.d > c.d - 30 AND u.d <= c.d GROUP BY c.d ORDER BY c.d;For early retention, monthly renewal charges do not happen until day ~30, so inside month 1 we track weekly Ultra activity retention as a leading indicator. Watch out for right-censoring (when a user's observation window has not finished yet before
data_end):launch (Mar 02) data_end (Apr 01) |--- Week 0 [0,7d) ---|--- Week 1 [7,14d) ---|--- Week 2 [14,21d) ---|--- Week 3 [21,28d) ---| User A (paid Mar 02): complete complete complete (observable!) User B (paid Mar 20): complete cuts off on Apr 01! --> EXCLUDE from Week 1+ denominatorIf we included User B in Week 2 or Week 3, late sign-ups would look like they churned simply because April has not happened yet:
WITH params AS ( SELECT TIMESTAMP '2026-03-02 00:00' AS launch_ts, TIMESTAMP '2026-04-01 00:00' AS data_end ), subs AS ( SELECT t.user_id, MIN(t.transaction_time) AS first_paid_at FROM transactions t CROSS JOIN params p WHERE t.product = 'ultra' AND t.status = 'completed' AND t.amount_gbp > 0 AND t.transaction_time >= p.launch_ts AND t.transaction_time < p.data_end GROUP BY t.user_id ), observable_weeks AS ( -- week_no = 1 means days [7, 14) after paying; keep only fully elapsed weeks. SELECT s.user_id, s.first_paid_at, w.week_no FROM subs s CROSS JOIN generate_series(1, 3) AS w(week_no) CROSS JOIN params p WHERE s.first_paid_at + (w.week_no + 1) * INTERVAL '7 days' <= p.data_end ), retention_flags AS ( SELECT o.week_no, CASE WHEN EXISTS ( SELECT 1 FROM activity a WHERE a.user_id = o.user_id AND a.product = 'ultra' AND a.event_time >= o.first_paid_at + o.week_no * INTERVAL '7 days' AND a.event_time < o.first_paid_at + (o.week_no + 1) * INTERVAL '7 days' ) THEN 1 ELSE 0 END AS retained FROM observable_weeks o ) SELECT week_no, COUNT(*) AS observable_subscribers, SUM(retained) AS retained_subscribers, ROUND(100.0 * SUM(retained) / NULLIF(COUNT(*), 0), 1) AS retention_pct FROM retention_flags GROUP BY week_no ORDER BY week_no;Once the first signup cohort passes day 30 plus a ~7-day payment-retry grace period, pair this with the true billing renewal rate (share with a second completed Ultra fee).
Prevent false conclusions from seasonality, mix shift, and self-selection
Three classic traps distort launch readouts unless we explicitly control for them:
- Seasonality and launch novelty: Launching during December holidays or summer travel lifts card spend and app opens for everyone. Compare metrics against the same calendar weeks last year across the whole active base, and split adoption by signup-week cohort (users grouped by the week they subscribed) so a noisy day-1 email blast does not hide weak week-3 organic demand.
- Country mix shift (Simpson's paradox — when an overall blended rate moves in the opposite direction of individual groups because group weights changed): Suppose Country A converts at
2.0%and Country B converts at0.5%in both months, while marketing expands Country B's share of the active base from50%to70%:
Month 1 (50% A, 50% B): 0.50 * 2.0% + 0.50 * 0.5% = 1.25% blended penetration Month 2 (30% A, 70% B): 0.30 * 2.0% + 0.70 * 0.5% = 0.95% blended penetration (looks like a 24% drop!) Standardized to Month 1: 0.50 * 2.0% + 0.50 * 0.5% = 1.25% (true flat performance)Always report per-country rates alongside an overall rate **standardized** (re-weighted) to fixed pre-launch country shares.- Self-selection bias: Frequent travellers and high spenders naturally choose Ultra. Seeing Ultra subscribers spend
£1,200/monthvs£300/monthfor non-subscribers does not mean Ultra caused+£900of spend. Match each subscriber to non-subscribers in the same country, tenure bucket, and pre-launch spend decile, and compute difference-in-differences (comparing the pre-to-post change of subscribers against the pre-to-post change of matched non-subscribers, excluding the Ultra fee itself):- Subscribers:
£1,100pre ->£1,200post (+£100) - Matched controls:
£1,080pre ->£1,120post (+£40seasonal trend) - Estimated Ultra lift:
£100 - £40 = +£60/month. (Note that this still assumes parallel trends; holding out a random 5–10% control group from Ultra promotional emails gives a clean causal benchmark.)
- Subscribers:
Design the Fincrime alert schema and executable SQL rules
For Scenario 2, every rule needs a concrete pattern, time window, initial threshold (seeded from ~99.9th percentiles of historical non-fraud users), point weight, and human-readable evidence string:
Rule ID Suspicious pattern & threshold Points ------------------- -------------------------------------------------------------------- ------ R1_LARGE_AMOUNT Single tx >= 10,000 GBP; OR >= 10x user's 90-day median completed tx 30 (if >= 5 prior txs and tx >= 500 GBP); OR >= 2,000 GBP within 30d of account creation. R2_BURST >= 10 transactions (completed or declined) within any sliding 10m. 25 R3_PROBING >= 5 small attempts (0 < amount_gbp <= 2) within any sliding 1h, 40 with >= 3 of those attempts declined (classic card testing). R4_PRODUCT_SPREAD Touched >= 4 distinct products today vs <= 1 in prior 90 days. 15 R5_GEOGRAPHY >= 3 distinct ip_country values in activity today; OR ip_country 15 differs from users.country AND a completed tx >= 500 GBP today.Notice why
R5_GEOGRAPHYrequires multiple countries or money movement: flagging every IP mismatch alone would flood reviewers with legitimate holidaymakers and VPN users.Store granular rule hits in
fincrime_alerts(for per-rule analytics and auditability) and user-level cases inreview_queue(where reviewers recordtrue_positiveorfalse_positivelabels):CREATE TABLE fincrime_alerts ( alert_id BIGSERIAL PRIMARY KEY, run_date DATE NOT NULL, user_id BIGINT NOT NULL, transaction_id BIGINT, -- populated for tx-level R1; NULL for user-level R2-R5 rule_id VARCHAR NOT NULL, -- versioned name, e.g. 'R3_PROBING_V1' points INT NOT NULL, evidence VARCHAR NOT NULL, -- plain-English explanation for the analyst created_at TIMESTAMP NOT NULL DEFAULT now() ); CREATE TABLE review_queue ( run_date DATE NOT NULL, user_id BIGINT NOT NULL, risk_score INT NOT NULL, rules_triggered VARCHAR NOT NULL, status VARCHAR NOT NULL DEFAULT 'open', -- 'open' | 'escalated' | 'closed' disposition VARCHAR, -- 'true_positive' | 'false_positive' reviewed_at TIMESTAMP, PRIMARY KEY (run_date, user_id) );When computing velocity rules (
R2andR3), use SQLRANGE BETWEEN INTERVAL ... PRECEDINGsliding windows rather thanDATE_TRUNC('minute', ...)clock buckets so a burst spanning10:09:30to10:10:15is caught cleanly, and pull 1 hour of lookback beforerun_startso00:05transactions see their full trailing hour:INSERT INTO fincrime_alerts (run_date, user_id, transaction_id, rule_id, points, evidence) WITH params AS ( SELECT TIMESTAMP '2026-03-10 00:00' AS run_start, TIMESTAMP '2026-03-11 00:00' AS run_end ), todays_tx AS ( SELECT t.* FROM transactions t CROSS JOIN params p WHERE t.transaction_time >= p.run_start AND t.transaction_time < p.run_end ), history AS ( -- Each user's 90-day baseline median completed transaction amount before today. SELECT t.user_id, COUNT(*) AS n_hist, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY t.amount_gbp) AS median_amt FROM transactions t CROSS JOIN params p WHERE t.status = 'completed' AND t.transaction_time >= p.run_start - INTERVAL '90 days' AND t.transaction_time < p.run_start GROUP BY t.user_id ), windowed AS ( -- Include 1 hour before run_start so midnight windows have full lookback. SELECT t.user_id, t.transaction_time, COUNT(*) OVER w10 AS n_10min, SUM(CASE WHEN t.amount_gbp > 0 AND t.amount_gbp <= 2 THEN 1 ELSE 0 END) OVER w60 AS small_1h, SUM(CASE WHEN t.amount_gbp > 0 AND t.amount_gbp <= 2 AND t.status = 'declined' THEN 1 ELSE 0 END) OVER w60 AS small_declined_1h FROM transactions t CROSS JOIN params p WHERE t.transaction_time >= p.run_start - INTERVAL '1 hour' AND t.transaction_time < p.run_end WINDOW w10 AS (PARTITION BY t.user_id ORDER BY t.transaction_time RANGE BETWEEN INTERVAL '10 minutes' PRECEDING AND CURRENT ROW), w60 AS (PARTITION BY t.user_id ORDER BY t.transaction_time RANGE BETWEEN INTERVAL '1 hour' PRECEDING AND CURRENT ROW) ), r1_large AS ( SELECT x.user_id, x.transaction_id, 'R1_LARGE_AMOUNT' AS rule_id, 30 AS points, 'amount ' || x.amount_gbp || ' GBP vs 90d median ' || COALESCE(ROUND(h.median_amt::numeric, 2)::text, 'n/a') AS evidence FROM todays_tx x JOIN users u ON u.user_id = x.user_id LEFT JOIN history h ON h.user_id = x.user_id WHERE x.amount_gbp >= 10000 OR (h.n_hist >= 5 AND x.amount_gbp >= 500 AND x.amount_gbp >= 10 * h.median_amt) OR (x.transaction_time < u.create_date + INTERVAL '30 days' AND x.amount_gbp >= 2000) ), r2_burst AS ( SELECT w.user_id, CAST(NULL AS BIGINT) AS transaction_id, 'R2_BURST' AS rule_id, 25 AS points, 'peak ' || MAX(w.n_10min) || ' transactions in 10 minutes' AS evidence FROM windowed w CROSS JOIN params p WHERE w.transaction_time >= p.run_start GROUP BY w.user_id HAVING MAX(w.n_10min) >= 10 ), r3_probing AS ( SELECT w.user_id, CAST(NULL AS BIGINT) AS transaction_id, 'R3_PROBING' AS rule_id, 40 AS points, '>= 5 small attempts (<= 2 GBP) in 1h with >= 3 declined' AS evidence FROM windowed w CROSS JOIN params p WHERE w.transaction_time >= p.run_start AND w.small_1h >= 5 AND w.small_declined_1h >= 3 GROUP BY w.user_id ), touches AS ( SELECT user_id, product, transaction_time AS ts FROM transactions UNION ALL SELECT user_id, product, event_time AS ts FROM activity ), r4_spread AS ( SELECT d.user_id, CAST(NULL AS BIGINT) AS transaction_id, 'R4_PRODUCT_SPREAD' AS rule_id, 15 AS points, COUNT(DISTINCT CASE WHEN d.ts >= p.run_start THEN d.product END) || ' products today vs ' || COUNT(DISTINCT CASE WHEN d.ts < p.run_start THEN d.product END) || ' in prior 90d' AS evidence FROM touches d CROSS JOIN params p WHERE d.ts >= p.run_start - INTERVAL '90 days' AND d.ts < p.run_end GROUP BY d.user_id HAVING COUNT(DISTINCT CASE WHEN d.ts >= p.run_start THEN d.product END) >= 4 AND COUNT(DISTINCT CASE WHEN d.ts < p.run_start THEN d.product END) <= 1 ), r5_geo AS ( -- COALESCE guards against NULL country values turning evidence into NULL. SELECT a.user_id, CAST(NULL AS BIGINT) AS transaction_id, 'R5_GEOGRAPHY' AS rule_id, 15 AS points, 'registered ' || COALESCE(MAX(u.country), 'unknown') || ', IPs today: ' || COALESCE(STRING_AGG(DISTINCT a.ip_country, ','), 'unknown') AS evidence FROM activity a JOIN users u ON u.user_id = a.user_id CROSS JOIN params p WHERE a.event_time >= p.run_start AND a.event_time < p.run_end GROUP BY a.user_id HAVING COUNT(DISTINCT a.ip_country) >= 3 OR (MAX(CASE WHEN a.ip_country <> u.country THEN 1 ELSE 0 END) = 1 AND EXISTS (SELECT 1 FROM todays_tx x WHERE x.user_id = a.user_id AND x.status = 'completed' AND x.amount_gbp >= 500)) ) SELECT CAST(p.run_start AS DATE), r.user_id, r.transaction_id, r.rule_id, r.points, r.evidence FROM ( SELECT * FROM r1_large UNION ALL SELECT * FROM r2_burst UNION ALL SELECT * FROM r3_probing UNION ALL SELECT * FROM r4_spread UNION ALL SELECT * FROM r5_geo ) r CROSS JOIN params p;Score the review queue and measure precision, recall, and false positives
To keep one 30-transaction burst from counting 30 times, aggregate distinct
(user_id, rule_id)hits per day, add a+20interaction bonus when small-amount probing is followed by a large cash-out attempt (R3_PROBING+R1_LARGE_AMOUNT), cap at100, and routerisk_score >= 40up to daily reviewer capacity (LIMIT 300):INSERT INTO review_queue (run_date, user_id, risk_score, rules_triggered) WITH distinct_hits AS ( -- Deduplicate multiple R1 transaction hits so each rule contributes once per user/day. SELECT DISTINCT run_date, user_id, rule_id, points FROM fincrime_alerts WHERE run_date = DATE '2026-03-10' ), scored AS ( SELECT run_date, user_id, SUM(points) + CASE WHEN COUNT(*) FILTER (WHERE rule_id IN ('R1_LARGE_AMOUNT', 'R3_PROBING')) = 2 THEN 20 ELSE 0 END AS raw_score, STRING_AGG(rule_id, ', ' ORDER BY rule_id) AS rules_triggered FROM distinct_hits GROUP BY run_date, user_id ) SELECT run_date, user_id, LEAST(raw_score, 100) AS risk_score, rules_triggered FROM scored WHERE raw_score >= 40 ORDER BY risk_score DESC, user_id LIMIT 300;Notice how the point design separates routine events from high-risk combinations: - Legitimate £10,000 rent payment (
R1alone =30) is logged infincrime_alertsfor analytics, but stays out of the manual queue (< 40). - Card probing alone (R3=40) or burst + foreign high-value payment (R2 + R5=40) enters the queue; probing + large transfer (R3 + R1 + 20=90) jumps straight to the top.Finally, evaluate the system monthly using independent label sources:
Metric Definition & worked monthly example ---------------- ----------------------------------------------------------------------------------- Precision Confirmed fraud / total reviewed = 1,350 / 9,000 = 15.0%. Track per rule and score band; retire or tighten rules near 0% precision. Recall Independently confirmed fraud (chargebacks, victim reports, law enforcement) that our rules flagged BEFORE the loss: 300 / 500 = 60.0%. Never include cases discovered ONLY by these rules, or recall is biased upward. False positives 9,000 - 1,350 = 7,650 innocent users reviewed (~1,275 analyst-hours at 10 min/case, plus customer friction if accounts are temporarily frozen). Threshold audit Sample ~200 unqueued users scoring 30-39 ("below the line") each month to measure missed fraud, and test new rules in shadow mode (logging without alerting) first.
Intuition & how it works
Measuring a subscription launch and catching financial crime from raw logs is like running an airport lounge when all you have are door-sensor pings (activity) and card-terminal receipts (transactions). For the Ultra launch, peeking through the lounge window (activity on 'ultra') only shows curiosity, whereas a completed positive charge (product = 'ultra', status = 'completed', amount_gbp > 0) proves someone bought a pass. For Fincrime, a single unusual action (such as paying rent or logging in on holiday) is usually innocent, so good SQL rules act like a multi-signal checklist — combining velocity, probing declines, account age, product spread, and geography into one account-level risk score sized to human review capacity.
Naive analytics and naive fraud rules fail in predictable ways. Dividing subscribers by all historical accounts dilutes conversion with millions of abandoned sign-ups, while comparing subscribers' post-launch spend directly against non-subscribers mistakes wealthy self-selection (heavy spenders naturally choosing a premium tier) for a product effect. On the fraud side, counting velocity inside fixed clock-minute buckets misses bursts that straddle 10:09:50–10:10:10, and alerting on every single foreign IP or large transfer buries analysts under thousands of false alarms.
Walk through a small numeric trace across both halves of the design:
- Denominator & mix-shift check: With 400,000 pre-launch active users (active in the 30 days before launch) and 5,200 who buy Ultra in month 1, primary paid penetration (share of the target base who paid) is 5,200 / 400,000 = 1.30%. If Country A (2.0%) and Country B (0.5%) shift from a 50/50 user mix (1.25% blended) to 30/70 (0.95% blended), re-weighting to the pre-launch 50/50 mix shows true performance stayed flat at 1.25%.
- Rule scoring check: User 101 makes a £10,500 rent payment (R1_LARGE_AMOUNT = 30 points) -> logged, not queued (< 40). User 202 runs 6 declined £1 card tests in 20 minutes (R3_PROBING = 40) followed by a £3,000 transfer (R1_LARGE_AMOUNT = 30) plus the +20 combo bonus -> risk_score = 90, jumping straight to the top of the manual review_queue.
Key points
- Make proxies explicit and validate them first: Define a paid Ultra subscriber by a completed positive-amount
product = 'ultra'transaction, and check amount distributions, refunds, and free-trial rules before trusting downstream metrics. - Anchor on one frozen-denominator primary metric: Day-30 paid penetration of the pre-launch 30-day active base aligns with revenue, normalizes across market sizes, and cannot be gamed by mid-month reactivation blasts; pair it with funnel, stickiness (
DAU / MAU, the share of monthly users engaging on an average day), payment decline, and guardrail metrics (business health indicators that must not degrade, such as non-Ultra spend). - Use calendar joins and right-censoring in SQL: Compute sliding 7-day WAU and 30-day MAU by joining a daily calendar spine to deduplicated
(user_id, day)rows, and apply right-censoring (including a subscriber in Week-kretention only when all 7 days of Weekkhave elapsed before the data cutoff). - Control for seasonality, Simpson's paradox, and self-selection: Use year-over-year baselines and cohort splits (groups of users who joined or subscribed in the same week), standardize blended rates against Simpson's paradox (when shifting group sizes reverse an overall trend), and estimate spend lift with difference-in-differences (comparing pre-to-post spend changes of subscribers against matched non-subscribers).
- Separate rule hits from the scored review queue: Store every rule trigger with a readable
evidencestring (usingCOALESCEsoNULLcountries never breakNOT NULLstrings), deduplicate per(user_id, rule_id)when summing points, use SQLRANGEsliding windows (rolling intervals anchored at each event's timestamp) for bursts, and cap the queue at daily analyst capacity. - Measure precision and recall without circular labels: Compute precision (share of reviewed alerts confirmed as bad) from analyst dispositions, and compute recall (share of true bad actors caught early) strictly on fraud discovered independently via chargebacks, victim reports, or law enforcement, supplemented by monthly below-the-line audits.
Common mistakes
- Treating Ultra
activityviews or clicks as subscriptions: Browsing the upgrade screen measures marketing curiosity, not paid adoption. - Letting the denominator float during launch month: Dividing by "users active in launch month" penalizes successful reactivation campaigns that bring dormant users back into the denominator.
- Evaluating retention on incomplete windows: Counting subscribers who paid 10 days ago as "churned in Week 2" artificially tanks retention near the end of the month.
- Using fixed clock buckets (
DATE_TRUNC('minute', ...)) for velocity rules: Fraudsters whose 10-transaction script spans12:00:40to12:01:20slip past fixed minute buckets (5per minute) while aRANGE BETWEEN INTERVAL '10 minutes' PRECEDINGwindow catches all10. - Alerting on IP-country mismatch alone or summing duplicate hits: Flagging every traveller swamps analysts with false positives (innocent users flagged as suspicious), and failing to deduplicate
R1orR2per user lets one noisy burst crowd out more dangerous multi-rule patterns. - Calculating recall using only rule-generated alerts: If you only know about fraud that your rules flagged, measured recall is trivially
100%while blind spots stay completely hidden.
Follow-up questions
- Before launch day arrives, how would you calibrate what paid penetration rate qualifies as a commercial win? Partner with Finance and Product before launch to set a break-even and target range using pricing research, unit economics (subscription fees minus expected perk costs per subscriber), and historical benchmarks from earlier paid tiers like Metal. With
400,000active users, the statistical 95% confidence interval (the range likely to contain the true underlying rate) around1.30%is tight — roughly±0.035percentage points — so sampling noise is tiny and the real check is whether1.30%clears the pre-agreed commercial bar and sustains healthy Week-2/3 signup cohorts beyond the day-1 email spike. - How can you quantify whether Ultra subscribers are merely downgrading net revenue by cannibalizing existing paid plans or fee income? Check
transactionsfor prior recurring plan fees (such as Plus or Metalproductcodes) that stop right when a user's Ultra charges begin, and compute net incremental subscription revenue =Ultra fee - discontinued plan fee. For broader fee cannibalization (for example, perks waiving FX or ATM fees that users previously paid), compare the pre-to-post change in total net revenue (subscription fees + transaction fees minus perk costs) between Ultra adopters and matched pre-launch lookalikes, or measure net revenue per user directly inside a randomized promotional holdout (a random subset of eligible users kept out of Ultra marketing). - At what stage should the financial-crime team evolve from fixed SQL point weights to a supervised machine-learning scorer, and how would you roll it out safely? Once manual reviews accumulate several thousand labelled cases, train a gradient-boosted tree or logistic regression model (supervised classifiers that predict fraud probability from features) using both the engineered rule signals and continuous underlying ratios (amount-to-median ratio, 10-minute velocity, account age, distinct IP count). Crucially, include below-the-line audit samples and independently reported chargebacks in training so the model is not blinded by selection bias from training only on users the old rules queued. Keep hard SQL rules alongside the model for regulatory explainability and instant blocking of new attack patterns, and verify the model beats the SQL score at equal daily review volume in shadow mode (scoring live traffic silently without altering the queue) before rollout.
Follow-up questions
- Before launch day arrives, how would you calibrate what paid penetration rate qualifies as a commercial win?
- How can you quantify whether Ultra subscribers are merely downgrading net revenue by cannibalizing existing paid plans or fee income?
- At what stage should the financial-crime team evolve from fixed SQL point weights to a supervised machine-learning scorer, and how would you roll it out safely?
Similar questions
- First-Month Metrics for Ultra and Rule-Based FinCrime Scoring
- Thread-Safe Dining Reservation Service Without Overlapping Bookings
- Automated Location-Based Travel Insurance Enrollment
- Global Banking Ledger and Account Sync Across Regions
- Database Isolation, Production Latency Triage, and DDD vs CQRS
- Bounded-Capacity Uniform Random Node Router
More Revolut interview questions
- First-Month Metrics for Ultra and Rule-Based FinCrime Scoring Easy
- Database Isolation, Production Latency Triage, and DDD vs CQRS Medium
- Thread-Safe Dining Reservation Service Without Overlapping Bookings Medium Pro
- Automated Location-Based Travel Insurance Enrollment Medium Pro
- Global Banking Ledger and Account Sync Across Regions Medium Pro
- Bounded-Capacity Uniform Random Node Router Medium Pro
- Deadlock-Free Concurrent Account Ledger Transfers Medium Pro