InstaWebhook
November 26, 2026By InstaWebhook TeamRetries and Replay

Designing Human-in-the-Loop Replay Approval Workflows for Financial and Billing Webhooks

Prevent duplicate charges, refunds, or customer emails during webhook replays. Learn approval gates, dry-run diff previews, and audit trails for billing infrastructure.

Designing Human-in-the-Loop Replay Approval Workflows for Financial and Billing Webhooks

Designing Human-in-the-Loop Replay Approval Workflows for Financial and Billing Webhooks

In many payment stacks, a webhook replay is treated as a routine recovery step, much like restarting a stalled pod or draining a dead-letter queue (DLQ). A 502 Bad Gateway or an exhausted database connection pool causes a batch of incoming Stripe, Adyen, or internal ledger events to fail. Once the downstream service recovers, the usual reflex is to click “Replay All” in the webhook gateway.

For telemetry or low-stakes UI notifications, that is fine. For financial and billing webhooks, such as charge.succeeded, invoice.payment_failed, charge.refunded, payout.paid, or an internal ledger.entry.committed, an unreviewed bulk replay carries real risk. Re-emitting a stale payload can trigger a duplicate refund, send a contradictory dunning email, or write a second journal entry into a general ledger after the consumer’s deduplication window has lapsed.

The safer approach is to treat replay as a governed workflow rather than a developer shortcut. It combines risk-based approval gates, dry-run diff previews, and tamper-evident audit trails. This article walks through each piece, grounded in how Stripe and Adyen actually deliver, retry, and let you resend events.

What Providers Actually Give You (and Where the Gaps Are)

Replay design starts with knowing what the upstream provider already does, because your gateway has to cover the rest.

Stripe. In live mode, Stripe retries failed webhook deliveries with exponential backoff for up to three days. In a sandbox it retries three times over a few hours, so you cannot reproduce day-three behavior in test mode. Stripe states that it doesn’t guarantee events arrive in the order they were generated, and it can deliver the same event more than once, so consumers are expected to record processed event IDs. You can also resend events manually, and the CLI’s stripe events resend only works for events created within the last 30 days. The Events API likewise lists events going back up to 30 days. Beyond that window, the only authoritative copy of the original delivery is the one your own infrastructure stored, which is a strong argument for archiving raw webhook bodies at ingestion.

Adyen. If your endpoint doesn’t return a successful HTTP status within 10 seconds, Adyen marks the webhook as Failing. It retries three times immediately, then moves messages to a per-endpoint retry queue and keeps retrying for up to 30 days at intervals that grow from 2 minutes to 8 hours. Queued messages behind a failing one wait until the retry succeeds, and the Customer Area lets you Retry or Ignore individual failed messages. Adyen also delivers at least once, so duplicates are expected. Because of that 30-day queue, a message can reach you long after the event it describes.

Two things follow from this. First, provider-side retries are designed to cover short outages, and long outages shift the recovery burden onto you. Second, provider-side “retry” or “resend” buttons give an operator the same unreviewed, single-click power as a naive gateway “Replay All”. A governed replay layer in front of your own consumers is where review can happen.

Why Blind Webhook Replays Fail in Financial Systems

Most webhook reliability designs rest on two pillars: retries with backoff at the producer or gateway, and idempotency at the consumer. Both are necessary, and both can break down during long outages, schema migrations, or partial consumer failures.

1. Deduplication State Can Expire Before the Replay Happens

Stripe’s own API is a useful reference point: its idempotency keys can be pruned once they are at least 24 hours old, after which a reused key is treated as a new request. Many consumer-side idempotency stores follow a similar pattern, with a TTL in Redis or a time-bounded idempotency_keys table to cap storage growth. If a replay arrives after that window, the consumer may treat the event as brand new and execute a second capture, refund, or ledger posting.

Two mitigations work together. For financial flows, keep processed webhook event IDs in a durable table with a unique constraint rather than a short-lived cache, since the storage cost of a few hundred bytes per event is small. And have your risk policy treat any event older than your shortest deduplication window as high risk, regardless of what the dedup store says.

2. Temporal State Drift and Out-of-Order Events

Billing entities are state machines: pending → authorized → captured → refunded → disputed. Suppose a payment_intent.payment_failed webhook fails to deliver at T+0 because of a consumer deployment bug. At T+15m the customer retries with a valid card and payment_intent.succeeded is delivered and processed. If an on-call engineer replays the failed event at T+2h, a naive consumer may mark an active account as past due or send an erroneous payment-failure email.

