Blog

How to Make Webhook Processing Idempotent in Spring Boot

Payment providers retry webhooks, out of order and sometimes at the same time. An inbox table, a row lock and a sequencer make each event count once.

webhooksidempotencyspring-bootpostgresql

A payment provider sends payment.succeeded. Your handler marks the order paid, queues the shipment, and takes four seconds to answer because a downstream call is slow. The provider gives up after three, marks the delivery failed, and sends it again. Your handler, which already committed the first attempt, does all of it a second time. A customer gets two packages, or two refunds, and nobody notices until finance reconciles the month.

This is not an exotic failure. Payment providers commonly deliver webhooks at least once, with no ordering guarantee: the same event can arrive twice, out of order, or twice at the same moment. Your webhook handler has to make each event count exactly once anyway.

This article walks through how we did that in Ledgerline, an open-source internal demo built with Spring Boot 4, Java 25 and PostgreSQL 17. Every snippet below is copied from the repository at commit e360215.

The naive approaches, and why they break

Check, then insert. Look up the event ID; if it isn’t there, process the event and record it. Two deliveries of the same event that arrive within a few milliseconds both see “not there” and both process it. Retries that pile up after a slow response arrive exactly that close together.

A Redis “seen” set. SETNX the event ID before processing. This lives outside your database transaction, so it has two failure modes. Set the key first and crash before committing the order change, and the event is lost forever: every retry is now a “duplicate”. Set it after committing, and you are back to the race above.

A unique constraint and a caught exception. Closer. The database is now the referee. But in PostgreSQL a violated constraint aborts the whole transaction, so you can’t record anything about the duplicate (an audit row, a metric with context) in the same unit of work.

Process in arrival order. Even with perfect deduplication, order matters. If refund #5 arrives before refund #4 and you apply them as they come, a rule like “ignore events older than the last one applied” silently drops #4 and its amount. The repository keeps a test that shows exactly this loss (more below).

Answer 409 Conflict to duplicates. Most providers treat any 4xx as a failed delivery. They retry, alert you, or disable the endpoint. A duplicate is not an error from the provider’s point of view; it is your problem to absorb.

The design

Per delivery, in one database transaction:

  1. Verify the signature on the raw bytes before anything parses the body. The controller takes @RequestBody byte[], checks an HMAC-SHA256 over the timestamp and body with a 300-second tolerance, and compares with MessageDigest.isEqual. Forged and replayed deliveries never reach business code.
  2. Insert the event into an inbox table whose unique key is (provider, provider_event_id). If the row already exists, the event is a duplicate: record that and stop.
  3. Lock the order row with SELECT ... FOR UPDATE, so concurrent events for the same order are handled one at a time.
  4. Apply all of the order’s pending events in sequence order, not arrival order. Events after a gap wait until the missing one arrives.
  5. Persist the order, each event’s outcome, an audit row and an outbox row for the merchant notification, then commit.

If anything throws, the whole transaction rolls back, including the inbox row, and the endpoint answers 500, so the provider’s retry is processed as new.

Code walkthrough

1. The inbox table

The dedupe guard is a plain unique constraint. A later migration (V2) adds the order_id column used below.

-- Raw provider events, stored before processing. UNIQUE(provider, provider_event_id) is the dedupe guard.
CREATE TABLE order_events_inbox (
    id                bigserial    PRIMARY KEY,
    provider          varchar(64)  NOT NULL,
    provider_event_id varchar(255) NOT NULL,
    payload           jsonb        NOT NULL,
    signature_valid   boolean      NOT NULL,
    received_at       timestamptz  NOT NULL,
    processed_at      timestamptz,
    outcome           varchar(16)  CHECK (outcome IN ('APPLIED', 'DUPLICATE', 'STALE', 'IGNORED', 'ORPHAN',
                                                      'REJECTED', 'FAILED')),
    CONSTRAINT order_events_inbox_provider_event_uk UNIQUE (provider, provider_event_id),
    CONSTRAINT order_events_inbox_processed_has_outcome CHECK ((processed_at IS NULL) = (outcome IS NULL))
);

The processed_has_outcome check keeps the table honest: a row is either unprocessed or has exactly one outcome.

2. Insert without aborting the transaction

Instead of a plain insert that throws, the repository uses ON CONFLICT DO NOTHING RETURNING id. The constraint still decides, but a duplicate comes back as an empty result instead of an exception, so the transaction stays usable for the audit row.

