developer

Custom Fraud & Velocity Engines: Protecting Gateways from Mass Abuse

How to engineer high-performance fraud detection, sliding-window velocity limiters, and bot mitigation engines using Redis and Lua for payment platforms.

GS Gaurav Sharma Fintech Architect & Systems Engineer 3 min read
Custom Fraud & Velocity Engines: Protecting Gateways from Mass Abuse guide
fraud detection system payment gateway velocity shield rate limiting prevent carding upi abuse redis lua rate limit fintech cybersecurity

Every public payment endpoint is an attractive target for automated botnets, credential testing rings, and malicious actors seeking to test illicit accounts. Without rigorous, real-time velocity shields and heuristic fraud engines, a payment gateway can suffer API exhaustion, bank sanctions, or severe financial exposure within minutes.

Engineering an in-memory, sub-millisecond fraud detection engine protects your payment switch from abuse while ensuring legitimate customers experience zero checkout friction.


The Anatomy of Fintech Abuse

Malicious actors exploit payment gateways through several distinct attack patterns:

  1. Carding & Micro-Probing: Running thousands of automated ₹1 or ₹5 transactions per hour to identify active bank accounts or stolen debit card credentials.
  2. Dynamic QR Flooding: Generating millions of unpaid checkout intent strings to exhaust server memory and trigger database lock contention.
  3. Mule Account Rotating: Rapidly dispersing illicit funds across dozens of unique Virtual Payment Addresses (VPAs) before banks can flag the originating accounts.
  4. Scraping & Price Tampering: Modifying client-side checkout payloads to pay below the required transaction threshold.

Architecting a Real-Time Velocity Engine

A payment fraud engine must operate inline with transaction authorization. Because introducing more than 25ms of latency directly harms conversion rates, all behavioral and velocity checks must execute entirely within in-memory data structures.

Incoming Request -> [WAF / Edge Cloudflare Filter]
                            |
                            v
               [Fastify API Gateway Node]
                            |
                            v
         +-------------------------------------+
         | Redis Lua Sliding-Window Evaluator  |
         | - IP Velocity (Max 10 req / 60s)    |
         | - VPA Velocity (Max 3 req / 60s)    |
         | - Amount Anomaly Check              |
         +------------------+------------------+
                            |
               [Velocity Violation Detected?]
                           / \
                         YES  NO
                         /     \
                        v       v
           [429 Quarantined]   [Forward to Core Payment Switch]

Leaky Bucket vs Sliding Window Algorithms

Traditional fixed-window rate limiters create critical vulnerabilities: an attacker permitted 60 requests per minute could fire 60 requests at 11:59:59 and another 60 requests at 12:00:01, resulting in 120 requests within 2 seconds.

A Sliding Window Log algorithm prevents this by storing Unix timestamps in a Redis Sorted Set (ZSET), pruning records older than the sliding threshold (now - windowSize), and rejecting requests when cardinality exceeds the limit.


Fingerprinting & Bot Mitigation Strategies

Beyond simple IP addresses, modern fraud engines synthesize multiple hardware and networking signals to generate a unique Device Risk Hash:

  • TCP/IP Fingerprint: Inspecting TLS ciphers, MTU sizes, and HTTP/2 framing characteristics.
  • Headless Browser Detection: Checking for automated WebDriver flags, missing Canvas rendering contexts, and non-standard user-agent headers.
  • ASN & Geo-Anomaly: Flagging requests originating from commercial data center IP ranges (AWS, DigitalOcean, OVH) attempting customer checkout actions.

Redis Lua Scripts for Sub-Millisecond Checks

By compiling the evaluation logic into an atomic Lua script, Redis executes the sliding window check, updates transaction counters, and sets expiration TTLs in a single memory operation:

-- sliding_window_velocity.lua
-- KEYS[1]: Redis key (e.g., velocity:ip:192.168.1.50)
-- ARGV[1]: Current Unix Timestamp (milliseconds)
-- ARGV[2]: Window Size (milliseconds, e.g., 60000 for 1 minute)
-- ARGV[3]: Maximum Allowed Requests in Window (e.g., 10)

local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local clearBefore = now - window

-- 1. Remove timestamps older than the sliding window
redis.call('ZREMRANGEBYSCORE', key, '-inf', clearBefore)

-- 2. Count requests in the current active window
local currentRequests = redis.call('ZCARD', key)

if currentRequests < limit then
    -- Add current request timestamp
    redis.call('ZADD', key, now, now)
    -- Set key expiration to prevent orphan memory leaks
    redis.call('PEXPIRE', key, window)
    return 1 -- APPROVED
else
    return 0 -- REJECTED_VELOCITY_BREACH
end

Automated Quarantine and Circuit Breakers

When an IP address or VPA triggers multiple velocity alerts:

  1. Dynamic Blacklist: The entity is automatically moved to a Redis Bloom filter, immediately rejecting subsequent calls at the reverse proxy layer for 24 hours.
  2. Webhook Notification: Internal alerting triggers a high-priority Slack or PagerDuty incident.
  3. Graceful Degradation: If an upstream banking partner experiences abnormal error spikes (> 15%), an automated circuit breaker temporarily halts traffic to that provider and routes to a backup switch.

Deploying a custom-engineered velocity engine provides proactive immunity against botnets and malicious testing, safeguarding your payment infrastructure and preserving platform uptime.

Direct answers

Frequently asked questions

Why do fraudsters target UPI payment gateways with automated micro-transactions?
Syndicates use automated scripts on open payment gateways to validate lists of stolen bank credentials, test mule accounts, or spam merchant settlement portals to trigger denial-of-service conditions or exhaust API credit lines.
How does a sliding-window velocity limiter differ from a simple fixed-window counter?
Fixed-window counters reset at rigid boundary intervals (e.g., top of the minute), allowing attackers to burst double the traffic across the boundary seam. Sliding-window algorithms evaluate timestamped entries in real time, delivering smooth, tamper-proof rate limiting.
Why execute velocity rules inside Redis using Lua scripts instead of application logic?
Executing checks in Lua scripts directly inside Redis ensures atomic execution without network round trips between database queries. This eliminates race conditions during multi-threaded bursts and resolves velocity checks in under 0.8 milliseconds.

Build your payment flow

Explore the API and browser-only merchant tools.

Create UPI checkout orders, verify signed events, or test the free calculators and generators without exposing credentials.