The concept Implement business rules, not assumptions
Matching is not payment.amount == settlement.amount. The engine may compare the transaction reference, provider, loan account, amount, currency, transaction date, settlement date and bank reference, and the customer must approve the rules. Start with explicit, deterministic rules: the same inputs always give the same result, and every result can be explained.
Run it A rule engine with evidence
javaReconciliation.java: two rules, four outcomes
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
public class Reconciliation {
record Payment(String id, String providerReference, long amountMinorUnits, String currency, Instant receivedAt) {}
record Settlement(String id, String bankReference, long amountMinorUnits, String currency, LocalDate settlementDate) {}
enum Status { MATCHED, AMBIGUOUS, UNMATCHED, AWAITING_SETTLEMENT }
record Result(String paymentId, Status status, String settlementId, String ruleId, int ruleVersion, String evidence) {
@Override public String toString() {
return String.format("%-9s %-19s %-7s %-26s %s", paymentId, status, settlementId == null ? "-" : settlementId,
ruleId == null ? "-" : ruleId + " v" + ruleVersion, evidence);
}
}
/** One approved rule. It returns the candidates it accepts; the engine decides what the count means. */
interface MatchingRule {
String id();
int version();
List<Settlement> candidates(Payment p, Collection<Settlement> open);
String evidence();
}
static boolean sameMoney(Payment p, Settlement s) {
return p.amountMinorUnits() == s.amountMinorUnits() && p.currency().equals(s.currency());
}
/** Rule 1: the bank reference equals the provider reference, and amount and currency agree. */
static final MatchingRule EXACT = new MatchingRule() {
public String id() { return "EXACT_REFERENCE_AMOUNT"; }
public int version() { return 2; }
public List<Settlement> candidates(Payment p, Collection<Settlement> open) {
return open.stream().filter(s -> s.bankReference().equals(p.providerReference()) && sameMoney(p, s)).toList();
}
public String evidence() { return "providerReference, amountMinorUnits, currency"; }
};
/** Rule 2: an alias approved by finance maps the provider reference to a bank reference; settled within 3 days. */
static final Map<String, String> APPROVED_ALIASES = Map.of("REF-900190", "BNK-44120");
static final MatchingRule ALIAS = new MatchingRule() {
public String id() { return "APPROVED_ALIAS_AMOUNT"; }
public int version() { return 1; }
public List<Settlement> candidates(Payment p, Collection<Settlement> open) {
String alias = APPROVED_ALIASES.get(p.providerReference());
if (alias == null) return List.of();
LocalDate paid = LocalDate.ofInstant(p.receivedAt(), ZoneOffset.UTC);
return open.stream().filter(s -> s.bankReference().equals(alias) && sameMoney(p, s)
&& !s.settlementDate().isAfter(paid.plusDays(3))).toList();
}
public String evidence() { return "approved alias, amountMinorUnits, currency, settled within 3 days"; }
};
static final List<MatchingRule> RULES = List.of(EXACT, ALIAS);
static final Duration SETTLEMENT_WINDOW = Duration.ofDays(2); // example: the real window is agreed with finance
/** Final results already stored, by payment. A re-run returns the stored match instead of matching again. */
static final Map<String, Result> STORED = new HashMap<>();
static Result reconcile(Payment p, Map<String, Settlement> open, Instant now) {
Result stored = STORED.get(p.id());
if (stored != null && stored.status() == Status.MATCHED) return stored;
Result r = evaluate(p, open, now);
STORED.put(p.id(), r);
return r;
}
static Result evaluate(Payment p, Map<String, Settlement> open, Instant now) {
for (MatchingRule rule : RULES) {
List<Settlement> found = rule.candidates(p, open.values());
if (found.size() == 1) {
open.remove(found.get(0).id()); // claimed: no other payment can match it
return new Result(p.id(), Status.MATCHED, found.get(0).id(), rule.id(), rule.version(), rule.evidence());
}
if (found.size() > 1) {
return new Result(p.id(), Status.AMBIGUOUS, null, rule.id(), rule.version(),
found.size() + " candidates: " + found.stream().map(Settlement::id).toList());
}
}
boolean sameRefOtherAmount = open.values().stream().anyMatch(s -> s.bankReference().equals(p.providerReference()));
if (sameRefOtherAmount) return new Result(p.id(), Status.UNMATCHED, null, null, 0, "reference found, amount differs");
if (Duration.between(p.receivedAt(), now).compareTo(SETTLEMENT_WINDOW) < 0) {
return new Result(p.id(), Status.AWAITING_SETTLEMENT, null, null, 0, "inside the settlement window");
}
return new Result(p.id(), Status.UNMATCHED, null, null, 0, "no settlement after the window");
}
public static void main(String[] args) {
Instant now = Instant.parse("2026-11-19T12:00:00Z");
List<Payment> payments = List.of(
new Payment("PAY-77821", "REF-900182", 42550, "USD", Instant.parse("2026-11-18T14:30:00Z")),
new Payment("PAY-77830", "REF-900190", 30000, "USD", Instant.parse("2026-11-18T15:00:00Z")),
new Payment("PAY-77840", "REF-900200", 25000, "USD", Instant.parse("2026-11-18T15:10:00Z")),
new Payment("PAY-77850", "REF-900210", 18000, "USD", Instant.parse("2026-11-19T09:00:00Z")),
new Payment("PAY-77860", "REF-900220", 51000, "USD", Instant.parse("2026-11-18T16:00:00Z")),
new Payment("PAY-77870", "REF-900230", 12500, "USD", Instant.parse("2026-11-16T10:00:00Z")));
Map<String, Settlement> open = new LinkedHashMap<>();
for (Settlement s : List.of(
new Settlement("STL-501", "REF-900182", 42550, "USD", LocalDate.parse("2026-11-19")),
new Settlement("STL-502", "BNK-44120", 30000, "USD", LocalDate.parse("2026-11-19")),
new Settlement("STL-503", "REF-900200", 25000, "USD", LocalDate.parse("2026-11-19")),
new Settlement("STL-504", "REF-900200", 25000, "USD", LocalDate.parse("2026-11-19")),
new Settlement("STL-505", "REF-900220", 50100, "USD", LocalDate.parse("2026-11-19")))) {
open.put(s.id(), s);
}
System.out.printf("%-9s %-19s %-7s %-26s %s%n", "PAYMENT", "STATUS", "MATCH", "RULE", "EVIDENCE");
for (Payment p : payments) System.out.println(reconcile(p, open, now));
Result again = reconcile(payments.get(0), open, now);
System.out.println("Re-run PAY-77821: " + again.status() + " to " + again.settlementId() + " (the stored result, not a second match)");
}
}Output
PAYMENT STATUS MATCH RULE EVIDENCE
PAY-77821 MATCHED STL-501 EXACT_REFERENCE_AMOUNT v2 providerReference, amountMinorUnits, currency
PAY-77830 MATCHED STL-502 APPROVED_ALIAS_AMOUNT v1 approved alias, amountMinorUnits, currency, settled within 3 days
PAY-77840 AMBIGUOUS - EXACT_REFERENCE_AMOUNT v2 2 candidates: [STL-503, STL-504]
PAY-77850 AWAITING_SETTLEMENT - - inside the settlement window
PAY-77860 UNMATCHED - - reference found, amount differs
PAY-77870 UNMATCHED - - no settlement after the window
Re-run PAY-77821: MATCHED to STL-501 (the stored result, not a second match)Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.
| Payment | Why it got that result |
|---|---|
| PAY-77821 | Rule 1: STL-501 has the same reference, amount and currency |
| PAY-77830 | Rule 1 found nothing; rule 2 used the alias finance approved (REF-900190 is BNK-44120) |
| PAY-77840 | Two bank lines fit equally (STL-503, STL-504): an exception, not a coin toss |
| PAY-77850 | Received three hours before the run: still inside the 2-day example window |
| PAY-77860 | The bank has the reference but 501.00 instead of 510.00 dollars |
| PAY-77870 | Received three days earlier and nothing arrived: missing settlement |
A real bug Re-running must not change a match
The first version of this program had a bug worth learning from. Re-running reconciliation for PAY-77821 found its settlement already claimed, so it reported AWAITING_SETTLEMENT for a payment that was already matched. The fix, now in the code above, is to check for a stored final result first and return it. Reconciliation must be repeatable without changing or duplicating financial results, and a test for exactly this belongs in the suite.
Concurrency Prevent duplicate matching
In memory, the claimed set keeps one settlement from matching twice. In production, the database must guarantee it, because two workers may evaluate at the same moment. Lesson 05’s script showed the guard: partial unique indexes allow only one MATCHED row per settlement and per payment, so the second worker’s insert fails and it re-reads the state. Add transaction boundaries and clear ownership of each reconciliation run on top.
Time matters The settlement window
AWAITING_SETTLEMENT must not last forever. A scheduled job re-evaluates waiting payments; once the window agreed with finance has passed (2 days in this example), the payment becomes UNMATCHED with the reason missing settlement and an exception case is opened. Compare instants in UTC, and remember that the bank’s settlement date is a calendar date in the bank’s own time zone.
Explainable Store the result and its evidence
jsonMatching evidence stored with the result
{
"ruleId": "EXACT_REFERENCE_AMOUNT",
"ruleVersion": 2,
"matchedFields": ["providerReference", "amountMinorUnits", "currency"],
"settlementRecordId": "STL-501",
"result": "MATCHED",
"evaluatedAt": "2026-11-19T12:00:00Z"
}The processing sequence: receive a normalized payment; look for candidates; apply the approved rules in order; check uniqueness under concurrency; store the result with its rule version and evidence; open an exception when needed; publish a result event; update what finance sees.
Practice Implement reconciliation
Practical exercise
Exercise 07: a working reconciliation engine
Build the engine and prove its edge cases.
- A matching rule interface, the exact rule and an approved alternate rule.
- Ambiguous match detection.
- Reconciliation persistence with duplicate-match protection.
- Matching evidence on every result.
- Unit tests for normal and edge cases, including a re-run.
Show sample test names
- matchesWhenReferenceAmountAndCurrencyAgree
- returnsAmbiguousWhenTwoSettlementsFitEqually
- keepsAwaitingSettlementInsideWindowAndUnmatchedAfter
- neverMatchesOneSettlementToTwoPayments (two concurrent workers, real database)
- rerunReturnsStoredMatch: the bug found above, now covered
3 questions
Check your understanding
What you can do now
- Implement deterministic, versioned, explainable matching rules.
- Handle ambiguous, waiting and unmatched payments correctly.
- Prevent duplicate matches under concurrency.
- Make reconciliation safe to re-run.