ClearStaq
Log inBook a DemoFree Trial — 50 Docs

True revenue, positions, and 27 fraud signals included. No credit card.

API/Technical

Building Custom Fraud Rules with ClearStaq's Machine Learning Pipeline

ClearStaq TeamEngineering Team
September 2, 2026Updated August 21, 2026
19 min read
Share:
Building Custom Fraud Rules with ClearStaq's Machine Learning Pipeline

Custom fraud rules for machine learning fraud detection are built by configuring signal weights, defining rule logic, and combining ML scores with rule outcomes in a hybrid pipeline deployed via API. ClearStaq's pipeline provides 27 pre-built fraud signals, sandbox testing, webhook alerting, and sub-3-second scoring — purpose-built for bank statement and lending workflows.

What you'll learn

  • A hybrid architecture — rules as guardrails, ML as the primary scoring engine — outperforms either approach alone for bank statement and lending fraud detection
  • ClearStaq's 27 fraud signals span document-level, cash flow, and behavioral categories, each configurable with individual weights ranging from 0.0 to 1.0
  • Custom rule logic is defined via the /fraud/rules API endpoint using JSON payloads with AND/OR/NOT boolean conditions, priority integers, and APPROVE/REVIEW/DECLINE/ESCALATE outcomes
  • Shadow mode lets new rules run in observation-only mode alongside live rules, enabling safe validation before production promotion
  • Merchant-category-specific rulesets reduce false positives for seasonal businesses, gig workers, and cash-heavy restaurants without loosening thresholds portfolio-wide

Custom fraud rules for machine learning fraud detection are built by configuring signal weights, defining rule logic, combining ML scores with rule outcomes in a hybrid pipeline, and deploying via API. ClearStaq's pipeline provides 27 pre-built fraud signals, sandbox testing, webhook alerting, and sub-3-second scoring — purpose-built for bank statement and lending workflows.

Why Custom Fraud Rules Beat One-Size-Fits-All Detection

Generic fraud models are trained on payment and e-commerce data. They weren't built for bank statement fraud, document fabrication, or the cash flow patterns that define MCA and fintech lending risk. When you deploy them in a lending context, they're essentially guessing.

According to the ACFE's fraud statistics, financial institutions lose a median of $125,000 per fraud incident — and lending fraud is among the fastest-growing categories. The stakes of miscalibrated fraud detection are directly financial. For context on how widespread the problem has become, see our 2026 bank statement fraud data report.

Custom rules solve the root problem: they let you encode your institution's actual risk knowledge into the detection pipeline instead of accepting vendor defaults calibrated for someone else's portfolio.

The Cost of Getting Fraud Detection Wrong

Fraud detection errors fall into two costly categories. False negatives — fraud that passes through undetected — directly destroy capital. A fabricated bank statement that clears your review process means real money leaving on a loan that was never going to be repaid.

False positives — legitimate applications that get declined — are equally damaging. They erode conversion rates, generate underwriter rework, and damage your reputation with brokers who route deals elsewhere. Manual review queues clog when your model is miscalibrated, adding hours or days to decisioning timelines.

The FDIC's data on bank failures consistently shows lending fraud exposure as a contributing factor. Getting detection right isn't a technical nicety — it's a capital preservation priority.

What Custom Rules Actually Unlock

Custom fraud rules allow you to do things generic models can't:

  • Merchant-specific thresholds: A seasonal restaurant legitimately shows erratic deposit patterns in January. Custom rules let you calibrate NSF tolerance differently for that merchant category. See our guide to seasonal restaurant revenue underwriting for the full context.
  • Signal weighting that reflects your portfolio: If your fraud loss data shows document fabrication accounts for 60% of losses, you can upweight metadata anomaly signals accordingly.
  • Audit-trail explainability: Compliance teams and underwriters can see exactly which conditions triggered which outcome — not just a black-box score.
  • Fast iteration: A rule update deploys in minutes. Retraining a full ML model takes days or weeks. Custom rules let you respond to new fraud patterns immediately.

Rule-Based vs Machine Learning Fraud Detection: Choosing the Right Foundation

Before building custom fraud rules, you need to understand what each detection approach actually does — and why neither works optimally on its own for document fraud in lending.

Rule-based detection is deterministic: explicit conditions produce explicit outcomes. "If NSF count exceeds 8 in 90 days, decline." The logic is transparent, immediately auditable, and fast to update. The limitation is that rules only catch what you've anticipated.

Machine learning detection is probabilistic: statistical models trained on labeled examples learn to recognize fraud patterns across dozens of signals simultaneously. ML catches novel fraud patterns that no one wrote a rule for yet. The tradeoff is that ML scores are harder to explain to regulators or borrowers without additional tooling.

The research on 27 fraud signals in bank statement analysis shows why ML's ability to aggregate weak signals matters: no single signal reliably distinguishes fraud from legitimate activity. It's the combination of signals — and how they interact — that creates a reliable composite score.

