Senior LevelSoftware Engineering Principles
How do Idempotency Keys guarantee Exactly-Once execution processing in financial APIs?
❓ Interview Prompt: Explain Idempotency Keys (Stripe model), `Idempotency-Key` HTTP header, atomic Redis locks, payload caching, and handling network retries.
In distributed networks, API requests can time out or fail. If a client retries a payment request ('POST /charges'), the server must avoid charging the user twice!
Idempotency Key Implementation:
1
Client includes a unique 'Idempotency-Key: uuid-v4' header.
2
Server checks Redis for the key:
•
If key exists & completed: Return cached HTTP response payload immediately!
•
If key exists & processing: Return '409 Conflict' (Processing in progress).
•
If key new: Acquire atomic Redis lock, execute payment, cache response in Redis for 24h, and return response.
Code Implementation Example
typescript
export async function handleIdempotentPayment(req: Request, res: Response) {
const idempotencyKey = req.headers['idempotency-key'] as string;
if (!idempotencyKey) return res.status(400).send('Missing Idempotency-Key');
const cachedResponse = await redis.get('idempotency:\${idempotencyKey}');
if (cachedResponse) {
return res.status(200).json(JSON.parse(cachedResponse)); // Return cached payload!
}
const paymentResult = await processStripePayment(req.body);
await redis.setex('idempotency:\${idempotencyKey}', 86400, JSON.stringify(paymentResult));
res.json(paymentResult);
}💡Handling idempotent API requests using Redis caching and Idempotency Keys.
🎯 Interview Key Takeaway
Enforce Idempotency Keys on state-changing API endpoints to guarantee safe retry handling without duplicate side-effects.
#Idempotency#API Design#Distributed Systems#Senior
Back to all Software Engineering Principles Questions→