Sub topic 2
Making Payments Safe to Retry
Assume you know basic REST APIs, relational transactions, unique constraints, and distributed-system failures such as timeouts. A payment service must make retries safe because a client cannot tell whether a timed-out request reached the processor.
Making payments idempotent
Idempotency means repeating the same operation produces the same result. The client sends an idempotency key with each logical payment attempt. The server stores that key per merchant and associates it with a hash of the request.
A unique constraint prevents two requests with the same merchant and key from creating two payments. If the key exists, the service returns the stored result. If the request hash differs, the service rejects the request because the key was reused incorrectly.
CREATE TABLE payments (
id UUID PRIMARY KEY,
merchant_id UUID NOT NULL,
idempotency_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
status TEXT NOT NULL,
UNIQUE (merchant_id, idempotency_key)
);
INSERT INTO payments (
id, merchant_id, idempotency_key, request_hash,
amount_minor, currency, status
)
VALUES (
gen_random_uuid(), :merchant_id, :key, :request_hash,
:amount_minor, :currency, 'created'
)
ON CONFLICT (merchant_id, idempotency_key) DO NOTHING
RETURNING id;Modeling payments as a state machine
A state machine defines valid states and transitions. It prevents operations that would corrupt the payment lifecycle.
ALLOWED = {
"created": {"authorized", "failed"},
"authorized": {"captured", "voided", "failed"},
"captured": {"refunded"},
"voided": set(),
"failed": set(),
"refunded": set(),
}
def transition(current, target):
if target not in ALLOWED.get(current, set()):
raise ValueError(f"illegal transition: {current} -> {target}")
return targetRecording money in a double-entry ledger
Store amounts as integer minor units, such as 1999 cents, with an explicit currency. A double-entry ledger records equal debits and credits for every transaction. This makes missing or duplicated money easier to detect.
For example, charging a customer debits customer funds receivable and credits the merchant payable account for the same amount and currency.
Handling failures and retries
Retry only retryable failures, such as network timeouts. Reuse the same idempotency key and use exponential backoff with jitter. Never create a new key merely because the response was lost.
import random
import time
def retry(send, key, attempts=4):
for attempt in range(attempts):
try:
return send(key)
except TimeoutError:
if attempt == attempts - 1:
raise
time.sleep(random.uniform(0, 0.2 * 2**attempt))Keeping state consistent
Use a transactional outbox: write the payment change and an event row in one database transaction. A worker publishes the event later and marks it sent. For multi-service workflows, a saga coordinates local transactions and compensating actions, such as voiding an authorization after a later step fails.
Exercise
A client times out after submitting a charge. What should its retry contain?
Show answer
The same idempotency key and the same request values, so the server returns the original result or safely continues the operation.