Course contentsShow
← Node.js
Lesson 591 of 1,9806. Networking and HTTP FundamentalsFree lesson

Implementing Idempotency Keys

Create a mechanism to ensure that repeated requests with the same key do not trigger duplicate side-effects.

In this lesson, you will learn how to prevent accidental duplicate actions in your API by using idempotency keys.

The Problem: The "Double-Click" Effect

Imagine a user clicks a "Place Order" button on your website. Due to a momentary network hiccup, their browser sends the request twice. Without a safety mechanism, your server might charge the user's credit card twice or create two separate shipments. This is where Idempotency Keys come in.

An idempotency key is a unique identifier (usually a UUID) generated by the client. The server remembers this key; if a subsequent request arrives with the same key, the server knows it is a duplicate and returns the original result instead of processing the action again.

Implementing in Node.js

To implement this, you need a storage layer (like Redis or a database) to map the unique key to the outcome of the initial request.

Here is a conceptual approach:

async function handleOrder(req, res) {
  const idempotencyKey = req.headers['x-idempotency-key'];

  // 1. Check if we have already processed this key
  const cachedResponse = await redis.get(idempotencyKey);
  if (cachedResponse) {
    return res.status(200).json(JSON.parse(cachedResponse));
  }

  // 2. Process the actual business logic
  const result = await processPaymentAndOrder(req.body);

  // 3. Store the result for future identical requests
  await redis.set(idempotencyKey, JSON.stringify(result), 'EX', 86400);

  res.status(201).json(result);
}

Why this works

By checking the x-idempotency-key before performing any "side-effect" (like modifying a database or calling a payment gateway), you effectively turn a non-idempotent operation (like POST /orders) into an idempotent one.

Even if the network connection drops and the client retries the request five times, your server performs the expensive work only once. The subsequent four requests are intercepted by your cache, providing a consistent response without repeating the unintended side effects.

Key Takeaway: Idempotency keys allow you to safely retry network requests by using a unique client-generated identifier to ensure that processing occurs exactly once, regardless of how many times the request reaches your server.