1. What is HTTP Method Idempotency and how do you implement Idempotency Keys for REST APIs?
❓ Context: Which HTTP methods are idempotent? How do Payment APIs (like Stripe) use Idempotency-Key headers to prevent double billing?
An HTTP method is idempotent if making multiple identical requests has the same side-effect on the server as making a single request.
HTTP Method Breakdown:
Idempotency Keys:
To make 'POST' endpoints (like charging a credit card) safe against retries due to network timeouts, clients send a unique 'Idempotency-Key' UUID in headers. The API checks Redis/DB for the key and returns cached responses on duplicate requests.
import { Request, Response, NextFunction } from 'express';
export async function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
const idempotencyKey = req.header('Idempotency-Key');
if (!idempotencyKey) return next();
const cacheKey = 'idempotency:\${idempotencyKey}';
const cachedResponse = await redis.get(cacheKey);
if (cachedResponse) {
const { status, body } = JSON.parse(cachedResponse);
return res.status(status).json(body);
}
// Intercept and cache POST execution responses...
next();
}Idempotency keys ensure critical non-idempotent POST operations are safe against retries in distributed systems.