When Rule-Based Logic Wins

Rules outperform ML in specific scenarios:

  • Regulatory hard stops: Some thresholds are non-negotiable regardless of ML score. If NSF count exceeds your regulatory ceiling, you decline. Period.
  • Known fraud signatures: When a specific, deterministic pattern is definitively associated with fraud, a rule is faster and more reliable than a probability score.
  • Mandatory explainability: Adverse action notices require specific, articulable reasons. Rule outcomes provide those; ML scores alone don't.
  • Rapid response to emerging fraud: When a new fraud pattern is identified, a rule can block it within minutes while you wait for enough labeled data to retrain an ML model.

When Machine Learning Wins

ML outperforms rules when:

  • Fraud patterns don't have explicit deterministic signatures — the signals are weak individually but collectively predictive
  • You're combining dozens of signals into a composite risk score that no rule set could replicate
  • Fraudster behavior is evolving and you need a model that adapts to new patterns over time
  • Your fraud dataset is large enough to train on — ensemble methods like gradient boosting (see scikit-learn's ensemble documentation) excel at fraud classification problems with class imbalance

The Hybrid Architecture: Best of Both

The optimal architecture for bank statement and lending fraud uses rules as guardrails and ML as the primary scoring engine. Rules handle what they're best at — hard stops, regulatory limits, deterministic known patterns. ML handles the rest.

In a hybrid pipeline, rules can operate in three modes relative to the ML score:

  1. Pre-score rules: Rules evaluate first. If a hard-block rule fires, the document is declined before ML scoring even runs — saving compute and ensuring regulatory compliance.
  2. Post-score rules: ML scoring runs first; rules then gate on the score. "If ml_score > 85, decline regardless of rule outcome."
  3. Parallel rules: Both run simultaneously; the final outcome is determined by escalation logic when results conflict.

The key concept here is the precision-recall tradeoff: tightening rules increases fraud catch rate (recall) but also increases false positives (lower precision). Custom hybrid configurations let you tune this tradeoff per merchant category or risk tier rather than accepting a single portfolio-wide setting.

ClearStaq's ML Pipeline Architecture: How It Works

ClearStaq's fraud detection pipeline executes in a defined sequence: document ingestion → parsing → signal extraction → ML scoring → rule evaluation → outcome. Every stage is configurable, and every evaluation is logged for compliance review.

The pipeline supports 900+ bank formats, which means your custom rules apply consistently across the full document corpus — not just the banks your parser happens to support well. This breadth matters because fraudsters don't limit themselves to major banks. For a full overview of how documents move through automated processing, see the bank statement processing pipeline documentation.

The ClearStaq API platform exposes every stage of this pipeline as a configurable endpoint, giving engineering teams full programmatic control over detection logic without building or maintaining an ML infrastructure of their own.

ClearStaq Document Parser
statement_jan_mar.pdf
2.4 MB • 12 pages
output.json
Supported Banks:
ChaseBank of AmericaWells FargoCapital OneCitiUS BankPNC+893 more
47 transactions2.1s parse time99.7% accuracy

The Three Signal Categories

ClearStaq's 27 fraud signals fall into three categories, each targeting a different fraud vector:

Category Signals Primary Fraud Vector
Document-level PDF metadata anomalies, font inconsistency, alteration artifacts, creation timestamp mismatches Bank statement fabrication and tampering
Cash flow NSF frequency, round-dollar deposits, balance trajectory, velocity spikes, income smoothing patterns Revenue inflation, balance manipulation
Behavioral Deposit regularity, merchant diversity, transaction timing patterns, stacking indicators Identity fraud, MCA stacking, synthetic business patterns

Document-level signals are particularly powerful for catching fabricated statements. For a deep dive into how metadata flags document manipulation, see our PDF metadata analysis guide.

How Rule Outcomes and ML Scores Interact

ClearStaq supports three execution modes, set via the fraud_mode parameter:

  • rules_only: Pure deterministic evaluation, no ML scoring
  • ml_only: Pure ML composite score, no rule evaluation
  • hybrid: Both run; outcome determined by escalation logic

Rule outcomes are one of four values: APPROVE, REVIEW, DECLINE, or ESCALATE. ML scores range from 0–100, with thresholds configurable per rule set. A single API call returns both the composite ML score and the complete rule evaluation trace — everything you need for underwriter review or adverse action documentation.

Step 1: Authenticate and Configure Your API Environment

For a full walkthrough of environment setup, see the ClearStaq API authentication and setup guide. Here's the core configuration pattern:

Generate your API key from the ClearStaq dashboard and set it as an environment variable. Authentication uses a bearer token in the request header:

# curl
curl -X GET https://api.clearstaq.com/v1/fraud/config \
  -H "Authorization: Bearer $CLEARSTAQ_API_KEY" \
  -H "Content-Type: application/json"

# Python
import requests

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.get(
    "https://api.clearstaq.com/v1/fraud/config",
    headers=headers
)

You can set a default fraud ruleset at the account level via the dashboard, or override it per request using the ruleset_id parameter in your API payload. Per-request overrides are useful when processing applications from different merchant categories that require different detection profiles.

Sandbox vs Production Configuration

The sandbox environment uses synthetic bank statement test fixtures covering clean, low-fraud, mid-fraud, and high-fraud scenarios. All custom rule configurations are isolated per environment — changes in sandbox don't affect production until you explicitly promote them.

To target the sandbox, use the sandbox base URL:

https://sandbox.api.clearstaq.com/v1/

Production promotion is a single API call to the /fraud/rules/promote endpoint, which copies a named rule configuration from sandbox to production with a confirmation step. Rate limits differ between environments — sandbox is throttled more aggressively to prevent abuse. For high-volume testing scenarios, see API rate optimization for high-volume processing.

Step 2: Define Your Custom Fraud Signal Weights

Signal weights control how much each of the 27 signals contributes to the composite ML score. Weights range from 0.0 (signal disabled entirely) to 1.0 (maximum contribution). The pipeline normalizes weights across all active signals, so upweighting one signal proportionally reduces the influence of others.

Retrieve your current signal weights and update them via the /fraud/config endpoint:

POST https://api.clearstaq.com/v1/fraud/config

{
  "signal_weights": {
    // Document-level signals
    "metadata_anomaly": 0.9,          // High weight: catches fabricated PDFs
    "font_inconsistency": 0.85,       // High weight: common in edited statements
    "alteration_artifact": 0.95,      // Highest weight: direct evidence of tampering

    // Cash flow signals
    "nsf_frequency": 0.8,             // Strong indicator of cash flow distress
    "round_dollar_deposits": 0.6,     // Moderate: context-dependent
    "balance_trajectory": 0.7,        // Downward trend signals distress
    "velocity_spike": 0.65,           // Sudden deposit surges

    // Behavioral signals
    "deposit_regularity": 0.5,        // Lower for volatile income profiles
    "stacking_indicator": 0.85,       // High for MCA lenders
    "merchant_diversity": 0.4         // Lower weight, supporting signal
  }
}

For guidance on round-dollar deposit fraud signals and when to weight them up or down, see our dedicated analysis. For MCA lenders specifically, NSF pattern detection is typically the highest-value signal to upweight.

ClearStaq Fraud Detection
ParsingExtractingFraud DetectionIncome
0HIGH RISK
Fraud Risk Score
Duplicate deposit detectedCRITICAL
Account number mismatchHIGH
Inconsistent balance historyHIGH
Unusual transaction patternMEDIUM
This statement would have been flagged for manual review
4 fraud signals detected • Automated rejection recommended

Recommended Signal Weight Profiles by Lender Type

Different lending contexts call for different signal emphasis. Here are three baseline profiles to start from:

Lender Type Upweight Downweight Rationale
MCA lender nsf_frequency, stacking_indicator, daily_balance_variance deposit_regularity MCA fraud centers on cash flow misrepresentation and stacking; irregular deposits are normal for small businesses
Fintech personal loan metadata_anomaly, font_inconsistency, income_regularity merchant_diversity Document fabrication is the primary vector; income consistency matters more than spending diversity
Gig / contractor metadata_anomaly, alteration_artifact nsf_frequency, income_volatility Gig income is legitimately volatile; document integrity is the more reliable fraud signal

Export your finalized signal weight configuration as a versioned JSON file and store it in your application's Git repository alongside your API integration code. This gives you a full audit trail of configuration changes over time — a requirement for SOC2 compliance.

Disabling Signals for Specific Use Cases

Setting a signal weight to 0.0 removes it from the composite score entirely. This is appropriate when a signal systematically over-triggers on a legitimate applicant profile:

  • Seasonal businesses: Disable or heavily downweight seasonal_deposit_irregularity during predictable off-season periods. A ski resort with near-zero deposits in July isn't committing fraud.
  • Crypto-active businesses: Round-dollar transactions are common in crypto accounting workflows. Adjust round_dollar_deposits weight down for borrowers with visible crypto exchange transactions.
  • Cash-heavy restaurants: Daily cash deposit aggregation often produces round-dollar amounts legitimately. Calibrate threshold up before disabling the signal entirely.

Always document signal disables in your rule audit log with a business justification. This documentation protects you during compliance reviews and helps future team members understand why a configuration decision was made.

Step 3: Build and Deploy Custom Rule Logic

Rules are created, updated, and deleted via the /fraud/rules endpoint. Each rule has three required components: conditions, an outcome, and a priority integer.

Rule anatomy:

  • Conditions: Signal thresholds combined with boolean logic (AND / OR / NOT)
  • Outcome: One of APPROVE, REVIEW, DECLINE, or ESCALATE
  • Priority: Integer where lower values evaluate first (1 = highest priority)

When conflicting rules fire, the rule with the lowest priority integer wins. DECLINE outcomes always override APPROVE outcomes from lower-priority rules regardless of priority setting — safety takes precedence.

Example: Building an NSF Hard-Block Rule

This rule declines any application where NSF count exceeds 8 over a 90-day statement period — a non-negotiable hard stop that runs before ML scoring:

POST https://api.clearstaq.com/v1/fraud/rules

{
  "rule_id": "nsf_hard_block_90d",
  "name": "NSF Hard Block — 90 Day Statement",
  "priority": 1,
  "conditions": {
    "AND": [
      { "signal": "nsf_count", "operator": "gt", "value": 8 },
      { "signal": "statement_period_days", "operator": "eq", "value": 90 }
    ]
  },
  "outcome": "DECLINE",
  "reason_code": "NSF_THRESHOLD_EXCEEDED",
  "active": true
}

// API Response
{
  "rule_id": "nsf_hard_block_90d",
  "status": "active",
  "created_at": "2026-03-15T14:22:00Z",
  "environment": "sandbox"
}

Example: Building a Document Integrity Review Rule

This rule escalates applications where document-level signals suggest tampering, routing them to human review before any credit decision:

POST https://api.clearstaq.com/v1/fraud/rules

{
  "rule_id": "doc_integrity_escalate",
  "name": "Document Integrity — Escalate to Review",
  "priority": 2,
  "conditions": {
    "OR": [
      { "signal": "metadata_anomaly_score", "operator": "gt", "value": 0.7 },
      { "signal": "font_inconsistency_detected", "operator": "eq", "value": true }
    ]
  },
  "outcome": "ESCALATE",
  "reason_code": "DOCUMENT_INTEGRITY_FLAG",
  "active": true
}

The ESCALATE outcome doesn't end decisioning — it routes the application to a human review queue. Your downstream system can consume this via webhook (covered in Step 6) and assign it to an underwriter automatically.

Boolean Logic and Nested Conditions

ClearStaq's rule condition syntax supports three logical operators:

  • AND: All conditions must be true for the outcome to trigger
  • OR: Any single condition triggers the outcome
  • NOT: Inverts a condition — useful for allowlisting specific patterns

Conditions can be nested to create complex logic. For example, you can combine an OR block inside an AND block to express "signal A must exceed threshold AND (signal B or signal C must be present)." Nesting depth is capped at 5 levels. Deeply nested rules evaluate slower at scale — keep critical high-priority rules simple and reserve complex logic for lower-priority secondary rules.

Step 4: Combine ML Scores with Rule Outcomes (Hybrid Mode)

Hybrid mode is where the full power of ClearStaq's pipeline becomes available. Enable it by setting fraud_mode: "hybrid" in your API request payload.

In hybrid mode, ML scoring and rule evaluation both run within the same API call. The final outcome follows escalation logic: the most severe outcome from either system wins. A DECLINE from a rule overrides an APPROVE from the ML score. An ESCALATE from the ML score escalates even if a rule would APPROVE.

POST https://api.clearstaq.com/v1/analyze

{
  "document_id": "stmt_abc123",
  "ruleset_id": "mca_standard_v2",
  "fraud_mode": "hybrid",
  "ml_thresholds": {
    "approve_below": 40,
    "review_between": [40, 75],
    "decline_above": 75
  }
}

// API Response
{
  "document_id": "stmt_abc123",
  "ml_score": 68,
  "ml_outcome": "REVIEW",
  "rule_outcome": "APPROVE",
  "final_outcome": "REVIEW",          // ML outcome wins (more conservative)
  "signal_breakdown": {
    "nsf_frequency": 0.72,
    "round_dollar_deposits": 0.31,
    "metadata_anomaly": 0.12,
    "balance_trajectory": 0.65
  },
  "rule_trace": [
    {
      "rule_id": "nsf_hard_block_90d",
      "evaluated": true,
      "triggered": false,
      "reason": "nsf_count (4) did not exceed threshold (8)"
    },
    {
      "rule_id": "doc_integrity_escalate",
      "evaluated": true,
      "triggered": false,
      "reason": "metadata_anomaly_score (0.12) below threshold (0.7)"
    }
  ],
  "processing_time_ms": 1847
}

Yes — you can absolutely combine rule-based and machine learning fraud detection in a single pipeline. The hybrid mode API call shown above is the standard production pattern for ClearStaq integrations.

Ready to Build Your First Hybrid Fraud Rule?

Explore the ClearStaq API docs and run your first custom rule configuration in the sandbox — no infrastructure required. Start testing in minutes with pre-loaded synthetic bank statement fixtures.

Configuring Score Thresholds Per Risk Tier

ML score thresholds should reflect your portfolio's actual risk tolerance, not a generic industry default. ClearStaq lets you define thresholds per risk tier and assign merchant categories to each tier:

Risk Tier APPROVE (ml_score below) REVIEW (range) DECLINE (ml_score above)
Low-risk portfolio < 40 40–70 > 70
Standard portfolio < 35 35–75 > 75
High-risk portfolio < 30 30–60 > 60

Adjust tiers dynamically using the /fraud/config/tiers endpoint. This is particularly useful when your portfolio mix shifts — for example, if you begin accepting more gig worker applications and need to loosen income volatility thresholds without changing your document integrity rules.

Audit Trail and Explainability in Hybrid Mode

Every hybrid mode response includes two explainability fields. The signal_breakdown object shows the individual score for each signal that fired — exactly what you need for underwriter review or to construct an adverse action notice. The rule_trace array shows every rule that evaluated, whether it triggered, and the reason it did or didn't.

This audit trail is retained in ClearStaq's SOC2-compliant logging infrastructure. For teams building monitoring interfaces, these fields can be surfaced directly in a fraud detection dashboard to give underwriters real-time visibility into decisioning logic.

Step 5: Test in Sandbox Before Going Live

ClearStaq's sandbox environment includes pre-loaded test fixtures across four fraud severity bands: clean, low-fraud, mid-fraud, and high-fraud. Each fixture is a synthetic bank statement designed to trigger predictable signal patterns, allowing you to validate rule behavior against known expected outcomes before a real application ever touches your configuration.

Submit a test statement and check whether your rules produce the expected outcome:

POST https://sandbox.api.clearstaq.com/v1/analyze

{
  "document_id": "test_fixture_high_fraud_001",
  "ruleset_id": "mca_standard_v2",
  "fraud_mode": "hybrid"
}

Compare the final_outcome and rule_trace in the response against your expected result. If a high-fraud fixture is returning APPROVE, your rules need tightening. If a clean fixture is returning REVIEW, you have a false positive problem to address before going live.

Interpreting Sandbox Test Results

Three metrics matter most when reviewing sandbox test results:

  1. True positive rate (recall): What percentage of the fraud fixtures did your rules correctly catch? Target > 90% before promoting to production.
  2. False positive rate: What percentage of clean fixtures triggered REVIEW or DECLINE? Keep this below 5% for most lending portfolios.
  3. REVIEW queue volume: What percentage of all fixtures landed in REVIEW? A high REVIEW rate means underwriters will be overwhelmed — tighten your DECLINE thresholds or loosen your REVIEW triggers.

When a rule is triggering too broadly, look at the signal_breakdown in false positive responses. Identify which signal is causing the over-trigger and adjust that signal's weight or the rule's threshold value.

Shadow Mode Implementation Steps

Shadow mode lets new rules run in observation-only mode alongside your existing production rules. Shadow mode logs outcomes without affecting live decisioning — you can see what would have happened without any risk.

Enable shadow mode in your rule configuration payload:

POST https://api.clearstaq.com/v1/fraud/rules

{
  "rule_id": "new_stacking_rule_v3",
  "shadow_mode": true,
  "priority": 3,
  "conditions": {
    "AND": [
      { "signal": "stacking_indicator_score", "operator": "gt", "value": 0.6 },
      { "signal": "active_mca_count", "operator": "gt", "value": 2 }
    ]
  },
  "outcome": "ESCALATE",
  "reason_code": "STACKING_DETECTED"
}

Pull shadow mode comparison reports via the /fraud/rules/shadow-report endpoint. The report shows how often the shadow rule would have overridden the live outcome — and in which direction. Before promoting a shadow rule to active, validate that its DECLINE confirmation rate (cases where a human reviewer agreed with the DECLINE) exceeds 70% and its false positive rate is below your portfolio threshold.

Step 6: Set Up Real-Time Alerts with Webhooks

Custom rule outcomes become more powerful when they trigger immediate downstream action. ClearStaq's webhook integration, covered in depth in our guide to real-time fraud alerts via webhooks, lets you route DECLINE and ESCALATE outcomes to Slack, PagerDuty, or your internal decisioning system within seconds of a document being analyzed.

Register a webhook endpoint via the /webhooks/register endpoint:

POST https://api.clearstaq.com/v1/webhooks/register

{
  "endpoint_url": "https://your-system.com/webhooks/fraud-alerts",
  "events": ["fraud.rule.triggered"],
  "filter_outcomes": ["DECLINE", "ESCALATE"],   // Only fire on these outcomes
  "secret": "your_hmac_signing_secret"
}

Filtering webhooks to fire only on DECLINE and ESCALATE outcomes keeps alert volume manageable. An APPROVE outcome doesn't need immediate human attention — a fraud flag does.

Webhook Payload Example and Parsing

Here's an annotated example of the webhook payload delivered to your endpoint on a DECLINE outcome:

{
  "event": "fraud.rule.triggered",
  "idempotency_key": "evt_7f3a9b2c",     // Use this to prevent duplicate processing
  "document_id": "stmt_abc123",
  "timestamp": "2026-03-15T14:22:47Z",
  "outcome": "DECLINE",
  "triggered_rule_id": "nsf_hard_block_90d",
  "reason_code": "NSF_THRESHOLD_EXCEEDED",
  "ml_score": 81,
  "signal_breakdown": {
    "nsf_frequency": 0.94,
    "balance_trajectory": 0.78,
    "round_dollar_deposits": 0.22,
    "metadata_anomaly": 0.09
  }
}

A Node.js webhook handler that routes ESCALATE outcomes to a review queue:

const express = require('express');
const crypto = require('crypto');
const app = express();

app.post('/webhooks/fraud-alerts', express.json(), (req, res) => {
  // Verify HMAC signature
  const signature = req.headers['x-clearstaq-signature'];
  const expectedSig = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(JSON.stringify(req.body))
    .digest('hex');

  if (signature !== `sha256=${expectedSig}`) {
    return res.status(401).send('Invalid signature');
  }

  const { idempotency_key, outcome, document_id, ml_score, signal_breakdown } = req.body;

  // Prevent duplicate processing
  if (await isAlreadyProcessed(idempotency_key)) {
    return res.status(200).send('Duplicate — already processed');
  }

  if (outcome === 'ESCALATE') {
    await routeToReviewQueue({ document_id, ml_score, signal_breakdown });
  }

  res.status(200).send('OK');
});
ClearStaq Real-Time Fraud Alerts
0 alerts in last 30 seconds
Critical
High
Medium
Low

Security Best Practices for Fraud Alert Webhooks

Fraud webhook payloads contain sensitive financial data. Secure your receiving endpoint properly:

  • HMAC-SHA256 signature verification: Verify every incoming payload using the signing secret set during registration (shown in the Node.js example above). Reject any payload with an invalid or missing signature.
  • IP allowlisting: Restrict your webhook endpoint to accept traffic only from ClearStaq's documented delivery IP ranges.
  • TLS 1.2 or higher: Your receiving endpoint must use a valid TLS certificate. ClearStaq will not deliver to HTTP endpoints.
  • Idempotency key processing: Store processed idempotency keys and reject duplicates to prevent replay attacks.

For a comprehensive guide to securing financial API webhooks, including the full OWASP API Security Top 10 checklist applied to webhook endpoints, see our guide on securing webhook endpoints for financial data. The OWASP API Security project is also an essential reference for teams building production fraud alert infrastructure.

Step 7: Monitor, Tune, and Iterate

Custom fraud rules aren't a deploy-and-forget configuration. Fraud patterns shift, your portfolio mix changes, and rules that were well-calibrated six months ago may be producing too many false positives or missing new fraud vectors today.

Pull rule performance data programmatically via the /fraud/metrics endpoint:

GET https://api.clearstaq.com/v1/fraud/metrics?ruleset_id=mca_standard_v2&period=30d

// Response includes:
{
  "fraud_catch_rate": 0.94,
  "false_positive_rate": 0.038,
  "review_queue_volume_pct": 0.18,
  "avg_ml_score_by_outcome": {
    "APPROVE": 24.3,
    "REVIEW": 58.7,
    "DECLINE": 87.2,
    "ESCALATE": 71.4
  },
  "rule_performance": [
    {
      "rule_id": "nsf_hard_block_90d",
      "triggered_count": 142,
      "confirmed_fraud_rate": 0.91
    },
    {
      "rule_id": "doc_integrity_escalate",
      "triggered_count": 67,
      "confirmed_fraud_rate": 0.73
    }
  ]
}

A rule with a high trigger count but a low confirmed fraud rate is producing false positives. A rule with a high confirmed fraud rate but a low trigger count may have a threshold set too conservatively — you're catching fraud when it triggers, but not triggering often enough.

False Positive Tuning by Merchant Risk Profile

Different merchant categories require different calibration approaches:

  • Seasonal businesses: Use date-conditional rule logic to suppress deposit_irregularity signals during predictable off-season months. A business that generates 80% of revenue in three months shouldn't be penalized in January.
  • Gig workers: Reduce income_volatility signal weight; increase metadata_anomaly weight instead. Gig income is legitimately erratic — document tampering is the real risk. See our analysis of income volatility in gig economy bank statements for the full signal profile.
  • Restaurant operators: Cash-heavy businesses produce legitimate round-dollar daily deposits. Calibrate your round_dollar_deposits threshold higher before treating it as a fraud signal. Our guide to restaurant cash flow and deposit patterns covers the specific norms to reference.

Build merchant-category-specific rule sets and assign them at request time using the ruleset_id parameter. This gives you precision tuning for each portfolio segment without cross-contaminating thresholds across categories.

The Business Case ROI of Custom Rules

Custom fraud rules produce measurable financial returns on two dimensions. First, they improve fraud catch rates: lenders using merchant-category-specific rule sets typically see fraud catch rates 15–25 percentage points higher than generic default configurations across 1,000 applications. Second, they reduce manual review volume: tighter DECLINE rules with well-tuned thresholds typically cut REVIEW queue volume by 30–40%, freeing underwriter time for applications that genuinely need human judgment.

The cost of false positives is real and often underestimated. A declined legitimate application represents lost origination revenue, not just a neutral miss. If your average loan size is $50,000 and your false positive rate is 5% across 500 applications per month, you're turning away 25 legitimate deals — a significant revenue impact that custom rule tuning directly addresses.

Common Configuration Patterns for MCA Lenders and Fintechs

The following reference configurations are starting points, not finished products. Every portfolio is different. Use these as baselines and tune from your own fraud loss data.

MCA Lender Reference Configuration

MCA fraud centers on cash flow misrepresentation, balance manipulation, and MCA stacking detection. The reference configuration prioritizes hard stops for the most common MCA fraud vectors:

{
  "ruleset_id": "mca_reference_v1",
  "fraud_mode": "hybrid",
  "ml_thresholds": {
    "approve_below": 35,
    "review_between": [35, 75],
    "decline_above": 75
  },
  "signal_weights": {
    "nsf_frequency": 0.9,
    "stacking_indicator": 0.88,
    "daily_balance_variance": 0.8,
    "metadata_anomaly": 0.75,
    "round_dollar_deposits": 0.55,
    "deposit_regularity": 0.3        // Lower: irregular deposits are normal for SMBs
  },
  "rules": [
    {
      "rule_id": "mca_nsf_hard_block",
      "priority": 1,
      "conditions": {
        "AND": [
          { "signal": "nsf_count", "operator": "gt", "value": 6 },
          { "signal": "statement_period_days", "operator": "eq", "value": 60 }
        ]
      },
      "outcome": "DECLINE",
      "reason_code": "NSF_THRESHOLD_EXCEEDED"
    },
    {
      "rule_id": "mca_stacking_escalate",
      "priority": 2,
      "conditions": {
        "AND": [
          { "signal": "stacking_indicator_score", "operator": "gt", "value": 0.6 }
        ]
      },
      "outcome": "ESCALATE",
      "reason_code": "STACKING_DETECTED"
    }
  ]
}

Fintech Personal Loan Reference Configuration

Fintech personal loan fraud most commonly involves fabricated bank statements submitted to inflate apparent income. Document integrity rules should run at the highest priority. For equipment and trade finance use cases, see our guide to fabricated invoice detection in trade finance — the signal profile is distinct from bank statement fraud.

{
  "ruleset_id": "fintech_personal_loan_v1",
  "fraud_mode": "hybrid",
  "ml_thresholds": {
    "approve_below": 30,
    "review_between": [30, 50],      // Lower REVIEW threshold: surface borderline cases
    "decline_above": 50
  },
  "signal_weights": {
    "metadata_anomaly": 0.92,
    "font_inconsistency": 0.88,
    "alteration_artifact": 0.95,
    "income_regularity": 0.85,
    "nsf_frequency": 0.4             // Lower: less relevant for personal loan fraud profile
  },
  "rules": [
    {
      "rule_id": "doc_integrity_escalate",
      "priority": 1,
      "conditions": {
        "OR": [
          { "signal": "metadata_anomaly_score", "operator": "gt", "value": 0.65 },
          { "signal": "font_inconsistency_detected", "operator": "eq", "value": true }
        ]
      },
      "outcome": "ESCALATE",
      "reason_code": "DOCUMENT_INTEGRITY_FLAG"
    }
  ],
  "webhooks": {
    "filter_outcomes": ["ESCALATE"],
    "routing": "loan_officer_review_queue"
  }
}

Frequently Asked Questions

What is the difference between rule-based and machine learning fraud detection?

Rule-based fraud detection uses explicit, deterministic conditions — for example, "decline if NSF count exceeds 8" — that are auditable and immediately updatable without retraining. Machine learning fraud detection uses statistical models to score risk across dozens of signals simultaneously, catching novel patterns that no pre-written rule would catch. A hybrid approach — rules as guardrails, ML as the primary score — outperforms either method alone for bank statement and lending fraud.

How do you configure custom fraud rules via an API?

Custom fraud rules are configured via the /fraud/rules endpoint using JSON payloads that define conditions (signal thresholds and boolean logic), outcomes (APPROVE, REVIEW, DECLINE, ESCALATE), and priority order. Signal weights are adjusted separately via /fraud/config. Both configurations can be tested in the sandbox environment before promotion to production, and shadow mode lets new rules run in observation-only mode alongside existing live rules.

How do you reduce false positives in ML fraud detection?

False positives are reduced by tuning signal weights down for signals that over-trigger on legitimate profiles — for example, lowering NSF sensitivity for seasonal businesses or reducing income volatility weight for gig workers. Raising ML score thresholds for specific merchant risk tiers, building merchant-category-specific rule sets, and using shadow mode to measure rule impact before live deployment all contribute to false positive reduction without increasing false negatives.

Can you combine rule-based and machine learning fraud detection in a single pipeline?

Yes. ClearStaq's hybrid mode runs both rule evaluation and ML scoring in a single API call. Rules can execute before the ML score (pre-filter), after it (score-gated rules), or in parallel. The API response includes both the composite ML score and a rule_trace showing every rule evaluated and its outcome, providing full auditability alongside ML-powered detection.

What fraud signals should be included in a custom ML pipeline for bank statement analysis?

Bank statement fraud pipelines should include document-level signals (PDF metadata anomalies, font inconsistency, alteration artifacts), cash flow signals (NSF frequency, round-dollar deposit patterns, balance trajectory, velocity spikes), and behavioral signals (deposit regularity, merchant diversity, transaction timing). Optimal signal weights depend on lender type — MCA lenders typically upweight NSF and stacking signals, while fintech lenders prioritize document integrity signals.

How does a fraud rules engine work in machine learning?

A fraud rules engine in a machine learning context operates as a deterministic layer that works alongside a probabilistic ML score. The rules engine evaluates explicit conditions against extracted signal values and produces a defined outcome. In a hybrid architecture, the rules engine can override ML scores (a DECLINE rule always wins), escalate borderline ML scores to human review, or run in parallel with the ML model and apply escalation logic when outcomes conflict. The combined system is both adaptive (ML) and auditable (rules).

Stop Relying on Generic Fraud Thresholds That Weren't Built for Your Portfolio

ClearStaq's custom fraud rule pipeline lets you configure exactly how 27 signals combine into decisions — with sandbox testing today and production deployment tomorrow. Book a demo to see how MCA lenders and fintech teams configure ClearStaq for their specific fraud profiles.

Ready to see it in action?

Start parsing bank statements in minutes.

Frequently Asked Questions

What is the difference between rule-based and machine learning fraud detection?

Rule-based fraud detection uses explicit, deterministic conditions — such as 'decline if NSF count exceeds 8' — that are auditable and immediately updatable without retraining. Machine learning fraud detection uses statistical models to score risk across dozens of signals simultaneously, catching novel patterns that no pre-written rule would catch. A hybrid approach, with rules as guardrails and ML as the primary score, outperforms either method alone for bank statement and lending fraud.

How do you configure custom fraud rules via an API?

Custom fraud rules are configured via the /fraud/rules endpoint using JSON payloads that define conditions (signal thresholds and boolean logic), outcomes (APPROVE, REVIEW, DECLINE, or ESCALATE), and a priority integer. Signal weights are adjusted separately via /fraud/config. Both configurations can be tested in the sandbox environment before promotion to production, and shadow mode allows new rules to run in observation-only mode alongside existing live rules.

How do you reduce false positives in ML fraud detection?

False positives are reduced by tuning signal weights down for signals that over-trigger on legitimate profiles — for example, lowering NSF sensitivity for seasonal businesses or reducing income volatility weight for gig workers. Raising ML score thresholds for specific merchant risk tiers and building merchant-category-specific rulesets allow precision tuning without affecting the broader portfolio.

Can you combine rule-based and machine learning fraud detection in a single pipeline?

Yes. ClearStaq's hybrid mode runs both rule evaluation and ML scoring within a single API call. Rules can execute before the ML score as a pre-filter, after it as score-gated rules, or in parallel. The API response includes both the composite ML score and a rule_trace array showing every rule evaluated and its outcome, providing full auditability alongside ML-powered detection.

What fraud signals should be included in a custom ML pipeline for bank statement analysis?

Bank statement fraud pipelines should include document-level signals such as PDF metadata anomalies, font inconsistency, and alteration artifacts; cash flow signals including NSF frequency, round-dollar deposit patterns, balance trajectory, and velocity spikes; and behavioral signals such as deposit regularity, merchant diversity, and transaction timing. Optimal signal weights depend on lender type — MCA lenders typically upweight NSF and stacking signals, while fintech lenders prioritize document integrity signals.

How does a fraud rules engine work in machine learning?

A fraud rules engine in a machine learning context operates as a deterministic layer alongside a probabilistic ML score. The rules engine evaluates explicit conditions against extracted signal values and produces a defined outcome. In a hybrid architecture, rules can override ML scores — a DECLINE rule always wins — escalate borderline ML scores to human review, or run in parallel with escalation logic applied when outcomes conflict.

ClearStaq Team

Engineering Team

The ClearStaq team builds AI-powered tools for bank statement parsing, fraud detection, and income verification.

Ready to transform your underwriting?

Start parsing bank statements in under 5 seconds.

Start free — no credit card required

Take back your time and automate loan underwriting

Join the lending teams using ClearStaq to parse statements, catch fraud, and verify income — all in under 5 seconds.

True revenue, positions, and 27 fraud signals included. No credit card.