A steel balance scale holding three stacked paper documents on one side, symbolizing three-way invoice matching

Three-Way Match Automation: Build an Invoice Verification Engine

•11 min read

Most invoice fraud does not beat a clever detection model. It beats a payables system that pays whatever lands in the inbox once someone clicks "approve". Three-way match automation fixes that at the engineering level. Before money moves, the software checks three things. The invoice must match a purchase order your company issued. A receipt must show that the goods or services actually arrived. And the bank account being paid must be one you verified. This guide covers the data model, the matching algorithm, duplicate detection, vendor bank account controls, failure handling and the trade-offs between approaches.

The risk is well documented. The FBI's 2024 IC3 Internet Crime Report lists $2,770,151,146 in reported losses from business email compromise (BEC). Abnormal's summary of the same report counts 21,442 BEC incidents that year. For the non-technical side (red flags and a process for the finance team), read our guide on how to spot and stop a fake invoice scam. This article covers the system behind that process.

What the engine has to decide

The engine does not output a score. It returns one of three decisions per invoice, each with a reason code that software can read:

  • PAY: every line matches within tolerance, the vendor is active, and the bank account is verified and has not changed recently.
  • HOLD: a person needs to look at it (price variance above tolerance, partial receipt, new bank account, possible duplicate).
  • REJECT: there is no matching purchase order, the vendor is blocked, or the invoice is an exact duplicate of one already paid.

Three fixed outcomes make the system auditable. An auditor, a developer and an accounts payable clerk can all act on a reason like "Held because the unit price on line 3 is above the PO price by more than the vendor tolerance".

Data model

The key design choice: invoices, purchase orders (POs) and receipts are separate aggregates linked line by line. Vendor bank accounts are versioned records with their own lifecycle, never a column on the vendor table.

CREATE TABLE vendors (
  id            uuid PRIMARY KEY,
  legal_name    text NOT NULL,
  tax_id        text NOT NULL UNIQUE,
  status        text NOT NULL CHECK (status IN ('active','blocked','pending'))
);

CREATE TABLE vendor_bank_accounts (
  id               uuid PRIMARY KEY,
  vendor_id        uuid NOT NULL REFERENCES vendors(id),
  account_hash     text NOT NULL,          -- hash of normalized routing + account
  account_last4    text NOT NULL,
  status           text NOT NULL CHECK (status IN
                     ('requested','verifying','verified','rejected','retired')),
  requested_by     uuid NOT NULL,
  verified_by      uuid,
  verified_via     text,                   -- e.g. 'callback_known_number'
  verified_at      timestamptz,
  active_from      timestamptz             -- verified_at + cooling-off period
);

CREATE TABLE purchase_orders (id uuid PRIMARY KEY, vendor_id uuid NOT NULL,
  currency char(3) NOT NULL, status text NOT NULL);
CREATE TABLE po_lines (id uuid PRIMARY KEY, po_id uuid NOT NULL,
  sku text, qty numeric NOT NULL, unit_price numeric NOT NULL);

CREATE TABLE receipts (id uuid PRIMARY KEY, po_id uuid NOT NULL,
  received_at timestamptz NOT NULL, received_by uuid NOT NULL);
CREATE TABLE receipt_lines (id uuid PRIMARY KEY, receipt_id uuid NOT NULL,
  po_line_id uuid NOT NULL, qty_received numeric NOT NULL);

CREATE TABLE invoices (
  id              uuid PRIMARY KEY,
  vendor_id       uuid NOT NULL REFERENCES vendors(id),
  invoice_number  text NOT NULL,           -- as printed
  invoice_number_norm text NOT NULL,       -- normalized for duplicate checks
  invoice_date    date NOT NULL,
  currency        char(3) NOT NULL,
  total           numeric NOT NULL,
  source          text NOT NULL,           -- 'email_ocr','portal','edi'
  status          text NOT NULL
);
CREATE TABLE invoice_lines (id uuid PRIMARY KEY, invoice_id uuid NOT NULL,
  po_line_id uuid, qty numeric NOT NULL, unit_price numeric NOT NULL);

CREATE TABLE match_results (
  id           uuid PRIMARY KEY,
  invoice_id   uuid NOT NULL REFERENCES invoices(id),
  decision     text NOT NULL CHECK (decision IN ('PAY','HOLD','REJECT')),
  reasons      jsonb NOT NULL,
  rules_version text NOT NULL,
  evaluated_at timestamptz NOT NULL DEFAULT now()
);