@Override
public Optional<Long> insertIfAbsent(
        String provider, String providerEventId, UUID orderId, String payloadJson, Instant receivedAt) {
    return jdbc.sql("""
                    INSERT INTO order_events_inbox (provider, provider_event_id, order_id, payload, signature_valid, received_at)
                    VALUES (:provider, :eventId, :orderId, CAST(:payload AS jsonb), true, :receivedAt)
                    ON CONFLICT (provider, provider_event_id) DO NOTHING
                    RETURNING id
                    """)
            .param("provider", provider)
            .param("eventId", providerEventId)
            .param("orderId", orderId)
            .param("payload", payloadJson)
            .param("receivedAt", Timestamp.from(receivedAt))
            .query(Long.class)
            .optional();
}

3. One transaction per delivery

PaymentEventService.process is the whole decision in one place. An empty insert result means duplicate. Unknown event types are stored and ignored. An event for an order that doesn’t exist yet is stored as an orphan and retried by a scheduled job. Everything else locks the order and applies pending events.

@Transactional
public Result process(DecodedEvent event, String payloadJson) {
    Instant now = clock.instant();
    Optional<Long> inserted =
            inbox.insertIfAbsent(decoder.provider(), event.eventId(), event.orderId(), payloadJson, now);
    if (inserted.isEmpty()) {
        audit(event.orderId(), "DUPLICATE", detail(event), now);
        return new Result(Outcome.DUPLICATE, 0, 0);
    }
    long inboxId = inserted.get();
    if (!event.knownType()) {
        inbox.markProcessed(inboxId, Outcome.IGNORED.name(), now);
        audit(event.orderId(), "EVENT_IGNORED", detail(event), now);
        return new Result(Outcome.IGNORED, 0, 0);
    }
    Optional<Order> order = orders.findByIdForUpdate(event.orderId());
    if (order.isEmpty()) {
        inbox.markProcessed(inboxId, Outcome.ORPHAN.name(), now);
        audit(event.orderId(), "EVENT_ORPHAN", detail(event), now);
        return new Result(Outcome.ORPHAN, 0, 0);
    }
    return applyPending(order.get(), event.eventId(), now);
}

The lock is a Spring Data method annotated with @Lock(LockModeType.PESSIMISTIC_WRITE), which issues SELECT ... FOR UPDATE. Two layers handle concurrency. Copies of the same event stop at the unique index: PostgreSQL makes a concurrent insert of the same key wait for the first transaction, then does nothing. Different events for the same order, such as a success and a refund arriving together, queue on the order’s row lock instead of racing each other.

4. Apply events in sequence, not arrival order

The provider numbers each order’s events 1, 2, 3, and so on. OrderEventSequencer.drain receives every unprocessed inbox event for the locked order, sorts by that sequence, and applies each one that is next in line. Anything after a gap waits.

unique.sort(BY_SEQUENCE);

Order current = order;
List<Step> steps = new ArrayList<>();
List<PaymentEvent> waiting = new ArrayList<>();
for (PaymentEvent event : unique) {
    boolean ready =
            current.status() == OrderStatus.CANCELLED || event.sequence() <= current.lastEventSequence() + 1;
    if (!ready) {
        waiting.add(event);
        continue;
    }
    try {
        Transition t = machine.apply(current, event);
        steps.add(new Step(event, t, null));
        if (t instanceof Transition.Applied applied) {
            current = applied.order();
        }
    } catch (IllegalTransitionException e) {
        steps.add(new Step(event, null, e));
    }
}
return new Result(current, steps, duplicates, waiting);

A late event below the order’s last applied sequence (say, a retried PAYMENT_FAILED arriving after the order is already PAID) is marked STALE by the state machine and changes nothing.

5. The controller answers based on “will retrying help?”

A duplicate gets 200 {"received":true,"duplicate":true}, so the provider stops retrying. An invalid signature or malformed body gets 400, because sending the same bytes again cannot succeed. An unexpected failure gets 500 after a full rollback, because a retry can succeed. That rule, from the repository’s ADR 0002, is worth writing down for your own endpoints.

How we test it

Duplicate handling that only works in a demo is worthless, so each guarantee has a named test.

  • LL-I07: the same event delivered twice. The second response says duplicate=true and the order changes once.
  • LL-I08: 50 concurrent deliveries of one event, released together with a latch against a real PostgreSQL in Testcontainers. These are its assertions:
assertThat(responses).extracting(HttpResponse::statusCode).containsOnly(200);
assertThat(responses)
        .filteredOn(r -> r.body().contains("\"duplicate\":true"))
        .hasSize(deliveries - 1);
assertThat(status(orderId)).isEqualTo("PAID");
assertThat(jdbc.queryForObject("select version from orders where id = ?::uuid", Long.class, orderId))
        .as("INITIATED and SUCCEEDED: exactly two updates")
        .isEqualTo(2);
assertThat(jdbc.queryForObject(
                "select count(*) from order_events_inbox where provider_event_id = 'evt_i08_race'", Long.class))
        .isEqualTo(1);
  • LL-P01: a jqwik property test, 1,000 tries. Any valid event history, with each event duplicated up to four extra times and the whole list shuffled, must end in the same status and refunded amount as the canonical history applied once. A companion example test shows the naive in-arrival-order approach losing an out-of-order refund.
  • LL-I12: a test hook throws after the order changed but before commit. The response is 500, nothing is committed, and redelivery succeeds.
  • LL-U08 to LL-U13 and LL-I09: tampered bodies, wrong secrets, timestamps 301 seconds old or in the future, rotated secrets, malformed and oversized headers. All are rejected with no change to the order.

The latest published evidence, from CI on GitHub-hosted ubuntu-24.04 runners for commit e360215 (November 24, 2026): 371 tests (226 unit, 134 integration, 11 end-to-end), 0 failed; 95.2% line coverage (99.5% in the domain package); a 90.1% mutation score. Load testing has not been published for this commit, so we make no throughput or latency claims. The raw numbers are in evidence/latest.json.

Trade-offs, and what changes at scale

The inbox grows. Every delivery, including every rejected one, writes a row. You need a retention policy, and at higher volume a partitioned table so old rows are dropped by partition instead of deleted row by row.

Gaps can wait forever. If the provider never sends event #3, events #4 and up stay pending. That is the correct behavior (applying them would be wrong), but it needs a “stuck events” alert. Ledgerline doesn’t have one yet; a five-minute reconciliation job against the provider’s own ledger catches the drift instead (test LL-I19).

The row lock serializes one order, not the system. Contention only appears when many events hit the same order at once, which is exactly when you want them serialized.

No broker yet. Merchant notifications go through a transactional outbox polled with SKIP LOCKED. Once a second consumer appears, the outbox can feed Kafka or SQS without changing the event IDs consumers deduplicate on. The repository’s README describes this as a plan, not a measured result.

The secret is the trust boundary. Signature checks stop forgery, but anyone holding the secret can sign events. Support two active secrets so you can rotate without downtime; Ledgerline accepts either during rotation (LL-U12).

A checklist you can copy

  • Verify the provider’s signature on the raw request bytes, with a timestamp tolerance and a constant-time comparison.
  • Store every verified event in an inbox table with a unique key on (provider, event ID).
  • Insert with ON CONFLICT DO NOTHING (or your database’s equivalent) so a duplicate doesn’t abort the transaction.
  • Write the inbox row, the business change, the audit record and any outbound message in the same transaction.
  • Lock the aggregate (order, subscription, invoice) before applying events to it.
  • Apply events in the provider’s sequence order and hold events that arrive after a gap.
  • Answer 200 to duplicates, 400 to bad signatures, 500 after a rollback.
  • Test duplicates with real concurrency against your real database, not an in-memory substitute.
  • Add a property test: shuffled, duplicated histories must converge to the same final state.
  • Reconcile against the provider’s records on a schedule, and alert on events stuck behind a gap.

Try it

The code is public: github.com/specshield-io/ledgerline. Run docker compose up --build, open the ops console at localhost:8080, and start the duplicate-storm scenario: five deliveries, one state change, four duplicates blocked. A hosted version of the demo isn’t published yet; when it is, it will be on the Ledgerline lab page.

If duplicate or out-of-order events are costing you, book a 20-minute engineering call. We’ll look at how your handler deals with retries, ordering and signatures.

Talk to the engineers who would do the work

20 minutes with a senior engineer about your integration, webhook or backend problem. You leave with a concrete next step, whether or not we work together.