Skip to main content

Event-Driven Payment Architecture

Last Updated: 2026-12-01 Status: Complete

Event-driven payment architecture means the facts that happen to a payment, such as authorized, captured or disputed, are recorded as events that other components react to. After this page you can define an event catalog and envelope, publish events reliably with a transactional outbox, and write consumers that stay correct under duplicates and reordering.

Quick Reference​

TopicRule
PublishingWrite the business change and the outbox row in one transaction; never dual-write
DeliveryAssume at-least-once; exactly-once ends at the broker boundary
OrderingPer aggregate only; never rely on global order
ConsumersIdempotent, with an inbox table keyed by event id
FailuresBounded retries, then a DLQ with alerting and replay tooling
PayloadIdentifiers and non-sensitive fields; never PAN or raw PII

Why Are Payment Platforms Event-Driven?​

Most outcomes arrive later and from someone else: a processor's asynchronous result, a settlement file, a dispute notification from the network, a payout return from the bank. Your customers also want to be told, which means webhooks. Events decouple these producers from consumers such as the ledger, notifications, risk monitoring and reporting.

Martin Fowler distinguishes three meanings of "event-driven":

StyleWhat the event carriesPayments example
Event notificationLittle: an id and a type; the consumer calls back for detailpayment.captured with the payment id; the consumer fetches the payment
Event-carried state transferEnough state that consumers need not call backA payout event with amount, currency and destination token
Event sourcingThe event log is the source of truth; state is derivedThe ledger: immutable journal entries from which balances are derived

A ledger is the natural event-sourced core of a payment platform. Everything else can stay conventional state plus published events. See Double-Entry Ledger.

What Domain Events Should You Define?​

Event typeEmitted whenTypical consumers
payment.authorizedAuthorization approvedLedger (pending), risk, customer webhook
payment.capturedCapture acceptedLedger, fee engine, customer webhook
refund.succeededRefund confirmedLedger, customer webhook
dispute.openedChargeback receivedLedger (hold), evidence workflow, merchant alert
dispute.closedOutcome known (won or lost)Ledger, reserve logic
payout.paidPayout confirmed by the railLedger, merchant webhook
payout.failedPayout failed or returnedLedger reversal, support, retry logic
merchant.verifiedOnboarding approvedEnable processing, send credentials
merchant.suspendedAccount suspendedBlock new payments, hold payouts

Name events in the past tense, as facts. One event per state transition keeps the catalog aligned with the state machines.

Event Envelope​

{
"id": "evt_01J_[example]",
"type": "payment.captured",
"schema_version": 2,
"occurred_at": "2026-12-01T10:15:30Z",
"aggregate": { "type": "payment", "id": "pay_01J_[example]", "sequence": 4 },
"tenant_id": "tnt_[example]",
"correlation_id": "req_[example]",
"causation_id": "evt_01J_[previous]",
"data": {
"amount": 4999,
"currency": "USD",
"payment_method": "pm_tok_[redacted]",
"card": { "brand": "visa", "last4": "1111" }
}
}

sequence is a per-aggregate counter used for ordering. Take it from a dedicated event_seq column on the aggregate row, incremented (UPDATE ... SET event_seq = event_seq + 1 RETURNING event_seq) only when an outbox row is inserted, never from a general-purpose row version: a version also changes on updates that emit no event, and two events emitted in one transaction would collide on the unique constraint. Even so, treat it as monotonic, not gapless (a rolled-back transaction can leave a gap), so consumers compare "greater than", not "next". correlation_id ties events to the originating request; causation_id points to the event that triggered this one. data holds tokens and masked values only. Never put a PAN, SAD or raw PII in an event: events are copied to brokers, logs, replay tools and customer endpoints. See Tokenization.

Why Do You Need a Transactional Outbox?​

The dual-write problem: a service updates its database and then publishes to a broker. If it crashes between the two, the payment is captured but nobody hears about it. Reverse the order and consumers hear about a capture that rolled back. A database transaction cannot span both.

The transactional outbox fixes this: store the event in the same database transaction as the business change, and let a separate relay forward it.

CREATE TABLE outbox (
id bigserial PRIMARY KEY,
event_id uuid NOT NULL UNIQUE,
event_type text NOT NULL,
schema_version int NOT NULL,
aggregate_type text NOT NULL,
aggregate_id text NOT NULL,
sequence bigint NOT NULL,
tenant_id uuid NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
UNIQUE (aggregate_type, aggregate_id, sequence)
);
CREATE INDEX ix_outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
@Injectable()
export class CaptureService {
constructor(private readonly dataSource: DataSource) {}

async capture(paymentId: string, tenantId: string): Promise<void> {
await this.dataSource.transaction(async (manager) => {
const result = await manager.update(
Payment,
{ id: paymentId, tenantId, status: PaymentStatus.Authorized }, // guarded transition
{ status: PaymentStatus.Captured },
);
if (result.affected !== 1) throw new ConflictException('Payment not capturable');

// event_seq changes only when an outbox row is written, so it is unaffected by other updates.
const [{ event_seq }] = await manager.query(
`UPDATE payments SET event_seq = event_seq + 1 WHERE id = $1 AND tenant_id = $2 RETURNING event_seq`,
[paymentId, tenantId],
);
const payment = await manager.findOneByOrFail(Payment, { id: paymentId, tenantId });
await manager.insert(OutboxEvent, {
eventId: randomUUID(),
eventType: 'payment.captured',
schemaVersion: 2,
aggregateType: 'payment',
aggregateId: paymentId,
sequence: event_seq, // dedicated per-aggregate counter
tenantId,
payload: { amount: payment.amountMinor, currency: payment.currency },
});
}); // both rows commit, or neither does
}
}

