Implementing Idempotency in Django REST APIs: Prevent Duplicate Requests and Transactions

By Anurag Shankar Maurya • Published: 2026-11-11 • Category: Django Backend Development • 5 min read
Implementing Idempotency in Django REST APIs: Prevent Duplicate Requests and Transactions

Imagine a user clicks the payment button on your application. The request reaches your Django backend, and the payment is successfully processed.

However, the response takes a few seconds to arrive. The user assumes something went wrong and clicks the button again.

Your API receives the same request twice.

Without proper handling, your application might create two payment records, generate duplicate orders, or trigger multiple payment transactions.

This problem becomes even more common in distributed systems where network failures, retries, mobile connectivity issues, and API timeouts are normal.

The important thing to understand is that a request being sent multiple times does not necessarily mean the operation should be executed multiple times.

This is where idempotency becomes important.

In this article, we'll understand how idempotency works, why it matters for production APIs, and how to implement a reusable idempotency mechanism in Django REST Framework using PostgreSQL, unique constraints, and database transactions.

1. What Is Idempotency in REST APIs?



Idempotency is a property of an operation where executing the same operation multiple times produces the same intended result as executing it once.

Consider a simple example.

An API receives a request to create an order:

``http
POST /api/orders/
Content-Type: application/json

{
"product_id": 101,
"quantity": 2
}
`

The first request successfully creates an order.

But because of a network timeout, the client does not receive the response.

The client retries the request.

Without idempotency, the backend may create another order.

`text
Request 1
|
v
Create Order #101
|
v
Response Lost

Request 2 (Retry)
|
v
Create Order #102
|
v
Response Successful
`

Now the user has two orders instead of one.

With idempotency, the backend recognizes that the second request represents the same operation.

`text
Request 1
|
v
Create Order #101
|
v
Store Response

Request 2 (Retry)
|
v
Check Idempotency Key
|
v
Existing Operation Found
|
v
Return Previous Response
`

The second request does not create another order.

Instead, the API returns the original result.

Idempotency vs HTTP Methods



HTTP already defines idempotency for certain methods.

| HTTP Method | Idempotent? | Explanation |
|---|---|---|
| GET | Yes | Repeated requests should not change server state |
| HEAD | Yes | Same intended behavior as GET without the response body |
| PUT | Yes | Repeating the same replacement operation has the same intended effect |
| DELETE | Yes | Repeated deletion requests have the same intended final state |
| POST | Not inherently | Repeated requests can create multiple resources |
| PATCH | Not inherently | Depends on the operation being performed |

An important distinction: HTTP idempotency is about the intended effect on server state, not necessarily identical response codes.

For example, deleting a resource twice might return
204 the first time and 404 the second time while still being idempotent.

For POST operations involving payments, orders, registrations, or other business transactions, implementing application-level idempotency is particularly valuable.

2. Understanding Idempotency Keys



A common approach is to use an idempotency key.

An idempotency key is a unique identifier generated by the client for a particular operation.

The client sends it through an HTTP header:

`http
POST /api/orders/
Content-Type: application/json
Idempotency-Key: 7c9d4f21-9a31-4a90-8b23-123456789abc
`

The backend uses this key to determine whether the operation has already been processed.

For example:

`text
Idempotency-Key: abc-123
`

If the same key is received again, the backend checks whether a previous operation exists.
  • If no record exists, process the request.

  • If a completed record exists with the same request payload, return its stored response.

  • If the key exists with a different payload, reject the request.

  • If an operation is still being processed in an architecture that exposes in-progress records, return an appropriate conflict or retry response.


Why should we use a request hash?



Consider this situation:

The client sends:

`json
{
"product_id": 101,
"quantity": 2
}
`

With:

`http
Idempotency-Key: abc-123
`

The request succeeds.

Later, the client accidentally reuses the same key but sends:

`json
{
"product_id": 102,
"quantity": 5
}
`

Should the backend return the previous response?

No.

The key identifies one logical operation, not an unlimited collection of different requests.

Therefore, we should store a hash of the original request payload and compare it whenever the same key is reused.

3. Designing an Idempotency System in Django



Let's build a reusable implementation using Django REST Framework and PostgreSQL.

We'll create a database table that stores:
  • Idempotency key.

  • User associated with the request.

  • API endpoint or operation scope.

  • Request payload hash.

  • Response body.

  • HTTP response status.

  • Creation timestamp.


Step 1: Create the Idempotency Model



Create a model in your Django application.

`python
import uuid

