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
| Topic | Rule |
|---|---|
| Publishing | Write the business change and the outbox row in one transaction; never dual-write |
| Delivery | Assume at-least-once; exactly-once ends at the broker boundary |
| Ordering | Per aggregate only; never rely on global order |
| Consumers | Idempotent, with an inbox table keyed by event id |
| Failures | Bounded retries, then a DLQ with alerting and replay tooling |
| Payload | Identifiers 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":
| Style | What the event carries | Payments example |
|---|---|---|
| Event notification | Little: an id and a type; the consumer calls back for detail | payment.captured with the payment id; the consumer fetches the payment |
| Event-carried state transfer | Enough state that consumers need not call back | A payout event with amount, currency and destination token |
| Event sourcing | The event log is the source of truth; state is derived | The 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 type | Emitted when | Typical consumers |
|---|---|---|
payment.authorized | Authorization approved | Ledger (pending), risk, customer webhook |
payment.captured | Capture accepted | Ledger, fee engine, customer webhook |
refund.succeeded | Refund confirmed | Ledger, customer webhook |
dispute.opened | Chargeback received | Ledger (hold), evidence workflow, merchant alert |
dispute.closed | Outcome known (won or lost) | Ledger, reserve logic |
payout.paid | Payout confirmed by the rail | Ledger, merchant webhook |
payout.failed | Payout failed or returned | Ledger reversal, support, retry logic |
merchant.verified | Onboarding approved | Enable processing, send credentials |
merchant.suspended | Account suspended | Block 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?
| Relay | How | Trade-offs |
|---|---|---|
| Polling publisher | A worker selects unpublished rows, publishes, marks them | Simple. Adds polling load and some latency. |
| Transaction log tailing | A tool such as Debezium reads the database log; its Outbox Event Router routes rows to topics | Low 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.
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
sequencelets 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.paidfor one merchant has no ordering relation to apayment.capturedfor 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.
- Retry transient failures with exponential backoff and jitter.
- After a bounded number of attempts, move the message to a dead-letter queue. In SQS this is the redrive policy's
maxReceiveCount. - Alert on DLQ depth above zero, and on the age of the oldest message. Thresholds come from your own baseline.
- Build inspect-and-replay tooling: view the payload and error, fix the cause, then redrive. A DLQ without replay tooling is a graveyard.
- 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.
Related Topics
- Idempotency Key Implementation — the request side of the same discipline.
- Webhook Delivery and Signature Verification — events delivered to customers and received from processors.
- Payments API Design — long-running operations that finish with an event.
- Ledger Overview — the event-sourced core.
- Check your understanding: Reliability Quiz
References
- Transactional outbox — Chris Richardson, microservices.io
- Outbox Event Router — Debezium documentation
- What do you mean by "Event-Driven"? — Martin Fowler, 2017
- Event Sourcing — Martin Fowler, 2005
- Amazon SQS standard queues — AWS docs
- Amazon SQS FIFO exactly-once processing — AWS docs
- Amazon SQS dead-letter queues — AWS docs
- Apache Kafka: Message delivery semantics — Apache Software Foundation
- Idempotent Receiver and Dead Letter Channel — Enterprise Integration Patterns