Three details matter more than they seem to:

  1. Bank details never come from the invoice. An attacker can type any account number on an invoice. Payment instructions come from vendor_bank_accounts rows with status = 'verified'. If the invoice shows a different account, that is a reason to HOLD, not an update.
  2. Store rules_version on every result. When you change tolerances, you still need to explain why an invoice was paid last month under the old rules.
  3. Use numeric, not floats, for money and quantities, and store the currency on every document. A PO in MXN and an invoice in USD is a mismatch, not something to convert.

Three-way match automation: the matching algorithm

Match each line, not just the invoice header. If you only compare totals (invoice total equals PO total), an attacker can rearrange lines or bill for items that never arrived and still keep a believable total.

def evaluate(invoice, po, receipts, vendor, bank, rules):
    reasons = []

    if vendor.status != "active":
        return Decision("REJECT", ["vendor_not_active"])
    if po is None or po.vendor_id != invoice.vendor_id:
        return Decision("REJECT", ["no_matching_po"])
    if invoice.currency != po.currency:
        reasons.append("currency_mismatch")

    received = sum_received_by_po_line(receipts)        # {po_line_id: qty}
    already_billed = sum_billed_by_po_line(po.id,        # excludes this invoice
                                           exclude=invoice.id)

    for line in invoice.lines:
        pol = po.lines.get(line.po_line_id)
        if pol is None:
            reasons.append(f"line_without_po:{line.id}")
            continue
        billable = received.get(pol.id, 0) - already_billed.get(pol.id, 0)
        if line.qty > billable + rules.qty_tolerance(pol):
            reasons.append(f"qty_exceeds_received:{line.id}")
        if not within(line.unit_price, pol.unit_price, rules.price_tolerance(vendor, pol)):
            reasons.append(f"price_variance:{line.id}")

    if bank is None or bank.status != "verified" or now() < bank.active_from:
        reasons.append("bank_account_not_cleared")

    return Decision("HOLD", reasons) if reasons else Decision("PAY", [])

Design notes:

  • Billable quantity is what was received minus what was already billed. Without the already_billed term, one receipt can justify two invoices. That is exactly how split or repeated invoices get through.
  • Tolerances are data, not code. Store them per vendor or category with both a percentage and an absolute cap (for example, "2% but never more than X"). That way a small percentage on a very large line cannot hide a big overpayment.
  • Keep evaluate a pure function. It takes documents and rules and returns a decision. Loading data and saving results happen elsewhere. That makes it easy to unit test and to re-run when a late receipt arrives.

Two-way vs three-way vs four-way

Two-way matching (invoice vs PO) is cheaper to build and works for services with no physical receipt, but it cannot tell you whether anything was delivered. Three-way adds the receipt and is the sensible default for goods. Four-way adds an inspection or quality record, and is only worth it where acceptance is a separate step. A practical approach is to let each PO declare its match type, so a software subscription and a pallet of product do not go through the same rules.

Duplicate invoice detection

Both fraudsters and honest vendors resend invoices. Exact duplicates are easy to catch. The hard cases are near-duplicates: INV-00123 vs inv 123, or the same amount and date with a new number.

Normalize the number first, then enforce uniqueness in the database, not only in application code:

import re
def normalize_invoice_number(raw: str) -> str:
    s = raw.upper()
    s = re.sub(r"[^A-Z0-9]", "", s)          # drop spaces, dashes, slashes
    s = re.sub(r"^(INV|FACT|FACTURA|NO)", "", s)
    return s.lstrip("0") or "0"
CREATE UNIQUE INDEX uniq_invoice_per_vendor
  ON invoices (vendor_id, invoice_number_norm)
  WHERE status <> 'void';

The PostgreSQL partial index lets a voided invoice be issued again without breaking the constraint. On top of that hard rule, run softer checks that add HOLD reasons instead of raising errors. Look for the same vendor and total within a few days, the same total across vendors that share a bank account hash, and PO lines billed twice. Soft checks will flag some legitimate invoices. That is fine, because the result is a human review, not a rejection.

Vendor bank account changes: the real attack surface

Most fake invoice schemes end with a request to "update our bank details". Treat a bank account change as a security event with its own state machine:

requested -> verifying -> verified -> (cooling-off) -> active
     \            \
      -> rejected  -> rejected
  • Verify through a separate channel. Confirm using contact details you already had on file, such as a phone number saved before the request. Never use contact details that came with the change request itself. Record who verified, how and when in verified_by, verified_via and verified_at.
  • Maker-checker. The person who requests the change cannot be the one who verifies it. Enforce this in the database or the service layer, not in the UI.
  • Cooling-off period. active_from delays the first use of a new account. The first payment to that account goes to HOLD whatever the match result.
  • Cross-vendor checks. If a new account hash already belongs to another vendor, flag it.
  • Account validation where available. The ACH network already uses this idea in another context. Nacha's WEB debit rule, effective March 19, 2021, requires validating consumer account information the first time it is used for an online debit. If your bank or payment provider offers account validation for payees, call it during verifying.

The same pattern applies beyond suppliers. A network marketing platform that pays commissions to thousands of distributors has the same risk when someone changes a payout account, and the same state machine works there.

Architecture and trade-offs

A workable pipeline has four stages:

  1. Ingestion (email with OCR, vendor portal, EDI or e-invoicing feeds). Treat everything here as untrusted input. Store the original file and its hash.
  2. Normalization and enrichment: find the vendor by tax ID, link invoice lines to PO lines and normalize the invoice number.
  3. Evaluation: the pure evaluate function, which writes a match_results row.
  4. Payment release: a separate service that pays only invoices whose latest result is PAY, and looks up bank details at the moment of payment.

Trade-offs to decide on purpose:

  • Inside the ERP vs a separate service. Building inside the ERP or accounting tool keeps one source of truth, but you are limited to what its extension model allows. A separate service is easier to test and version, but you need reliable sync of POs, receipts and vendors. If you build your own, have a team experienced in custom software development define the sync contract before anyone writes matching code.
  • Rules vs ML scoring. Rules are explainable and predictable, which auditors value. Anomaly scoring can catch patterns that rules miss, but it should only add HOLD reasons. It should never approve a payment on its own.
  • Strict vs tolerant. Tight tolerances mean more manual reviews. Loose ones let more overpayments through. Make tolerances visible, track how often people override a HOLD, and adjust.

Failure handling and concurrency

  • Late receipts. Invoices often arrive before the goods. Re-run the check on held invoices when a receipt for the same PO is recorded (through an event or a scheduled job), so a clerk does not have to re-check by hand.
  • Concurrent evaluation. If two invoices for the same PO line are evaluated at the same time, both can see the full billable quantity. Lock the PO row (SELECT ... FOR UPDATE) during evaluation, or use serializable transactions and retry on conflict.
  • Idempotent payment release. Send the invoice ID plus the bank account ID as an idempotency key to your payment provider, so a retried job never pays twice.
  • Re-check at release. The bank account or vendor status can change between evaluation and payment. The release service must read both again and stop if either differs from what was evaluated.
  • Append-only audit log. Record every decision, override and bank change with who did it and when. Overrides need a reason, and above a set amount, a second approver.

Common mistakes

  • Updating a vendor's bank account with data parsed from an invoice or email.
  • Matching on header totals only.
  • Enforcing segregation of duties in the UI while the API lets the same user create and approve.
  • Using floats for money, or ignoring currency.
  • Checking for duplicates on the raw invoice number.
  • Letting an anomaly model approve payments.
  • Not storing rules_version, so past decisions cannot be explained.

Implementation checklist

  1. Versioned bank accounts with a state machine, verification through a separate channel and a cooling-off period.
  2. Line-by-line matching, with billable quantity = received minus already billed.
  3. Tolerances stored as data, with percentage and absolute caps.
  4. Normalized invoice numbers and a partial unique index per vendor.
  5. Soft duplicate checks that add HOLD reasons.
  6. A pure evaluation function with unit tests for each reason code.
  7. Row locking or serializable transactions on PO lines.
  8. A separate payment release service with idempotency keys and a final re-check.
  9. Maker-checker enforced in the API and the database.
  10. An append-only audit log and rules_version on every decision.

Frequently asked questions

Can three-way match automation work for services with no physical delivery?

Yes, if you define what counts as a receipt: an approved timesheet, a milestone sign-off or a service confirmation entered by the person who requested it. Without that, use two-way matching for those POs and require a named approver.

Should we use OCR to read invoices?

OCR is fine for capturing data, but treat what it reads as untrusted. Use it to suggest line links and amounts, then let the matching rules and a human reviewer decide. Never use OCR output to change vendor master data.

Where should the payment decision live: in the ERP or a separate service?

Either can work. What matters is that only one component can release payments, that it reads bank details from verified records and that it re-checks everything right before paying.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

It is never published.