November 2026 · 7 min read · Django, Celery, payments

Idempotent payment callbacks in Django

An ordering app moves money between three systems: the customer's balance in our database, a card payment provider, and the point-of-sale system where staff see the order. Any of them can fail, time out or send the same message twice. Here are four places where a customer could be charged twice, the small Django patterns that stop it, and one database rule that backs them up.

1Two orders spending the same balance

A customer has some cashback left and taps "order" on two phones at once. Both requests read the balance, both see enough money, both spend it. A classic race.

The order view runs in one transaction and starts by locking the customer's row:

@transaction.atomic
def post(self, request):
    customer = (
        Customer.objects.select_for_update()
        .get(pk=request.customer.pk)
    )
    # ... validate items, spend balance, create the order

The second request waits at that line until the first one commits, then reads the balance that's really left. It's one line, but it's the difference between "usually fine" and correct.

2The payment callback arrives twice

When a card payment succeeds, the provider calls our server. Providers retry callbacks when they don't get an answer fast enough, so the same "paid" message can arrive more than once, sometimes at the same moment.

The handler checks the signature, then locks the payment row and looks at its status before changing anything:

with transaction.atomic():
    payment = Payment.objects.select_for_update().get(pk=payment_pk)
    if payment.status in ("paid", "credited"):
        return Response({"success": True})   # replay: do nothing
    payment.status = "paid"
    ...
The detail that matters: a replay must still answer "success". With many providers, a failed answer means "reverse the payment". Answering an honest duplicate with an error would refund a customer who really paid. Idempotent here means "same answer, no second effect", not "reject the duplicate".

For the signature itself, compare with hmac.compare_digest rather than ==. It takes the same time no matter which character is wrong, so the comparison doesn't leak anything.

3Sending the order to the POS, with retries

After payment, a Celery task sends the order to the POS. Networks fail, so the task retries a few times, a minute apart. But a retry after a timeout is dangerous. The first attempt may have arrived after all, and a naive retry creates a second order. Staff make it twice.

The fix is to choose the order's external ID ourselves, and make it the same on every attempt:

# Same order -> same id, on the first try and on every retry.
key = f"order-{order.pk}"
external_id = str(uuid.uuid5(ORDER_NAMESPACE, key))

A random uuid4() would give each attempt a new identity. uuid5 is calculated from the order's primary key, so every retry describes the same order, and the other system can tell it already has it.

Not every error deserves a retry, either:

If the POS refuses the order for good, the task also releases the balance it put on hold for that order, so no money stays stuck.

4Refunds that can't happen twice

Sometimes the customer has paid and the order still can't be made. A card refund takes days, which is too slow for a small order, so the money goes back to the customer's balance right away.

That's another place to pay twice. An admin double-clicks "resolve", or two staff members press it at once. The refund function:

Saving the ID first is the important part. If the call times out and someone tries again, the second attempt sends the same ID. The other system can recognise the repeat, instead of receiving what looks like a new top-up.

One more small thing: when the external call fails, the error is saved to the payment row first and raised after the transaction commits. Raising inside the transaction would roll back the error message too, and the next person would have no idea what went wrong.

5A backstop in the database

Row locks protect the normal path, but they only work where the code remembers to take them. A new admin action, a management command or a script written in a hurry can skip the lock. So the last line of defence belongs in the database: the provider's transaction ID is unique.

class Payment(models.Model):
    provider_txn_id = models.CharField(max_length=64, null=True)
    ...
    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["provider_txn_id"], name="unique_provider_txn"
            ),
        ]

If anything tries to record the same provider payment twice, PostgreSQL refuses the second row with an IntegrityError. Catch it, log it, and answer the same way as a replay. The null=True matters: payments that haven't been confirmed yet have no transaction ID, and NULLs don't clash with each other in a unique index.

The pattern

Every case above has the same shape:

And under all of it, a unique constraint, so the database refuses what the code misses. None of it is clever. It's a few habits, applied everywhere money moves.

The code: Every pattern above as working code, with tests that fire the same callback from 8 threads at once: github.com/Aysuliw/django-payment-callbacks.

More writing

I’m Aysulu, a backend developer (Python, Django) in Nukus, Uzbekistan, open to remote work. If your team deals with this kind of thing, I’d like to hear about it: aysulu.mambetnazarova@gmail.com. Or see my projects.