Engineering

Paystack Webhook Retries: Why Redis Idempotency Keys Drop Payments Under Network Flaps

O
Oluwaseun AlabiTechnical Director
October 29, 202615 min read
Paystack Webhook Retries: Why Redis Idempotency Keys Drop Payments Under Network Flaps

Relying on Redis SETNX for Paystack or Flutterwave webhook deduplication causes double-credits or silently dropped payments when networks degrade in Nigeria. Here is why database-level atomic locking is the only safe architecture.

Every growth-stage fintech in Lagos reaches a point where payment webhooks start behaving strangely. Your primary database reports that a customer's wallet was credited once, but your audit log shows Paystack sent the charge.success event three times. Worse, during major network degradation across IXPN or IXP fiber cuts, customers complain about funded accounts that remain uncredited, even though your logs show 200 OK responses delivered back to Paystack's delivery engines.

When backend teams investigate, the root cause almost always traces back to a pattern taught in popular tutorials: using Redis SETNX (or SET key value NX EX TTL) as an idempotency layer before touching the primary relational database.

In high-volume payment processing across Sub-Saharan Africa, Redis-based webhook deduplication is a ticking time bomb. It introduces race conditions during downstream latency spikes, creates silent failure states where payments remain unfulfilled forever, and misleads payment gateways into believing transactions are finalized when they are not.

If you process money, you must ditch Redis keys for webhook idempotency and shift transaction locking entirely inside your ACID-compliant database boundary.

A technical flow showing how Redis SETNX timeout causes race conditions during payment webhook delivery

The Anatomy of a Flawed Redis Idempotency Check

To understand why Redis idempotency fails under load, look at how a standard Node.js or Go HTTP handler processes an incoming webhook from Paystack Webhook Notifications:

  1. Paystack sends an HTTP POST request containing charge.success and a transaction reference ref_882910384.
  2. Your API gateway verifies the x-paystack-signature header using HMAC-SHA512.
  3. The application executes SET lock:ref_882910384 1 EX 300 NX against Redis.
  4. If Redis returns nil (key already exists), the app assumes this is a duplicate retry and immediately returns HTTP 200 OK.
  5. If Redis returns OK, the app opens a PostgreSQL transaction, mutates the account ledger, inserts a transaction log, and commits.

This workflow looks clean on paper. In production under real network conditions, it fails in two distinct, dangerous ways.

Failure Mode 1: The Phantom Drop (Under-Crediting)

Suppose Paystack issues a webhook for ref_882910384. Your Go handler successfully sets the key in Redis with a 5-minute TTL. However, right after setting the Redis key, your database connection pool starves, or an upstream network flap stalls the application worker before the PostgreSQL transaction begins.

The application context times out or crashes. The PostgreSQL transaction never runs. But the key lock:ref_882910384 now exists in Redis for the next 300 seconds.

Paystack's automated delivery system, sensing an interrupted HTTP socket, retries the payload 15 seconds later. The retry hits your endpoint. Your code checks Redis. Redis says: "Key exists!" Your application assumes another thread processed it, short-circuits, and returns 200 OK to Paystack.

Paystack flags the event as successfully delivered. Your system never retries it. The user's money sits in Paystack's merchant balance, but their balance inside your application never updates. You now have a customer support nightmare.

Failure Mode 2: The Double-Credit Race Condition (Over-Crediting)

Consider the opposite scenario: network latency between your Lagos application servers and your managed database cluster spikes to 8,000ms due to transient routing issues.

Worker A receives ref_882910384, sets the 30-second Redis lock, and begins writing to PostgreSQL. The DB transaction takes 35 seconds to complete due to write-ahead log (WAL) lock contention.

At second 31, the Redis lock expires automatically due to its TTL. Paystack, still waiting for Worker A's HTTP response, fires a concurrent retry. Worker B receives the retry, checks Redis, finds no lock, sets a new lock, opens a second PostgreSQL transaction, and credits the user's account.

At second 35, Worker A finishes committing its transaction. Worker B finishes committing at second 40. You have just double-credited a user wallet.

As discussed in our analysis of Telco API Failures in Nigeria: Ditch Celery for a Go Transactional Outbox Engine, network instability is a baseline environment condition, not an anomaly. Designing idempotency around ephemeral in-memory stores with arbitrary TTL expiration guarantees eventual state corruption.

|

The Strongest Counterargument: "Database Locking Does Not Scale"

