Overview

Organisations that put a modern orchestration engine in front of a legacy book of record tend to end up with the same topology, and payments is the clearest example — the one this article uses throughout. A payment hub runs the rails: instant payments, high-value RTGS, bill payments, bulk files, request-to-pay. It builds and parses ISO 20022 messages, talks to the schemes and tracks scheme status. It does not hold accounts. The legacy core — the system of record — holds the accounts, balances, holds and the ledger, and knows nothing about schemes. The same split appears wherever a scarce resource must be reserved before an external party confirms: stock reserved while a marketplace confirms an order, prepaid credit reserved while a network session runs, a seat held while a payment clears.

Between the two sits an integration layer. Its job is narrow and should stay narrow: translate protocols, correlate requests and replies, enforce idempotency, route, and protect the system of record with circuit breakers and retries. It holds no payment business logic and no accounting rules.

This article describes a pattern for the money-movement part of that integration: how a scheme-bound payment reserves, books or releases funds in the system of record, and how to keep that safe under retries, timeouts and late scheme replies. The organisational side — moving schemes onto a hub one at a time without a big-bang cutover — is covered in the companion essay Strangle the Rails, Not the Channels.

Three owners, three domains

The hub owns the payment lifecycle and scheme messaging. The system of record owns account state, holds and posting. The integration layer owns translation, correlation, idempotency, resilience and routing. If a design review cannot say in one sentence which of the three owns a field or a decision, fix that first. Ambiguous ownership turns into duplicated logic, and duplicated logic turns into reconciliation breaks.

Why Two Phases

The tempting design is a single call: when a customer sends money, debit the account in the core, then submit to the scheme. It is simple and it works on the happy path. It fails badly on every other path.

  • The scheme rejects after the debit. The customer has been debited for a payment that never left the institution. You now need a compensating credit, a customer notification and an explanation on the statement — for what should have been a non-event.
  • The scheme times out. You do not know whether the money moved. With a booked debit, the only safe options are to leave it and investigate, or to reverse it and risk a double payment if the scheme later confirms.
  • Submit first, debit later is worse. If the scheme accepts and the debit then fails on insufficient funds, the institution has paid out money it cannot collect.

The two-phase pattern separates the reservation of funds from the booking of the debit. Phase one validates the debit and places a hold, so the money cannot be spent elsewhere while the scheme decides. Phase two either books the debit and lifts the hold together, or lifts the hold and books nothing. A rejected or timed-out payment leaves no entry on the statement, only a hold that existed for a few seconds. This is the same idea as card authorisation and capture, applied to account-to-account payments — and the same idea as an online-charging reservation in telecoms or a soft allocation of stock in retail.

Two phases is not a distributed transaction

The hold and the post are separate commits in the system of record. Nothing rolls back automatically if the second call never arrives. The pattern is safe only if every hold has an owner that is guaranteed to issue the second call, and a sweeper that catches the cases where it did not. Both are covered below.

The System-of-Record Contract

The system of record needs to expose two operations for hub-driven payments.

  • Verify-and-hold. One synchronous call that validates the debit (account status, restrictions, limits, available balance) and places a hold for the amount. On success it returns a hold reference. Validation and reservation happen atomically, so there is no window in which funds were checked but not yet reserved.
  • Post, with two modes, both keyed on the hold reference. Post-and-release books the debit and lifts the hold in one step. Release-only lifts the hold and books nothing.

Not every flow has a customer debit to reserve. Inbound credits, scheme-initiated settlement and bulk file postings have nothing to hold. Mapping the full surface as four routes keeps the contract small:

RouteCallsHold referenceTypical use
A — hold then postverify-and-hold, then post-and-releaseRealCustomer-initiated debit that must be reserved before scheme submission
B — verify then postverify (no reservation), then postNoneEligibility or compliance check without reserving funds: an inbound credit, or a payment funded outside the deposit account
C — direct postpost onlyNoneScheme-initiated entries: inbound files, returns, refunds, reversals after posting
D — release onlypost in release-only modeReleasedHold placed, but the payment will not complete: scheme reject, timeout, cancellation

Exposed as REST by the integration layer, the shape looks like this. Paths and field names are illustrative.