How Does the Relay Work?​

RelayHowTrade-offs
Polling publisherA worker selects unpublished rows, publishes, marks themSimple. Adds polling load and some latency.
Transaction log tailingA tool such as Debezium reads the database log; its Outbox Event Router routes rows to topicsLow latency and no polling. More infrastructure.
SELECT id, event_id, event_type, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;

FOR UPDATE SKIP LOCKED lets several relay workers run without blocking each other, but the row locks last only while the relay's transaction is open. Select, publish and mark published_at inside that one transaction (or use a lease or claim column with an expiry); otherwise a second worker can pick up a row that is published but not yet marked. Run a retention job that deletes published outbox rows, and one that prunes processed_events, after a period you choose. A further catch: with several workers, two events of the same aggregate can be published out of order. Either run one relay per shard or partition the work by aggregate id. The relay can publish a row twice (crash after publish, before marking), which is why consumers must be idempotent.

What Delivery Semantics Can You Rely On?​

At-least-once is the norm. Amazon SQS standard queues are at-least-once with best-effort ordering. SQS FIFO queues order messages within a message group and deduplicate sends within a five-minute interval; AWS markets this as exactly-once processing, but consumers still need idempotency. Apache Kafka orders only within a partition and defaults to at-least-once; its idempotent producer dedupes producer retries, and its transactions give exactly-once only for Kafka-to-Kafka read-process-write. A database update, an email or a processor call is an external side effect, so you need an idempotent sink.

Design rule

Treat "exactly-once" as "at-least-once delivery plus an idempotent consumer". It is the only version that survives a crash at the wrong moment.

How Do You Keep Events in Order?​

You get ordering per aggregate, not globally.

  • Partition key or message group: use the aggregate id (the payment id), so a payment's events share a partition or group.
  • Sequence numbers: the envelope's sequence lets a consumer detect gaps and stale events.
  • Stale-event handling: a consumer ignores an event whose sequence is not greater than the last one it applied, or, for notification-style events, fetches the current state instead of trusting the event.
  • Never rely on global order: a payout.paid for one merchant has no ordering relation to a payment.captured for another.

AWS warns against dead-letter queues where strict FIFO order matters, because moving one message aside breaks the sequence for its group.

How Do You Write an Idempotent Consumer?​

Record the event id in a processed_events table (an inbox) in the same transaction as the side effect.

CREATE TABLE processed_events (
consumer text NOT NULL,
event_id uuid NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);
@Injectable()
export class LedgerEventHandler {
constructor(private readonly dataSource: DataSource, private readonly posting: LedgerPostingService) {}

async handle(event: DomainEvent): Promise<void> {
await this.dataSource.transaction(async (manager) => {
const claimed = await manager.query(
`INSERT INTO processed_events (consumer, event_id) VALUES ($1, $2)
ON CONFLICT DO NOTHING RETURNING event_id`,
['ledger', event.id],
);
if (claimed.length === 0) return; // duplicate: already applied

// Ledger entries also carry a unique external reference as a second guard.
await this.posting.postCapture(manager, event);
}); // if posting throws, the inbox row rolls back too and the message can be retried
}
}

If the side effect fails, the inbox row rolls back, so the retry is not mistaken for a duplicate. For side effects outside your database, such as a processor call, use that API's own idempotency key, derived from the event id. This is the Idempotent Receiver pattern; the sender-side counterpart is Idempotency Keys.

What About Retries, Poison Messages and DLQs?​

A poison message fails every time, for example a payload the consumer cannot parse. Without a limit it blocks or loops forever.

  1. Retry transient failures with exponential backoff and jitter.
  2. After a bounded number of attempts, move the message to a dead-letter queue. In SQS this is the redrive policy's maxReceiveCount.
  3. Alert on DLQ depth above zero, and on the age of the oldest message. Thresholds come from your own baseline.
  4. Build inspect-and-replay tooling: view the payload and error, fix the cause, then redrive. A DLQ without replay tooling is a graveyard.
  5. Keep the DLQ payload free of sensitive data; it is another place data can leak.

How Do You Replay Events and Evolve Schemas?​

Replay. You can replay events to rebuild a read model (reports, search index) from the log or from the outbox. An inbox keyed by (consumer, event_id) will skip replayed events, so replay into a new consumer name or a fresh projection, or clear that consumer's inbox rows first. Verify the new projection, then switch over. Rebuilding the ledger from events is the event-sourcing case and must be reconciled against processor files; see Ledger Reconciliation.

Schema evolution.

  • Make additive changes only: new optional fields, never renamed or repurposed ones.
  • Carry schema_version; publish a new type or version for a breaking change and run old and new in parallel.
  • Consumers ignore unknown fields.
  • Customer-facing webhook payloads follow the same rules; see Webhooks.

References​

Share: