Course contentsShow
← System Design
Lesson 1010 of 1,91926. Idempotency and RetriesFree lesson

Idempotency Keys for POST Requests

Use client-generated idempotency keys in request headers or body to make non-idempotent operations idempotent.

Idempotency Keys for POST Requests

What you'll learn: How to use client-generated idempotency keys to make POST requests safely repeatable, eliminating duplicate operations.

The Challenge with POST

As you learned, POST requests are naturally non-idempotent—sending the same request twice creates two resources. But networks fail, timeouts occur, and clients retry. Without protection, a retry could charge a customer twice or create duplicate orders.

Client-Generated Idempotency Keys

The solution: the client generates a unique identifier (an idempotency key) for each logical operation and includes it with the request. This key can be sent in:

  • A custom header (common): Idempotency-Key: 7f8e9d0a-1b2c-3d4e-5f6a-7b8c9d0e1f2a
  • The request body: {"idempotency_key": "...", "amount": 100}

When the server receives a POST with an idempotency key, it:

  1. Checks if it has seen this key before
  2. If new: processes the request and stores the result with the key
  3. If duplicate: returns the stored result from the first request

Think of it like a ticket stub at a coat check. You hand in your coat once with a unique ticket number. If you return with the same ticket, they don't take another coat—they just retrieve the one you already checked.

Example Flow

Client generates key: abc-123
POST /payments {"amount": 50} + Idempotency-Key: abc-123
→ Server processes payment, stores result

Network timeout, client retries:
POST /payments {"amount": 50} + Idempotency-Key: abc-123
→ Server sees abc-123 again, returns stored result (no duplicate charge!)

Key Takeaway: Client-generated idempotency keys in headers or body transform non-idempotent POST requests into safely retriable operations by allowing servers to detect and handle duplicates.