When we advise engineering teams to move webhook deduplication to PostgreSQL, senior architects often raise a reasonable concern:

"Paystack and Flutterwave occasionally fire burst retries or thundering herds of webhooks during peak sales events like Black Friday. Routing every incoming HTTP payload directly to PostgreSQL transactions to check idempotency will exhaust our DB connection pool and spike CPU utilization. Redis is fast precisely because it shields PostgreSQL from unthrottled external webhooks."

This argument fails to distinguish between read throughput and financial correctness.

Shielding your database is a noble goal for public read APIs, content feeds, or catalog views. But for financial ledgers, accuracy supersedes connection throttling. If your idempotency check is decoupled from the transaction boundary that writes money, your system is non-deterministic.

Furthermore, modern PostgreSQL deployments handle connection overhead effortlessly when coupled with pgBouncer or built-in application connection pooling. A simple indexed INSERT on an idempotency table takes sub-millisecond execution times in Postgres. The CPU cost of an indexed primary key lookup inside Postgres is drastically cheaper than reconciling double-credited ledger balances manually at 2:00 AM.

The Solution: Database-Native Atomic State Transitions

To build a crash-resilient webhook pipeline, you must bind webhook processing directly to PostgreSQL ACID guarantees. The database table handling idempotency must be updated in the exact same logical transaction that alters your financial balances.

Instead of checking Redis before opening a database connection, structure your persistence model so that duplicate webhook events are rejected atomically by PostgreSQL constraints.

Design Pattern: The Idempotent Processed Events Schema

Create a dedicated processed_webhooks table that enforces unique constraints on provider references.

CREATE TABLE processed_webhooks (
    id BIGGENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    provider VARCHAR(32) NOT NULL,
    event_id VARCHAR(128) NOT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT unique_provider_event UNIQUE (provider, event_id)
);

When a webhook arrives, do not use SELECT to check if event_id exists. SELECT-then-INSERT logic is subject to race conditions under concurrent requests. Instead, utilize PostgreSQL Explicit Locking Mechanisms or INSERT ... ON CONFLICT DO NOTHING combined with transaction-scoped row locks.

Concrete Implementation: Go Engine with Transactional Lock Execution

Below is a complete, production-ready Go handler pattern demonstrating how to safely execute Paystack webhooks using PostgreSQL transactions and FOR UPDATE semantics.

package payment

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"net/http"
	"time"
)

var ErrEventAlreadyProcessed = errors.New("webhook event already processed or currently locked")

type WebhookService struct {
	DB *sql.DB
}

type PaystackPayload struct {
	Event string `json:"event"`
	Data  struct {
		Reference string `json:"reference"`
		Amount    int64  `json:"amount"`
	} `json:"data"`
}

func (s *WebhookService) ProcessPaystackWebhook(ctx context.Context, payload PaystackPayload) error {
	// Begin transaction with strictly isolated boundaries
	tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		return fmt.Errorf("failed to initiate transaction: %w", err)
	}
	defer tx.Rollback()

	// Step 1: Attempt to register the event atomically.
	// ON CONFLICT DO NOTHING ensures that concurrent identical events do not crash the statement,
	// but returning the ID tells us if this execution was the creator.
	var webhookID int64
	query := `
		INSERT INTO processed_webhooks (provider, event_id, status)
		VALUES ('paystack', $1, 'PROCESSING')
		ON CONFLICT (provider, event_id) DO NOTHING
		RETURNING id;
	`      
	err = tx.QueryRowContext(ctx, query, payload.Data.Reference).Scan(&webhookID)
	
	if errors.Is(err, sql.ErrNoRows) {
		// Row exists. Check if it's already finished or currently locked by another worker.
		var status string
		checkQuery := `
			SELECT status FROM processed_webhooks 
			WHERE provider = 'paystack' AND event_id = $1 
			FOR UPDATE;
		`             
		err = tx.QueryRowContext(ctx, checkQuery, payload.Data.Reference).Scan(&status)
		if err != nil {
			return fmt.Errorf("failed to evaluate duplicate event state: %w", err)
		}

		if status == "COMPLETED" {
			// Event fully finished. Return nil so HTTP layer responds 200 OK to provider.
			return nil
		}

		// Event is still PROCESSING in another thread or previously failed.
		// Returning error forces HTTP handler to return 500/409, signaling Paystack to retry later.
		return ErrEventAlreadyProcessed
	}
	if err != nil {
		return fmt.Errorf("failed inserting webhook record: %w", err)
	}

	// Step 2: Perform financial credit inside the exact same database transaction.
	err = s.creditUserWalletTx(ctx, tx, payload.Data.Reference, payload.Data.Amount)
	if err != nil {
		// Rollback happens automatically via defer tx.Rollback()
		return fmt.Errorf("ledger update failed: %w", err)
	}

	// Step 3: Mark event status as COMPLETED before committing transaction
	updateQuery := `UPDATE processed_webhooks SET status = 'COMPLETED', updated_at = NOW() WHERE id = $1;`  
	_, err = tx.ExecContext(ctx, updateQuery, webhookID)
	if err != nil {
		return fmt.Errorf("failed updating webhook status: %w", err)
	}

	// Step 4: Commit transaction. Idempotency lock and balance change become visible simultaneously.
	return tx.Commit()
}

