Idempotency in Payment APIs: Why a Retry Must Never Become a Second Charge
Lessons from building and testing customer-scoped idempotency, SHA-256 payload fingerprinting and PostgreSQL 18 concurrency controls in SecurePay.
The Failure Mode: Network Timeouts Under Uncertainty
When a mobile app, checkout service or ERP integration sends a POST /api/payments request and the connection drops before receiving the HTTP response, the caller faces an ambiguous state: did the payment service commit the charge or did the request fail before reaching the database?
If the client retries without an idempotency contract—or if two concurrent threads send the same retry simultaneously—a naive API creates two distinct payment records and charges the customer twice.
Three Design Rules Implemented in SecurePay
- Scope the key to the authenticated customer: An Idempotency-Key is never global. The composite uniqueness constraint is (customer_id, idempotency_key) so one tenant cannot collide with or probe another customer's keys (OWASP API1:2023 Broken Object Level Authorization).
- Bind the key to a canonical SHA-256 request fingerprint: If a client reuses the same Idempotency-Key with a different amount, currency or merchantId, the API must not silently return the first payment. SecurePay hashes the normalized fields with SHA-256 and returns HTTP 409 Conflict (RFC 9457 Problem Details) when the fingerprint differs.
- Enforce concurrency at the database boundary, not only in JVM memory: A check-then-act in Java fails under parallel requests. SecurePay enforces the unique constraint in PostgreSQL 18 and verifies race conditions with concurrent integration tests.
POST /api/payments HTTP/1.1
Authorization: Bearer <signed-jwt>
Idempotency-Key: ord-2026-10-26-001
Content-Type: application/json
{"merchantId":"merchant-456","amount":10.00,"currency":"USD"}
Defense in Depth: Rate Limiting, Ownership & Observability
Around the idempotency core, SecurePay layers controls verified across 120 automated tests:
- Access matrix: 401 for missing/tampered JWTs, 403 for insufficient role, and 404 (identical Problem Details structure) when a customer requests another customer's payment UUID.
- Rate limiting: Token-bucket filter limiting /auth/login by client IP and /api/payments by authenticated customer (HTTP 429 + Retry-After), hardened against X-Forwarded-For spoofing.
- Observability: Structured JSON logs with validated X-Correlation-Id, bounded Micrometer payment counters and OpenTelemetry spans with W3C Trace Context propagation.