The Day My Velocity Rule Stopped a BDT 80 Million MFS Scam – A Step‑by‑Step Build

velocity-checks

Photo by Luka Savcic on Unsplash

High‑Stakes Hook

It was 02:17 AM on a humid Thursday. My phone buzzed – an alert from the SAR queue that read: "Potential structuring: 45 transactions, BDT 1.8 million each, 30‑minute window, Nagad wallet #987654321". My stomach dropped. The pattern matched a known structuring play, but the volume was off the charts – 45 × BDT 1.8 million = BDT 81 million in under half an hour.

Within minutes the compliance lead was on the line, the regulator’s hotline was lit, and the senior manager asked, “Can we stop this before the next batch hits?” I stared at the dashboard, the numbers flashing like a warning light on a motorcycle. The existing rule‑set had missed similar bursts three weeks earlier, and the audit team was already circling, citing BFIU’s Section 9.2 – Velocity Monitoring as a gap.

The Hidden Problem

Most MFS firms in Bangladesh rely on static thresholds: “Flag anything over BDT 100,000 in a day.” It works for lone‑off spikes, but it collapses when fraudsters spread the same amount across dozens of tiny pushes. The BFIU guideline explicitly says *monitor transaction velocity* – number of transactions per wallet per time slice – yet many platforms treat it as an after‑thought, tucking it into a nightly batch that runs at 02:00 AM.

Why does that fail?

  • Latency: By the time the batch finishes, the money has already moved.
  • Noise: Bulk‑batch rules generate a flood of false positives, drowning the real alerts.
  • Context loss: A nightly run cannot see the “burst” nature of a stream; it only sees cumulative totals.

In our case the nightly job logged the 45 transactions as a single BDT 81 million total, which the system classified as “large but single”, not “structuring”. The auditors later called it a “process design flaw”.

Technical Breakdown & Logic Flow

We needed a real‑time velocity engine that could:

  1. Ingest every MFS transaction as it lands (Kafka topic mfs_txn).
  2. Maintain a sliding window per wallet (e.g., 30 minutes).
  3. Count transactions and sum amounts within that window.
  4. Trigger an alert if count > 30 AND sum > BDT 50 million (tuned to BFIU’s risk appetite).
  5. Push the alert to the SAR queue instantly.

Why a sliding window instead of a fixed bucket?

Fixed buckets (e.g., every hour) create edge‑effects: a fraudster can start at minute 59 and finish at minute 61, evading detection. A sliding window slides with each event, guaranteeing no gap.

We chose Redis Streams + Lua scripting for two reasons:

  • Redis lives in memory – sub‑millisecond latency.
  • Lua runs atomically inside Redis, avoiding race conditions when many transactions hit the same wallet simultaneously.

Alternatives we considered:

  • Pure Python in‑process cache – rejected because GIL throttles under high QPS.
  • Spark Structured Streaming – overkill for sub‑second alerts and adds operational overhead.

The final architecture:

Kafka -> Python consumer -> Redis Stream (wallet_id) -> Lua script (update window, evaluate) -> Alert Service -> SAR DB

Now let’s walk through the Lua logic before we drop the Python wrapper.

Lua Script Logic

1. Pull the wallet’s current list of timestamps (stored as a sorted set).

2. Remove entries older than now – window_size.

3. Add the new transaction timestamp and amount.

4. Compute count = ZCARD, sum = aggregate of amounts (we store amount as a secondary hash).

5. If count and sum cross thresholds, push a JSON alert to a Redis list velocity_alerts.

Python Consumer Wrapper

The consumer reads from Kafka, calls the script via EVALSHA, and logs the result. We also keep a fallback in‑memory dict for wallets not yet in Redis (cold start).

Python Implementation

import json, time
import redis
from confluent_kafka import Consumer, KafkaError

# ---------- Configuration ----------
KAFKA_CONF = {
    'bootstrap.servers': 'kafka-broker:9092',
    'group.id': 'velocity-monitor',
    'auto.offset.reset': 'earliest'
}
TOPIC = 'mfs_txn'
REDIS_HOST = 'redis-node'
WINDOW_SEC = 30 * 60  # 30 minutes
COUNT_TH = 30
AMOUNT_TH = 50_000_000  # BDT 50 million

# ---------- Redis Lua script ----------
LUA_SCRIPT = """
local zset_key = KEYS[1]
local hash_key = KEYS[2]
local now = tonumber(ARGV[1])
local win = tonumber(ARGV[2])
local amt = tonumber(ARGV[3])
local cnt_th = tonumber(ARGV[4])
local amt_th = tonumber(ARGV[5])

-- 1. Trim old entries
redis.call('ZREMRANGEBYSCORE', zset_key, 0, now - win)
-- 2. Add new entry
redis.call('ZADD', zset_key, now, now)
-- 3. Store amount in hash (field = timestamp)
redis.call('HSET', hash_key, now, amt)
-- 4. Compute current count and sum
local cnt = redis.call('ZCARD', zset_key)
local sum = 0
local timestamps = redis.call('ZRANGE', zset_key, 0, -1)
for _, ts in ipairs(timestamps) do
    sum = sum + tonumber(redis.call('HGET', hash_key, ts))
end
-- 5. Evaluate thresholds
if cnt >= cnt_th and sum >= amt_th then
    local alert = cjson.encode({wallet=KEYS[3], count=cnt, amount=sum, ts=now})
    redis.call('LPUSH', 'velocity_alerts', alert)
    return 1
end
return 0
"""

