HMAC webhooks and payment sagas

You can verify raw provider callbacks and coordinate forward-only payment actions, giving the payment service safe rules for duplicate and late events.

Learning outcomes

  • Explain how HMAC-SHA256 signatures authenticate provider webhooks before JSON parsing.
  • Distinguish event deduplication from atomic payment state transitions.
  • Design a payment saga that handles late captures through compensating refunds.
  • Explain how reconciliation recovers unresolved payments using provider status and an injected clock.
  • Test concurrent webhook delivery and identify data races with Go's race detector.

A customer pays for an order, but the provider's callback arrives after the order has already been cancelled. Another callback arrives three times because the provider never received your acknowledgement. What happens if your backend processes every callback independently?

Your payment service must handle these situations without placing an order twice, reversing a completed payment, or leaving a customer charged for a cancelled order. You need authenticated webhooks, guarded state transitions, and a recovery mechanism for callbacks that never arrive.

The payment lifecycle

A payment begins with an order in PENDING_PAYMENT. Your backend creates a payment intent with the provider and stores a corresponding payment record.

A payment intent represents the provider-side operation that allows the customer to complete a payment. Your record needs its own ID, the order ID, the provider reference, the amount in paise, a status, and a creation timestamp.

The initial payment state is PENDING.

go
type Status string

const (
    StatusPending  Status = "PENDING"
    StatusCaptured Status = "CAPTURED"
    StatusFailed   Status = "FAILED"
)

The provider returns a reference that identifies its payment intent. Store this reference because you need it later to query payment status or request a refund.

Your service coordinates three dependencies through interfaces:

  • Store persists payments, retrieves them, performs atomic transitions, records event IDs, and finds old pending payments.
  • Orders marks orders placed or cancelled.
  • Provider creates payment intents, reports payment status, and issues refunds.

The Payment Saga connects these operations. Payment creation, payment settlement, and order updates are separate operations that together complete one business process.

A simplified lifecycle looks like this:

  1. The backend creates a payment intent with the provider.
  2. The backend stores a payment in PENDING.
  3. The customer completes or fails the payment.
  4. The provider sends a webhook.
  5. The backend authenticates the webhook and processes its event.
  6. The payment and order move to their corresponding states.

A successful capture should move the payment to CAPTURED and the order to PLACED. A failure should move the payment to FAILED and the order to CANCELLED.

The provider reference connects your local payment record to the provider's version of the operation.

Creating a payment intent

Payment intent creation has two distinct responsibilities. You first ask the provider to create an intent, then persist your own payment record using the returned reference.

The important part is that a payment record should not claim to be captured before the provider confirms a capture.

A simplified creation operation looks like this:

go
providerRef, err := provider.CreateIntent(
    ctx, orderID, amountPaise,
)
if err != nil {
    return Payment{}, err
}

p := Payment{
    ID:          paymentID,
    OrderID:     orderID,
    Status:      StatusPending,
    ProviderRef: providerRef,
    AmountPaise: amountPaise,
    CreatedAt:   now(),
}

paymentID represents a newly generated, non-empty identifier. The now function supplies the creation time.

Persist the payment through Store.Create before returning it. If provider intent creation fails, propagate the error rather than returning a payment that does not exist at the provider.

The creation timestamp matters later. Reconciliation uses it to distinguish payments that are still being processed from payments that have remained unresolved for too long.

Authenticating provider webhooks

A webhook is an HTTP callback sent by an external service when an event occurs. Your payment provider uses one to report that a payment was captured or failed.

A webhook is not trustworthy merely because it reaches your server. An attacker could construct a request claiming that a payment succeeded.

You need a webhook signature to authenticate both the sender and the request body.

The provider and your backend share a secret. The provider calculates an HMAC-SHA256 digest over the exact request body and sends its hexadecimal representation in the X-Signature header.

Your backend independently calculates the expected digest and compares it with the supplied signature.

HMAC-SHA256

Go provides HMAC through crypto/hmac and SHA-256 through crypto/sha256.

go
func Sign(secret, body []byte) string {
    mac := hmac.New(sha256.New, secret)
    mac.Write(body)
    return hex.EncodeToString(mac.Sum(nil))
}

The result is a hexadecimal string representing the digest.

The important detail is the input. You must sign the exact request bytes, not the decoded JSON object.

For example, these bodies represent equivalent JSON values:

json
{"id":"evt_1","type":"payment.captured"}
json
{
  "type": "payment.captured",
  "id": "evt_1"
}

Their byte sequences differ. Their HMAC values will also differ.

A provider that signed the first representation expects your backend to verify those original bytes, even when the second representation would produce the same decoded object.

Signature verification

Verification requires decoding the supplied hexadecimal signature and comparing the resulting bytes against the expected digest.

