
Payment Retry Logic: How to Build a Decline-Aware Retry Engine
Most payment retry logic starts as a cron job that re-charges every failed card each night. It works until it double-charges a customer, burns through a card network's reattempt limit, or keeps hammering a card whose issuer already said "never". This guide is about the engineering side: how to design payment retry logic as a small, decline-aware system with a clear data model, a policy layer, a scheduler, idempotent execution and the guardrails card networks expect. If you need the business view first (why cards fail and what to fix in checkout), read our guide on how to reduce payment declines in an online store. This article assumes that part is handled and focuses on what to build.
What a retry engine actually has to decide
Every failed charge leads to three questions, and your system should answer them explicitly instead of hiding them in a loop:
- Should we retry at all? Some declines are final. Retrying them wastes money and can trigger network fees.
- When? A technical error might clear in minutes; insufficient funds might clear after payday.
- How, safely? The retry must not create a second charge if the first one actually succeeded, and two workers must never retry the same payment at the same time.
Card networks give you signals for the first two. Visa groups declines into categories and, for the ones that may be reattempted, allows no more than 15 reattempts within any 30-day period. Mastercard sends Merchant Advice Codes (MAC) alongside the response code; its list of values includes 01 (new account information available), 02 (try again later), 03 (do not try again), 21 (payment cancellation) and 24–29, which mean "retry after" 1 hour, 24 hours, 2, 4, 6 or 8 days. Mastercard also charges a fee for each resubmission after a MAC 03 decline within a 30-day period. Your engine's job is to turn those signals into deterministic decisions.
Data model: separate intents, attempts and schedules
The most common design flaw is a single payments row with a status and a retry_count. You lose history, you cannot audit why a retry happened, and concurrency bugs become invisible. Model three things separately:
CREATE TABLE payment_intents (
id UUID PRIMARY KEY,
customer_id UUID NOT NULL,
payment_method TEXT NOT NULL, -- gateway token, never a card number
amount_minor BIGINT NOT NULL, -- cents, no floats
currency CHAR(3) NOT NULL,
status TEXT NOT NULL, -- pending | retry_scheduled | succeeded | failed_final | needs_customer
next_attempt_at TIMESTAMPTZ,
locked_until TIMESTAMPTZ,
version INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE payment_attempts (
id UUID PRIMARY KEY,
intent_id UUID NOT NULL REFERENCES payment_intents(id),
attempt_no INT NOT NULL,
idempotency_key TEXT NOT NULL UNIQUE,
outcome TEXT NOT NULL, -- approved | declined | error | unknown
gateway_code TEXT,
network_code TEXT,
advice_code TEXT, -- e.g. Mastercard MAC
decision TEXT, -- retry | stop | ask_customer
raw_response JSONB, -- scrubbed
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (intent_id, attempt_no)
);
CREATE INDEX ON payment_intents (next_attempt_at)
WHERE status = 'retry_scheduled';
The intent is the obligation ("charge this customer this amount"). Attempts are immutable facts. The schedule lives on the intent as next_attempt_at, which keeps the scheduler query cheap thanks to the partial index. The UNIQUE (intent_id, attempt_no) constraint is a cheap guard against two workers recording the same attempt.
To respect network limits per card rather than per invoice, count attempts by payment method over a rolling window. A query over payment_attempts joined to intents works at modest volume; at higher volume, keep a counter table keyed by payment method and day.
Normalize decline signals before deciding
Each gateway returns its own decline codes, and some also pass through the network response code and advice code. Do not let gateway-specific strings leak into your policy. Map them into a small internal vocabulary first:
from dataclasses import dataclass
from enum import Enum
class Action(Enum):
STOP = "stop" # never retry automatically
ASK_CUSTOMER = "ask_customer" # needs new card or customer action
RETRY_SOON = "retry_soon" # technical / transient
RETRY_LATER = "retry_later" # funds, limits
RETRY_AT = "retry_at" # network told us when
@dataclass
class Decision:
action: Action
delay_hours: float | None = None
reason: str = ""
MAC_DELAYS = {"24": 1, "25": 24, "26": 48, "27": 96, "28": 144, "29": 192}
def classify(attempt) -> Decision:
mac = attempt.advice_code
if mac in ("03", "21"):
return Decision(Action.STOP, reason=f"mac_{mac}")
if mac == "01":
return Decision(Action.ASK_CUSTOMER, reason="new_account_info")
if mac in MAC_DELAYS:
return Decision(Action.RETRY_AT, MAC_DELAYS[mac], f"mac_{mac}")
category = GATEWAY_MAP.get((attempt.gateway, attempt.gateway_code))
if category is None:
return Decision(Action.STOP, reason="unmapped_code") # fail closed
return category
Two details matter here. First, network advice wins over your heuristics: if the issuer gave an explicit instruction, follow it. Second, unknown codes fail closed. An unmapped code should stop automatic retries and raise an alert, not fall into a default "retry in 24 hours" bucket. Keep GATEWAY_MAP as data (a table or config file) so operations can update it without a deploy, and version it so each attempt records which mapping produced its decision.
Scheduling: delays, budgets and jitter
Once you have a decision, computing the next attempt is a pure function. Keeping it pure makes it trivial to unit test:
def next_attempt(decision, attempt_no, card_attempts_30d, now):
if decision.action in (Action.STOP, Action.ASK_CUSTOMER):
return None
if card_attempts_30d >= CARD_BUDGET_30D: # keep well under network caps
return None
if attempt_no >= MAX_ATTEMPTS_PER_INTENT:
return None
if decision.action == Action.RETRY_AT:
base = decision.delay_hours
elif decision.action == Action.RETRY_SOON:
base = 0.5 * (2 ** (attempt_no - 1)) # 30 min, 1 h, 2 h...
else: # RETRY_LATER
base = 24 * attempt_no # 1 day, 2 days, 3 days...
jitter = random.uniform(0, base * 0.1)
return now + timedelta(hours=base + jitter)
CARD_BUDGET_30D and MAX_ATTEMPTS_PER_INTENT are your own business decisions; set them comfortably below the network limits rather than at them, because other systems (a customer retrying in checkout, a different subscription on the same card) also consume the budget. Jitter avoids sending thousands of retries to the gateway at exactly the same second after a batch failure. For "retry later" declines, many teams also align attempts with the customer's local time or typical pay dates; if you do, store the timezone on the customer, not on the server.
Executing a retry without double charges
This is where real money is lost. The pattern has four parts.
1. Claim the intent atomically. Use a lease so only one worker can process an intent at a time:
UPDATE payment_intents
SET locked_until = now() + interval '5 minutes', version = version + 1
WHERE id = (
SELECT id FROM payment_intents
WHERE status = 'retry_scheduled'
AND next_attempt_at <= now()
AND (locked_until IS NULL OR locked_until < now())
ORDER BY next_attempt_at
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING *;
FOR UPDATE SKIP LOCKED (PostgreSQL) lets many workers pull from the same table without blocking each other.
2. Create the attempt row before calling the gateway, with a deterministic idempotency key such as intent_id:attempt_no. If the worker crashes after the gateway call, the next worker reuses the same key instead of generating a new one, and a gateway that supports idempotency keys will return the original result rather than charging twice. Check your provider's documentation for how long it stores keys and what it considers a conflicting request.
3. Treat timeouts as "unknown", not "declined". A timeout means you do not know whether the charge happened. Before scheduling another attempt, query the gateway for the payment status or wait for the webhook. Retrying an unknown outcome with a new key is the classic double-charge bug.
4. Reconcile with webhooks. Webhooks can arrive before your API call returns, late, or more than once. Process them idempotently (store the event ID, ignore duplicates) and let them move the intent forward only through valid state transitions. An intent in succeeded must never go back to retry_scheduled.
pending ──approved──▶ succeeded
│
├─declined (retryable)──▶ retry_scheduled ──claim──▶ pending
├─declined (final)──────▶ failed_final
├─needs new card────────▶ needs_customer ──card updated──▶ pending
└─timeout───────────────▶ unknown ──status check──▶ (any of the above)
Build, buy or hybrid: the trade-offs
Gateway-managed retries. Many processors and billing tools offer automatic retries for subscriptions. Fast to enable, and the provider may use signals you do not see. The cost: limited control, little visibility into why a retry happened, and lock-in if you use more than one processor.
Your own engine. Full control over policy, per-card budgets across processors, and data you can analyze. The cost is everything in this article: state machine, scheduling, idempotency, monitoring and upkeep of code mappings.
Hybrid. Let the gateway handle in-session recovery (network tokens, card updater features where available) and own the scheduled retries and customer communication yourself. For most mid-size stores and subscription businesses this is the pragmatic middle ground. Never run both automatic schedulers on the same invoice: you will exceed limits without noticing.
On the scheduler itself: a cron job plus the indexed query above is enough for a single database and modest volume. A queue with delayed messages scales better but makes "what is scheduled for tomorrow?" harder to answer; a common compromise is to keep the database as the source of truth and use the queue only for dispatch. Durable workflow engines fit when retries are part of a longer process with emails, grace periods and account suspension.
Security and compliance notes
- Store only gateway tokens. Card numbers in your database put you deep into PCI DSS scope.
- Scrub raw gateway responses before persisting or logging them; keep codes, drop anything resembling card data or personal details.
- Restrict who can trigger manual retries and log every manual action with the user who performed it.
- Rate limit the customer-facing "update card and pay" endpoint; it is an attractive target for card testing.
Common mistakes
- Retrying every decline with the same fixed delay.
- Counting attempts per invoice instead of per card, so a customer with three subscriptions gets three times the attempts.
- Generating a new idempotency key on every retry of the same attempt.
- Treating a timeout as a decline.
- Defaulting unknown decline codes to "retry".
- Running the gateway's automatic retries and your own on the same charge.
- No metrics: you cannot tell whether recovered revenue comes from retries or from customers updating their card.
Payment retry logic checklist
- Separate tables for intents and immutable attempts.
- A normalization layer from gateway codes to internal actions, stored as versioned data.
- Network advice codes (such as Mastercard MAC 03 and 21) respected before any heuristic.
- Per-card attempt budget over a rolling 30-day window, set below network caps.
- Pure, unit-tested scheduling function with backoff and jitter.
- Atomic claiming with leases or
SKIP LOCKED. - Deterministic idempotency keys created before the gateway call.
- An explicit "unknown" state for timeouts, resolved by status query or webhook.
- Idempotent webhook processing with enforced state transitions.
- Dashboards for recovery rate by decline category, attempts per card and stopped retries.
If you sell subscriptions or recurring orders, such as autoship in a direct-selling business, this engine sits at the center of your revenue; it is one of the components we build into Ariani, our platform for direct-selling companies. For other businesses, it is a typical piece of custom software built around your billing and payment flows.
Frequently asked questions
How many times should I retry a failed card payment?
There is no universal number. Respect the network limits (Visa allows at most 15 reattempts in 30 days for retryable declines, and Mastercard MAC 03 or 21 means no retries), then set your own lower budget per card based on your data.
Should retries use the same idempotency key?
Use the same key when you are repeating the same attempt after a crash or timeout, so the gateway can return the original result. Use a new key for a genuinely new attempt that you scheduled after a confirmed decline.
Is a cron job good enough for payment retries?
For one database and moderate volume, yes, if it claims rows atomically and the schedule lives in the database. Move to a queue or workflow engine when volume grows or retries become part of a longer dunning process.
Comments
No comments yet. Be the first to share what you think.


