Skip to content
Streaming Reconciliation ≠ Settlement: 10M+ Payment Architecture Lessons

Streaming Reconciliation ≠ Settlement: 10M+ Payment Architecture Lessons

The article shares a layered payment reconciliation architecture handling tens of millions of transactions, emphasizing that streaming reconciliation only serves as early warning while offline T+1 batch processing remains the authoritative settlement basis, detailing sharding, parallel scheduling, table designs, comparison logic, and production review checklists.

Internet Backend Architecture Stack
Internet Backend Architecture Stack
Internet Backend Architecture Stack

Failure Context: Big Promotion Settlement Day

On a major promotion settlement day, the reconciliation task triggered on schedule. A full-volume single-point comparison ran for over ten hours without finishing, saturating database CPU and I/O. Difference records piled up, the finance side could not produce settlement reports on time, and both customer complaints and internal post-mortem pressure mounted immediately.

Core Conflict: Two Incompatible Goals

Streaming solutions run fast but can only serve as alerts; they cannot be the basis for settlement. Offline batch results are trustworthy but suffer high latency and heavy resource consumption.

Many projects fall into the first major trap: treating Flink streaming reconciliation match results as the final reconciliation outcome for financial settlement. Payment channel callbacks, merchant refund reversals, asynchronous compensations, and message reordering replays — any of these cause temporary inconsistencies between the two sides. Streaming provides an incremental view, suitable only for detecting suspicious differences and early alert interception ; the true fund verdict still must fall to T+1 offline full reconciliation.

Core conclusion: Streaming is the alerting layer, offline is the final-state layer; each has its own role and cannot replace the other.

Performance Optimization Strategies (Layered Convergence)

Data Sharding — Shard by settlement date + merchant ID. This is the foundation of the entire system. Avoid full JOIN on a single large table; the shard key must address query skew — top merchants can be further sub-sharded. After sharding, tasks can be naturally distributed for scheduling.

Distributed Parallel Scheduling — Using XXL-Job, shards are split into independent subtasks running in parallel. Each subtask handles data pull, cleansing, and comparison for one shard only. Task isolation, concurrency caps, and resource quotas are set to prevent reconciliation tasks from contending with transaction database resources.

MQ Asynchronous Flow Ingestion — Channel callbacks and upstream order flows all land asynchronously via MQ into flow tables, without blocking the order/payment main path. Flow landing is idempotent, deduplicated by unique business flow number, avoiding duplicate writes that would create dirty reconciliation data.

Cache Warming — Static configurations such as merchant settings, fee rules, and black/white lists are pre-warmed into local cache before the reconciliation task starts, reducing frequent database lookups during comparison. Dynamic fee rates must carry version numbers and effective times to prevent cross-version rule confusion.

Streaming Incremental Reconciliation (Flink) — Consume the flow topic, perform real-time incremental matching, and write mismatches directly into a difference alert table, pushing alerts to business and finance. Again: streaming match differences ≠ final error records; offline reconciliation will re-adjudicate.

Streaming + offline reconciliation vertical data flow diagram
Streaming + offline reconciliation vertical data flow diagram

Core Data Table Designs (Simplified)

All reconciliation-related tables must carry business unique ID, channel flow ID, settlement date, reconciliation status, version number for traceability and rerun capability.
-- Upstream order flow table (business side)
CREATE TABLE order_flow (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    order_no VARCHAR(64) NOT NULL COMMENT 'order number',
    pay_no VARCHAR(64) NOT NULL COMMENT 'payment flow number',
    merchant_no VARCHAR(32) NOT NULL COMMENT 'merchant ID',
    settle_date DATE NOT NULL COMMENT 'settlement date',
    amount DECIMAL(18,2) NOT NULL COMMENT 'transaction amount',
    trade_status TINYINT NOT NULL COMMENT 'trade status',
    create_time DATETIME NOT NULL,
    UNIQUE KEY uk_pay_no(pay_no),
    KEY idx_merchant_date(merchant_no,settle_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Channel bill table (third-party payment side landing)
CREATE TABLE channel_bill (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    channel_bill_no VARCHAR(64) NOT NULL COMMENT 'channel bill number',
    pay_no VARCHAR(64) NOT NULL COMMENT 'our payment flow number',
    merchant_no VARCHAR(32) NOT NULL,
    settle_date DATE NOT NULL,
    amount DECIMAL(18,2) NOT NULL,
    fee DECIMAL(18,2) NOT NULL COMMENT 'channel fee',
    bill_status TINYINT NOT NULL,
    UNIQUE KEY uk_channel_bill(channel_bill_no),
    KEY idx_merchant_date(merchant_no,settle_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Reconciliation difference record table (core error record)
CREATE TABLE bill_diff_record (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    settle_date DATE NOT NULL,
    merchant_no VARCHAR(32) NOT NULL,
    pay_no VARCHAR(64) NOT NULL,
    diff_type TINYINT NOT NULL COMMENT 'diff type: one-sided, amount mismatch, status mismatch',
    flow_source TINYINT NOT NULL COMMENT 'source: 1 streaming alert 2 offline reconciliation',
    handle_status TINYINT NOT NULL DEFAULT 0 COMMENT 'pending/verified/adjusted/ignored',
    remark VARCHAR(512),
    create_time DATETIME NOT NULL,
    update_time DATETIME NOT NULL,
    KEY idx_date_merchant(settle_date,merchant_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Pitfall reminder: do not run reconciliation queries directly on the transaction master database. Sync a copy of flows to an independent reconciliation database for read-write isolation. Reconciliation is a heavy-query task; once it brings down the transaction database, the loss far exceeds the reconciliation itself.

Comparison Logic and Boundary Handling

Comparison logic is not simple equality judgment; many business boundaries are easily missed:

Refund reverse flows: forward and refund records must be linked for offset, not compared independently.

Channel fees, discount allocation: many differences are not bugs but fee-rate caliber inconsistencies.

Async delay: channel bills land on T+1 morning; early-morning streaming reconciliation inevitably produces large numbers of one-sided differences. A delay window filter is needed to avoid garbage alert storms.

Rerun mechanism: shard task failure supports single-shard rerun. Before rerun, clean old results based on settle_date+merchant_no to prevent duplicate difference generation.

Reference simplified comparison pseudo-code:

// Single-shard reconciliation logic
public void compareShard(String merchantNo, LocalDate settleDate) {
    List<OrderFlow> orderList = orderFlowMapper.queryByMerchantDate(merchantNo, settleDate);
    Map<String, ChannelBill> channelBillMap = channelBillMapper.queryByMerchantDate(merchantNo, settleDate)
            .stream().collect(Collectors.toMap(ChannelBill::getPayNo, Function.identity()));

    for (OrderFlow flow : orderList) {
        ChannelBill bill = channelBillMap.get(flow.getPayNo());
        if (bill == null) {
            saveDiff(flow.getPayNo(), DiffType.SINGLE_SIDE_CHANNEL, flow);
            continue;
        }
        if (!Objects.equals(flow.getAmount(), bill.getAmount())) {
            saveDiff(flow.getPayNo(), DiffType.AMOUNT_MISMATCH, flow, bill);
        }
    }
    // Reverse check: channel exists, upstream order does not
    for (ChannelBill bill : channelBillMap.values()) {
        if (orderList.stream().noneMatch(o -> o.getPayNo().equals(bill.getPayNo()))) {
            saveDiff(bill.getPayNo(), DiffType.SINGLE_SIDE_ORDER, bill);
        }
    }
}

This code is only for understanding the flow; production must use batched paging, never load full volume into memory at once, to prevent OOM.

Reconciliation difference closure process diagram
Reconciliation difference closure process diagram

Production Review Checklist (Architecture Red Lines)

Before launching the reconciliation system, review each item. These are hard constraints distilled from multiple pitfalls:

Transaction database and reconciliation database physically isolated; reconciliation queries must not connect directly to the primary transaction database.

Streaming reconciliation only for alerts; settlement reports and fund adjustments only trust offline T+1 reconciliation results.

Sharding strategy includes skew protection; top merchants support secondary splitting.

Difference records differentiate source (streaming/offline), alert grading to avoid flooding.

Support independent shard rerun; rerun has idempotent cleanup logic to avoid duplicate error generation.

All adjustment operations leave audit trail: operator, reason, evidence fully recorded to satisfy financial audit.

Tasks have timeout circuit breakers and resource caps to prevent reconciliation tasks from exhausting cluster resources.

Reconciliation caliber documented: fee, refund, coupon,补差 comparison rules aligned across business, finance, and engineering.

Closing: Architecture Trade-off Thinking

The real test of a reconciliation system is not whether you can make it run faster, but knowing how to draw boundaries among timeliness, cost, and fund risk .

Many teams chase "real-time reconciliation" trying to eliminate all latency, eventually coupling the reconciliation system tightly with the transaction chain. Once upstream jitters, reconciliation follows chaotically, even triggering fund errors. A mature fund architecture is always layered fallback: streaming provides early anomaly detection, giving operations and finance a handling window; offline full reconciliation delivers the audit-grade final result. Performance optimization is merely a means; fund trustworthiness and traceable errors are the reconciliation system's first priority.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

distributed schedulingFlinkdata shardingdatabase designstreaming processingAudit Trailpayment reconciliationoffline batch processing
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.