← Back to Django, page 2

django-0038 · Hard senior

What does select_for_update() do in Django, and how do nowait and skip_locked change it?

select_for_update() adds SELECT ... FOR UPDATE so the selected rows are locked until the surrounding transaction ends; other transactions that try to lock or update them wait. It must run inside transaction.atomic(). nowait=True raises an error instead of waiting, skip_locked=True skips rows already locked (useful for job queues), and of=(...) limits which joined tables are locked. SQLite ignores it, so test on the real database.

Full answer

F() updates solve simple counters, but some logic must read, decide, and then write. For example, approving a hostel room request: read the room, check that beds are free, then assign. Two admins doing this at once could both see one free bed and both assign it.

Pessimistic locking stops that:

python
with transaction.atomic():
    room = Room.objects.select_for_update().get(pk=room_id)
    if room.free_beds == 0:
        raise NoBedsLeft
    room.free_beds -= 1
    room.save(update_fields=["free_beds"])

The second transaction blocks on the SELECT ... FOR UPDATE until the first commits, then reads the updated value.

Rules and options:

  • It must be inside atomic(). Evaluating it in autocommit mode raises TransactionManagementError on databases that support it.
  • nowait=True fails immediately with DatabaseError if the row is locked. Good for user-facing actions where waiting is worse than a "try again" message.
  • skip_locked=True returns only unlocked rows. This is how several workers can take jobs from one table without picking the same job.
  • of=("self",) locks only the main table when you also select_related other tables. On PostgreSQL, no_key=True takes a weaker lock that does not block inserts referencing the row.
  • Support varies: PostgreSQL and Oracle support all options; MySQL 8 supports nowait and skip_locked; SQLite ignores select_for_update entirely.

Costs: locks reduce concurrency and can deadlock if two transactions lock rows in different orders. Lock in a consistent order (for example by primary key), keep the transaction short, and never call slow external services while holding a lock.

The alternative is optimistic locking: a version column, update(..., version=F("version") + 1) filtered on the old version, and retry if zero rows changed. It suits low-contention data.

python
import os
import sys
import types

import django
from django.conf import settings

sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("PGDATABASE", "school"),
        "USER": os.environ.get("PGUSER", "postgres"),
        "PASSWORD": os.environ.get("PGPASSWORD", ""),
        "HOST": os.environ.get("PGHOST", "localhost"),
        "PORT": os.environ.get("PGPORT", "5432"),
    }},
)
django.setup()

import threading
import time

from django.db import connection, connections, models, transaction, DatabaseError
from django.db.transaction import TransactionManagementError


class Room(models.Model):
    name = models.CharField(max_length=10)
    free_beds = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_room")
with connection.schema_editor() as editor:
    editor.create_model(Room)
Room.objects.create(name="H-101", free_beds=1)

try:
    list(Room.objects.select_for_update())
except TransactionManagementError:
    print("select_for_update outside atomic() is an error")

results = []


def assign_bed(who, hold):
    try:
        with transaction.atomic():
            room = Room.objects.select_for_update().get(name="H-101")
            time.sleep(hold)
            if room.free_beds == 0:
                results.append(f"{who}: no beds left")
                return
            room.free_beds -= 1
            room.save(update_fields=["free_beds"])
            results.append(f"{who}: got the bed")
    finally:
        connections.close_all()


t1 = threading.Thread(target=assign_bed, args=("admin-1", 0.5))
t2 = threading.Thread(target=assign_bed, args=("admin-2", 0))
t1.start(); time.sleep(0.1); t2.start()
t1.join(); t2.join()
print(results)


def try_nowait():
    try:
        with transaction.atomic():
            Room.objects.select_for_update(nowait=True).get(name="H-101")
            results.append("nowait: locked it")
    except DatabaseError:
        results.append("nowait: row busy, failing fast")
    finally:
        connections.close_all()


results.clear()
with transaction.atomic():
    Room.objects.select_for_update().get(name="H-101")
    t = threading.Thread(target=try_nowait)
    t.start(); t.join()
    with connections["default"].cursor():
        pass
print(results)
print(Room.objects.get(name="H-101").free_beds)

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Ran on PostgreSQL 17 with two threads to show the second transaction waiting for the first. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): select_for_update outside atomic() is an error ['admin-1: got the bed', 'admin-2: no beds left'] ['nowait: row busy, failing fast'] 0

Key points

  • Locks selected rows until the transaction ends
  • Must run inside transaction.atomic()
  • nowait fails fast; skip_locked skips locked rows
  • SQLite ignores it; test on PostgreSQL or MySQL
  • Keep locked transactions short and lock in a consistent order

Common mistakes

  • Calling select_for_update() outside a transaction
  • Testing locking code on SQLite, where it silently does nothing
  • Holding the lock while calling a payment gateway or sending email
  • Locking rows in different orders in different code paths and causing deadlocks

Follow-ups

  • How would you build a job queue table that several workers read from?
  • Compare optimistic and pessimistic locking
  • What does of=('self',) change when using select_related?

Tips

  • Use a read-decide-write example where F() is not enough
  • Know nowait and skip_locked and give a use case for each
  • Mention database support differences, especially SQLite