Settlement Ingestion and Data Normalization

The second data path: settlement files as tracked batches, strict parsing and normalization, duplicate files and lines, and record-level plus file-level controls.

  • Advanced
  • About 19 minutes
  • Includes an exercise and a knowledge check

The concept A file in storage is not a processed file

Reconciliation needs both sides. Apex receives settlement data from the bank as scheduled files, so the platform must handle file receipt, validation, batch identification, parsing, normalization, duplicate files, invalid records and processing status. A file landing in storage says nothing about whether its records were processed correctly.

The batch lifecycle: RECEIVED, VALIDATING, PROCESSING, then COMPLETED when all records are accepted and totals agree, or COMPLETED_WITH_ERRORS when some are rejected and reported. From validating, FAILED when the file is unusable: wrong record count, no trailer, duplicate file. Every batch keeps the source object reference, source provider, file checksum, received timestamp, record count, accepted count, rejected count, processing status and error summary.
Finance can always see where a file is, and what happened to every record in it.

Different formats Normalize settlement records

Sources differ in date formats, currency formats, reference fields, amount representations and status codes. Normalize them into the internal settlement model, keep the original line and file reference so finance can trace every result, and parse strictly: a lenient parser turns bad input into wrong data.

Prove completeness Record-level and file-level controls

On the left, a photo of an old ledger page with a column of amounts and a total. In the middle, the fictional bank file: a header, six detail lines and a trailer saying 6 records and 1337.00. Line 5 repeats line 4; line 6 has the amount 12.5O with a letter O; line 7 has the date 11/31/2026. On the right, the controls: 6 read and the trailer says 6; 4 accepted and 2 rejected; line 5 counted and flagged; control total 122,550 against 133,700 cents; of the 11,150-cent gap, 9,900 cents is line 7 and 1,250 cents is unknown because line 6 cannot be read; the same file again is rejected by checksum. Batch status: COMPLETED_WITH_ERRORS.
The total at the bottom must agree, or the difference must be explained.

javaSettlementBatch.java: one bank file as a tracked batch

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SettlementBatch {

    static final String FILE = String.join("\n",
            "H,APEX-SETTLEMENT,2026-11-19",
            "D,BNK-44120,11/19/2026,300.00,USD",
            "D,REF-900182,11/19/2026,425.50,USD",
            "D,REF-900200,11/19/2026,250.00,USD",
            "D,REF-900200,11/19/2026,250.00,USD",
            "D,REF-900240,11/19/2026,12.5O,USD",
            "D,REF-900250,11/31/2026,99.00,USD",
            "T,6,1337.00");

    record SettlementRecord(int line, String bankReference, LocalDate settlementDate, long amountMinorUnits, String currency) {}

    static String sha256(String s) throws Exception {
        byte[] d = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));
        return HexFormat.of().formatHex(d);   // the full 64 hex characters; never shorten a checksum
    }

    public static void main(String[] args) throws Exception {
        // In production this is the settlement_batch table with UNIQUE (file_sha256), so a restart
        // still remembers every file (settlement.sql shows it). A set is enough for one run here.
        Set<String> filesAlreadyProcessed = new HashSet<>();
        String checksum = sha256(FILE);
        System.out.println("Batch received, checksum " + checksum + ", status RECEIVED");

        DateTimeFormatter bankDate = DateTimeFormatter.ofPattern("MM/dd/uuuu").withResolverStyle(java.time.format.ResolverStyle.STRICT);
        List<SettlementRecord> accepted = new ArrayList<>();
        List<String> rejected = new ArrayList<>();
        List<String> flagged = new ArrayList<>();
        long rejectedReadableTotal = 0;
        int rejectedUnreadable = 0;
        Set<String> seen = new HashSet<>();
        int detailLines = 0;
        long declaredCount = -1, declaredTotal = -1, readTotal = 0;
        boolean trailerReadable = true;
        String[] lines = FILE.split("\n");
        for (int i = 0; i < lines.length; i++) {
            String[] f = lines[i].split(",");
            switch (f[0]) {
                case "T" -> {
                    try {
                        declaredCount = Long.parseLong(f[1]);
                        declaredTotal = new BigDecimal(f[2]).movePointRight(2).longValueExact();
                    } catch (NumberFormatException | ArithmeticException e) {
                        trailerReadable = false;
                    }
                }
                case "D" -> {
                    detailLines++;
                    try {
                        long cents = new BigDecimal(f[3]).movePointRight(2).longValueExact();
                        SettlementRecord r = new SettlementRecord(i + 1, f[1], LocalDate.parse(f[2], bankDate), cents, f[4]);
                        String key = r.bankReference() + "|" + r.amountMinorUnits() + "|" + r.settlementDate();
                        accepted.add(r);   // counts toward the control total either way: the bank's trailer includes it
                        readTotal += cents;
                        if (!seen.add(key)) {
                            // Not dropped: it may be a real second payment. Matching will see two equal
                            // candidates and mark the payment AMBIGUOUS, so an investigator decides.
                            flagged.add("line " + (i + 1) + ": same reference, amount and date as an earlier line; counted, flagged for matching to treat as ambiguous");
                        }
                    } catch (NumberFormatException e) {
                        rejectedUnreadable++;   // the amount cannot be read, so it cannot be added to anything
                        rejected.add("line " + (i + 1) + ": amount '" + f[3] + "' is not a number");
                    } catch (ArithmeticException e) {
                        rejectedUnreadable++;   // more than two decimals, or too large for the amount column
                        rejected.add("line " + (i + 1) + ": amount '" + f[3] + "' has too many digits for US dollars");
                    } catch (java.time.format.DateTimeParseException e) {
                        rejectedReadableTotal += new BigDecimal(f[3]).movePointRight(2).longValueExact();
                        rejected.add("line " + (i + 1) + ": date '" + f[2] + "' does not exist");
                    }
                }
                default -> { }
            }
        }
        System.out.println("Lines read: " + detailLines + ", trailer says " + declaredCount);
        System.out.println("Records accepted: " + accepted.size() + ", rejected: " + (detailLines - accepted.size()));
        rejected.forEach(r -> System.out.println("  rejected " + r));
        flagged.forEach(r -> System.out.println("  flagged  " + r));
        long gap = declaredTotal - readTotal;
        long unexplained = gap - rejectedReadableTotal;
        System.out.println("Accepted total: " + readTotal + " cents (includes flagged lines), trailer total: " + declaredTotal + " cents, gap: " + gap + " cents");
        System.out.println("  explained by rejected lines with a readable amount: " + rejectedReadableTotal + " cents");
        System.out.println("  still unexplained: " + unexplained + " cents, across " + rejectedUnreadable + " line(s) whose amount could not be read");
        System.out.println("Sent to matching: " + accepted.size() + " records, " + flagged.size() + " of them flagged");
        boolean countOk = trailerReadable && declaredCount == detailLines;
        String status = !trailerReadable ? "FAILED (trailer cannot be read)"
                : !countOk ? "FAILED (record count does not match the trailer)"
                : accepted.size() < detailLines || gap != 0 ? "COMPLETED_WITH_ERRORS (finance must resolve the unexplained amount)" : "COMPLETED";
        System.out.println("Batch status: " + status);

        filesAlreadyProcessed.add(checksum);
        System.out.println("Same file delivered again: " + (filesAlreadyProcessed.contains(sha256(FILE)) ? "rejected as a duplicate file" : "processed"));
    }
}

Output

Batch received, checksum 39b6ef103bce25d27803049ca223e7becb2bb93a5322f408e16b1fa9e50b66f9, status RECEIVED
Lines read: 6, trailer says 6
Records accepted: 4, rejected: 2
  rejected line 6: amount '12.5O' is not a number
  rejected line 7: date '11/31/2026' does not exist
  flagged  line 5: same reference, amount and date as an earlier line; counted, flagged for matching to treat as ambiguous
Accepted total: 122550 cents (includes flagged lines), trailer total: 133700 cents, gap: 11150 cents
  explained by rejected lines with a readable amount: 9900 cents
  still unexplained: 1250 cents, across 1 line(s) whose amount could not be read
Sent to matching: 4 records, 1 of them flagged
Batch status: COMPLETED_WITH_ERRORS (finance must resolve the unexplained amount)
Same file delivered again: rejected as a duplicate file

Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.

  • The record count matched (6 and 6), so the file was not truncated.
  • Two lines were rejected and reported, not dropped: an amount with a letter O, and November 31. The STRICT date resolver caught the date; a lenient one would quietly have made it December 1.
  • Line 5 was counted and flagged: identical lines can be a real second payment or a bank duplicate. It counts toward the control total, because the bank's trailer includes it, and it goes to matching, where two equal candidates make the payment AMBIGUOUS (Lesson 07), so an investigator decides.
  • The control total did not agree, and only part of the gap is explained. Line 7 has a readable amount (99.00 dollars, 9,900 cents). Line 6 cannot be read, so nobody can say what it carried: 1,250 cents stay unexplained until the bank confirms it. 12.5O probably meant 12.50 is a guess, not a calculation, and a guess must never close a financial gap.
  • How the numbers must reconcile: accepted total, plus readable rejected amounts, plus amounts confirmed later by the bank, must equal the trailer total. Until they do, the batch stays COMPLETED_WITH_ERRORS.
  • The same file again was refused by its full SHA-256 checksum, before any record was read.

