The user wants a comprehensive "Payment Idempotency Plan."
This is a critical systems design task for any fintech or e-commerce platform.
The core problem is ensuring that exactly one payment is processed for a single user intent, even if the network fails, the user retries, or bugs occur.
Key components to cover as requested:
- Keys: How to generate and manage idempotency keys.
- Replay Windows: How long to store/reject keys.
- Reconciliation: How to fix discrepancies when idempotency fails or edge cases occur.
- Alerts: Monitoring and observability.
Drafting the structure:
- Introduction: Define idempotency in the context of payments (safety vs. liveness).
- Phase 1: The Idempotency Key (The "Front Door")
- Who generates it? (Client vs. Server). Best practice: Client generates, Server validates/hashes.
- Format? (UUID v4 is standard).
- Header transmission (standard HTTP headers).
- Request fingerprinting (what if they forget the key? use body hash?).
- Phase 2: The Request Lifecycle (The "Engine")
- Storage mechanism (Redis vs. DB). Redis is faster, DB is safer. Hybrid is best.
- The state machine:
IN_PROGRESS -> COMPLETED / FAILED.
- Handling concurrent requests (locking).
- Parameter mismatch validation (same key, different payload = error).
- Phase 3: Replay Windows (Time constraints)
- Why do we need a window? To prevent accidental duplicates days later.
- Standard duration? (24 hours is common, some do 48-72).
- Expiration mechanism (TTL).
- After expiration? Treat as new? Or soft reject? Usually treat as new, but log aggressively.
- Phase 4: Reconciliation (The "Back Office")
- Why idempotency isn't enough (downstream failures, race conditions).
- Internal Reconciliation: Comparing Ledger vs. Transaction DB.
- External Reconciliation: Comparing Internal DB vs. Stripe/Bank files.
- Automated fixing scripts.
- Phase 5: Alerts & Observability (The "Sirens")
- What to watch?
- High collision rates (client bugs).
- Stuck
IN_PROGRESS states.
- Mismatch errors (same key, different body).
- Dashboards.
Refining specific points:
- Keys: Should I mention HMAC? Yes, validating that the request body matches the key is crucial to prevent "key hijacking" or confusion where a key maps to a different payment amount.
- Storage: Write-through caching. Write to DB (source of truth) and Cache (speed).
- Replay: What if a payment is Pending for too long? Need a timeout logic, not just a window.
- Reconciliation: This is often overlooked. Idempotency prevents double charging on retries, but Reconciliation fixes single charges that weren't recorded or double charges that happened due to logic bugs.
Structuring the Output:
I will organize this into a logical flow: Strategy -> Implementation -> Maintenance.
- Core Concept: Idempotency-Key header.
- Data Model: The
IdempotencyRecord.
- Lifecycle Flow: The algorithm (Check DB -> Lock -> Process -> Unlock/Save).
- Replay Window Strategy: TTL settings.
- Reconciliation Strategy: Daily batch jobs.
- Alerting Strategy: Key metrics.
Self-Correction/Edge Cases:
- What if the client sends the same key for a different user? -> The key should be scoped to the user/merchant ID.
- What if the payment provider times out? -> The state remains
IN_PROGRESS. We need a specific "Status Check" flow or timeout mechanism to resolve it.
Final Polish:
Make it actionable. Use clear headings. Provide code-like logic snippets (pseudocode) or schema definitions. Emphasize the difference between Syntactic idempotency (keys match) and Semantic idempotency (money moved correctly).
Let's write it out.
- Section 1: Keys: Client-side generation (UUID). Scoping to
UserID. Fingerprinting the payload.
- Section 2: Storage & Window: Redis (hot path) + Postgres (audit). 24-48 hour window.
- Section 3: Logic: The state machine.
- Section 4: Reconciliation: The safety net.
- Section 5: Alerts: The signals.
(Self-correction on Replay Windows): If a user retries after 48 hours, should we charge them? No, that's dangerous. We should probably error out or force a new key. Usually, keys expire, and the endpoint rejects old keys or generates a new ID. Standard practice: Reject if key exists and is finished. If key doesn't exist, process. If key exists and is old (expired), reject strictly.
Let's proceed with this structure.
Designing a robust payment idempotency plan is critical for financial systems to prevent double-charging customers during network timeouts or retry storms.
Here is a comprehensive design plan covering Keys, Storage, Replay Windows, Reconciliation, and Alerts.
1. Idempotency Keys (The Identity)
The core of the plan relies on the Idempotency-Key header. This key represents a unique intent to pay, not just a specific API call.
- Generation Strategy:
- Client-Side: The client (frontend or merchant system) generates a v4 UUID.
- Scope: The key must be unique per Merchant ID (
scope). Key ABC for Merchant X should not block Key ABC for Merchant Y.
- Key Constraints:
- Length: Max 255 characters.
- Uniqueness: Enforced via database unique constraints.
- Request Fingerprinting (Safety Layer):
- Alongside the key, store a SHA-256 hash of the request body (
amount, currency, destination).
- Logic: If Key
ABC is reused with a different request body, reject it with a 409 Conflict or 422 Unprocessable Entity. This prevents a client bug from accidentally reusing a key for a different payment amount.
2. Lifecycle & Replay Windows (The Timing)
You must define how long a key is valid and how the system handles time.
- Storage Architecture:
- Database: Persistent storage (PostgreSQL/MySQL) is required. Redis is acceptable only as a cache layer, but the "Source of Truth" must be the DB to survive crashes.
- Schema:
CREATE TABLE idempotency_keys (
key VARCHAR(255) PRIMARY KEY,
merchant_id VARCHAR(255),
request_hash VARCHAR(64),
status ENUM('IN_PROGRESS', 'COMPLETED', 'FAILED'),
response_code INT,
response_body JSONB,
created_at TIMESTAMP,
locked_at TIMESTAMP
);
- Replay Window (TTL):
- Duration: 24 to 48 hours is standard.
- Rationale: This covers weekend retries and extended network outages.
- Post-Window Behavior: After the window expires, the key should be archived or deleted. If a client retries after 72 hours, treat it as a new request (or reject it with
410 Gone depending on strictness).
- State Machine:
- New: Key does not exist. Lock it, process payment.
- In-Progress: Key exists, status
IN_PROGRESS.
- Action: Return
202 Accepted (polling) or make the client wait. Do not reprocess.
- Completed: Key exists, status
COMPLETED.
- Action: Return the cached original
200 OK response immediately.
3. The Processing Flow (The Logic)
Implement this logic at the API Gateway or Controller level before touching the ledger.
- Check Key:
SELECT * FROM idempotency_keys WHERE key = ?
- If Found:
- Verify
request_hash. If mismatch -> 422 Error.
- If
status == COMPLETED -> Return cached response.
- If
status == IN_PROGRESS -> Return 202 Accepted (client should retry later).
- If Not Found:
- Insert key with
status = IN_PROGRESS.
- Execute Payment Logic (Database Transaction).
- Update key with
status = COMPLETED and cache the response.
- Commit Transaction.
4. Reconciliation (The Safety Net)
Idempotency prevents double processing, but Reconciliation fixes what slips through (e.g., database deadlocks, race conditions, partial failures).
- Internal Reconciliation (Ledger vs. Idempotency):
- Run a nightly batch job joining the
transactions table with the idempotency_keys table.
- Check: Ensure every successful transaction has exactly one idempotency key.
- Check: Ensure every
COMPLETED idempotency key matches a transaction.
- External Reconciliation (Provider vs. Internal):
- Compare your database records against your Payment Service Provider (PSP), like Stripe or Adyen.
- Logic: If the PSP shows a "Charge Success" but your DB shows "Failed" (due to a timeout receiving the response), the reconciliation worker must "heal" the state by updating the local DB to success and triggering the webhook/email.
- Orphan Handling:
- Keys stuck in
IN_PROGRESS for > 60 minutes are considered "Zombies." A sweeper process should investigate the payment status at the PSP and resolve the state to either COMPLETED or FAILED.
5. Alerts & Observability (The Signals)
You need visibility into the health of the idempotency system.
Key Metrics to Track:
- Idempotency Hit Rate: Percentage of requests that returned a cached response vs. processed a new payment.
- Alert: If Hit Rate spikes > 20%, clients are likely experiencing network issues and retrying aggressively.
- Conflict Rate (422s): Percentage of requests where the key matched but the payload hash differed.
- Alert: If > 0, a client has a bug reusing keys for different amounts. Critical Security Alert.
- Zombie Key Count: Number of keys stuck in
IN_PROGRESS for > 30 minutes.
- Alert: Indicates your processing logic is hanging or the database is locking up.
- Latency Differential: Time taken to serve a cached response vs. a new execution.
- Goal: Cached responses should be < 10ms.
Summary Checklist
| Component | Strategy |
|---|
| Key Source | Client-generated UUID v4. |
| Scope | Scoped to Merchant ID. |
| Validation | SHA-256 Hash of request body. |
| Storage | Persistent DB (Primary), Redis (Optional Cache). |
| Window | 48 Hours Strict, then Archive. |
| Locking | Optimistic locking or DB row-level locks. |
| Recovery | Sweeper job for IN_PROGRESS timeouts. |