core-payments.httphttp
# 1. Verify and hold
POST /core/v1/payments/verify HTTP/1.1
Idempotency-Key: pay-7d1c0a52e9b84f3a
Content-Type: application/json

{ "paymentId": "P-000184223", "debtorAccount": "ACC-00012345",
  "amount": "2500.00", "currency": "EUR", "paymentType": "INSTANT_OUTBOUND" }

# 200 OK
{ "status": "HELD", "holdReference": "H-90311475" }

# 2a. Scheme accepted: post and release
POST /core/v1/payments/P-000184223/post HTTP/1.1
{ "holdReference": "H-90311475", "mode": "POST_AND_RELEASE",
  "accountingEvent": "OUTBOUND_INSTANT_DEBIT", "postingItems": [ { "account": "ACC-00012345", "side": "DEBIT", "amount": "2500.00" } ] }

# 2b. Scheme rejected or timed out: release only
POST /core/v1/payments/P-000184223/post HTTP/1.1
{ "holdReference": "H-90311475", "mode": "RELEASE_ONLY",
  "releaseReason": "SCHEME_REJECTED" }

One property of this contract is non-negotiable: the post must be idempotent on the hold reference. A second post against a hold that has already been consumed returns the original result; it never books again. Without that, every timeout on the post call becomes a potential double debit.

The Payment State Machine

Every scheme-bound payment moves through the same states. Internal transfers that never leave the institution can collapse to a single posted state, because there is no scheme leg to wait for. The status codes on the transitions use ISO 20022 as the example: a pacs.002 status report carries acceptance (ACCP) or rejection (RJCT), and a camt.056 carries a recall request.

Three rules make the machine safe.

  1. Terminal states are final

    POSTED, RELEASED, REJECTED and REVERSED accept no further transitions, except POSTED → REVERSED. A late scheme message for a RELEASED payment does not move it back; it raises an exception case (see failure modes).

  2. One trigger, one core side effect per transition

    HELD is entered only by a successful verify-and-hold. RELEASED is entered only after release-only has succeeded. If the core call fails, the state does not move; the retry policy decides what happens next.

  3. Reversal is a new entry

    When a recall is accepted after posting, nothing is undone. A compensating entry is booked through the direct-post route. Both the original posting and the reversal stay on the ledger, which is exactly what auditors expect to see.

PaymentState.javajava
public enum PaymentState {
    RECEIVED, VALIDATING, HELD, SUBMITTED, SCHEME_PENDING,
    POSTED, RELEASED, REJECTED, REVERSED;

    private static final Map<PaymentState, Set<PaymentState>> ALLOWED = Map.of(
        RECEIVED,       Set.of(VALIDATING, REJECTED),
        VALIDATING,     Set.of(HELD, REJECTED),
        HELD,           Set.of(SUBMITTED, RELEASED),
        SUBMITTED,      Set.of(SCHEME_PENDING, RELEASED),
        SCHEME_PENDING, Set.of(POSTED, RELEASED),
        POSTED,         Set.of(REVERSED),
        RELEASED,       Set.of(),
        REJECTED,       Set.of(),
        REVERSED,       Set.of());

    public PaymentState to(PaymentState next) {
        if (!ALLOWED.get(this).contains(next)) {
            // Never "fix" an illegal transition in code. Raise a case for operations.
            throw new IllegalTransitionException(this, next);
        }
        return next;
    }
}

Deriving the Accounting-Event Catalogue

Every post call carries an accounting event that tells the core which accounts to debit and credit. The catalogue of events is a contract between the integration team and finance operations, and it is where payment programmes quietly lose months.

The usual way to build the catalogue is a walkthrough: list the flows the team knows best and write an event for each. That produces a catalogue that looks complete and is not. The gaps surface one at a time during testing — an outbound flow with no customer-debit event, a funding source nobody listed, a refund leg with no settlement entry — and each one costs a round trip with operations and a configuration change in the core.

Derive the catalogue from a matrix instead. The axes are payment type, funding source and lifecycle outcome. Every cell needs either an event or an explicit “not applicable” with a reason. An illustrative excerpt:

Payment typeFunding sourcePost (accepted)ReleaseReverse / refund
Instant, outboundDeposit accountDebit customer, credit outgoing suspenseHold-release audit markerRecall after posting
Instant, inbound— (scheme)Debit scheme suspense, credit beneficiaryn/a (no hold)Debit on accepted recall
Request-to-payDeposit accountDebit payer, credit outgoing suspenseHold-release audit markerRecall after posting
Bill paymentDeposit accountDebit customer, credit billerHold-release audit markerMirror entry if advice fails after posting
Bill paymentCardDebit card settlement pool, credit billern/a (verify only)Mirror entry, funding-aware
Bulk, outboundDeposit accountFile, batch or item-level debitn/a (direct post)Item-level credit-back
Interbank refund— (scheme)Settlement and refund legsn/an/a

The method takes an afternoon with finance operations and saves weeks later. Three practices make it stick.

  • Make the matrix additive. New payment types and funding sources add rows; existing event codes are never renamed or repurposed. Renaming an event breaks historical reporting and reconciliation.
  • Keep funding source out of the hub. Schemes do not care whether a customer paid from an account or a card. The integration layer carries the funding source from the channel session to the verify call, and the core selects the event. Adding a funding type later becomes a core and integration change with no hub scope.
  • Pair two-system postings with a daily control. When a card platform books the customer-level debit and the core books against a settlement pool, the two totals must match every day. A gap is either a duplicate or a fraud signal, and it belongs in an operations queue.

The Idempotent Channel API

Channels — mobile, internet banking, corporate portals, branch systems — should call one transfer API. They should not know whether a payment is processed by the hub or by the core. That single property is what makes it possible to change routing later without touching a channel.

The general mechanics of idempotency keys are covered in Idempotency Keys at Scale. A channel API in front of two engines adds a few specific decisions.

  • Namespace the key to the authenticated customer. Store customerId + ":" + clientKey, with customerId taken from the verified token and never from the request body. Two customers who generate the same key never collide, and one customer cannot probe for another’s cached response.
  • Store a payload hash, not the payload. A SHA-256 of the canonicalised body detects a key reused with different inputs, without retaining sensitive data in the idempotency record.
  • Check before routing. The idempotency check runs before the router decides which engine to call. A replay returns the cached response regardless of where the original went, so a routing change mid-migration cannot create a duplicate.
  • Two record states. A new key is written as IN_FLIGHT, the request is forwarded, and the record becomes DONE with the response stored. A retry against IN_FLIGHT gets 409 with Retry-After.
  • Derive keys for channels that cannot send one. Legacy channels that speak fixed-length records over IBM MQ cannot add a header. Their adapter derives the key deterministically, for example a SHA-256 of the channel identifier and the channel’s own message id. Use one derivation rule for every legacy channel; per-channel variants fork the replay semantics.
idempotency-decision.txttext
lookup(customerId:key)
  absent                        -> write IN_FLIGHT (ttl 24h) -> route -> write DONE + response
  present, same hash, DONE      -> return cached status + body
  present, same hash, IN_FLIGHT -> 409 + Retry-After        (original still running)
  present, different hash       -> 409/422 DUPLICATE_TRANSACTION (key reused)
  store unavailable             -> 503, do NOT forward       (fail closed)

Whether a mismatched payload returns 409 or 422 matters less than the error code in the body. Channels should map on a stable code such as DUPLICATE_TRANSACTION, not on the HTTP status.

Choosing the Idempotency Store

A distributed cache such as Redis is the obvious first choice for idempotency records: sub-millisecond, native TTLs, and an atomic claim with SET NX. For APIs that reserve and move money, a relational store replicated with synchronous commit is usually the safer choice. The trade-off is worth spelling out, because it comes up on every payment programme.

ConcernCache, asynchronous replicationRelational store, synchronous commit
Recovery point on failoverA write acknowledged by the primary can be lost if the primary fails before replicating. An IN_FLIGHT marker can vanish.RPO 0. The commit is acknowledged only after a secondary has hardened it.
Read-modify-writeCheck, claim and update are separate commands or a script. Correct, but easy to get subtly wrong.Check-or-reserve and finalise are each one transaction with row locks.
Related stateHold reference and lifecycle state live elsewhere.Idempotency record, hold reference and payment state can commit together.
LatencySub-millisecond.Single-digit milliseconds. Budget it explicitly, e.g. ≤10 ms p95 for the check.
AuditNeeds a separate durable trail.The table is the trail.

