← Back to Django, page 5

django-0100 · Hard senior

How do you implement optimistic locking in Django with a version field to prevent lost updates, and when do you choose it over select_for_update()?

Optimistic locking adds a version column. A writer reads the row with its version, and the update runs as UPDATE ... WHERE id = x AND version = v SET ..., version = version + 1. If zero rows change, someone else updated first, so the code raises a conflict (HTTP 409 or 412) or retries after reloading. It avoids holding locks while users edit, and fits forms and APIs where conflicts are rare; select_for_update() suits short, contended read-modify-write sections.

Full answer

The lost update problem: two staff members open the same student record, both edit, and the second save silently overwrites the first one's changes, because Django's save() writes all fields without checking whether the row changed.

Pessimistic locking (select_for_update()) holds a row lock inside a transaction; it works for short critical sections but cannot span a user's think time (a form open for minutes) and risks deadlocks.

Optimistic locking detects conflicts at write time:

python
updated = Student.objects.filter(pk=self.pk, version=self.version).update(
    name=self.name, version=F("version") + 1)
if not updated:
    raise StaleObjectError
self.version += 1

How to expose it:

  • Include version in the response (or use it as an ETag). The client sends it back in the update (If-Match: "7" or a body field).
  • On mismatch, answer 409 Conflict (or 412 Precondition Failed when using If-Match) with the current representation so the user can merge or retry.
  • In server-side flows, catch the conflict, reload the row, reapply the change and retry a bounded number of times (only when the change is a function of the new state, like incrementing a counter).

Details:

  • The version check and the update must be one statement; reading then comparing in Python reintroduces the race.
  • For counters, skip versions and use F("count") + 1, which is atomic.
  • Every write path must bump the version: save(), update(), bulk_update(). Centralise it in a model method or service. Libraries such as django-concurrency add VersionField and handle save() for you.
  • PostgreSQL's xmin or an updated_at timestamp can serve as the version, but timestamps risk precision ties.
  • Choose optimistic when conflicts are rare and edits are long-lived; choose select_for_update when conflicts are frequent or the work must be serialised (inventory, balances).
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import connection, models
from django.db.models import F


class StaleObjectError(Exception):
    pass


class Student(models.Model):
    name = models.CharField(max_length=40)
    grade = models.CharField(max_length=2)
    version = models.IntegerField(default=1)

    class Meta:
        app_label = "school"

    def save_if_current(self):
        updated = Student.objects.filter(pk=self.pk, version=self.version).update(
            name=self.name, grade=self.grade, version=F("version") + 1)
        if not updated:
            raise StaleObjectError(f"student {self.pk} changed since version {self.version}")
        self.version += 1


with connection.schema_editor() as editor:
    editor.create_model(Student)

Student.objects.create(name="Asha", grade="B")

teacher_a = Student.objects.get(pk=1)                     # both users open the same record
teacher_b = Student.objects.get(pk=1)

teacher_a.grade = "A"
teacher_a.save_if_current()
print("first save ok, version", teacher_a.version)

teacher_b.name = "Asha Rao"
try:
    teacher_b.save_if_current()
except StaleObjectError as exc:
    print("conflict:", exc)

# plain save() would have silently overwritten teacher_a's grade change:
naive = Student.objects.get(pk=1)
stale = Student(pk=1, name="Asha Rao", grade="B", version=1)
stale.save()
print("naive save wrote:", Student.objects.get(pk=1).grade, "(grade A was lost)")

def update_with_retry(pk, change, attempts=3):
    for _ in range(attempts):
        obj = Student.objects.get(pk=pk)
        change(obj)
        try:
            obj.save_if_current()
            return obj
        except StaleObjectError:
            continue
    raise StaleObjectError("too many conflicts")

fresh = update_with_retry(1, lambda s: setattr(s, "grade", "A+"))
print(fresh.grade, fresh.version)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): first save ok, version 2 conflict: student 1 changed since version 1 naive save wrote: B (grade A was lost) A+ 2

Key points

  • Lost update: the second save overwrites the first without noticing
  • Version check and update happen in one statement
  • Zero rows updated means conflict: answer 409 or 412 or retry
  • Every write path must increment the version
  • Optimistic for long edits and rare conflicts; select_for_update for hot rows

Common mistakes

  • Using plain save() on shared records and losing concurrent edits
  • Reading the version and comparing it in Python before updating
  • Forgetting to bump the version in update() or bulk paths
  • Retrying blindly when the change does not depend on the latest state
  • Using optimistic locking for hot rows with constant conflicts

Follow-ups

  • How would you expose the version through ETag and If-Match in DRF?
  • When would you use select_for_update instead?
  • How does a database-generated xmin differ from a version column?

Tips

  • Describe the lost update
  • Show the single-statement check
  • Pick between optimistic and pessimistic