go
func Verify(secret, body []byte, signature string) bool {
    provided, err := hex.DecodeString(signature)
    if err != nil {
        return false
    }

    mac := hmac.New(sha256.New, secret)
    mac.Write(body)

    return hmac.Equal(mac.Sum(nil), provided)
}

Notice the use of hmac.Equal.

This function performs a constant-time comparison of the byte slices. An ordinary string comparison can stop at the first differing byte. Timing differences can reveal information about how much of a supplied signature matches the expected value.

Constant-time comparison removes that particular timing signal.

A malformed hexadecimal value cannot represent a valid signature, so verification must return false. An empty, truncated, or incorrectly generated signature must also fail verification.

Authentication before parsing

The order of operations matters as much as the cryptographic algorithm.

Read the raw request body, verify X-Signature, and only then parse the JSON.

go
body, err := io.ReadAll(r.Body)
if err != nil {
    http.Error(w, "invalid request", http.StatusBadRequest)
    return
}

if !Verify(secret, body, r.Header.Get("X-Signature")) {
    http.Error(w, "unauthorized", http.StatusUnauthorized)
    return
}

var event WebhookEvent
if err := json.Unmarshal(body, &event); err != nil {
    http.Error(w, "invalid event", http.StatusBadRequest)
    return
}

This is a simplified handler fragment. The important boundary is that unauthenticated input never reaches JSON parsing.

The expected responses are:

ConditionResponse
Missing signature401
Invalid signature401
Valid signature with malformed JSON400
Valid event successfully handled200

A signature proves that the request was generated by someone possessing the shared secret and that its signed body has not changed. It does not prove that the event is new or that its payment can still be settled.

At-least-once delivery

Payment providers commonly use at-least-once delivery. They retry an event when they cannot establish that your backend processed it successfully.

Suppose the provider sends event evt_1 three times.

Your backend might process the first request and place the order. However, the response could fail to reach the provider. The provider has no reliable way to know whether the operation happened, so it sends the same event again.

Your handler must acknowledge repeated events without repeating their business effects.

This is the problem addressed by an idempotent consumer.

An operation is idempotent when repeating the same operation produces no additional change after the first successful application.

Event IDs as idempotency keys

Every provider event contains an ID. Use this value as an idempotency key.

Consider this event:

json
{
  "id": "evt_1",
  "payment_id": "pay_123",
  "type": "payment.captured"
}

The event ID identifies the delivery operation. The payment ID identifies the payment being changed.

These identifiers have different responsibilities.

Two deliveries of evt_1 refer to the same event. A capture event with ID evt_2 could refer to the same payment but represent a different delivery event.

Your store needs an atomic first-seen operation. It should report whether an event ID has already been recorded.

A relational database can implement this with a unique constraint:

sql
CREATE TABLE processed_payment_events (
    provider_event_id VARCHAR(128) PRIMARY KEY,
    payment_id VARCHAR(128) NOT NULL,
    processed_at TIMESTAMP NOT NULL
);

The unique key prevents two requests from successfully inserting the same event ID.

Redis offers another approach through SET NX. It creates a key only when that key does not already exist.

go
result, err := redisClient.SetNX(
    ctx,
    "payment:event:"+eventID,
    "1",
    expiration,
).Result()

The returned boolean tells you whether this request created the key.

These are alternative storage strategies. The payment processing exercise exposes Store.SeenEvent, which must provide an atomic first-seen check. You do not need to introduce a separate Redis dependency for it.

Lookup before deduplication

There is a subtle ordering requirement.

Suppose a provider delivers a capture event before your payment record is available. Your backend records the event ID first and then discovers that the payment does not exist.

The provider retries the event later. Your deduplication check now identifies it as already processed, even though the payment was never updated.

You have permanently discarded a valid event.

Prevent this by retrieving the payment before recording the event ID.

The processing order is:

  1. Authenticate the raw body.
  2. Decode and validate the event.
  3. Retrieve the payment using payment_id.
  4. Return 404 if the payment does not exist.
  5. Record the event ID through the atomic first-seen operation.
  6. Return 200 if the event was already recorded.
  7. Apply the payment transition.

The unknown-payment case is important because the tests deliver the same event ID again for a payment that exists. That delivery must still be processed.

The transaction boundary

Event deduplication and payment updates are related operations. A production implementation should consider how they behave when one succeeds and the other fails.

A database transaction can combine event recording and payment-state changes when both operations share the same database. This prevents a transaction from committing only the event ID while leaving the payment unchanged.

However, your order service and payment provider may be separate systems. A MySQL transaction cannot atomically commit changes across those external operations.

A production design therefore needs durable recovery for failures between these boundaries, such as an outbox or retry mechanism.

Forward-only payment transitions

Event deduplication solves repeated delivery of the same event. It does not solve every ordering problem.

Imagine the provider sends two different events for one payment:

  1. evt_1 reports payment.captured.
  2. evt_2 reports payment.failed.

Both events have different IDs. Both pass event deduplication.

Without another safeguard, the second event could incorrectly change an already captured payment to failed.

Your payment record needs a state machine.

Its permitted transitions are:

Current stateEventNext state
PENDINGpayment.capturedCAPTURED
PENDINGpayment.failedFAILED
CAPTUREDpayment.failedNo change
FAILEDpayment.capturedNo state reversal

A forward-only transition permits a payment to leave PENDING, but never to move backwards from a final state.

Atomic compare-and-set

A naive implementation reads the payment, checks its status, and then performs an update.

go
payment, err := store.Get(ctx, paymentID)
if err != nil {
    return err
}

if payment.Status == StatusPending {
    return store.UpdateStatus(ctx, paymentID, StatusCaptured)
}

This is unsafe when requests execute concurrently.

Two handlers can read PENDING before either updates the record. Both can then proceed as though they own the transition.

This is a logical race condition.

Use optimistic locking instead. Ask the store to update the payment only when its current status matches the expected status.

A relational database can express that condition directly:

sql
UPDATE payments
SET status = 'CAPTURED'
WHERE id = ?
AND status = 'PENDING';

Check the affected-row count.

  • One affected row means the transition succeeded.
  • Zero affected rows means the payment was no longer in the expected state.

The exercise exposes this operation through Store.Transition(ctx, id, from, to). Its boolean result indicates whether the change actually happened.

The store must perform the comparison and update atomically. Checking the status in Go and then issuing an unconditional update defeats the purpose.

The order side effect depends on the result.

go
changed, err := store.Transition(
    ctx, paymentID, StatusPending, StatusCaptured,
)
if err != nil {
    return err
}

if changed {
    return orders.MarkPlaced(ctx, orderID)
}

Only the request that successfully changes the payment should place the order.

When a second capture event arrives with another event ID, the transition returns false because the payment is already captured. The service must not place the order again.

A failure arriving after capture follows the same rule. It cannot cancel an already placed order.

The payment saga

Payment settlement involves more than one record.

When the provider reports a successful capture, your backend changes the payment to CAPTURED and asks the order service to mark the order as PLACED.

When the provider reports a failure, your backend changes the payment to FAILED and asks the order service to mark it as CANCELLED.

These operations form the payment saga.

A saga consists of local operations that collectively complete a business workflow. Each operation commits independently rather than relying on one transaction spanning every system.

This boundary creates an important failure case.

The payment transition might succeed, but the subsequent order update might fail. The payment now says CAPTURED, while the order has not been placed.

A successful payment transition does not guarantee that every subsequent operation succeeded.

In production, you need a way to retry or recover the unfinished order update. An outbox can record the required follow-up action durably.

Compensating actions

Now consider a different failure.

The provider reports that payment failed. Your service moves the payment to FAILED and the order to CANCELLED.

Later, the provider reports a successful capture for the same payment.

The customer has been charged for an order that your application has already cancelled.

You cannot solve this by changing the payment back to CAPTURED and placing the order. The cancellation may already have triggered other business operations.

Instead, use a compensating action: issue a refund through the provider.

The original payment remains FAILED. The refund is a separate financial operation that compensates for the late capture.

This distinction preserves the history of what happened. A refund does not erase the original events or rewrite the payment's state.

The service needs to distinguish three capture outcomes:

  • If the transition from PENDING to CAPTURED succeeds, mark the order placed.
  • If the payment is already CAPTURED, do nothing.
  • If the payment is already FAILED, refund the provider payment.

The third case is why the handler must inspect the current payment status when a capture transition does not succeed.

Refund idempotency

Refunds are financial operations. Repeating a refund request can return money more than once unless the operation has its own idempotency protection.

The same capture event might be delivered repeatedly after a payment has failed. Event-ID deduplication prevents the same event from triggering another refund.

The tests verify that a late capture delivered twice results in exactly one refund for provider reference pi_o-1.

For a production refund workflow, event deduplication alone is not sufficient protection against every possible retry. Different event IDs could describe the same underlying capture, and a retry after a network timeout might not reveal whether the provider completed the refund.

A durable refund record with a unique payment or capture reference, together with a stable provider refund idempotency key, protects that financial operation independently.

The payment transition, event ID, and refund operation each need their own clear consistency rules.

Reconciliation

Webhooks provide a fast way to learn about payment outcomes. They cannot guarantee that every event reaches your backend.

Your server might be unavailable when the provider retries. A callback might never arrive. A network failure might leave the application uncertain about an operation's outcome.

You need a reconciliation loop to recover unresolved payments.

Reconciliation compares your local payment records against the provider's current status. The provider acts as the source of truth for whether the payment was captured or failed.

The payment service selects records that are still PENDING and older than five minutes.

Why five minutes?

A payment that was created moments ago might still be undergoing normal provider processing. Querying it immediately creates unnecessary requests without improving correctness.

The cutoff is calculated from the current time:

go
cutoff := now().Add(-5 * time.Minute)

payments, err := store.Pending(ctx, cutoff)
if err != nil {
    return err
}

The store returns payments older than the cutoff. The service queries the provider for each returned payment using its provider reference.

The outcomes follow the same state-transition rules as webhooks.

Provider statusPayment actionOrder action
CAPTUREDPENDING to CAPTUREDMark placed
FAILEDPENDING to FAILEDMark cancelled
PENDINGNo changeNo change

A reconciliation pass must not query a payment younger than five minutes.

It must also avoid placing an order again when a webhook has already captured the payment. The atomic transition provides this protection.

If a webhook wins the transition first, reconciliation sees that the payment is no longer PENDING. Its attempted transition cannot succeed, so it cannot repeat the order side effect.

Injected time

A service that directly calls time.Now() throughout its implementation is difficult to test against specific timestamps.

Use an injected clock instead.

The constructor accepts a function that supplies the current time. Both payment creation and reconciliation can use that same dependency.

A test can advance the clock by six minutes and verify that the payment becomes eligible for reconciliation. Another test can advance it by four minutes and verify that no provider query occurs.

The test does not need to sleep or wait for real time to pass.

The important property is that time is controlled by the test, while the service still uses normal time comparisons.

Reusing settlement logic

A webhook handler and a reconciliation pass should not implement separate payment state machines.

Both paths need the same rules:

  • A successful capture transition places the order.
  • A successful failure transition cancels the order.
  • A failed capture transition checks whether a refund is required.
  • An already settled payment does not repeat its order side effect.
  • A provider status of PENDING leaves the payment unchanged.

A deployed application can schedule reconciliation to run periodically. The exercise tests the Reconcile operation directly, without requiring you to implement a scheduler.

Concurrent webhook processing

Sequential tests cannot expose every concurrency problem.

Suppose 20 webhook requests for the same payment arrive at almost the same time. Each request has the same signed event.

The service must ensure that only one request successfully applies the payment transition and places the order.

Go executes concurrent work through goroutines. Shared state accessed by multiple goroutines requires proper synchronization.

There are two separate problems to consider.

Logical concurrency

The payment store must enforce the expected-state condition atomically.

If 20 handlers attempt the same transition from PENDING to CAPTURED, exactly one should succeed.

The other handlers observe that the payment has already changed and must not place the order again.

Event deduplication provides another layer of protection for requests carrying the same event ID. Its first-seen check must also be atomic.

Application-level mutexes alone cannot replace these storage guarantees when multiple processes or server instances can handle webhooks.

Data races

A data race occurs when concurrent goroutines access the same memory location, at least one access writes, and the accesses are not properly synchronized.

A data race can affect counters, maps, shared configuration, or other state used by the service.

Go includes a race detector that identifies many unsynchronized memory accesses during execution.

Run it through the exercise's test command:

bash
cd backend
make test W=8B2

The payment exercise runs its matching tests with the race detector. It also sends 20 concurrent copies of the same signed webhook and checks that the order is placed exactly once.

The two checks provide different guarantees.

The race detector looks for unsafe memory access. The concurrent payment test checks business correctness under competing operations.

A program can pass the race detector and still have a logical concurrency bug. For example, two goroutines might use individually synchronized reads and writes but still perform an invalid sequence of state transitions.

That is why the store's atomic compare-and-set contract matters independently of memory synchronization.

Applying the payment model

The Payment processing service exercise brings these ideas together in backend/internal/payments/payments.go.

The supplied interfaces define the boundary between payment persistence, order operations, and provider operations. Your implementation needs to coordinate them while preserving the rules of the payment state machine.

Pay particular attention to the distinction between the two forms of idempotency:

Event-ID deduplication prevents the same provider event from being processed repeatedly. Atomic payment transitions prevent different events from settling the same payment more than once.

The late-capture case adds another requirement. When a capture arrives after failure, preserve the failed state and compensate through a refund rather than reversing the payment history.

Finally, reconciliation must settle only old pending payments and must reuse the same transition rules as webhook processing.

The tests exercise valid signatures, invalid signatures, duplicate events, unknown payments, reordered events, late captures, reconciliation outcomes, and concurrent delivery. These cases define the behaviour your service must preserve.

Check your understanding

Question 1 of 4

Why must your webhook handler authenticate the raw request body before parsing its JSON?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from.

Finished Lesson 8.3?