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"
...
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:
- 5xx and network errors are retried. They're usually temporary.
- 4xx errors are not. They mean our request is wrong, and repeating it won't help. Some APIs also block an integration that keeps sending bad requests, which would stop every order, not just this one.
- 429 Too Many Requests is handled inside the API client, waiting a little longer each time.
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:
- locks the payment row with
select_for_update, - returns immediately if the payment is already marked as credited,
- creates a transaction ID and saves it before calling the other system, then sends that same ID with the top-up.
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:
- Lock the row that represents the money (
select_for_update). - Check whether this already happened, and if it did, return the same answer as last time.
- Give the action a stable ID before talking to another system, and reuse it on every retry.
- Retry only what can actually succeed on a second try.
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.
More writing
- Multi-tenant Django with PostgreSQL row-level security
- Streaming a teacher’s screen to a classroom of phones
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.