func (s *WebhookService) creditUserWalletTx(ctx context.Context, tx *sql.Tx, ref string, amount int64) error {
	// Business logic for dual-entry posting
	// See our reference guide on multi-tenant billing models for context.
	_, err := tx.ExecContext(ctx, 
		`UPDATE wallets SET balance = balance + $1 WHERE id = (SELECT wallet_id FROM transactions WHERE reference = $2);`,
		amount, ref,
	)
	return err
}

In our post on Dual-Currency SaaS Billing in Go: Multi-Tenant Pricing with Dynamic FX Indexing, we highlighted how atomic balance updates require zero external cache reliance. The same operational strictness applies here.

Why This Prevents Both Failure Modes

  1. No Phantom Drops: If your application worker crashes mid-execution, PostgreSQL automatically rolls back the INSERT INTO processed_webhooks. When Paystack retries 30 seconds later, the row does not exist. The retry succeeds and credits the account correctly.
  2. No Double-Credits: If two identical webhooks hit two different application workers at the exact same millisecond, PostgreSQL's unique index constraint ensures only one worker receives a row back from RETURNING id. The second worker hits ON CONFLICT DO NOTHING, falls into FOR UPDATE, blocks until Worker A finishes, reads status 'COMPLETED', and safely exits without double-crediting.

Practical Migration Checklist

If you currently run Redis-based locks in production, follow this phased migration path to migrate safely without downtime:

  1. Deploy the processed_webhooks Table: Run migrations to add the table with unique constraints on (provider, event_id).
  2. Backfill Active References: Populate the table with transaction references from the last 7 days of raw transaction logs marked as successful. Set their initial status to 'COMPLETED'.
  3. Switch Handler Logic: Replace the Redis SETNX code in your payment service with database-level INSERT ... ON CONFLICT inside transaction blocks.
  4. Demote Redis to Thundering Herd Protection (Optional): If you still want Redis to prevent abusive traffic from hitting your database during DDoS attacks, use Redis strictly as a rate limiter, never as an idempotency engine. Never return 200 OK to a payment provider based purely on a Redis cache hit.

Frequently Asked Questions (FAQ)

What HTTP status code should I return to Paystack when a retry arrives while processing is still in progress?

Return an HTTP status code in the 4xx or 5xx range (such as 409 Conflict or 429 Too Many Requests). This informs Paystack or Flutterwave that your system received the payload but is not yet ready to confirm finality, prompting their delivery infrastructure to back off and retry later according to exponential backoff policies.

Doesn't SELECT FOR UPDATE cause database lock contention under high TPS?

SELECT FOR UPDATE locks only a single row matching (provider, event_id). Because webhook references are unique per transaction, different payment events lock entirely distinct rows in parallel. PostgreSQL handles thousands of non-overlapping row locks per second with negligible latency impact.

Should I store the entire raw JSON webhook payload in PostgreSQL?

Yes. Storing the raw payload in a jsonb column on your processed_webhooks table is invaluable for debugging signature mismatches, payload format changes by providers, and audit compliance requirements during financial reconciliations.

How should we clean up old records in the processed_webhooks table?

Do not delete them. Instead, use PostgreSQL range partitioning based on created_at (e.g., monthly partitions). Archive older partitions to cold storage like AWS S3 or Google Cloud Storage after 90 days if disk space becomes a constraint. Retaining idempotency records permanently prevents late-arriving retries from re-triggering ancient payments.

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#Go#PostgreSQL#Paystack#Fintech#System Design#Architecture

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.