Event-Driven Architecture and Transaction Integrity

When asynchronous processing fits, event contracts, delivery versus processing versus business status, idempotency, the transactional outbox, status lifecycles, matching rules, retries and dead letters.

  • Intermediate to advanced
  • About 26 minutes
  • Includes an exercise and a knowledge check

The concept Why asynchronous processing fits here

Reconciliation does not need to finish during the provider’s API call. The provider sends a notification; Apex validates and records it and acknowledges receipt; then a background processor normalizes it, the engine looks for a settlement record, and the result appears for finance. This separates request handling from longer business processing. It also brings new responsibilities to design on purpose: event ordering, duplicate delivery, retries, dead letters, schema evolution, processing visibility and eventual consistency.

The contract The event lifecycle

jsonPaymentReceived event (fictional)

{
  "eventId": "EVT-10001",
  "eventType": "PaymentReceived",
  "eventVersion": 1,
  "occurredAt": "2026-11-18T14:30:00Z",
  "correlationId": "CORR-20001",
  "source": "PROVIDER_A",
  "data": {
    "paymentId": "PAY-77821",
    "loanAccountId": "LN-10042",
    "amountMinorUnits": 42550,
    "currency": "USD"
  }
}

A production event contract defines its identity, type, schema version, timestamp, source, correlation information, data fields, privacy classification, and delivery and retention expectations.

jsonpayment-received-v1.schema.json (fictional)

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "urn:apex:events:payment-received:1",
  "title": "PaymentReceived, version 1 (fictional Apex Auto Finance)",
  "description": "Published from the outbox after a payment is stored. Delivery is at least once: consumers deduplicate by eventId. Within version 1 only new optional fields may be added.",
  "type": "object",
  "required": ["eventId", "eventType", "eventVersion", "occurredAt", "correlationId", "source", "data"],
  "properties": {
    "eventId": { "type": "string", "minLength": 1, "maxLength": 64 },
    "eventType": { "const": "PaymentReceived" },
    "eventVersion": { "const": 1 },
    "occurredAt": { "type": "string", "format": "date-time" },
    "correlationId": { "type": "string", "minLength": 1 },
    "source": { "enum": ["PROVIDER_A", "PROVIDER_B"] },
    "data": {
      "type": "object",
      "required": ["paymentId", "loanAccountId", "amountMinorUnits", "currency"],
      "properties": {
        "paymentId": { "type": "string", "minLength": 1, "maxLength": 64 },
        "loanAccountId": { "type": "string", "minLength": 1, "maxLength": 32 },
        "amountMinorUnits": { "type": "integer", "minimum": 1, "description": "Cents. Never a binary floating-point number." },
        "currency": { "const": "USD" }
      }
    }
  }
}

Checking the schema, then the example and four bad events

payment-received-v1.schema.json: valid JSON Schema 2020-12

Lesson 05 event                        accepted
amountMinorUnits as 425.5              rejected: 425.5 is not of type 'integer'
eventVersion 2                         rejected: 1 was expected
occurredAt without a time zone         rejected: '2026-11-18 14:30' is not a 'date-time'
no eventId                             rejected: 'eventId' is a required property

Real output from jsonschema 4.23.0 (JSON Schema 2020-12) running tools/fde/m06/validate.py, November 22, 2026.

The schema has a version, and the version is part of the contract. A consumer built for version 1 rejects an event that says version 2 instead of guessing what changed. The publisher validates every event against this schema before writing it to the outbox, so a bad event fails in Apex, not in someone else's consumer.

Do not mix them up Delivered is not processed, and processed is not reconciled

A message can be delivered twice. It can be processed while its acknowledgement fails. A consumer can crash after writing to the database. A downstream service can be down. An event can arrive before a related record. So the design keeps three separate states: transport (was it delivered?), processing (did the consumer process it?) and business (was the payment reconciled?).

The key idea Idempotency

An operation is idempotent when repeating it creates no additional effect. Provider A sends the same notification three times because it never received the first response. Without idempotency, Apex might record three payments, or apply one payment three times.

On the left, a photo of a crowded elevator button panel: pressing a lit button again still brings one elevator. On the right, Provider A sends PAY-77821 three times. Attempt 1, whose response was lost, is stored and creates ING-90012. Attempts 2 and 3 are duplicates: nothing new is created and ING-90012 is returned. The rule UNIQUE(provider_id, provider_transaction_id) is enforced in the database, so it survives restarts, unlike an in-memory cache. Three deliveries, one payment, one financial effect; agree the uniqueness rule with the provider.
Press it five times, one elevator comes. A repeated request must not create a second payment.
  1. Define a stable provider transaction identifier.
  2. Combine it with the provider identity, or another agreed uniqueness scope.
  3. Enforce uniqueness in persistent storage.
  4. Store the processing outcome.
  5. Return the previously recorded result when the same request comes again.

sqlIdempotent ingestion in SQL

CREATE TABLE payments (
    payment_id              INTEGER PRIMARY KEY,
    provider_id             TEXT    NOT NULL,
    provider_transaction_id TEXT    NOT NULL,
    loan_account_id         TEXT    NOT NULL,
    amount_minor_units      INTEGER NOT NULL,
    currency                TEXT    NOT NULL,
    UNIQUE (provider_id, provider_transaction_id)
);

-- Run three times for Provider A, once for Provider B (same ID text):
INSERT INTO payments
    (provider_id, provider_transaction_id, loan_account_id, amount_minor_units, currency)
VALUES ('PROVIDER_A', 'PAY-77821', 'LN-10042', 42550, 'USD')
ON CONFLICT (provider_id, provider_transaction_id) DO NOTHING;

Rows stored after four deliveries