Stripe event payloads are also point-in-time snapshots: the event’s data field embeds the resource’s state at the time of the change, and it never changes afterward. A replayed event therefore carries historical state, not current state. Consumers handling replays should compare the event’s created timestamp and object version against what they have stored, or fetch the current object from the provider API, before acting.

3. Partial Side-Effect Execution

A single billing handler often orchestrates several side effects across different systems:

  1. Updating the local PostgreSQL invoices table.
  2. Emitting an internal Kafka event to an ERP connector.
  3. Sending a transactional receipt through an email provider.

If step 1 commits and the worker then times out before returning 200 OK, the gateway records a failed delivery. Replaying that event without checking current downstream state can re-trigger step 2 (duplicate revenue recognition) or step 3 (a duplicate customer email).

4. Segregation of Duties and Audit Expectations

Compliance frameworks do not mention webhook replays by name, but their controls apply directly to them:

The practical implication is that no single engineer should be able to re-trigger high-value settlement events, or alter a payload during recovery, without a second person’s approval and an immutable record tying the action to an incident ticket. Auditors will look for that evidence.

Architecture of a Human-in-the-Loop (HITL) Replay Pipeline

To remove unreviewed money movement while keeping incident recovery fast, replace the direct FAILED → DELIVERING transition with an explicit approval and simulation state machine.

Code example
[Delivery Failed / DLQ]
         │
         ▼
[Replay Request Created] ──► (Risk Policy Engine Evaluates Payload)
         │
         ├──► Low Risk (e.g., metadata sync) ──► [Auto-Approved] ──► [Dispatch]
         │
         └──► High Risk (e.g., refund ≥ $1,000) ──► [Pending Dry-Run]
                                                        │
                                                        ▼
                                            [Dry-Run Diff Simulation]
                                                        │
                                                        ▼
                                            [Pending Peer / Finance Approval]
                                                        │
                                        ┌───────────────┴───────────────┐
                                        ▼                               ▼
                                   [Rejected]                  [Approved & Signed]
                                        │                               │
                                        ▼                               ▼
                                [Archived / Closed]         [Rate-Limited Dispatch]
                                                                        │
                                                                        ▼
                                                            [Immutable Audit Log]

Core State Transitions

  • DLQ_QUARANTINED: The event exhausted its automated retries and sits in storage with its original headers, raw payload bytes, provider signature, and failure diagnostics.
  • REPLAY_DRAFTED: An operator selects one or more quarantined events (by event ID, time window, or status filter) and attaches a mandatory justification, such as an incident ID like INC-4092.
  • DRY_RUN_COMPLETED: The gateway runs a non-mutating simulation against the consumer, capturing the state changes and side effects that would occur.
  • PENDING_APPROVAL: Based on risk policy, the batch stays locked until the required approvers sign off.
  • APPROVED_QUEUED: Approval tokens are attached to the job, which is released into a rate-limited dispatch queue.
  • REPLAYED_VERIFIED: Delivery succeeds with a 2xx, and the full lifecycle (original failure, diff preview, approver identities, final response) is sealed in an append-only audit store.

Designing Risk-Based Approval Gates

Not every webhook needs a finance executive’s sign-off. If approval adds too much friction for low-risk events, engineers will write bypass scripts that go around the gateway entirely. A policy-as-code engine such as Open Policy Agent (Rego) or Cedar can inspect event metadata and the payload, then route each request to the right approval tier.

Risk Classification Dimensions

  1. Event type taxonomy. Classify event types into tiers (examples use Stripe event names):
    • Tier 0 (low risk): customer.updated, payment_method.attached. Auto-approve when fresh and unmodified.
    • Tier 1 (billing state): customer.subscription.updated, invoice.finalized, invoice.paid. Single peer approval.
    • Tier 2 (direct money movement): charge.refunded, refund.created, payout.paid, transfer.reversed, invoice.voided. Dual approval from engineering and finance or billing operations.
  2. Monetary thresholds. Parse amount and currency fields and normalize to a base currency. Stripe expresses amounts in the smallest currency unit, so 1400 means $14.00 in USD but ¥1,400 in a zero-decimal currency like JPY. Normalize carefully before comparing against a threshold.
  3. Event age. Any event older than your shortest deduplication window (for example, 24 hours) should be escalated, because you can no longer assume automatic deduplication will catch a duplicate.
  4. Payload mutation. If an operator edits a payload before replay, the provider’s signature no longer matches. The gateway must re-sign with an internal replay key, record the change, and force dual review.

Example Policy-as-Code Rule (Rego)

The policy below uses Rego v1 syntax, which is the default in OPA 1.0 and later (the if and in keywords are built in). Escalation conditions are computed first, and the auto-approve rule can only fire when none of them apply, so rules never conflict.

Code example
package webhook.replay.policy

import rego.v1

default approval_tier := "tier_1_peer"

money_movement_types := {
    "charge.refunded", "refund.created", "payout.paid",
    "payout.created", "transfer.reversed", "invoice.voided",
}

low_risk_types := {"customer.updated", "payment_method.attached"}

# Any one of these escalates the request to dual approval.
requires_dual if input.event_type in money_movement_types
requires_dual if object.get(input, "normalized_amount_usd", 0) >= 1000
requires_dual if input.event_age_seconds >= 86400
requires_dual if input.payload_mutated == true

auto_approvable if {
    input.event_type in low_risk_types
    input.event_age_seconds < 3600
    input.payload_mutated == false
}

approval_tier := "tier_2_dual_quorum" if requires_dual

approval_tier := "auto_approve" if {
    auto_approvable
    not requires_dual
}

Enforcing the Four-Eyes Principle

The replay control plane must compare the requester’s identity with the approver’s identity and reject any approval where they match for Tier 1 and Tier 2 requests. With OIDC, compare the issuer and subject pair (iss plus sub), since sub is only unique within an issuer. Require a fresh MFA assertion for approvals, and prevent approvers from approving batches they edited. This stops a compromised workstation or a single fatigued operator from draining a DLQ alone.

Implementing Dry-Run Diff Previews

Approvers cannot make good decisions by reading nested JSON and stack traces. Before anyone signs off on a financial replay, the system should answer one question: “If we deliver this webhook right now, what will actually change in our billing database and external integrations?”

Pattern 1: Header-Signaled Simulation Mode

The gateway sends the exact replay payload to the consumer with extra headers:

Code example
POST /webhooks/stripe HTTP/1.1
Host: billing-api.internal
Content-Type: application/json
X-Webhook-Event-Id: evt_1Q9xK2L8mNp4Qr7s
X-Webhook-Replay-Id: rpl_9981a7b2c3d4
X-Webhook-Dry-Run: true
X-Webhook-Original-Received-At: 2026-11-26T04:12:09Z
X-Replay-Signature: t=<unix-timestamp>,v1=<hmac>

When the consumer sees X-Webhook-Dry-Run: true, it first verifies the gateway’s signature so outside parties cannot trigger or spoof simulations. Then it:

  1. Runs validation and business logic against live database state.
  2. Wraps all database writes in a transaction that is always rolled back.
  3. Runs outbound adapters (email, payment APIs, ERP queues) in a no-op interceptor mode that records the intended calls.
  4. Returns a structured JSON diff of the state transitions that would have occurred.

Pattern 2: Transaction Rollback with Outbox Inspection (Go)

For services using PostgreSQL and the transactional outbox pattern, a dry run can execute the real domain logic inside a transaction, read the resulting state and outbox rows, and then roll back. The sketch below shows the control flow; applyInvoicePaymentTransition stands in for your domain logic, which must insert the event ID into processed_webhooks in the same transaction on the live path.

Code example
package webhook

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
)

type StateDiff struct {
	Entity      string         `json:"entity"`
	EntityID    string         `json:"entity_id"`
	BeforeState map[string]any `json:"before_state"`
	AfterState  map[string]any `json:"after_state"`
	SideEffects []string       `json:"side_effects"` // outbox rows written inside the tx
	Idempotent  bool           `json:"already_processed"`
}

func HandleBillingWebhook(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		isDryRun := r.Header.Get("X-Webhook-Dry-Run") == "true" // only after verifying the gateway signature
		eventID := r.Header.Get("X-Webhook-Event-Id")

		tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
		if err != nil {
			http.Error(w, "tx begin failed", http.StatusInternalServerError)
			return
		}
		// Rollback is a no-op after a successful Commit, so this is safe on every path.
		defer func() { _ = tx.Rollback() }()

		// 1. Idempotency check against a durable ledger of processed events.
		var exists bool
		if err := tx.QueryRowContext(ctx,
			`SELECT EXISTS(SELECT 1 FROM processed_webhooks WHERE event_id = $1)`,
			eventID,
		).Scan(&exists); err != nil {
			http.Error(w, "idempotency check failed", http.StatusInternalServerError)
			return
		}
		if exists {
			respondJSON(w, StateDiff{Entity: "webhook_event", EntityID: eventID, Idempotent: true})
			return
		}

		// 2. Apply the domain mutation and capture before/after snapshots.
		diff, err := applyInvoicePaymentTransition(ctx, tx, eventID, r.Body)
		if err != nil {
			http.Error(w, fmt.Sprintf("domain error: %v", err), http.StatusUnprocessableEntity)
			return
		}

		// 3. Dry run: discard everything. Live: commit.
		if isDryRun {
			w.Header().Set("X-Dry-Run-Executed", "true")
			respondJSON(w, diff) // deferred Rollback discards all writes
			return
		}
		if err := tx.Commit(); err != nil {
			http.Error(w, "commit failed", http.StatusInternalServerError)
			return
		}
		respondJSON(w, diff)
	}
}