from django.conf import settings
from django.db import models


class IdempotencyRecord(models.Model):

id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)

user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)

key = models.CharField(
max_length=255
)

endpoint = models.CharField(
max_length=255
)

request_hash = models.CharField(
max_length=64
)

response_body = models.JSONField(
null=True,
blank=True
)

response_status = models.PositiveSmallIntegerField(
null=True,
blank=True
)

created_at = models.DateTimeField(
auto_now_add=True
)

class Meta:
constraints = [
models.UniqueConstraint(
fields=["user", "endpoint", "key"],
name="unique_user_endpoint_idempotency_key"
)
]

indexes = [
models.Index(
fields=["created_at"],
name="idempotency_created_idx"
)
]

def __str__(self):
return f"{self.user_id} - {self.key}"
`

Let's understand the important fields.

key

Stores the idempotency key provided by the client.

user

Associates the operation with an authenticated user.

This prevents one user's idempotency key from interfering with another user's operation.

endpoint

Identifies the operation scope.

The same key can be used for different API operations without accidentally sharing responses.

request_hash

Stores a SHA-256 hash of the validated request data.

response_body and response_status

Store the original API response so that repeated requests can receive the same result.

The unique database constraint is particularly important.

It ensures that two concurrent requests cannot successfully create separate idempotency records for the same user, endpoint, and key.

Run migrations:

`bash
python manage.py makemigrations
python manage.py migrate
`

Step 2: Generate a Request Hash



We need to determine whether two requests contain the same logical payload.

Create a utility function:

`python
import hashlib
import json


def generate_request_hash(data):

serialized_data = json.dumps(
data,
sort_keys=True,
separators=(",", ":"),
default=str
)

return hashlib.sha256(
serialized_data.encode("utf-8")
).hexdigest()
`

Why use
sort_keys=True?

Because JSON object key ordering should not determine whether two otherwise equivalent payloads are considered different.

For example:

`json
{
"product_id": 101,
"quantity": 2
}
`

And:

`json
{
"quantity": 2,
"product_id": 101
}
`

These should generate the same hash.

In production, hash the serializer's validated and normalized data rather than blindly hashing raw request input.

This ensures that the hash represents the actual business operation being performed.

Step 3: Implement Idempotency Handling



Now we need to build the actual request-processing logic.

The following service uses a database transaction to ensure that the business operation and its stored response are committed together.

`python
from django.db import IntegrityError, transaction
from rest_framework.exceptions import APIException

from .models import IdempotencyRecord
from .utils import generate_request_hash


class IdempotencyConflict(APIException):
status_code = 409
default_detail = (
"Idempotency key was already used "
"with a different request."
)
default_code = "idempotency_conflict"


def execute_idempotent_request(
*,
user,
endpoint,
key,
request_data,
operation
):

if not key or len(key) > 255:
raise APIException("Invalid Idempotency-Key.")

request_hash = generate_request_hash(
request_data
)

with transaction.atomic():

try:
# Use a savepoint so a uniqueness violation
# does not break the outer transaction.
with transaction.atomic():

record = IdempotencyRecord.objects.create(
user=user,
endpoint=endpoint,
key=key,
request_hash=request_hash
)

except IntegrityError:

record = (
IdempotencyRecord.objects
.select_for_update()
.get(
user=user,
endpoint=endpoint,
key=key
)
)

if record.request_hash != request_hash:
raise IdempotencyConflict()

if record.response_status is None:
raise APIException(
"The operation has no completed response."
)

return (
record.response_body,
record.response_status,
True
)

# Execute the business operation.
response = operation()

record.response_body = response.data
record.response_status = response.status_code

record.save(
update_fields=[
"response_body",
"response_status"
]
)