provider_id  provider_transaction_id  amount_minor_units  rows_stored
-----------  -----------------------  ------------------  -----------
PROVIDER_A   PAY-77821                             42550            1
PROVIDER_B   PAY-77821                             18000            1

Real output from SQLite 3.54 running tools/fde/apex_idempotency.sql (fictional data), November 18, 2026.

Three deliveries from Provider A stored one row. Provider B’s payment with the same ID text is a different payment, because the uniqueness scope includes the provider. The exact rule must be agreed with each provider: some reuse identifiers across accounts, regions or transaction types.

Reliable publication The transactional outbox pattern

Apex stores a payment and then publishes a message. What if the write succeeds but the publish fails? The payment exists, but no processor ever hears about it. This is the dual-write problem.

Top, the dual-write problem: payment ingestion writes the payment to the database, which succeeds, then publishing to the queue fails, so the payment is saved but its event never leaves. Bottom, the transactional outbox: in one database transaction, payment ingestion inserts the payment and an outbox row for PaymentReceived and commits both or neither. An outbox publisher reads pending rows, publishes them to the queue and marks them sent. The reconciliation worker is idempotent, because a message may still arrive twice. The outbox does not make messaging exactly-once.
Store the change and the message to send in one transaction, then publish from the stored copy.
  1. In one database transaction, store the payment and store an outbox record.
  2. Commit both together, or neither.
  3. A separate publisher reads pending outbox records and publishes them.
  4. After successful publication, it marks the outbox record as sent.
A sequence diagram with six lifelines: Provider A, payment API, database, outbox publisher, queue and reconciliation worker. The provider posts a signed notification; the API stores the payment and an outbox row in one transaction and replies 202 ACCEPTED with ING-90012. The publisher reads pending rows, publishes EVT-10001 to the queue and marks the row sent. The queue delivers the event to the worker, which in one transaction checks processed_event, applies the change and records the event, then acknowledges. Six red markers: 1 reply lost, the retry gets 200 and the same ingestion ID; 2 transient error on publish, retried with backoff and jitter; 3 publisher crashes after sending and before marking, so the event is sent again; 4 repeated event, skipped through processed_event; 5 worker crashes mid-change, its transaction rolls back and the redelivery starts over; 6 poison message, to the dead-letter queue after the retry limit.
The whole path, with every place it can break. Lesson 08 turns each red number into a row of the failure-paths table.

Eventual consistency Waiting is not failing

A payment notification arrives at 10:00 a.m.; its bank settlement record arrives at 10:20 a.m. At 10:05 the engine finds no settlement. That does not mean the payment failed: it is awaiting settlement. Related information arrives at different times, and the status model and the screens must say so honestly.

The statuses of one payment in three separate vocabularies. Payment processing: RECEIVED, then NORMALIZED, or REJECTED when it cannot be read. Reconciliation: AWAITING_SETTLEMENT, then MATCHED when a settlement record agrees, UNMATCHED when the agreed window passes, or AMBIGUOUS when more than one record could match. UNMATCHED and AMBIGUOUS open an exception case, a separate record with its own states: OPEN, ASSIGNED, UNDER_INVESTIGATION, PENDING_APPROVAL, RESOLVED or CANCELLED. SETTLED is not a payment status: the bank file brings a settlement record, and matching it moves the payment to MATCHED. Awaiting settlement is not failed: a payment at 10:00 a.m. settled at 10:20 a.m. is normal. Below, three questions that are often confused: transport, was the event delivered; processing, did the consumer process it; business, was the payment reconciled.
The exact statuses come from the customer’s business rules; these are the common shape.

Matching rules Unmatched and ambiguous records

Do not match on one weak identifier unless the business rules allow it. Candidate attributes are the provider reference, loan account, amount, currency, transaction date, settlement date and bank reference. One rule might require an exact reference and amount; another might combine several attributes within a defined tolerance. For financial operations, rules are deterministic, versioned, explainable and approved by the business owner. Ambiguous matches go to the exception workflow; they are never silently forced.

When processing fails Retries and dead letters

FailureLikely handling
Temporary database connection failureRetry with backoff
Messaging service unavailableRetry publication
Invalid event schemaQuarantine or dead-letter
Unknown required accountBusiness exception or controlled retry
Expired credentialsAlert and fix the configuration
Duplicate eventIdempotent acknowledgement

Every retry policy has a maximum number of attempts, a backoff strategy, jitter where it helps, a classification of failures, monitoring, dead-letter or quarantine handling and replay controls. Never retry every failure forever.

Practice Design transaction integrity

Practical exercise

Exercise 05: event and transaction integrity design

Write the integrity design for payment ingestion.

  1. A payment ingestion sequence diagram with acknowledgements, transactions, retries and failure paths.
  2. An event schema, an idempotency strategy and an outbox (or justified alternative).
  3. A retry and dead-letter policy.
  4. A status lifecycle and a matching rules explanation.
Show sample decisions
  • Idempotency: UNIQUE(provider_id, provider_transaction_id); duplicates return the stored ingestion ID.
  • Publication: outbox row in the same transaction; publisher retries with backoff; consumers idempotent by eventId.
  • Retries: 5 attempts with exponential backoff and jitter for transient errors; schema errors go straight to quarantine; the dead-letter queue raises an alert.
  • Matching: rule v1 needs exact provider reference, amount and currency; anything else becomes an exception with the evidence attached.

3 questions

Check your understanding

1. What is idempotency meant to prevent?
2. What problem does the transactional outbox address?
3. Why not mark an unmatched payment as failed straight away?
Answer every question to submit.

What you can do now

  • Separate transport, processing and business status.
  • Design idempotent ingestion with a database uniqueness rule.
  • Explain the dual-write problem and the outbox pattern.
  • Write a status lifecycle, matching rules and a bounded retry policy.