QA
Beginner LevelREST APIs & Web Services

What is HTTP Method Idempotency and how do you implement Idempotency Keys for REST APIs?

❓ Interview Prompt: 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:

•
Idempotent: 'GET', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'.
•
NOT Idempotent: 'POST' (submitting twice creates two distinct resources).

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.

Code Implementation Example

typescript
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 key middleware pattern.
🎯 Interview Key Takeaway

Idempotency keys ensure critical non-idempotent POST operations are safe against retries in distributed systems.

#REST API#HTTP#Idempotency#Backend#Beginner
Back to all REST APIs & Web Services Questions→

More REST APIs & Web Services Interview Questions

Beginner LevelREST APIs & Web Services

What are standard HTTP Status Codes (200, 201, 204, 400, 401, 403, 404, 409, 429, 500, 503)?

Beginner LevelREST APIs & Web Services

What are HTTP Verbs (GET, POST, PUT, PATCH, DELETE) and when to use PUT vs PATCH?

Beginner LevelREST APIs & Web Services

What is the Statelessness constraint in REST architecture?