An idempotency lease with a conditional ON CONFLICT, an outbox relayed with publisher confirms, consumer-side dedupe and a Stripe webhook that settles once, with at-least-once delivery on every hop
Published: November 21, 2026
Reading time: 18 min
Keywords: transactional outbox, idempotency key, payment idempotency, rabbitmq publisher confirms, stripe webhook hmac
Payments Platform in practice series
A client sends POST /api/v1/payments. The network drops before the response arrives. The client app does what any reasonable app does: it retries. If the server treats the second request as new, the customer pays twice.
On the other side, the server stores the payment and has to tell the notifications module through RabbitMQ. If it publishes before the commit and the transaction fails, there is a notification for a payment that does not exist. If it commits and crashes before publishing, there is a payment nobody was told about.
And when Stripe confirms the charge, it sends a webhook. If the server is slow to answer, Stripe sends it again. The same event can arrive two or three times.
All three problems share a root: no network delivery is exactly-once. What you can build is at-least-once delivery with effects that happen once, and that takes a different defense at each edge. This chapter walks through the Payments Platform's four defenses, in the order a payment meets them, and where each one stops.
In chapter 3 we saw how facts are stored in the event store. Now the subject is what happens at the edges, where the system talks to clients, the broker and the payment provider. Code from commit 5277f6c.
Every arrow that crosses the network can fail or repeat. Every commit box is where the system turns that uncertainty into a known state.
The client sends an Idempotency-Key header. The server must guarantee three things: the same key with the same body returns the same response; the same key with a different body is rejected; and two concurrent requests with the same key do not create two payments.
The table is simple, with primary key (user_id, key):
-- src/main/resources/db/migration/V1__shared.sql:26-37
CREATE TABLE idempotency_keys (
key VARCHAR(120) NOT NULL,
user_id UUID NOT NULL,
request_hash VARCHAR(64) NOT NULL,
status VARCHAR(30) NOT NULL,
response_code INTEGER NULL,
response_body JSONB NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
lease_id UUID,
PRIMARY KEY (user_id, key)
);
Acquiring the lease is a single SQL statement:
-- src/main/java/com/muse/payments/shared/infrastructure/idempotency/JdbcIdempotencyRepository.java:52-62
INSERT INTO idempotency_keys (key, user_id, request_hash, status, created_at, expires_at, lease_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (user_id, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash,
status = EXCLUDED.status,
response_code = NULL,
response_body = NULL,
created_at = EXCLUDED.created_at,
expires_at = EXCLUDED.expires_at,
lease_id = EXCLUDED.lease_id
WHERE idempotency_keys.expires_at <= EXCLUDED.created_at
The detail that matters is the WHERE at the end. Without it, ON CONFLICT DO UPDATE would overwrite any existing row, including one for a request still in flight. With it, the existing row is only taken over if it has expired. Otherwise the statement affects zero rows, and the code knows another request got there first.
That choice resolves concurrency inside PostgreSQL itself, with no explicit lock and without the gap that exists between a SELECT and an INSERT. Two simultaneous requests with the same key compete for the same row: one inserts, the other gets rowsAffected = 0. IdempotencyService then reads the live row and decides (IdempotencyService.java):
PROCESSING: another request is in flight, the answer is 409.COMPLETED with the same body hash: replay, return the stored response.COMPLETED with a different hash: "payload mismatch", 409.The lease_id protects against a subtler problem. Suppose request A takes the lease, stalls for more than two minutes (the PROCESSING TTL), the lease expires, request B takes a new lease for the same key, and then A wakes up and tries to record completion. Unprotected, A would overwrite B's state. markCompleted requires the same lease_id and an unexpired lease:
// src/main/java/com/muse/payments/shared/infrastructure/idempotency/JdbcIdempotencyRepository.java:87-91
String sql = """
UPDATE idempotency_keys
SET status = ?, response_code = ?, response_body = CAST(? AS JSONB), expires_at = ?
WHERE user_id = ? AND key = ? AND status = ? AND request_hash = ? AND lease_id = ? AND expires_at > ?
""";
If A's lease is no longer current, the UPDATE affects zero rows and saveCompleted throws, which rolls back A's transaction.
There is one last piece I find elegant. The payment id is not a UUID.randomUUID(). It is derived from the lease:
// src/main/java/com/muse/payments/payments/application/PaymentIds.java:17-20
public static UUID forLease(UUID userId, String idempotencyKey, Instant leaseCreatedAt) {
String name = userId + ":" + idempotencyKey + ":" + leaseCreatedAt.toEpochMilli();
return UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8));
}
Within one lease, every attempt produces the same id, and that id becomes the Idempotency-Key sent to the fraud provider and to Stripe. A new lease for the same client key, after the previous one expired or was released, produces a different id, because the lease's createdAt is part of the seed. A new payment never reuses an old payment's idempotency key at the provider.
The create use case shows the order ADR 0012 requires:
// src/main/java/com/muse/payments/payments/application/CreatePaymentUseCase.java:46-53
IdempotencyDecision decision = idempotencyPort.acquireProcessing(userId, idempotencyKey, payloadJson);
if (decision.isReplayed()) {
return new CreatePaymentResult.Replayed(StoredCreateOutcome.read(objectMapper, decision.responseBody()));
}
UUID paymentId = PaymentIds.forLease(userId, idempotencyKey, decision.acquiredAt());
try {
Money money = Money.of(canonical.amount(), canonical.currency());
FraudScreeningResult screening = fraudScreeningPort.screen(
REQUIRES_NEW), before any external call.COMPLETED commit together, in one transactionTemplate.execute (CreatePaymentUseCase.java:71-85).Step 3 is what closes the duplicate window. If the process dies after the commit, the replay finds COMPLETED and returns the response. If it dies before, nothing was written except the PROCESSING lease, which expires in two minutes. ADR 0012 owns the cost: a crash in that window can return 409 for the same key until the lease expires. "Two minutes is the bound, not 24 hours." Once completed, the response is kept for 24 hours (COMPLETED_TTL).
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
The same payment has two findById methods: one rebuilds the aggregate from events, the other reads an indexed projection. That is what CQRS means in the Payments Platform, with no second database.

Approach Designing Data-Intensive Applications through replication, stale reads and observable application contracts.
A BIGSERIAL sequence hands out numbers in order, but transactions commit out of order. If your async projection trusts global_position, it can lose events without a single error.
A 47-point checklist to find bugs, security risks, and performance issues before launch.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
The integration event is written to outbox_events in the same transaction as the payment. The outbox adapter enforces it: OutboxJpaAdapter.append carries @Transactional(propagation = Propagation.MANDATORY) (OutboxJpaAdapter.java:36) and fails if no transaction is in progress. Writing an outbox row in a transaction separate from the state change would defeat the whole pattern.
Publishing is the job of OutboxRelayService, scheduled every second. The contract is in the javadoc:
// src/main/java/com/muse/payments/shared/infrastructure/OutboxRelayService.java:86-94
/**
* Drains due outbox rows in batches. One transaction claims a batch, the batch is sent
* to the broker without waiting between messages, the publisher confirms are awaited
* together, and one transaction marks every confirmed row. A failed row is rescheduled
* on its own, so one bad event does not hold back the rest of the batch.
*
* <p>A batch holds at most one event per aggregate. A later event of the same aggregate
* is left unclaimed and goes out in a following batch, after the earlier one was confirmed.
*/
Every sentence in that comment maps to a decision.
Claim with a lease, not a status. The relay selects due rows with FOR UPDATE SKIP LOCKED (OutboxJpaRepository.java:20-24) and, in the same transaction, pushes those rows' next_attempt_at into the future:
// src/main/java/com/muse/payments/shared/infrastructure/OutboxJpaRepository.java:33-38
@Query(value = """
UPDATE outbox_events
SET next_attempt_at = :leaseUntil
WHERE id IN (:ids)
AND published_at IS NULL
""", nativeQuery = true)
leaseUntil is the confirm timeout (5 s by default) plus a 10 s margin. There is no CLAIMED status column. If the relay dies after the claim, the rows simply become due again when the lease runs out, and another instance picks them up. No row gets stuck in an intermediate state waiting for manual intervention.
Pipelined publishing with confirmation. The batch is sent without waiting between messages, and publisher confirms are awaited afterwards. RabbitTemplate is configured with correlated confirms (publisher-confirm-type: correlated in application.yml) and mandatory = true (RabbitMqConfig.java:167). Checking each message handles three different failures:
// src/main/java/com/muse/payments/shared/infrastructure/OutboxRelayService.java:244-252
ReturnedMessage returned = correlation.getReturned();
if (returned != null) {
throw new IllegalStateException("Broker returned unroutable outbox event " + eventId
+ ": " + returned.getReplyText());
}
if (confirm == null || !confirm.isAck()) {
String reason = confirm == null ? "missing confirm" : confirm.getReason();
throw new IllegalStateException("Broker nacked outbox event " + eventId + ": " + reason);
}
A confirm alone is not enough. RabbitMQ acks a message that reached the exchange even if no queue is bound to its routing key. Without mandatory, an accidentally deleted binding makes the relay mark as published an event that was dropped. With mandatory, the broker returns the message and the relay reschedules the row.
Mark only after the confirm. Only confirmed rows get published_at, in a single UPDATE. Failed rows are rescheduled individually with exponential backoff.
One event per aggregate per batch. If a batch held PaymentCreated and PaymentCompleted for the same payment and the first failed, the second would go out first. The relay leaves later events of the same aggregate for the next batch (OutboxRelayService.java:120-127). That preserves per-aggregate order on the happy path. On a retry, order can still flip: if the first event fails and is rescheduled a few seconds out, the second can go first. Consumers that depend on strict order need to look at the aggregate version.
ADR 0015 records the effect of batching, measured on a local machine with JDK 25.0.1 and 11 processors, with PostgreSQL 16 and RabbitMQ 3.13 in Testcontainers: draining 2,000 rows went from 131, 216 and 277 events/s (three rounds) to 872, 995 and 915 events/s. The ADR itself warns that these are single runs, not a benchmark suite. I read them as the order of magnitude of the improvement, not as system capacity.
If the broker confirms the message and the relay crashes before the UPDATE that sets published_at, the row becomes due again when the lease expires, and the event is published again. The relay is at-least-once by definition. No tweak to the relay removes that window, because the broker and the database are two systems with two commits. Deduplication has to happen on the receiving side.
The notifications consumer receives X-Event-Id on every message and writes the marker and the effect in the same transaction:
// src/main/java/com/muse/payments/notifications/infrastructure/PaymentNotificationConsumer.java:64-70
boolean isNewEvent = processedEventStore.tryMarkProcessed(CONSUMER_NAME, eventId);
if (!isNewEvent) {
log.info("Duplicate event {} already processed by {}. Discarding duplicate.", eventId, CONSUMER_NAME);
return;
}
notificationRepository.save(notification);
tryMarkProcessed is an INSERT ... ON CONFLICT (consumer, event_id) DO NOTHING (JdbcProcessedEventStore.java:22-34). The whole listener is @Transactional. If saving the notification fails, the rollback also undoes the marker, and the redelivery processes it again. There is no "marked as processed, but no effect" state.
The (consumer, event_id) key lets several consumers process the same event, each with its own record.
Failures are split into two kinds in the listener configuration (RabbitMqConfig.java). A transient failure, such as the database being down, gets up to 5 attempts with exponential backoff from 500 ms to 10 s and then goes to the DLQ. A permanent failure, such as invalid JSON or an event with no id or type, throws AmqpRejectAndDontRequeueException and goes straight to the DLQ, without spending the retry budget on a message that will never pass.
The limitation: the key is the producer's event_id. If someone manually recreates an outbox row with a new id, the consumer does not recognize the duplicate. And processed_events is purged after 30 days by the retention job, covered in chapter 5. A redelivery after that would be processed as new. In practice the relay only republishes before marking a row as published, so that window is theoretical, but it exists and it defines the real horizon of deduplication.
The payment provider integration follows ADR 0019. PaymentProviderStrategy is the port, and Stripe is the first implementation. The registry resolves the provider from the id in the webhook path and has no fallback: "a typo in the path never settles a payment at the wrong provider" (PaymentProviderRegistry.java:13-17).
The webhook goes through four stages.
Size limit first. A body over 512 KiB is rejected before any verification (ProcessProviderWebhookUseCase.java:22-40). Computing an HMAC over an arbitrarily large payload is a cheap denial-of-service vector.
Signature over the received bytes. The controller takes the body as byte[], without deserializing it. Stripe signs timestamp + "." + body, and any reformatting of the JSON (whitespace, field order, line breaks) invalidates the signature. A common mistake is to parse into a Java object and re-serialize it to verify.
// src/main/java/com/muse/payments/payments/infrastructure/psp/stripe/StripePaymentProviderAdapter.java:127-135
SignatureParts parts = parseHeader(header);
verifyTolerance(parts.timestamp());
String signedPayload = parts.timestamp() + "." + request.rawBody();
byte[] expected = hmac(signedPayload);
boolean matched = parts.signatures().stream()
.anyMatch(candidate -> matches(expected, candidate));
if (!matched) {
throw new InvalidProviderSignatureException("Signature verification failed");
}
The comparison uses MessageDigest.isEqual, which runs in constant time (StripePaymentProviderAdapter.java:210-214). A regular equals returns at the first differing byte, and the timing difference can be used to recover the signature byte by byte. The timestamp tolerance is checked against an injected Clock, which limits replays of old webhooks and keeps the test deterministic. One implementation detail: the use case decodes the bytes as UTF-8 into a String and the HMAC re-encodes them as UTF-8. For valid UTF-8 JSON, which is what Stripe sends, the round trip preserves the bytes.
Claim and settlement in the same transaction.
// src/main/java/com/muse/payments/payments/application/PaymentProviderSettlementService.java:61-77
@Transactional
public PaymentWebhookResponse settle(ProviderWebhookEvent event) {
Objects.requireNonNull(event, "event must not be null");
if (!eventStore.claim(event.provider(), event.eventId(), event.eventType(), event.paymentId())) {
duplicates.increment();
return new PaymentWebhookResponse(event.provider(), event.eventId(), PaymentWebhookResponse.DUPLICATE);
}
String outcome;
try {
outcome = apply(event);
} catch (RuntimeException ex) {
eventStore.resolve(event.provider(), event.eventId(), "FAILED");
throw ex;
}
eventStore.resolve(event.provider(), event.eventId(), outcome);
return new PaymentWebhookResponse(event.provider(), event.eventId(), outcome);
}
The claim is a row in payment_provider_events, with primary key (provider, event_id) (V9__payment_provider_webhooks.sql:11-19). A redelivery of the same event finds the row and answers DUPLICATE with a 200, so Stripe stops resending. If settlement fails, the exception propagates, the whole transaction rolls back (claim included), and the 500 makes Stripe retry later. The resolve(..., "FAILED") before the throw is undone by the same rollback. The redelivery finds no row and tries to settle again.
Domain rules the webhook cannot bypass. Settlement calls Payment.settleFromProvider, which has four guards (Payment.java:169-193):
UNDER_REVIEW, held by fraud screening, is never settled by a webhook. The decision stays with the human reviewer.COMPLETED payment does nothing. A failure on a COMPLETED payment is a conflict: a completed payment is never cancelled retroactively.CANCELLED payment does not come back.The second rule is the one I would highlight in a security review. Signature verification proves Stripe sent the message. It does not prove the payment should be settled. Those are two different questions, and the second belongs to the domain.
The application service decides what to tell Stripe when one of those guards blocks settlement, and the decision is careful. An unknown event type, a missing payment, a payment not in PENDING or a domain ConflictException becomes IGNORED, with a 200 response and the payments.psp.webhook.ignored counter (PaymentProviderSettlementService.java:79-104). The class javadoc explains the criterion: "a provider retry cannot change it". Answering 500 to a webhook for a held payment would make Stripe resend for days with no chance of success. Only a local write failure, which a retry can fix, returns 500.
The Stripe intent is created after the payment commits, outside any transaction, with the payment id as the Idempotency-Key (StripePaymentProviderAdapter.java:105). Calling Stripe inside the transaction would hold a pooled connection for the full network latency, and a Stripe timeout would roll back the local payment after the intent might already exist on the other side.
The price is written in the javadoc of InitiateProviderPaymentUseCase: "A provider failure leaves the payment PENDING without a reference and is counted, never silent; reconciliation is out of scope for this sample". The failure increments the payments.psp.intent.failed counter.
These gaps are documented in the repository itself, and I would list them in any pre-production review:
PENDING payment with no provider reference stays that way. In production, a periodic reconciliation job would need to query the provider (the idempotency key is the payment id, which makes that query possible) and fix the state.PublishRetryBackoff.java:11), but the number of attempts is unbounded. An event that will never be routable keeps trying forever, logging at error level from the eighth attempt. There is no DLQ on the outbox side.UNKNOWN and are recorded as IGNORED. Disputes, chargebacks and requires_action are not modeled as states.Idempotency-Key header is required only on creation (PaymentController.java:109-115). Confirm, cancel and review are state transitions: repeating one hits the aggregate guard and returns 409, which prevents the duplicate effect but does not return the original response the way a replay would. The key's scope is user plus key, not global.PUT that writes the full state is already idempotent. The key table is for operations that create new things or move money.On November 21, 2026, I ran PspWebhookIT, MessagingNotificationsIT and IdempotencyAndAccessIT with PostgreSQL, RabbitMQ and Redis in Testcontainers: 23 tests (10, 6 and 7), 0 failures, 1 minute. The database unavailable errors in the log are expected: MessagingNotificationsIT takes the database down on purpose to exercise transient retry and the DLQ. The unit suite with OutboxRelayBatchTest, IdempotencyServiceTest and StripeWebhookSignatureTest passed with 65 tests. The full scripts/ci-local.sh gate did not run in that session.
Everything in this chapter depends on knowing when something went wrong: an outbox that does not drain, a DLQ that fills up, a fraud provider that answers 401 forever. In chapter 5 I close the series with operations: the fail-closed policy for fraud screening, the order of Resilience4j decorators, the metrics and alerts the project exposes, and the process modes for migrations and rebuilds.
If your payment flow has had a double charge or a lost event and you want to find where the windows are, that is the kind of diagnosis I do at LEMON.DEV.
java-clean-arch-sample repository, commit 5277f6c (checked on November 21, 2026).INSERT ... ON CONFLICT.