The deciding scenario is a failover in the middle of a payment. The integration layer claims the key, calls verify-and-hold, the hold succeeds — and the cache primary fails before the claim replicates. The channel retries. The new primary has no record of the key, a second hold is placed, and later possibly a second debit. A few milliseconds per request is a cheap price for removing that path. A cache in front of the relational store, as in the hybrid design from the idempotency article, can still serve fast replays; the relational row remains the authority.

check_or_reserve.sqlsql
-- Claim the key atomically, or learn what is already there.
INSERT INTO idempotency_record
       (scoped_key, payload_hash, state, created_at, expires_at)
VALUES (:scoped_key, :payload_hash, 'IN_FLIGHT', now(), now() + interval '24 hours')
ON CONFLICT (scoped_key) DO NOTHING
RETURNING scoped_key;               -- no row returned = key already exists

-- If not claimed: read the existing record and apply the decision table.
SELECT state, payload_hash, response_code, response_body
  FROM idempotency_record
 WHERE scoped_key = :scoped_key;

-- After the upstream call: finalise in a second short transaction.
UPDATE idempotency_record
   SET state = 'DONE', response_code = :code, response_body = :body,
       hold_reference = :hold_ref, completed_at = now()
 WHERE scoped_key = :scoped_key AND state = 'IN_FLIGHT';
Fail closed when the store is down

If the idempotency store cannot be reached, reject the write with 503 and alert. Do not “degrade gracefully” by skipping the check. A declined payment is an inconvenience the customer can retry; a duplicate debit is an incident, a complaint and a reconciliation task. The cost is an availability dependency on the store, which is why it should run with synchronous secondaries, automatic failover, and readiness probes that take the integration pods out of rotation while it recovers.

Resilience Settings

Two upstreams, two sets of limits. A typical arrangement reaches the legacy core over IBM MQ with request/reply correlation and the hub over REST with mutual TLS. The values below are a starting point for illustration; tune them against measured latency, not intuition.

resilience.yamlyaml
resilience4j:
  circuitbreaker:
    configs:
      core-default:                        # shared settings; instances inherit via base-config
        sliding-window-type: COUNT_BASED
        sliding-window-size: 20            # last 20 calls
        failure-rate-threshold: 50         # open at 50% failures
        wait-duration-in-open-state: 30s
        permitted-number-of-calls-in-half-open-state: 3
    instances:
      legacy-core:
        base-config: core-default
      payment-hub:
        base-config: core-default          # base-config names a configs entry, not an instance
  timelimiter:
    instances:
      legacy-core: { timeout-duration: 8s }    # MQ request/reply
      payment-hub:  { timeout-duration: 10s }
  retry:
    instances:
      idempotent-only:
        max-attempts: 3                    # first call + 2 retries
        wait-duration: 1s
        enable-exponential-backoff: true
        exponential-backoff-multiplier: 2  # waits 1s, then 2s
        enable-randomized-wait: true
        randomized-wait-factor: 0.25       # jitter
  • Retry only what is idempotent end to end. Verify-and-hold carries an idempotency key the core honours, and the post is keyed on the hold reference. Anything that is not idempotent end to end gets no automatic retry.
  • One breaker per upstream. A slow hub must not trip the breaker that protects the system of record, and the other way round.
  • Timeouts are state transitions. If the hub does not accept a submission within its timeout, the integration layer issues release-only with reason TIMEOUT. Funds are never left reserved behind an unknown outcome.
  • An open breaker is an answer. Channels get 503 UPSTREAM_UNAVAILABLE quickly, which beats holding a connection for eight seconds to learn the same thing.

Per-Scheme Routing

Behind the unchanged channel contract, a single router decides per call which engine handles a payment. REST and MQ ingress adapters both normalise to one canonical payload, so the router has exactly one implementation. The routing table is configuration, not code.

scheme-routing.yamlyaml
routing:
  default: core                    # anything unlisted stays on the existing path
  schemes:
    instant:        { route: hub,  shadow: none }   # cut over
    bill-payment:   { route: hub,  shadow: core }   # soaking: old path kept as shadow
    rtgs:           { route: core, shadow: hub  }   # dark launch: hub compared, not trusted
  dark-launch:
    compare-fields: [decision, amount, accountingEvent, postingItems, errorCode]
    shadow-side-effects: forbidden   # shadow path never holds or posts
    cutover-threshold: 0.001        # example: < 0.1% discrepancies over the window

Three rules keep routing honest.

  • Pin the route per payment. Resolve it once, at RECEIVED, and store it on the payment. An in-flight payment finishes on the engine it started on, even if the flag changes mid-flight.
  • Shadow without side effects. The shadow path computes what it would hold and post; the comparison runs on those outputs. Enforce this in the router, not by convention in each flow.
  • A flag off is the rollback — for new payments only. Rehearse it under load before relying on it.

Failure Modes

Late acceptance after the hold was released

The outbound timer expires, the hold is released and the payment is RELEASED. Then a delayed pacs.002 arrives with ACCP: the scheme has settled, the customer has not been debited. Do not resurrect the payment. Route the late status to an exception queue, book the debit through the direct-post route under a dedicated event, and notify the customer. Size the outbound timer from the scheme’s documented maximum response time, not from your own SLA, and measure how often this case occurs.

Post succeeded, reply lost

The core books the debit and releases the hold, but the MQ reply misses the timeout. A naive retry could book twice. Two defences: the post is idempotent on the hold reference, and the retry path first queries the hold’s status. Test this deliberately by dropping replies in a non-production environment.

Keys stuck IN_FLIGHT

If an integration pod dies between claiming a key and finalising it, the record stays IN_FLIGHT and every retry gets 409 until the TTL expires. A recovery job should find IN_FLIGHT records older than the maximum end-to-end timeout, resolve the true outcome from the payment state and the core hold status, and finalise them. Never just delete them.

Orphaned holds

A hold that is neither posted nor released reduces the customer’s available balance for no reason. Typical causes are a crash between HELD and SUBMITTED, or an unhandled hub error. A sweeper compares open holds against payment states every few minutes and resolves any hold whose payment is terminal or older than the scheme window. Alert on the count of open holds, not only on errors.

Shadow path with side effects

The most expensive dark-launch mistake is a shadow call that places a real hold or books a real entry. The customer sees two reservations; the ledger may see two debits. Test it with a balance check before and after a shadowed payment.

Missing accounting event for a new combination

A new funding source or payment type is enabled without its event, and posts fail with a configuration error in the core. Make the matrix a release gate: a combination cannot be enabled in routing until every cell has a configured and tested event.

Production Checklist

  1. Write down the three owners

    Hub: lifecycle and scheme messaging. Core: accounts, holds, posting. Integration layer: translation, correlation, idempotency, resilience, routing. Review every new field against that list.

  2. Agree the two-phase core contract

    Verify-and-hold returns a hold reference. Post has two modes and is idempotent on that reference. Map every flow to one of the four routes.

  3. Encode the state machine as an allowed-transition table

    Reject illegal transitions loudly. Every exit from HELD ends in exactly one post call, in one of its two modes.

  4. Build the accounting matrix before the flows

    Payment type × funding source × outcome. Every cell has an event or a documented “not applicable”. Treat the matrix as a release gate.

  5. Make idempotency durable and fail closed

    Namespace keys to the authenticated customer, store a payload hash, check before routing, and keep the authoritative record in a synchronous-commit store. Rehearse a store failover under load and confirm no duplicates.

  6. One breaker and one timeout per upstream

    Retry only idempotent calls, with backoff and jitter. On hub submission timeout, release the hold.

  7. Run the sweepers

    One for orphaned holds, one for stuck IN_FLIGHT keys, one exception queue for late scheme statuses. Each has an owner and a runbook.

  8. Reconcile daily

    Hub payment states against core postings, open holds against non-terminal payments, and any two-system postings against each other. A clean reconciliation is the only real proof that the state machine works.