Loading topic guide...
Architect enterprise APIs that survive scale: Idempotency keys, HTTP status code semantics, rate limiting algorithms, API Gateway routing, and Protobuf serialization.
+---------------------------------------------------------------+
| API GATEWAY LAYER |
| - Rate Limiter (Token Bucket / Sliding Window) |
| - Authentication (JWT / API Key Verification) |
| - Correlation ID injection (X-Request-ID) |
+-------------------------------+-------------------------------+
|
+------------------+------------------+
| |
v (Internal gRPC / Protobuf) v (Public REST)
+-----------------------+ +-----------------------+
| Payments Service | | Users & Auth Service |
| - Idempotency Store | | - Role Based Access |
+-----------------------+ +-----------------------+
import { Request, Response, NextFunction } from 'express';
import { redis } from './redis';
export async function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
const key = req.headers['idempotency-key'] as string;
if (!key) return next();
const cacheKey = `idemp:${key}`;
const cached = await redis.get(cacheKey);
if (cached) {
const { status, body, headers } = JSON.parse(cached);
return res.status(status).set(headers).json(body);
}
// Intercept response to store atomically
const originalJson = res.json.bind(res);
res.json = (body: any) => {
redis.set(cacheKey, JSON.stringify({
status: res.statusCode,
body,
headers: { 'X-Cache-Lookup': 'HIT' }
}), 'EX', 86400); // 24h retention
return originalJson(body);
};
next();
}Caching the exact JSON response keyed by UUID ensures repeated network retries receive identical responses without re-executing critical business logic.