func respondJSON(w http.ResponseWriter, payload any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(payload)
}

A rollback only protects database state. Know the limits of this approach:

  • Any side effect that leaves the transaction (an HTTP call to a payment API, an email, a message published directly to a broker) will still happen unless it is stubbed in dry-run mode. This is why the outbox pattern helps: outbox rows are written inside the transaction and can be inspected, then discarded.
  • Row locks are still taken during a dry run, and sequences advance even when a transaction rolls back, so avoid running large dry-run batches against hot rows during peak traffic.

Pattern 3: Presenting the Diff to Approvers

The gateway aggregates the returned StateDiff objects into one table per batch. Illustrative rows:

Event IDTypeTargetCurrent stateSimulated next stateExternal side effectsRisk warning
evt_901ainvoice.paidinv_8821open ($250.00)paid ($0.00 due)Email: receipt_v2, ERP: journal_postNone
evt_901binvoice.paidinv_8822paid ($0.00 due)No changeNoneIdempotent skip
evt_901cinvoice.payment_failedsub_4410activepast_dueEmail: dunning_notice_1Stale: newer payment succeeded at 14:02 UTC
evt_901dcharge.refundedch_7719succeededrefunded (-$1,400.00)Bank creditHigh value: over $1,000 threshold

With this view, an approver can see at a glance that evt_901c would incorrectly flag a paying customer as past due. They deselect it and approve the rest.

Constructing Tamper-Evident Audit Trails

In regulated environments, proving that a replay succeeded is not enough. You need to show who requested it, which diff they reviewed, who approved it, whether the payload differs from the bytes the provider originally sent, and what the downstream system returned.

Anatomy of a Replay Audit Record

Persist each record to write-once storage. S3 Object Lock in compliance mode is one common option, and AWS’s own PCI DSS guidance recommends it for log buckets. Self-hosted verifiable databases such as immudb are another. Avoid planning around Amazon QLDB: AWS ended support for it on July 31, 2025 and recommends migrating ledger workloads to Aurora PostgreSQL, which does not itself provide cryptographic verifiability, so audit history there must be exported and protected separately.

The record below is illustrative. Hash values are shortened placeholders.

Code example
{
  "audit_version": "2.1",
  "replay_batch_id": "rpl_batch_20261126_071500_88a1",
  "event_id": "evt_1Q9xK2L8mNp4Qr7s",
  "provider": "stripe",
  "original_ingestion": {
    "received_at": "2026-11-26T04:12:09.412Z",
    "source_ip": "54.187.174.169",
    "original_payload_sha256": "3a7bd3e2360a…",
    "upstream_signature_verified": true,
    "initial_failure_reason": "HTTP_504_GATEWAY_TIMEOUT",
    "delivery_attempts": 8
  },
  "mutation_record": {
    "payload_modified": false,
    "replayed_payload_sha256": "3a7bd3e2360a…",
    "json_patch_diff": []
  },
  "simulation_summary": {
    "dry_run_executed_at": "2026-11-26T07:10:14.102Z",
    "dry_run_response_code": 200,
    "simulated_entity_state": "open -> paid",
    "simulated_monetary_impact_usd": 250.00
  },
  "governance": {
    "policy_tier": "tier_1_peer",
    "incident_reference": "INC-2026-1126-DB-POOL",
    "justification": "Replaying invoice.paid events dropped during database failover.",
    "requester": {
      "user_id": "usr_eng_042",
      "mfa_verified": true,
      "requested_at": "2026-11-26T07:09:50.000Z"
    },
    "approvers": [
      {
        "user_id": "usr_fin_009",
        "role": "billing_operations_lead",
        "mfa_verified": true,
        "approved_at": "2026-11-26T07:14:22.890Z",
        "approval_signature": "ed25519:7c9a8b1d…"
      }
    ]
  },
  "execution_result": {
    "dispatched_at": "2026-11-26T07:15:01.004Z",
    "target_url": "https://billing-api.internal/webhooks/stripe",
    "http_status_code": 200,
    "latency_ms": 84,
    "consumer_receipt_id": "rcpt_991204a"
  },
  "previous_audit_hash": "9f86d081884c…",
  "record_hash": "4b227777d4dd…"
}