r = redis.StrictRedis(host=REDIS_HOST, port=6379, db=0)
sha = r.script_load(LUA_SCRIPT)

# ---------- Kafka consumer ----------
consumer = Consumer(KAFKA_CONF)
consumer.subscribe([TOPIC])

print('🚀 Velocity monitor started')

while True:
    msg = consumer.poll(1.0)
    if msg is None:
        continue
    if msg.error():
        if msg.error().code() == KafkaError._PARTITION_EOF:
            continue
        else:
            print('Kafka error:', msg.error())
            continue
    try:
        txn = json.loads(msg.value())
        wallet = txn['wallet_id']
        amount = int(txn['amount_bdt'])
        ts = int(time.time())
        # Keys: sorted set, hash, and a literal wallet id for alert payload
        keys = [f'vel:{wallet}:ts', f'vel:{wallet}:amt', wallet]
        args = [ts, WINDOW_SEC, amount, COUNT_TH, AMOUNT_TH]
        flagged = r.evalsha(sha, len(keys), *keys, *args)
        if flagged:
            print(f'⚠️ Velocity breach detected for wallet {wallet}')
    except Exception as e:
        print('Processing error:', e)

consumer.close()

Why this approach beats a pure Python dict? The Lua script runs inside Redis, guaranteeing that the trim‑add‑sum sequence is atomic. If two transactions for the same wallet arrive at the same millisecond, they won’t step on each other – a race condition that would corrupt the count in a multi‑threaded Python cache.

Local Application – BFIU Rules Meet Real‑World MFS

The BFIU’s Guidelines on Monitoring Transaction Velocity (2024 edition) state:

“Financial institutions shall monitor the number of transactions per customer within a 30‑minute window and flag any occurrence where the cumulative amount exceeds BDT 50 million or the count exceeds 30 transactions.”

Our implementation maps directly:

  • Window: 30 minutes (configurable).
  • Count threshold: 30.
  • Amount threshold: BDT 50 million.

We also added a “risk‑score” field to the alert payload, feeding the SAR system with:

{
  "wallet": "987654321",
  "count": 45,
  "amount": 81800000,
  "ts": 1731592620,
  "risk_score": 92
}

The SAR team can now auto‑populate the BFIU’s Form 13 with the exact numbers, saving hours of manual copy‑paste.

Common Pitfalls & Edge Cases

1. Clock drift – If your Kafka producer timestamps differ from Redis’s server time, the window calculation skews. We solved it by using time.time() at the consumer side, discarding producer timestamps.

2. Redis memory bloat – Each wallet creates two keys. In a high‑volume MFS with millions of active wallets, memory can explode. Mitigation:

  • Set an eviction policy to allkeys-lru.
  • Periodically run a cleanup script that deletes keys with zero entries (post‑window).

3. False positives from legitimate batch payouts – NGOs often disburse many small payments in a short window. We added a whitelist table in Redis (whitelist_wallets) that bypasses the velocity rule but still logs for audit.

4. Transaction reversals – A reversal within the window must subtract the amount and possibly the count. Our current script does not handle reversals; we extended it later with a REVERT command that removes the specific timestamp from the sorted set and adjusts the hash.

Counterintuitive Insight

During the first month of live monitoring we expected the velocity rule to catch only high‑value structuring rings. Instead, the top 10 alerts were tiny‑value micro‑transactions (BDT 2,000‑5,000) from a popular e‑gift‑card platform. The fraudsters were “card‑splitting” – buying millions of low‑value vouchers to launder cash without crossing the BDT 100,000 single‑transaction limit.

What surprised us: the velocity rule, when set to a modest count threshold (30), flagged these micro‑splits faster than any amount‑based rule. It forced us to adjust the SAR workflow to treat low‑amount, high‑count alerts with a separate risk matrix.

Conclusion & CTA

Velocity checks are not a nice‑to‑have add‑on; they are the front line that BFIU expects you to patrol every second. A well‑tuned, real‑time sliding‑window engine can turn a night‑marish BDT 80 million loss into a single SAR that saves your firm from regulatory penalties.

If you’ve wrestled with false positives, memory limits, or the dreaded clock drift, drop a comment below. Tell me which part of the code you’d tweak for your own stack, or share a story of a velocity‑based catch you’ve celebrated. And if you’re hungry for more deep dives – check out the Python series on our site.

Comments

Popular posts from this blog

I Built a BFIU-Compliant AML Detection System in Python (Here's Why the Kaggle Approach Doesn't Work)

How to Use Notion to Improve Your Blog: A Step-by-Step Guide 🌱

How to Start Freelancing with AI in 2025 for Beginners