The program remembers the file only while it runs. A real platform must remember it after a restart, so the checksum lives in the database, with a unique constraint that decides, not the application:

sqlsettlement.sql: one batch per file, enforced by the database

-- FDE Module 07, Lesson 06: remember every settlement file in the database, so a restart cannot forget it.
-- Fictional Apex data. Run from web/: sqlite3 < tools/fde/m07/settlement.sql
.headers on
.mode column

CREATE TABLE settlement_batch (
    id          INTEGER PRIMARY KEY,
    file_name   TEXT NOT NULL,
    file_sha256 TEXT NOT NULL UNIQUE CHECK (length(file_sha256) = 64),   -- the full SHA-256, never a prefix
    status      TEXT NOT NULL,
    received_at TEXT NOT NULL
);

.print '-- 1. The bank sends the November 19 file'
INSERT INTO settlement_batch (file_name, file_sha256, status, received_at)
VALUES ('apex_settlement_20261119.csv',
        '39b6ef103bce25d27803049ca223e7becb2bb93a5322f408e16b1fa9e50b66f9', 'RECEIVED', '2026-11-19T06:02:11Z')
ON CONFLICT (file_sha256) DO NOTHING
RETURNING id AS new_batch_id;

.print ''
.print '-- 2. After a restart, the same content arrives again under a new name: nothing is inserted'
INSERT INTO settlement_batch (file_name, file_sha256, status, received_at)
VALUES ('apex_settlement_20261119_resend.csv',
        '39b6ef103bce25d27803049ca223e7becb2bb93a5322f408e16b1fa9e50b66f9', 'RECEIVED', '2026-11-19T09:40:52Z')
ON CONFLICT (file_sha256) DO NOTHING
RETURNING id AS new_batch_id;
SELECT id AS existing_batch, file_name, status FROM settlement_batch
WHERE file_sha256 = '39b6ef103bce25d27803049ca223e7becb2bb93a5322f408e16b1fa9e50b66f9';

.print ''
.print '-- 3. A shortened checksum is refused by the table itself'
INSERT OR IGNORE INTO settlement_batch (file_name, file_sha256, status, received_at)
VALUES ('test.csv', '39b6ef103bce25d2', 'RECEIVED', '2026-11-19T10:00:00Z');
SELECT changes() AS rows_inserted, (SELECT COUNT(*) FROM settlement_batch) AS batches;

Output

-- 1. The bank sends the November 19 file
new_batch_id
------------
           1

-- 2. After a restart, the same content arrives again under a new name: nothing is inserted
existing_batch           file_name             status
--------------  ----------------------------  --------
             1  apex_settlement_20261119.csv  RECEIVED

-- 3. A shortened checksum is refused by the table itself
rows_inserted  batches
-------------  -------
            0        1

Real output from SQLite 3.54 running this script (fictional data), November 22, 2026.

Practice Implement settlement ingestion

Practical exercise

Exercise 06: the settlement ingestion workflow

Build the bank file path.

  1. File intake and batch tracking with a checksum.
  2. File validation and record parsing.
  3. Canonical settlement mapping.
  4. Duplicate detection for files and lines.
  5. Rejected-record reporting and the batch completion status.
Show sample tests
  • Truncated file: trailer says 6, file has 4 lines; batch FAILED, nothing used for matching.
  • Impossible date: 11/31/2026 rejected with the line number.
  • Re-sent file: same checksum; refused as a duplicate file.
  • Totals: accepted total plus readable rejected amounts equals the trailer total, or the batch stays COMPLETED_WITH_ERRORS with the unexplained amount shown.
  • Restart: stop the service after the first file, start it again, resend the file: refused, because the checksum is in the database.
  • Overflow: an amount with too many digits is rejected with its line number, not a crash.

3 questions

Check your understanding

1. A file has the right record count but two invalid lines. What is the batch status?
2. Why parse dates strictly?
3. How is a duplicate file detected cheaply?
Answer every question to submit.

What you can do now

  • Ingest files as tracked batches with a clear status model.
  • Parse and normalize strictly with traceability.
  • Apply record-level and file-level controls.
  • Detect duplicate files and lines.