return (
response.data,
response.status_code,
False
)
`

Let's understand how this works.

First request:

1. The API receives an idempotency key.
2. Django generates a request hash.
3. A new idempotency record is inserted.
4. The business operation is executed.
5. The response is stored.
6. Both the business changes and idempotency record are committed together.

Repeated request:

1. Django attempts to insert another record with the same unique key.
2. PostgreSQL rejects the duplicate.
3. Django retrieves the existing record.
4. It compares the request hashes.
5. If they match, the previously stored response is returned.

The important detail is that the record and business operation are inside the same database transaction.

This implementation is appropriate for relatively short, database-backed operations.

It also handles concurrent requests: a competing insert for the same unique key waits for the first transaction to finish. If the first transaction commits, the second request retrieves the completed record. If it rolls back, the second request can proceed.

Step 4: Integrate Idempotency With Django REST Framework



Let's use the service in a real API endpoint.

Suppose we have an order creation API.

`python
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated

from .services import execute_idempotent_request
from .serializers import OrderSerializer


class CreateOrderAPIView(APIView):

permission_classes = [IsAuthenticated]

def post(self, request):

idempotency_key = request.headers.get(
"Idempotency-Key"
)

if not idempotency_key:
return Response(
{
"error": "Idempotency-Key header is required."
},
status=status.HTTP_400_BAD_REQUEST
)

serializer = OrderSerializer(
data=request.data
)

serializer.is_valid(raise_exception=True)

def create_order():

order = serializer.save(
user=request.user
)

return Response(
{
"message": "Order created successfully.",
"order_id": order.id,
"status": order.status
},
status=status.HTTP_201_CREATED
)

response_data, response_status, replayed = (
execute_idempotent_request(
user=request.user,
endpoint="create-order",
key=idempotency_key,
request_data=serializer.validated_data,
operation=create_order
)
)

return Response(
response_data,
status=response_status,
headers={
"Idempotency-Replayed": (
"true" if replayed else "false"
)
}
)
`

Now the endpoint supports idempotent order creation.

Example request:

`http
POST /api/orders/
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
Idempotency-Key: order-12345

{
"product_id": 101,
"quantity": 2
}
`

First response:

`json
{
"message": "Order created successfully.",
"order_id": 501,
"status": "pending"
}
`

HTTP status:

`http
201 Created
`

If the same request is sent again with the same key and payload, the backend returns the original response rather than creating another order.

The response includes:

`http
Idempotency-Replayed: true
`

This is useful for debugging and client-side observability.

Important implementation considerations



The example above demonstrates the core mechanism, but a reusable production implementation should also consider:
  • Validate and limit the key's length and format.

  • Define key expiration and cleanup policies.

  • Scope keys by authenticated user and operation.

  • Store only JSON-serializable response bodies.

  • Preserve relevant response headers if clients depend on them.

  • Ensure the serializer does not perform business-side effects before idempotency checking.

  • Decide which errors should be stored and replayed.

  • Handle database failures and unexpected exceptions consistently.


Also, avoid wrapping long-running external API calls inside the database transaction. We'll look at this problem shortly.

4. Handling Concurrent Requests and External Side Effects



This is where many basic idempotency implementations fail.

Checking whether an idempotency key exists is not enough.

Consider two requests arriving at almost exactly the same time.

`text
Request A Request B
| |
v v
Check key Check key
| |
v v
Not found Not found
| |
v v
Create order Create order
| |
v v
Two orders created
`

This is a race condition.

Both requests check the database before either one inserts a record.

A. Use Database-Level Uniqueness



The most reliable solution is to enforce uniqueness at the database level.

`python
models.UniqueConstraint(
fields=["user", "endpoint", "key"],
name="unique_user_endpoint_idempotency_key"
)
`

Application-level checks alone are insufficient because two requests can execute simultaneously.

PostgreSQL's unique constraint ensures that only one transaction can successfully claim the same key within the defined scope.

The implementation in the previous section uses this constraint and handles the resulting uniqueness conflict.

B. Why Database Transactions Matter



Consider this sequence:

`text
BEGIN TRANSACTION

Create Idempotency Record

Create Order

Save API Response

