So far every piece of work has happened inside one request: a confirm call, a webhook, an admin click. That's fine for a demo. In production, a payment touches a provider that can take seconds to answer, a ledger, a notification service, a payout rail and a reconciliation job. Doing all of that inside one HTTP request makes every slow dependency the customer's problem.
This part moves the work onto queues. Chapter 9 designs an event-driven payment engine on AWS SNS and SQS. Chapter 10 is about the SQS visibility timeout, the setting people most often mistake for a correctness guarantee. Chapter 11 deals with the dual write, which shows up as soon as a service that writes to a database also publishes events. All of it relies on the idempotency tools from Part 3.
Chapter 9
Building an event-driven payment engine
The problem: one request doing everything
A first version of a webhook handler often looks like this: verify the event, load the payment, update its status, write the ledger, call the notification service, send an email, maybe trigger a payout, and only then reply 200 OK to the provider.
Every one of those steps can be slow or fail. If the email service takes 20 seconds, the provider times out and retries the webhook, even though the payment was already applied. If the notification call fails, should the whole webhook fail? The provider will retry, and you'll run the ledger code again. Steps that have nothing to do with each other end up chained together by the lifetime of one request.
Stripe's guidance applies generally: the handler should return a successful status “before any complex logic that might cause a timeout”, and incoming events should be processed “with an asynchronous queue” (Stripe: webhooks).
Separate the responsibilities
| Stage | Job | Must be fast? | Talks to |
|---|---|---|---|
| API ingestion | Validate the request, check the idempotency key, record the intent | Yes: a customer is waiting | PostgreSQL |
| Webhook ingestion | Verify the signature, store the raw event durably, acknowledge | Yes: the provider will retry | PostgreSQL |
| Normalisation | Turn each provider's format into one internal event shape | No | Nothing external |
| Routing | Deliver each event to the consumers that care | No | SNS, SQS |
| Business processing | Apply state changes, post ledger journals | No, but must be correct | PostgreSQL |
| Notifications | Push, email, SMS | No | Notification providers |
| Payout execution | Send money out through a provider | No, but must be idempotent | Payout provider |
| Reconciliation | Compare our records with the provider and bank | No | Provider reports, bank files |
The first two stages are the only ones that need to finish inside a request. Their job is to accept work durably and quickly. Everything else happens afterwards, on workers that can take their time, retry on their own schedule, and fail without affecting each other.
Webhooks: store first, acknowledge second
The webhook handler should return 2xx only after the event is safely stored. If storing fails, return an error so the provider retries. If you acknowledge first and then crash, the provider considers the event delivered and you've lost it. The handler does two things, in this order:
- Verify the signature, so nobody can forge “payment succeeded” events. Reject stale timestamps to limit replays.
- In one transaction: insert the raw event, deduplicated on the provider's event ID, and an outbox row announcing it (Chapter 11). Commit. Return
200.
import hashlib, hmac, json, time
from fastapi import HTTPException, Request
from starlette.concurrency import run_in_threadpool
PAYCO_SECRET = load_secret("payco-webhook") # from a secrets manager, never from code
TOLERANCE_SECONDS = 300
def verify_signature(raw: bytes, header: str) -> None:
# PayCo is fictional; its header looks like "t=1764000000,v1=<hex HMAC-SHA256 of 't.body'>"
try:
parts = dict(p.split("=", 1) for p in header.split(","))
timestamp, sent = int(parts["t"]), parts["v1"]
except (KeyError, ValueError):
raise HTTPException(400, "malformed signature header")
if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
raise HTTPException(400, "stale signature")
expected = hmac.new(PAYCO_SECRET, f"{timestamp}.".encode() + raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sent):
raise HTTPException(400, "bad signature")
def store_event(raw: bytes, event: dict) -> None:
with pool.connection() as conn, conn.transaction():
inserted = conn.execute(
"""
INSERT INTO provider_events (provider, event_id, event_type, payload)
VALUES ('payco', %s, %s, %s::jsonb)
ON CONFLICT (provider, event_id) DO NOTHING
RETURNING 1
""",
(event["id"], event["type"], raw.decode()),
).fetchone()
if inserted: # first time we've seen it: announce it
conn.execute(
"""
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ('provider_event', %s, 'provider.event_received', %s::jsonb)
""",
(event["id"], json.dumps({"provider": "payco", "event_id": event["id"]})),
)
@app.post("/webhooks/payco")
async def payco_webhook(request: Request):
raw = await request.body()
verify_signature(raw, request.headers.get("PayCo-Signature", ""))
event = json.loads(raw)
await run_in_threadpool(store_event, raw, event) # blocking DB work off the event loop
return {"received": True} # 200 only after the commitCREATE TABLE provider_events (
provider text NOT NULL,
event_id text NOT NULL, -- the provider's stable event ID
event_type text NOT NULL,
payload jsonb NOT NULL, -- exactly what they sent, for audits and replays
received_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (provider, event_id)
);Keeping the raw payload is worth the storage. When a provider changes its format, or a normaliser has a bug, you can fix the code and replay the stored events. A duplicate delivery is answered with 200 and nothing else, because ON CONFLICT DO NOTHING recognises it.
One internal event shape
Every provider has its own idea of what an event looks like. Don't let those shapes leak into your business logic. A normaliser per provider turns their event into your event, wrapped in a standard envelope:
{
"event_id": "4a9c2f6e-8d1b-4c39-9f0e-3b7d2a51c8e4",
"type": "payment.succeeded",
"version": 1,
"occurred_at": "2026-11-23T10:15:42Z",
"producer": "payments",
"correlation_id": "req_8KQ2",
"payload": { "payment_id": "pay_81", "amount_minor": 4000, "currency": "EUR", "provider": "payco", "provider_payment_id": "pc_9KD" }
}event_idis what every consumer deduplicates on. It's generated once, when the event is created, and never changes on republication.typeandversionlet consumers route and parse it. Add fields freely within a version; consumers must ignore fields they don't know. For a breaking change, publish a new version and run both side by side until every consumer has moved over.correlation_idties together everything that happened because of one original request. Part VII builds tracing on it.- Amounts follow Part II: integer minor units plus currency, never floats.
Commands and events are different things
| Event | Command | |
|---|---|---|
| Meaning | A fact: “payment pay_81 succeeded” | A request: “send payout wd_88” |
| Tense | Past | Imperative |
| Receivers | Any number, including none | Exactly one handler |
| Can it be refused? | No, it already happened | Yes: the handler may reject it |
| AWS shape | SNS topic, fanned out to queues | An SQS queue owned by the handler |
| Naming | payment.succeeded | payout.send |
Mixing the two makes the system harder to change. If “payment succeeded” is sent straight to the credit worker's queue as if it were a command, then adding an email consumer means changing the producer. If it's published as an event, the email consumer just subscribes.
One topic, one queue per consumer
The usual AWS layout is an SNS topic per domain (here, payment events), with one SQS queue per consumer subscribed to it. Each subscription can carry a filter policy so the consumer only receives the event types it needs (AWS: SNS message filtering):
{ "event_type": ["payment.succeeded", "payment.reversed"] }For SQS subscriptions, turn on SNS raw message delivery so the queue receives your envelope as the body instead of SNS's JSON wrapper around it.
A queue per consumer, rather than one shared queue, lets each consumer fail, retry and scale on its own:
Standard or FIFO queues?
| Standard queue | FIFO queue | |
|---|---|---|
| Delivery | At least once; duplicates possible | Deduplicates sends within a 5-minute window; your consumer can still see a message twice after a crash |
| Order | “Messages may occasionally arrive out of order” | Strict order within a message group |
| Throughput | Very high | Lower, with per-queue limits (see the AWS quotas page) |
| Good for | Most payment events, guarded by state machines and idempotency | Work that must run in order per account or per payment |
The quotes are from AWS: standard queues may deliver duplicates and “messages may occasionally arrive out of order” (AWS: standard queues). With FIFO, “within a message group ID, all messages are sent and received in strict order”, but messages in different groups “may arrive or be processed out of order relative to one another” (AWS: FIFO delivery logic).
A common choice is the account or payment ID as the message group, which keeps each account's events in order while still processing many accounts in parallel.
I default to standard queues. The state machine from Part 1 already handles events arriving in the wrong order, and the idempotency from Part 3 already handles duplicates. FIFO is worth it when a consumer can't cope with reordering and you've checked that the throughput fits.
A consumer in Go
A consumer long-polls its queue, processes a bounded number of messages at once, and deletes each message only after its work has committed. Long polling waits up to 20 seconds for messages instead of returning empty responses (AWS: long polling), and one receive returns at most 10 messages (AWS: ReceiveMessage).
type Envelope struct {
EventID string `json:"event_id"`
Type string `json:"type"`
Version int `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
Producer string `json:"producer"`
CorrelationID string `json:"correlation_id"`
Payload json.RawMessage `json:"payload"`
}
type Handler func(ctx context.Context, msg sqstypes.Message) error
// Consume long-polls one queue and runs at most `workers` messages at a time.
// It only receives as many messages as it has free workers, so no message
// sits in memory while its visibility timeout runs down.
func Consume(ctx context.Context, client *sqs.Client, queueURL string, workers int, visibility time.Duration, handle Handler) error {
sem := make(chan struct{}, workers)
for ctx.Err() == nil {
free := cap(sem) - len(sem)
if free == 0 {
time.Sleep(50 * time.Millisecond)
continue
}
out, err := client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueURL),
MaxNumberOfMessages: int32(min(10, free)),
WaitTimeSeconds: 20,
VisibilityTimeout: int32(visibility.Seconds()),
MessageSystemAttributeNames: []sqstypes.MessageSystemAttributeName{
sqstypes.MessageSystemAttributeNameApproximateReceiveCount,
},
})
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
time.Sleep(time.Second) // Part VI replaces this with backoff and jitter
continue
}
for _, msg := range out.Messages {
sem <- struct{}{}
go func(msg sqstypes.Message) {
defer func() { <-sem }()
processOne(ctx, client, queueURL, visibility, msg, handle)
}(msg)
}
}
return ctx.Err()
}
// creditHandler applies payment events to wallets, at most once per event_id.
func creditHandler(pool *pgxpool.Pool) Handler {
return func(ctx context.Context, msg sqstypes.Message) error {
var ev Envelope
if err := json.Unmarshal([]byte(aws.ToString(msg.Body)), &ev); err != nil {
return fmt.Errorf("bad envelope: %w", err) // retried, then dead-lettered
}
_, err := HandleOnce(ctx, pool, "wallet-credit", ev.EventID, func(tx pgx.Tx) error {
return applyPaymentEvent(ctx, tx, ev) // state machine + ledger, Parts 1 and 2
})
return err
}
}HandleOnce is the inbox from Part 3. applyPaymentEvent stands for the state machine and ledger code from Parts 1 and 2. The function that processes one message, processOne, depends on the visibility timeout, so it's in Chapter 10.
Backpressure: the queue absorbs, the database decides
A big benefit of a queue is that it absorbs bursts: a sale, a payday, or a provider dumping a backlog of webhooks becomes a longer queue instead of an overloaded database.
That only works if consumers pull at a rate the database can handle, so set worker concurrency from database capacity, not from how many messages are waiting. Doubling workers when the queue grows can double the load on an already struggling database. Part V covers connection budgets, and Part VI covers how to recover from a backlog without overwhelming anything.
Lambda as a consumer
If your consumers are Lambda functions, AWS handles the polling loop, and you need to get two settings right. Set the queue's visibility timeout “to at least six times” the function's timeout (AWS: Lambda with SQS).
Then enable ReportBatchItemFailures, so a batch with one bad message only retries that message; otherwise, if the function throws, “the entire batch is considered a complete failure” and every message in it is redelivered (AWS: Lambda SQS error handling).
Checklist
- Requests only validate, record intent durably and acknowledge; real work runs on workers.
- Webhooks verify signatures and return 2xx only after the raw event is committed.
- Provider payloads are normalised into one versioned envelope with a stable
event_id. - Events go to topics; commands go to the queue of the one handler that owns them.
- Each consumer has its own queue, filter policy, retry policy and dead-letter queue.
- Worker concurrency is set from database capacity, not queue depth.
- No state exists only on a queue.
Chapter 10
Understanding SQS visibility timeout and worker concurrency
This chapter is about a single setting. I'm giving it a whole chapter because it's the one most often mistaken for a correctness guarantee.
What the visibility timeout is
When a consumer receives a message, SQS doesn't remove it. It hides it from other consumers for a while: the visibility timeout. During that time, the consumer is expected to process the message and delete it.
If it doesn't delete it in time, the message “becomes visible again in the queue and can be retrieved by another consumer” (AWS: visibility timeout). The default is 30 seconds, and a message can be kept hidden for at most 12 hours from when it was first received.
DeleteMessage. Only the delete removes the message.This design is what makes SQS reliable: a consumer that crashes mid-way doesn't lose the message, because it was never deleted. After the timeout, someone else gets it. The trouble is what that means when the first consumer didn't crash and is just slow.
When processing outlives the timeout
Worker A received the message and started work. The database was slow (a long lock wait, an autovacuum on a hot table), and the work took 75 seconds against a 60-second timeout. At 60 seconds, SQS made the message visible again, and worker B received it. Now two workers are processing the same payment event at the same time.
AWS is clear that this isn't the only way it can happen: even within the timeout, “there's no absolute guarantee that a message won't be delivered more than once” (AWS: visibility timeout).
Committed, but not deleted
A message can also come back a second way, with less noise. The worker commits its database transaction, then crashes, or the DeleteMessage call fails on a network blip, before the message is deleted. The work is done; the queue doesn't know. After the timeout, the message is redelivered.
There's no ordering of “commit” and “delete” that fixes this. Delete first and crash before commit, and you lose the work. Commit first and crash before delete, and you see it again. The second is the safe one, because the inbox from Part 3 recognises the event ID and skips it. Put together: at-least-once delivery, plus an idempotent consumer, gives effectively-once processing.
Receipt handles add one more wrinkle. Each time a message is received you get a different receipt handle, and you must delete with the most recent one. With an old handle, AWS says “the request will succeed, but the message might not be deleted” (AWS: DeleteMessage). The same page adds that, for standard queues, it's possible to receive a message even after you delete it. That's one more case only idempotency covers.
Choosing the visibility timeout
- Measure first. Use the p99 processing time for the queue's work, not the average, including time waiting for database connections and locks.
- Add a safety margin. I start at about three times the p99. Too short and you get needless redeliveries and duplicate work under load. Too long and a crashed worker's message sits hidden for a long time before anyone retries it.
- Set a processing deadline below it. Give the handler a context that expires at, say, three-quarters of the timeout. A worker that gives up and rolls back before its lease ends never races its own redelivery.
- For Lambda, follow the six-times-the-function-timeout rule from Chapter 9.
This is the processing function the consumer in Chapter 9 calls, with that deadline:
// processOne runs the handler with a deadline shorter than the visibility timeout,
// and deletes the message only if the handler succeeded.
func processOne(ctx context.Context, client *sqs.Client, queueURL string, visibility time.Duration, msg sqstypes.Message, handle Handler) {
workCtx, cancel := context.WithTimeout(ctx, visibility*3/4)
defer cancel()
if err := handle(workCtx, msg); err != nil {
// Don't delete. SQS makes the message visible again after the timeout,
// and after maxReceiveCount receives the redrive policy moves it to the DLQ.
slog.Warn("message failed",
"message_id", aws.ToString(msg.MessageId),
"receive_count", msg.Attributes["ApproximateReceiveCount"],
"err", err)
return
}
// Use a context that outlives a shutdown signal: the work is committed, so try
// hard to delete. If this fails, the message comes back and the inbox skips it.
_, err := client.DeleteMessage(context.WithoutCancel(ctx), &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: msg.ReceiptHandle,
})
if err != nil {
slog.Warn("delete failed after commit", "message_id", aws.ToString(msg.MessageId), "err", err)
}
}Long-running work: a heartbeat
Some steps legitimately take a long time: reconciling a large payout batch, or waiting on a slow provider. Rather than setting a huge timeout for every message, AWS suggests a heartbeat that “periodically extend[s] the visibility timeout” (AWS: visibility timeout) while the work is running:
// keepInvisible extends the message's visibility every visibility/3 until ctx is done.
// Run it in a goroutine next to long work, and cancel ctx when the work finishes.
func keepInvisible(ctx context.Context, client *sqs.Client, queueURL string, receipt *string, visibility time.Duration) {
ticker := time.NewTicker(visibility / 3)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_, err := client.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: receipt,
VisibilityTimeout: int32(visibility.Seconds()),
})
if err != nil {
// We may lose the lease and see a redelivery. Idempotency still protects us.
slog.Warn("could not extend visibility", "err", err)
return
}
}
}
}A heartbeat ties the lease to the worker being alive. If the worker hangs or dies, extensions stop and the message comes back within one timeout. There's still the 12-hour ceiling, though: no amount of extending keeps a message hidden longer than that.
Retries, receive counts and dead-letter queues
A message that keeps failing, say because its payload is malformed, will be received again and again. Each receive increments ApproximateReceiveCount, “the number of times a message has been received across all queues but not deleted” (AWS: ReceiveMessage). A redrive policy moves the message to a dead-letter queue (DLQ) once it has been received maxReceiveCount times (AWS: dead-letter queues):
{
"deadLetterTargetArn": "arn:aws:sqs:eu-west-1:111122223333:wallet-credit-dlq",
"maxReceiveCount": "5"
}- Choose
maxReceiveCountso that transient problems (a short database blip) get enough retries, but a poison message reaches the DLQ within minutes, not days. - Every message in a payments DLQ is a payment someone is waiting on. Alert on DLQ depth above zero, and have a runbook for inspecting, fixing and redriving messages.
- Redriving after a fix is safe only because consumers are idempotent: messages that partly succeeded before failing won't be applied twice.
What to monitor
| Metric | What it tells you | Illustrative alert |
|---|---|---|
ApproximateAgeOfOldestMessage | “The age of the oldest unprocessed message”: how far behind you are | Above a few minutes for a payments queue |
ApproximateNumberOfMessagesVisible | Messages waiting to be received: the backlog | Growing steadily for 10+ minutes |
ApproximateNumberOfMessagesNotVisible | Messages received but not yet deleted: in-flight work | Close to your concurrency limit for long periods |
| DLQ visible messages | Payments that have stopped being retried | Any value above zero |
| Receive count above 1 (from logs) | Redeliveries: timeouts, failed deletes or crashes | A sudden rise |
| Processing time p99 vs visibility timeout | How close you are to timeout-driven duplicates | p99 above half the timeout |
The first three are standard CloudWatch metrics for SQS (AWS: SQS CloudWatch metrics). I'd look at the age of the oldest message first. Depth tells you how much is waiting; age tells you how long a customer has been waiting.
What to test
- Set a tiny visibility timeout (a few seconds), make the handler sleep longer, and run two consumers. Expect both to receive the message and exactly one effect.
- Make
DeleteMessagefail after a successful commit. Expect a redelivery that the inbox skips. - Send a malformed message. Expect it in the DLQ after
maxReceiveCountreceives, and an alert. - Run a long task with the heartbeat, then kill the worker mid-way. Expect redelivery within one timeout.
Checklist
- No code or document treats the visibility timeout as a guarantee against duplicates.
- The timeout is set from measured p99 processing time, with margin.
- Handlers run with a deadline shorter than the visibility timeout.
- Long work extends visibility with a heartbeat that stops when the worker stops.
- Messages are deleted only after the work commits.
- Every queue has a redrive policy, and DLQ depth above zero alerts a person.
- Age of the oldest message is on the dashboard for every payment queue.
Chapter 11
Designing reliable transactional outbox and inbox patterns
The dual-write problem
When a payment succeeds, the payment service does two things: it commits the new state to PostgreSQL, and it publishes payment.succeeded to SNS. These are writes to two different systems, and there's no transaction that spans both. Whichever order you put them in, a crash between them leaves the systems disagreeing.
- Commit, then publish. The commit succeeds, then the process crashes or SNS is briefly unavailable. The payment is
SUCCESSin the database, but no event was sent. The wallet is never credited, and nothing will ever retry, because nothing knows the event is missing. - Publish, then commit. SNS accepts the event, then the commit fails (a constraint, a deadlock, a crash). Workers now credit a wallet for a payment that doesn't exist in the database. This is the more dangerous of the two, because you've announced something that isn't true.
A related version of the second case is publishing inside the transaction, before COMMIT. It feels safer, but the database can still roll back after SNS has accepted the message, and now your transaction is also holding locks while it waits on a network call.
The transactional outbox
The fix is to do one write instead of two. Write the event to an outbox table in the same database, in the same transaction as the state change. A separate publisher reads the outbox and publishes to SNS. AWS's own pattern guide describes it as resolving “the dual write operations issue that occurs in distributed systems” (AWS: transactional outbox pattern).
BEGIN;
UPDATE payments SET status = 'SUCCESS', updated_at = now()
WHERE id = 'pay_81' AND status = 'PROCESSING';
-- … ledger journal and entries, as in Part 2 …
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ('payment', 'pay_81', 'payment.succeeded',
'{"payment_id": "pay_81", "amount_minor": 4000, "currency": "EUR"}');
COMMIT;Now there's only one write that matters, and it's atomic. If the transaction commits, the event exists and will be published, however many crashes happen afterwards. If it rolls back, the event never existed. Publishing becomes a separate job that can be retried as many times as it takes.
The outbox table
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE, -- what consumers deduplicate on
aggregate_type text NOT NULL, -- 'payment', 'withdrawal', 'provider_event'
aggregate_id text NOT NULL,
event_type text NOT NULL, -- 'payment.succeeded'
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'PENDING'
CHECK (status IN ('PENDING', 'PUBLISHED', 'FAILED')),
attempts integer NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
locked_until timestamptz, -- a publisher's claim on the row
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
-- Publishers only ever look for pending rows that are due.
CREATE INDEX outbox_due ON outbox (next_attempt_at) WHERE status = 'PENDING';The event_id is generated when the row is inserted, so every publication of this event, including republication after a crash, carries the same ID. The partial index stays small however big the table gets, because published rows aren't in it.
In Go, writing an event is one more statement inside the business transaction:
// enqueueEvent writes an event to the outbox inside the caller's transaction,
// so it commits (or rolls back) together with the change it describes.
func enqueueEvent(ctx context.Context, tx pgx.Tx, aggregateType, aggregateID, eventType string, payload any) error {
body, err := json.Marshal(payload)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ($1, $2, $3, $4)`,
aggregateType, aggregateID, eventType, body)
return err
}The publisher: claim, publish, record
The publisher is a loop that claims a batch of due rows, publishes each one, and records the result. These choices make it safe to run several publishers at once and to crash at any point:
- Claim with a lease, using
SKIP LOCKED.FOR UPDATE SKIP LOCKEDmakes each publisher skip rows another publisher is claiming right now (PostgreSQL: the locking clause). The claim setslocked_untiland commits immediately, so no transaction stays open while publishing. - Publish outside any transaction. The SNS call is a network call; it never happens while holding database locks.
- Record success or schedule a retry. Success marks the row
PUBLISHED. Failure clears the claim and pushesnext_attempt_atinto the future with exponential backoff. After too many attempts, the row becomesFAILEDand someone is alerted.
-- Claim: up to 50 due rows for 30 seconds. Rows claimed by others are skipped.
UPDATE outbox
SET locked_until = now() + interval '30 seconds', attempts = attempts + 1
WHERE id IN (
SELECT id FROM outbox
WHERE status = 'PENDING'
AND next_attempt_at <= now()
AND (locked_until IS NULL OR locked_until < now())
ORDER BY id
LIMIT 50
FOR UPDATE SKIP LOCKED)
RETURNING id, event_id::text, aggregate_type, aggregate_id, event_type, payload, created_at, attempts;
-- Success
UPDATE outbox SET status = 'PUBLISHED', published_at = now(), locked_until = NULL WHERE id = $1;
-- Failure: back off exponentially (capped at 5 minutes), give up after 10 attempts
UPDATE outbox
SET locked_until = NULL,
last_error = $2,
next_attempt_at = now() + make_interval(secs => least(300, 2 ^ attempts)),
status = CASE WHEN attempts >= 10 THEN 'FAILED' ELSE 'PENDING' END
WHERE id = $1;type outboxRow struct {
ID int64
EventID string
AggregateType string
AggregateID string
EventType string
Payload json.RawMessage
CreatedAt time.Time
Attempts int
}
// PublishBatch claims due outbox rows, publishes each to SNS and records the outcome.
// A crash after Publish but before the UPDATE means the event is sent again later
// with the same event_id; consumers deduplicate on it.
func PublishBatch(ctx context.Context, pool *pgxpool.Pool, client *sns.Client, topicARN string) (int, error) {
rows, err := pool.Query(ctx, claimSQL)
if err != nil {
return 0, err
}
batch, err := pgx.CollectRows(rows, pgx.RowToStructByPos[outboxRow])
if err != nil {
return 0, err
}
published := 0
for _, r := range batch {
body, err := json.Marshal(Envelope{
EventID: r.EventID, Type: r.EventType, Version: 1,
OccurredAt: r.CreatedAt.UTC(), Producer: "payments", Payload: r.Payload,
})
if err != nil {
return published, err
}
_, err = client.Publish(ctx, &sns.PublishInput{
TopicArn: aws.String(topicARN),
Message: aws.String(string(body)),
MessageAttributes: map[string]snstypes.MessageAttributeValue{
"event_type": {DataType: aws.String("String"), StringValue: aws.String(r.EventType)},
},
})
if err != nil {
if _, dbErr := pool.Exec(ctx, retrySQL, r.ID, err.Error()); dbErr != nil {
return published, dbErr
}
continue
}
if _, err := pool.Exec(ctx, markPublishedSQL, r.ID); err != nil {
return published, err
}
published++
}
return published, nil
}The event_type message attribute is what the SNS filter policies in Chapter 9 match on. claimSQL, markPublishedSQL and retrySQL are the three statements above.
Crashes, leases and duplicate publication
Take a crash at the worst possible moment: after SNS accepted the event, before the row was marked published.
The claim's lease (locked_until) is what recovers from this. The crashed publisher's rows stay PENDING; once the lease expires, any publisher can claim them again. This is lease recovery, and it needs no coordination between publishers. The cost is that the event gets published twice. AWS's guide says the same: the relay “might send out duplicate messages or events”, so consumers must be idempotent (AWS: transactional outbox pattern).
Ordering, poison events and cleanup
With several publishers and retries, events can be published out of order, even for the same payment. Usually that's fine, because consumers check events against the state machine. If a consumer needs per-payment order, publish to an SNS FIFO topic with the aggregate ID as the message group, and make sure only one publisher handles a given aggregate at a time.
An event that can never be published (too large, or rejected by validation) shouldn't hold up the others, which is why each row is retried on its own and becomes FAILED after a limit. Alert on any FAILED row; it's an event your consumers will never see.
As for retention, the outbox is a delivery mechanism, not an audit log; the ledger and history tables are the audit log. Delete published rows after a few days, or partition the table by day and drop old partitions, which is cheaper on a busy table.
-- Housekeeping: published rows are no longer needed after a few days
DELETE FROM outbox WHERE status = 'PUBLISHED' AND published_at < now() - interval '7 days';
-- Outbox lag: how far behind publishing is (alert if the oldest pending row is old)
SELECT count(*) AS pending, max(now() - created_at) AS oldest_pending
FROM outbox
WHERE status = 'PENDING';Outbox lag, the age of the oldest pending row, is the outbox's equivalent of the queue's oldest-message age. If it grows, events are committed but not announced: wallets aren't being credited even though payments succeeded. Put it next to the SQS metrics on the same dashboard.
The inbox, revisited
The other half of the pattern is the inbox on every consumer, which you built in Part 3. It stores each incoming event's identity behind a uniqueness constraint, processes the business operation in the same transaction, and treats a duplicate as a successful no-op. The two halves combine like this:
- the outbox guarantees every committed change is announced at least once;
- the inbox guarantees every announcement is applied at most once;
- so every committed change is applied exactly once downstream, even though nothing in between is exactly-once.
The webhook ingestion at the start of this part is an inbox and an outbox in one transaction: provider_events deduplicates what PayCo sends, and the outbox row announces it.
Polling, change data capture or event sourcing?
| Approach | How events get out | Strengths | Costs |
|---|---|---|---|
| Polling outbox | A publisher queries the outbox table | Simple, no extra infrastructure, easy to debug with SQL | Polling load and latency; you run the publisher |
| Outbox + change data capture | A CDC tool reads the database's write-ahead log and forwards outbox inserts | Low latency, no polling queries | A CDC platform to run, e.g. Debezium with its outbox event router |
| Event sourcing | The events are the stored state; there is nothing extra to publish | One source of truth for state and events | A different programming model for the whole service |
Debezium's outbox event router is built for the middle row: it captures changes to an outbox table and routes them as events (Debezium: outbox event router). It makes sense once polling load or latency becomes a problem, or if you already run Kafka Connect.
I'd start with a polling outbox, though. It's a table and a loop, and the whole team can debug it with SQL. As Part II said, event sourcing and an immutable ledger are related but not the same thing; you don't need to event-source the whole service to get reliable events.
When an outbox is worth it, and when it isn't
An outbox means another table, a publisher to run, and monitoring and housekeeping on top. For anything involving money that's worth paying, because a lost event is a lost payment. For low-risk internal signals, a simpler approach can be fine:
| Event | If it's lost… | Approach |
|---|---|---|
payment.succeeded (credits a wallet) | A customer paid and got nothing | Outbox |
payout.requested | A withdrawal never goes out | Outbox |
receipt.email | A customer misses an email; support can resend | Outbox if cheap, or publish after commit plus a daily sweep |
| Cache invalidation | A stale cache entry until its TTL expires | Publish after commit, best effort |
| Analytics event | A dashboard is off by one | Publish after commit, best effort |
The question to ask is whether losing the event means losing track of money, the second of the handbook's three principles. If it does, it goes through the outbox.
Common mistakes
- Publishing to SNS inside or before the database transaction.
- Generating a new event ID each time a row is republished, so consumers can't deduplicate.
- Holding the claim transaction open while calling SNS.
- No lease on claims, so rows claimed by a crashed publisher are stuck forever.
- One poison row blocking the whole outbox.
- Treating the outbox as permanent history and letting it grow forever.
- Not monitoring outbox lag, so “published” and “committed” drift apart unnoticed.
What to test
- Roll back a business transaction after inserting an outbox row. Expect no event, ever.
- Crash the publisher after
Publishand before marking the row. Expect a second publication after the lease expires, and exactly one effect at the consumer. - Run three publishers against the same outbox. Expect every row published, and no row claimed by two publishers at the same moment.
- Make SNS reject one event permanently. Expect the others to flow, and that row to end up
FAILEDwith an alert. - Stop the publisher for ten minutes. Expect the outbox-lag alert, and a clean catch-up when it restarts.
Checklist
- Every event about money is written to an outbox in the same transaction as the change.
- Each event gets a stable
event_idwhen it's created, reused on every publication. - Publishers claim rows with
SKIP LOCKEDand a lease, and publish outside transactions. - Failed publications back off, and rows that keep failing become
FAILEDand alert. - Every consumer has an inbox keyed on
event_id. - Outbox lag is monitored alongside queue age.
- Published rows are cleaned up on a schedule.
Further reading
- AWS: SQS visibility timeout: leases, heartbeats and the 12-hour limit.
- AWS: DeleteMessage: receipt handles and redelivery.
- AWS: dead-letter queues and SQS CloudWatch metrics.
- AWS: standard queues and FIFO delivery logic: ordering and duplicates.
- AWS: Lambda with SQS and partial batch responses.
- AWS: SNS message filtering.
- AWS Prescriptive Guidance: transactional outbox.
- Debezium: outbox event router: the change-data-capture approach.
What's next
The pipeline is now reliable. Events aren't lost, duplicates do no harm, and a slow consumer doesn't hold up the fast ones.
Reliability isn't the same as performance, though. Part V, Workflow Design and Database Performance, looks at long-running payment workflows like withdrawals that must survive crashes halfway through, at connection pools and why scaling workers can take down your database, and at keeping transactions short enough that none of this queues up behind a lock.
If this was useful
Pass it on to someone who's building or fixing a payment system, or share it with your network. The handbook is free, and people passing it on is how it reaches the engineers it was written for.