The source IP in the example is one of the addresses Stripe publishes for webhook notifications. When you record the source IP at ingestion, check it against Stripe’s current list (which changes over time, with notice given via an announcement mailing list) rather than hard-coding it.

Two Cryptographic Details That Matter

1. Preserve the upstream signature and add your own. Stripe signs {timestamp}.{raw body} with HMAC-SHA256 and sends the result in the Stripe-Signature header. Its official libraries reject signatures older than a default tolerance of five minutes. A replay hours later will therefore fail verification if you forward the original header unchanged. Don’t tell consumers to disable timestamp checking. Instead, store the original provider signature and raw bytes as evidence of authenticity at ingestion, and have the gateway wrap the replay in its own fresh signature, bound to the replay batch ID and the approval signature, that the consumer verifies with a dedicated replay secret. Stripe also requires the raw, unmodified request body for verification, so never persist only a re-serialized JSON object.

2. Chain your audit records. Including previous_audit_hash in each record creates a hash chain. If someone alters or deletes a historical record, verification breaks from that point onward. A hash chain by itself does not detect removal of the newest records, so periodically anchor the latest hash somewhere the operators of the audit store can’t modify, such as a separate cloud account with Object Lock enabled.

For PCI DSS scope, remember that audit records should contain stable identifiers rather than account data, and sensitive authentication data must never be stored after authorization, even in encrypted logs.

Operational Guardrails During Approved Replay Execution

Even an approved batch can cause harm if it is released all at once.

1. Rate Limiting and Concurrency Caps

Consider a hypothetical two-hour outage that leaves 80,000 failed billing webhooks. Dispatching all of them at once would overwhelm database connection pools and third-party API rate limits.

  • Set a per-endpoint concurrency cap (for example, 15 in-flight requests) in a pool separate from live traffic, so historical replays never starve live checkout events.
  • Use adaptive pacing in the style of AIMD (additive increase, multiplicative decrease). If consumer p99 latency crosses a threshold you define (say 500 ms) or 429 Too Many Requests responses appear, cut throughput sharply and ramp back up gradually. The numbers here are starting points to tune for your system, not standards.

2. Chronological Ordering Per Entity

Since providers don’t guarantee ordering, the replay scheduler should impose it. Group events by a partition key such as customer_id or subscription_id, and dispatch each group strictly in original event-timestamp order, waiting for a 2xx on event N before sending event N+1. Events for different customers can run concurrently.

3. Circuit Breaking on Diff Divergence

If live execution diverges from what the dry run predicted (for example, the dry run predicted a 200 state transition but the live call returns 409 Conflict or 500), halt the remaining batch, revoke the approval token, and alert the operator. Divergence means production state changed between preview and execution, and the approver’s decision may no longer be valid.

Implementation Checklist for Engineering Teams

  1. Inventory and classify event types. Tag each webhook topic with a sensitivity tier and extract the monetary amount, currency, and entity ID at ingestion.
  2. Archive raw deliveries. Store raw bodies, headers, and signatures at ingestion. Stripe’s 30-day event window and Adyen’s 30-day retry queue are both finite, so your own archive is the long-term source of truth.
  3. Add dry-run support to consumers. Implement signed dry-run handling in billing, ledger, and notification services, and stub every side effect that leaves the database transaction.
  4. Make deduplication durable. Persist processed event IDs with a unique constraint instead of relying on a short TTL cache.
  5. Enforce policy-based approval gates. Block direct replays of Tier 1 and Tier 2 events until the required approvals are recorded via SSO/OIDC, with self-approval prevented.
  6. Ship audit records to immutable storage. Write dry-run diffs, approvals, and delivery receipts to write-once storage indexed by event ID and incident reference. Retain them at least as long as your compliance regime requires (PCI DSS requires 12 months of audit history).
  7. Rehearse. Run a game-day that replays a synthetic batch with a stale event, a duplicate, and a high-value refund, and confirm that the gates, diff, and circuit breaker each catch what they should.

Treating financial webhook replays with the same rigor as a schema migration or a treasury transfer removes the silent failure modes of blind replay. It also leaves finance and compliance teams with a complete, verifiable record of every recovered transaction.

Sources