COMMIT
`

All three operations are committed together.

If order creation fails, the transaction rolls back and the idempotency record is also removed.

This prevents a situation where the backend remembers a successful idempotency operation even though the order was never created.

However, this approach has an important limitation: the entire operation must remain relatively short and database-focused.

C. Handling External Payment Gateways



Now consider a more complicated operation.

A user makes a payment using an external payment gateway.

The workflow looks like this:

`text
Django API
|
v
Create Payment Record
|
v
Call Payment Gateway
|
v
Gateway Processes Payment
|
v
Save Payment Status
|
v
Return Response
`

What happens if the gateway successfully charges the customer but Django crashes before saving the payment status?

The database transaction may roll back, but the external payment cannot automatically be rolled back.

This is an important distributed systems problem.

A database transaction cannot guarantee atomicity across an independent payment gateway.

A better design is to use a combination of:

1. Idempotency at the API level.
2. Provider-supported idempotency keys.
3. A persistent payment operation record.
4. Background processing.
5. An outbox pattern or reliable job dispatch.
6. Webhook reconciliation.

For example:

`python
class Payment(models.Model):

class Status(models.TextChoices):
PENDING = "pending", "Pending"
PROCESSING = "processing", "Processing"
SUCCESS = "success", "Success"
FAILED = "failed", "Failed"

user = models.ForeignKey(
"auth.User",
on_delete=models.CASCADE
)

amount = models.DecimalField(
max_digits=10,
decimal_places=2
)

status = models.CharField(
max_length=20,
choices=Status.choices,
default=Status.PENDING
)

provider_reference = models.CharField(
max_length=255,
blank=True
)

created_at = models.DateTimeField(
auto_now_add=True
)
`

The payment operation should be created first, with its own stable identifier.

Then a background worker processes it using the same provider idempotency key on every retry.

For example:

`python
def process_payment(payment_id):

payment = Payment.objects.get(
id=payment_id
)

if payment.status == Payment.Status.SUCCESS:
return

result = payment_gateway.charge(
amount=payment.amount,
idempotency_key=str(payment.id)
)

# Persist the result using an appropriately
# protected transaction and state transition.
`

This is illustrative: the gateway must actually support idempotency, and the implementation must also handle concurrent workers, unknown gateway outcomes, and webhook reconciliation.

The key idea is that retries must not result in multiple charges.

D. Use Transactional Outbox for Reliable Background Processing



Another common problem occurs when Django saves an order but fails to dispatch its background task.

For example:

`python
order.save()

process_order.delay(order.id)
`

If the database commit succeeds but task dispatch fails, the order exists but processing never starts.

A transactional outbox solves this by storing the event in the same database transaction as the business operation.

`python
class OutboxEvent(models.Model):

event_id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)

event_type = models.CharField(
max_length=100
)

payload = models.JSONField()

processed = models.BooleanField(
default=False
)

created_at = models.DateTimeField(
auto_now_add=True
)
`

Save the order and outbox event together:

`python
from django.db import transaction


with transaction.atomic():

order = Order.objects.create(
user=request.user
)

OutboxEvent.objects.create(
event_type="order.created",
payload={
"order_id": order.id
}
)
`

A separate worker polls unprocessed events and dispatches them.

The worker must mark events as processed safely and handle retries.

Remember that outbox delivery is generally at-least-once, not automatically exactly-once. Consumers should also be idempotent.

This makes the overall system more resilient to failures.

5. Production Best Practices and Common Questions



Implementing idempotency is not just about storing a unique key.

You also need to consider retention, monitoring, error handling, and operational behavior.

A. Define an Idempotency Key Expiration Policy



Idempotency records should not necessarily remain in the database forever.

For example, you might retain keys for 24 hours or 7 days, depending on the business operation and client retry behavior.

A scheduled cleanup command can remove expired records.

`python
from datetime import timedelta

from django.utils import timezone

from .models import IdempotencyRecord


def cleanup_idempotency_records():

expiration_time = timezone.now() - timedelta(
days=7
)

IdempotencyRecord.objects.filter(
created_at__lt=expiration_time
).delete()
``

Do not choose the expiration period arbitrarily.

For payment and financial operations, permanent business-level uniqueness constraints and provider reconciliation may be necessary even after the API idempotency record expires.

B. Return Consistent Error Responses



Your API should communicate idempotency conflicts clearly.

For example,