Skip to the page

Django and DRF · mid

Transactions, race conditions, on_commit and signals

Two requests can read the same row and both write, so a read-modify-write needs a conditional UPDATE with F(), or a row lock. Work with side effects (email, a Celery task) must wait for the commit, and signals hide such side effects.

The notes

What you must know

  • Lost update: two requests read stock = 1, both pass the check and both save 0. Fix with one conditional update: Product.objects.filter(id=pid, stock__gt=0).update(stock=F("stock") - 1). 0 rows updated means sold out.
  • Wrap the update and the order creation in transaction.atomic() so both happen or neither does. A CheckConstraint (stock >= 0) is a last guard.
  • select_for_update() locks the row until the transaction ends and must be inside atomic(). Keep the transaction short, because other buyers wait on the lock.
  • After saving an F() assignment the attribute still holds the expression: call refresh_from_db(). save() writes every column; use save(update_fields=[...]) or update().
  • After a database error inside atomic(), PostgreSQL rejects more statements (TransactionManagementError). Wrap the risky insert in a nested atomic() (a savepoint) and catch the error outside it.
  • Queue tasks and send emails with transaction.on_commit(lambda: task.delay(id)) so a fast worker never reads a row that is not committed, and a rollback never leaves a message about a missing row. In tests use captureOnCommitCallbacks(execute=True).
  • Signals are synchronous and run inside the same transaction as save(). bulk_create(), QuerySet.update(), raw SQL and loaddata (raw=True) do not call the usual save signals. Connect receivers in AppConfig.ready() and use dispatch_uid to avoid duplicates.
  • Prefer an explicit service function such as register_user() that creates the user and wallet in one transaction and queues the email on commit. Do not decorate a whole view with atomic when it makes slow calls; ATOMIC_REQUESTS is simple but broad.

The red pen

Common traps: mistake → fix

  • Mistake: Check the stock, then save is safe because of the if

    Fix: two requests can pass the check together.

  • Mistake: Catching the database error heals the transaction

    Fix: it stays broken until the atomic block ends; use a savepoint.

  • Mistake: post_save fires for every way of creating rows

    Fix: bulk_create and update skip it.

  • Mistake: Queue the Celery task right after save, inside the transaction

    Fix: the worker may run before commit.

Easy to hard

Questions interviewers ask, easy to hard

  1. We sold 130 units of a phone with 100 in stock. What is wrong in this view?
  2. When do you use F() with update() and when select_for_update()?
  3. Why did someone get a welcome email but have no account?
  4. What does transaction.on_commit solve?
  5. Why did the imported users not get a wallet?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview