Backend Development 3 min read

Ensuring API Idempotency with Redis and Unique Serial Numbers

This article explains how to achieve API idempotency by having clients send a short‑lived unique serial number, storing it as a Redis key with SETNX and an expiration, and handling the Redis response to process or reject duplicate requests.

Lobster Programming
Lobster Programming
Lobster Programming
Ensuring API Idempotency with Redis and Unique Serial Numbers

There are many ways to implement API idempotency; this article introduces a solution that uses Redis together with a unique serial number.

When a client calls the server, it includes a short‑lived, globally unique serial number. Common forms of the serial number are a combination of timestamp, user ID and random number, or a combination of request source and a client‑generated unique identifier.

After the client generates the unique serial number and sends the request, the server constructs a Redis key from the serial number and attempts to add it using the SETNX command. The server then handles the result as follows:

If Redis returns 1, the key was added successfully, indicating the request is new; the business logic can be executed.

If Redis returns 0, the key already exists, meaning the request has been processed before; the server should not re‑execute the business logic and should return an error to the client.

The key stored in Redis should have an expiration time. This ensures that within the expiration window, duplicate requests carrying the same serial number are intercepted, while also preventing Redis memory from filling up and causing a crash.

Summary

The client generates a unique serial number; the server attempts to store it in Redis with SETNX . A successful addition allows business processing; a failure results in an error response.

The approach requires the client to provide the unique serial number and the server to set an expiration on the Redis entry. If Redis is unavailable, the method cannot be applied.

backendRedisunique identifierSETNXAPI idempotency
Lobster Programming
Written by

Lobster Programming

Sharing insights on technical analysis and exchange, making life better through technology.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.