Chapter 33 · Transactions, concurrency, and the last available seatCHAPTER 33
Complete six-part pre-release for review. Adds one migration (Event.version) and no package. Race tests run on PostgreSQL and are skipped on SQLite. The waitlist uses the same lock in Chapter 46; lock waits are measured under load in Chapter 66.
Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones
CHAPTER THIRTY-THREE
Transactions, concurrency, and the last available seat
Stage 4: Accounts and first release (Chapters 24 to 34)
Prerequisites: Chapters 15 to 32, including the Chapter 32 project on PostgreSQL 18 with its 343 passing tests, Event.register() and the one-active-place rule from Chapter 31, the edit page and capacity floor of Chapter 25, the event states of Chapter 26, and the test template database of Chapter 32
What you’ll build: A registration that gives the last place to exactly one member however many ask at once, proved by a test that makes the race happen every time; publishing, cancelling, and editing that read the event as it is now; a clear “busy” answer instead of an endless wait; an edit page that refuses to overwrite changes it has not seen; and clearer “full” and “closed” states
Why This Matters
Sam’s Django clinic has one place left. Sai and Raj both have the event page open, and both press Register in the same moment. Chapter 31’s register() counts the places taken, sees one left, and inserts a place, all inside a transaction. Each request does exactly that, and each sees one left, because neither has inserted yet when the other counts. The clinic now has one person more than its room. Chapter 31 said plainly that SQLite could not show this; Chapter 32 moved Otahque to PostgreSQL so that this chapter can.
The same thing happens to Sam’s edits. Raj organizes the Delhi event with Sam. Sam opens the edit page to fix the room name; while he types, Raj saves a higher capacity. Sam presses Save, and his form, which still holds the old capacity, puts it back. Chapter 25 recorded this as “last save wins”, a known limit. Nobody was told anything; Raj’s change simply vanished.
Both problems come from the same fact: between reading something and acting on it, someone else may change it. This chapter fixes both, and, as important, proves the fix with a test that fails every time without it.
By the end of the chapter, you will be able to:
explain what a transaction guarantees and what it does not, and what READ COMMITTED lets two transactions see;
write a test that makes a race happen every time, with threads and a meeting point, and know why TestCase cannot;
lock a row with select_for_update() and run every check on the locked row, not on an old copy;
put a time limit on waiting for a lock and turn only that error into a friendly “busy”;
refuse a save from a page that is out of date with a version number, and choose between locking and versions.
Out of scope: the waitlist, which promotes members inside the same lock (Chapter 46), measuring lock waits under load (Chapter 66), and version numbers in the API as ETags (Chapters 47 and 48).
Chapter 31 put register() inside transaction.atomic(). A transaction promises that its changes are kept together or undone together: if the insert fails, nothing of the request remains. It does not promise that the data it read stays true. Two transactions can run at the same moment, and each sees the world as it was when its statement started.
PostgreSQL’s default isolation level, the rule for what one transaction sees of another, is READ COMMITTED: each statement sees every change that was committed before it began, and nothing that is not yet committed. So when Sai’s request counts, it sees no place for Raj, whose insert has not happened; when Raj’s request counts, it sees none for Sai, whose insert has happened but is not committed yet. Both counts are correct for the moment they were made. The decision built on them is wrong. Figure 33.1 shows the two requests side by side.
Figure 33.1 — Two requests for the last place, without and with the row lock.
This interleaving is called a race: the result depends on which request happens to run first, and on timing nobody controls. Races are rare on a quiet site and certain on a busy one, which is the worst kind of bug: it passes every manual check.
Locking a row
New Concept: a row lock with select_for_update()
What problem exists? Two requests must not both decide on “one place left”. The second must decide after the first has finished.
What did people do before? Counters in a separate table, locks on the whole table, or “hope it is rare”. Each either slowed everything or failed under load.
What is it?Event.objects.select_for_update().get(pk=...) reads the event row and locks it until the transaction ends. Any other transaction that asks to lock or change the same row waits. Plain reads are not blocked, and other events are not affected.
Why use it? It makes requests for one event take turns, exactly where the decision is made, and nowhere else. The count stays where it is: the real rows.
Now let’s use it. Step 4 adds Event.locked() and calls it first in register().
Two details decide whether the lock helps. First, it only works inside a transaction: outside one, Django refuses with TransactionManagementError. Second, the decision must be made on the row the lock returned. When the waiting request finally gets the lock, PostgreSQL hands it the newest committed version of the row. A copy of the event that a view loaded a moment earlier may already be out of date: cancelled, edited, or full. So every check runs on the locked row.
Under the Hood: what the waiting request sees
When Raj’s request asks to lock a row that Sai’s transaction holds, PostgreSQL makes it wait. As soon as Sai’s transaction commits, PostgreSQL gives Raj’s request the row as it is now, not as it was when Raj’s statement started, and the lock passes to him. His next statement, the count, is a new statement, so under READ COMMITTED it sees Sai’s committed place. That is why the order “lock, then count, then insert” works: the lock decides who goes first, and READ COMMITTED makes sure the second sees what the first did.
A waiting request should not wait forever. PostgreSQL’s lock_timeout setting ends a wait after a limit, and SET LOCAL sets it for one transaction only. When the limit is reached, PostgreSQL stops the statement with the error code 55P03, “lock not available”. Otahque turns exactly that error into “Otahque is busy. Please try again.” and changes nothing. Any other database error is still raised, as Chapter 31 did with IntegrityError.
Testing a race
A race test needs two requests running at once, on two connections, each seeing what the other has committed. Django’s TestCase cannot do that: it runs each test inside one transaction that is never committed, so another connection sees nothing of the test’s rows. `TransactionTestCase` commits for real and empties the tables after each test instead. Each thread, a second line of execution inside the same Python program, gets its own database connection, as a second request would.
Starting two threads together is not enough. They might run one after the other, and the test would pass by luck. A barrier (threading.Barrier) is a meeting point: each thread waits there until the other arrives. The chapter’s test puts the meeting point right after the count, so both requests have counted before either inserts. Without a lock, the race happens every time. With the lock, the second request is still waiting for the row and never reaches the meeting point, so the first one’s wait times out after two seconds and it carries on. Figure 33.3, in Step 3, shows both.
A version for edits
A lock lasts one transaction, a fraction of a second. Sam’s edit page stays open for minutes, and nothing can be locked for that long. The edit needs a different tool: a version number on the event that grows by one with each save. The page sends the version it was opened at. The save compares it with the event’s version now; if they differ, someone saved in between, and Otahque refuses instead of overwriting. This is called optimistic locking, because it lets everyone work and checks at the end; the row lock is pessimistic, because it makes others wait in case of a conflict. Figure 33.2 places the two side by side.
Figure 33.2 — A lock for seconds, a version for minutes.
In practice: a busy evening
Situation. Sam announces the clinic in a chat with three hundred members, and forty of them press Register within the first minute.
Application. Each request locks the clinic’s row for the few milliseconds of its check and insert, so they take turns; requests for other events do not wait at all. The first twenty-five get places and the rest see “This event is full.”
Consideration. Turns cost time. Chapter 66 measures how long requests wait under load and decides whether this lock is still the right tool.
Try it yourself
Que. 1 With the lock in place, Sai and Raj press Register at the same moment for the last place at Sam’s clinic, and Raj’s request reaches the lock first. Who gets the place, and what does the other see?
Flip to check your answerFold answer back
Answer. Raj. Sai’s request waits for the row, and when Raj’s transaction commits, Sai’s request gets the row, counts one place taken of one, and is told “This event is full.” The order of arrival at the lock decides, not the order of the clicks.
Que. 2 Why would a race test that simply starts two threads at the same moment sometimes pass even without the lock?
Flip to check your answerFold answer back
Answer. Because nothing makes the two requests overlap. One thread may count and insert before the other starts counting, and then the second correctly sees no place left. A meeting point after the count forces both to count before either inserts.
Start from Chapter 32, in the folder containing manage.py, with Otahque on PostgreSQL 18, 343 passing tests, every migration applied, and the work committed. No package is added. The changed files are events/models.py, events/views.py, events/forms.py, events/admin.py, events/templates/events/edit.html, events/tests.py, and registrations/tests.py, plus one migration, two templates, the stylesheet source, and three design notes. The visible result: a full event stays full however many people press Register, a stale edit is refused with a message, and the “full” and “closed” states are easier to read. The chapter’s checks ran in Windows PowerShell 5.1 and Git Bash, against PostgreSQL 18.3.
The Custom Way
Before Django does it for you, see a row lock with your own eyes, in two psql windows. Open two terminals and, in each, sign in as Otahque’s role:
Terminal
psql -h localhost -U otahque -d otahque
In the first window, start a transaction and lock the first event’s row:
psql, window 1
BEGIN;
SELECT id, title FROM events_event WHERE id = 1 FOR UPDATE;
Output
BEGIN
id | title
----+---------------
1 | Python meetup
(1 row)
In the second window, type the same two lines. psql answers BEGIN and then nothing more: the SELECT is waiting for the row. Go back to the first window and type COMMIT;. At once the second window shows the row:
Output
BEGIN
id | title
----+---------------
1 | Python meetup
(1 row)
Type COMMIT; in the second window too. Now try a time limit. Lock the row again in the first window, then run this in the second:
psql, window 2
BEGIN;
SET LOCAL lock_timeout = '2s';
SELECT id, title FROM events_event WHERE id = 1 FOR UPDATE;
ROLLBACK;
Output
BEGIN
SET
ERROR: canceling statement due to lock timeout
CONTEXT: while locking tuple (0,1) in relation
"events_event"
ROLLBACK
After two seconds the second window gives up with an error, and ROLLBACK; ends its failed transaction. Type COMMIT; in the first window and \q in both. Every part of the Django Way is here already: FOR UPDATE locks, the other session waits, and lock_timeout ends the wait. Django adds the transaction around the request, the query, and a test that proves it.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 343 test(s).
Creating test database for alias 'default'...
...
Ran 343 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Move to PostgreSQL
Step 2: Picture the race
Before code, read Figure 33.1 again and name the two moments in register(): the count (places_taken(), inside registration_problems()) and the insert (registrations.create()). The race lives between them. Everything this chapter changes either closes that gap or makes it visible in a test.
Step 3: A test that makes the race happen
Tests first, and this test must fail every time without the fix. At the top of registrations/tests.py, the imports change in three places:
registrations/tests.py (replace the first two imports)
import threading
from datetime import UTC, datetime, timedelta
from unittest import mock
registrations/tests.py (replace the TestCase import)
from django.apps import apps
from django.contrib.auth.management import create_permissions
from django.contrib.auth.models import Permission
from django.test import (
TestCase, TransactionTestCase, skipUnlessDBFeature,
)
registrations/tests.py (replace the events.models import)
from events.models import (
ORGANIZERS, Event, OrganizerAssignment,
)
from events.tests import as_sent
Then three helpers at the end of the file. at_once() runs actions in threads, each with its own connection, closed at the end. meet_after_counting() patches Event.places_taken so that each request waits for the other right after counting. organizer() makes Sam an organizer without any group, because TransactionTestCase empties every table after each test, including the groups Chapter 30’s migration made. It also makes the permissions first, with create_permissions() as Chapter 30’s migration did, in case a test before it left that table empty; from Chapter 41, a test that restores its own data can:
registrations/tests.py (add at the end)
def at_once(*actions):
"""Run each action in its own thread; return outcomes.
An outcome is what the action returned, or the codes
of the ValidationError it raised. Each thread has its
own database connection, closed at the end, as two
requests would.
"""
outcomes = [None] * len(actions)
def run(n, action):
try:
outcomes[n] = action()
except ValidationError as error:
outcomes[n] = [e.code for e in error.error_list]
finally:
connection.close()
threads = [threading.Thread(target=run, args=(n, act))
for n, act in enumerate(actions)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return outcomes
def meet_after_counting(timeout=2):
"""Make each request wait, after counting, for the other.
Without a lock both count before either inserts, so
the race happens every time. With the lock the other
request is still waiting for the event row, so the
meeting times out and the requests take turns.
"""
barrier = threading.Barrier(2, timeout=timeout)
count = Event.places_taken
def counted(event):
taken = count(event)
try:
barrier.wait()
except threading.BrokenBarrierError:
pass
return taken
return mock.patch.object(Event, 'places_taken', counted)
def organizer(event):
"""Create Sam, who may edit event, without any group.
TransactionTestCase empties every table after a test,
including the groups Chapter 30's migration made, so
the permission is given to Sam directly. It is made
first if missing: a test that restores its own data
(Chapter 41) can leave the permission table empty for
the test after it.
"""
create_permissions(apps.get_app_config('events'),
verbosity=0)
sam = User.objects.create_user('sam@example.org',
display_name='Sam')
sam.user_permissions.add(
Permission.objects.get(codename='change_event')
)
OrganizerAssignment.objects.create(event=event,
member=sam)
return sam
Now the test. skipUnlessDBFeature('has_select_for_update') skips it on a database that cannot lock rows, such as SQLite when DB_ENGINE is empty:
registrations/tests.py (add at the end)
@skipUnlessDBFeature('has_select_for_update')
class RaceTests(TransactionTestCase):
"""Requests for one event at the same moment.
PostgreSQL only. Each test commits its rows, so other
threads see them, and the tables are emptied after it.
"""
def setUp(self):
self.event = soon(capacity=1)
self.now = timezone.now()
def register(self, member):
"""Return an action that registers, as a request does."""
def action():
event = Event.objects.get(pk=self.event.pk)
event.register(member, self.now)
return 'place'
return action
def test_the_last_place_goes_to_one_member(self):
sai = verified('sai@example.org')
raj = verified('raj@example.org')
with meet_after_counting():
outcomes = at_once(self.register(sai),
self.register(raj))
self.assertCountEqual(outcomes, ['place', ['full']])
self.assertEqual(self.event.places_taken(), 1)
Figure 33.3 — Where the test’s meeting point sits, and what it does with and without the lock.
Run only these tests while you work on them:
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
AssertionError: Element counts were not equal:
Ran 1 test in ...s
FAILED (failures=1)
The assertion names both outcomes:
Output
AssertionError: Element counts were not equal:
First has 2, Second has 1: 'place'
First has 0, Second has 1: ['full']
Two places for a capacity of one: the race, on demand. The test emptied its tables afterwards, so your own data is untouched.
Common Error: the race test passes, or cannot see its own event
Written as a TestCase, the same test either fails with Event.DoesNotExist inside a thread, because the thread’s connection cannot see rows that were never committed, or, if both calls run in one thread, passes every time. Neither proves anything. Race tests use TransactionTestCase, and one connection per thread.
Step 4: Lock the event row
In events/models.py, add a method above register() and replace register() with this version:
events/models.py (replace register())
def locked(self):
"""Return this event's row, locked until commit.
Another request that asks for the row waits until
this transaction ends. Call it inside atomic().
"""
return Event.objects.select_for_update().get(
pk=self.pk
)
def register(self, member, now):
"""Give member a place, or raise ValidationError.
The event row is locked first, so requests for it
take turns, and every check reads the locked row,
not this copy, which may be out of date. The unique
rule is still the backstop for the same member.
"""
with transaction.atomic():
event = self.locked()
problems = event.registration_problems(member,
now)
if problems:
raise refusal(problems)
try:
with transaction.atomic():
return event.registrations.create(
member=member, registered_at=now
)
except IntegrityError:
# Only the one-active-place rule means a
# repeat; any other failure is re-raised.
if event.place_of(member) is None:
raise
raise refusal(['already_registered'])
Two changes matter. self.locked() asks for the row and its lock, so a second request for the same event waits here. And every check after it reads event, the row the lock returned, not self, the copy the view loaded: the problems, the count, the insert, and the repeat check. Run the test again:
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
It passes, and takes about two seconds longer: that is the meeting point timing out while the second request waits for the lock, exactly as Figure 33.3 shows.
Common Error: select_for_update cannot be used outside of a transaction
Called in autocommit, outside transaction.atomic(), select_for_update() raises TransactionManagementError, because a lock would end the moment the query did. locked() is only called inside atomic(). Inside a TestCase the error does not appear, because the whole test is one transaction: one more reason to test locks with TransactionTestCase.
Step 5: The same member twice
Chapter 31’s double click, now with two real requests. Add this method to RaceTests, after the first test:
uv run python manage.py test registrations -k RaceTests
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
It passes without any new code. With five places free, the lock would not even be needed: the one-active-place rule from Chapter 21 and the inner atomic() from Chapter 31 refuse the second insert, and register() recognizes the repeat. This is the first time that backstop has been proved under real concurrency.
Step 6: A time limit, and “busy”
A request that waits for a lock should not wait for ever. The test holds the row in one thread, the way a slow request would, and expects the other to be told Otahque is busy. Add it to RaceTests:
uv run python manage.py test registrations -k RaceTests
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: 'place' != ['busy']
Ran 3 tests in ...s
FAILED (failures=1)
Without a limit, the request waited until the holder gave up after five seconds, and then got a place. In events/models.py, the imports grow:
events/models.py (replace the django.db import)
from django.db import (
IntegrityError, OperationalError, connection, models,
transaction,
)
The new reason and the limit go at the end of REASONS:
events/models.py (the end of REASONS, and after it)
'phone_missing': 'This event asks for your phone '
'number.',
'busy': 'Otahque is busy. Please try again.',
}
# How long a request waits for an event row that another
# request has locked, before Otahque says it is busy.
LOCK_TIMEOUT = '3s'
# PostgreSQL's error code for "lock not available".
LOCK_NOT_AVAILABLE = '55P03'
And locked() gets its final form:
events/models.py (replace locked())
def locked(self):
"""Return this event's row, locked until commit.
Another request that asks for the row waits until
this transaction ends, for at most LOCK_TIMEOUT;
then it is told Otahque is busy. Call it inside
atomic(). SQLite ignores both.
"""
if connection.vendor == 'postgresql':
with connection.cursor() as cursor:
cursor.execute('SET LOCAL lock_timeout = %s',
[LOCK_TIMEOUT])
try:
return Event.objects.select_for_update().get(
pk=self.pk
)
except OperationalError as error:
# Only the lock timeout means busy; any other
# database error is raised again.
code = getattr(error.__cause__, 'sqlstate', None)
if code != LOCK_NOT_AVAILABLE:
raise
raise refusal(['busy']) from None
SET LOCAL limits the wait for this transaction only. If the wait runs out, psycopg raises an error whose code is 55P03, which Django passes on as an OperationalError with psycopg’s error as its cause. Only that code becomes “busy”; a lost connection, for example, is still an error. The test patches LOCK_TIMEOUT to a tenth of a second so that it does not wait three:
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Step 7: Publish and cancel read the event again
The view that cancels an event loaded its copy at the start of the request. If Raj cancelled the event a moment before Sam pressed Publish on a stale page, or two organizers cancel at once, the copy is out of date. Tests at the end of registrations/tests.py:
registrations/tests.py (add at the end)
class StaleCopyTests(TestCase):
"""Actions read the event again, not the page's copy."""
def setUp(self):
self.event = soon()
# The copy a view loaded before someone else acted.
self.copy = Event.objects.get(pk=self.event.pk)
def test_register_sees_a_cancel_made_since(self):
Event.objects.get(pk=self.event.pk).cancel()
with self.assertRaises(ValidationError) as caught:
self.copy.register(verified('sai@example.org'),
timezone.now())
self.assertEqual(
[e.code for e in caught.exception.error_list],
['not_published'],
)
def test_cancel_sees_a_cancel_made_since(self):
Event.objects.get(pk=self.event.pk).cancel()
with self.assertRaises(ValidationError):
self.copy.cancel()
def test_publish_sees_a_publish_made_since(self):
Event.objects.filter(pk=self.event.pk).update(
status=Event.Status.DRAFT, description='Notes.'
)
organizer(self.event)
draft = Event.objects.get(pk=self.event.pk)
Event.objects.get(pk=self.event.pk).publish()
with self.assertRaises(ValidationError):
draft.publish()
Terminal
uv run python manage.py test registrations -k StaleCopy
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: ValidationError not raised
Ran 3 tests in ...s
FAILED (failures=2)
The register test already passes, because Step 4 made register() read the locked row. Publish and cancel still trust their copy. In events/models.py, replace both:
events/models.py (replace publish() and cancel())
def publish(self):
"""Draft to published, or ValidationError.
Reads the status under the lock, so a copy loaded
earlier cannot publish twice or publish a change.
"""
with transaction.atomic():
event = self.locked()
if event.status != self.Status.DRAFT:
raise ValidationError(
'Only a draft can be published.'
)
problems = event.readiness_problems()
if problems:
raise ValidationError(problems)
event.status = self.Status.PUBLISHED
event.save(update_fields=['status'])
self.status = event.status
def cancel(self):
"""Cancel if published, or raise ValidationError.
Reads the status under the lock, like publish().
"""
with transaction.atomic():
event = self.locked()
if event.status != self.Status.PUBLISHED:
raise ValidationError(
'Only a published event can be '
'cancelled.'
)
event.status = self.Status.CANCELLED
event.save(update_fields=['status'])
self.status = event.status
Each locks, checks the locked row, saves it, and then updates self so the caller sees the new status.
Terminal
uv run python manage.py test registrations -k StaleCopy
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Step 8: The capacity floor under the lock
Chapter 25’s capacity floor refuses a capacity below the places taken. It counts when the form is checked, and the save happens afterwards, so a registration in between slips past it. The test lowers the capacity from two to one while Sai’s registration is in flight, with Raj already holding a place. It uses the same meeting point: the capacity floor counts the places too, so the registration and the edit each count and then wait for each other. Add it to RaceTests, after the busy test:
registrations/tests.py (in RaceTests, at the end)
def test_capacity_edit_counts_a_place_being_made(self):
Event.objects.filter(pk=self.event.pk).update(
capacity=2
)
verified('raj@example.org').registrations.create(
event=self.event, registered_at=self.now
)
sam = organizer(self.event)
sai = verified('sai@example.org')
def lower_capacity():
client = self.client_class()
client.force_login(sam)
event = Event.objects.get(pk=self.event.pk)
return client.post(
reverse('events:edit', args=[event.pk]),
as_sent(event, capacity='1'),
).status_code
# The edit's capacity floor counts too, so it meets
# the registration right after both have counted.
with meet_after_counting():
at_once(self.register(sai), lower_capacity)
self.event.refresh_from_db()
# Either order is fair: Sai's place, then the edit
# refused; or the edit, then "full". Never both.
self.assertLessEqual(self.event.places_taken(),
self.event.capacity)
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
AssertionError: 2 not less than or equal to 1
Ran 4 tests in ...s
FAILED (failures=1)
The form saw one place taken and allowed a capacity of one; then Sai’s place arrived, and the event ended with two places for a capacity of one. No database rule catches it, because a count is not a column. The edit must lock the row before it checks the form. In events/views.py, replace event_edit with a helper and the view:
events/views.py (replace event_edit)
def save_edit(request, event):
"""Save the edit form under the event's lock.
Return None once saved, or the form to show again.
The lock makes the capacity floor count the places
taken now, not when the page was opened.
"""
with transaction.atomic():
event = event.locked()
before = model_to_dict(event)
form = EventForm(request.POST, instance=event)
if not form.is_valid():
return form
form.save()
after = model_to_dict(event)
changed = [name for name in form.fields
if before[name] != after[name]]
record(request.user, Action.EDIT_EVENT, event,
fields=changed)
return None
@login_required
def event_edit(request, event_id):
"""Edit the event, for those who may change it."""
event = event_to_manage(request, event_id,
Action.EDIT_EVENT)
title = event.title
if request.method == 'POST':
try:
form = save_edit(request, event)
except ValidationError as error:
refuse(request, error)
form = EventForm(request.POST, instance=event)
if form is None:
messages.success(request, 'Changes saved.')
return redirect(event)
else:
form = EventForm(instance=event)
return render(request, 'events/edit.html', {
'form': form,
'title': title,
'event_id': event.pk,
'taken': event.places_taken(),
})
save_edit() opens the transaction, locks the event, builds the form on the locked row, and only then validates and saves. Now the two requests take turns, in whichever order they reach the lock. If the registration goes first, the edit counts two places and is refused; if the edit goes first, the capacity becomes one and Sai is told the event is full. Both are fair, so the test checks the rule itself: never more places than capacity. A “busy” refusal shows the message and the form with what was typed.
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Step 9: A version for the edit page
Now Sam and Raj’s lost edit. Tests first, in events/tests.py. The two helpers that build what the pages send must also send the version: as_sent() for the edit page and event_form() for the admin. At the end of as_sent():
events/tests.py (the end of as_sent())
# The version the page was opened at (Chapter 33).
data['version'] = event.version
return data | changes
class EditVersionTests(TestCase):
"""A save from an out-of-date page is refused."""
@classmethod
def setUpTestData(cls):
cls.sam = editor()
cls.clinic = save_clinic(cls.sam)
def setUp(self):
self.client.force_login(self.sam)
self.url = reverse('events:edit',
args=[self.clinic.pk])
def test_the_page_sends_the_version(self):
response = self.client.get(self.url)
self.assertContains(
response, '<input type="hidden" name="version" '
'value="1">', html=True,
)
def test_a_save_counts_a_new_version(self):
self.client.post(self.url, as_sent(
self.clinic, title='Clinic, room 2'))
self.clinic.refresh_from_db()
self.assertEqual(self.clinic.title, 'Clinic, room 2')
self.assertEqual(self.clinic.version, 2)
def test_a_save_from_an_old_page_is_refused(self):
title = self.clinic.title
opened = as_sent(self.clinic, title='Clinic, room 2')
# Raj saves the event after Sam opened the page.
Event.objects.filter(pk=self.clinic.pk).update(
capacity=60, version=2
)
response = self.client.post(self.url, opened)
self.assertContains(response, 'your changes were not '
'saved')
self.clinic.refresh_from_db()
self.assertEqual(self.clinic.title, title)
self.assertEqual(self.clinic.capacity, 60)
def test_the_admin_refuses_an_old_page_too(self):
admin = User.objects.create_superuser(
'admin@example.org', display_name='Admin'
)
self.client.force_login(admin)
opened = event_form(self.clinic, location='Room 2')
Event.objects.filter(pk=self.clinic.pk).update(
version=2
)
response = self.client.post(
admin_url(Event, 'change', self.clinic.pk), opened
)
self.assertContains(response, 'Reload it')
self.clinic.refresh_from_db()
self.assertNotEqual(self.clinic.location, 'Room 2')
Terminal
uv run python manage.py test events -k EditVersion
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute 'version'
Ran 4 tests in ...s
FAILED (failures=1, errors=3)
In events/models.py, add the field above phone_required:
events/models.py (in Event, before phone_required)
# Counts saves of the edit page and the admin, so a
# save from an out-of-date page is refused (Chapter 33).
version = models.PositiveIntegerField(
default=1, editable=False
)
phone_required = models.BooleanField(
editable=False keeps it out of every model form: nobody types a version. Make and apply the migration:
Terminal
uv run python manage.py makemigrations events --name version
uv run python manage.py migrate
Output
Migrations for 'events':
events\migrations\0008_version.py
+ Add field version to event
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying events.0008_version... OK
Existing events start at version 1. At the end of events/forms.py, a small form reads the version the page sent:
events/forms.py (add at the end)
class VersionForm(forms.Form):
"""The event version the edit page was opened at."""
version = forms.IntegerField(min_value=1,
widget=forms.HiddenInput)
In events/views.py, import it:
events/views.py (replace the .forms import)
from .forms import (
CopyForm, EventForm, OrganizerForm, RemoveOrganizerForm,
VersionForm,
)
Then give save_edit() its final form, with the message above it:
events/views.py (replace save_edit())
STALE = ('This event was changed after you opened this '
'page, so your changes were not saved. The form '
'now shows the event as it is: make them again.')
def save_edit(request, event):
"""Save the edit form under the event's lock.
Return None once saved, or the form to show again.
The lock makes the capacity floor count the places
taken now; the version shows whether anyone saved the
event after this page was opened.
"""
with transaction.atomic():
event = event.locked()
seen = VersionForm(request.POST)
if (not seen.is_valid()
or seen.cleaned_data['version']
!= event.version):
messages.error(request, STALE)
return EventForm(instance=event)
before = model_to_dict(event)
form = EventForm(request.POST, instance=event)
if not form.is_valid():
return form
event.version += 1
form.save()
after = model_to_dict(event)
changed = [name for name in form.fields
if before[name] != after[name]]
record(request.user, Action.EDIT_EVENT, event,
fields=changed)
return None
The version is compared under the lock, so nobody can save between the comparison and the save. A mismatch saves nothing and shows the event as it is now, with a message. The edit page sends the version it was opened at; in events/templates/events/edit.html, under {% csrf_token %}:
The admin edits the same fields, so it checks the same version. In events/admin.py, add a form above EventAdmin:
events/admin.py (above EventAdmin)
class EventAdminForm(forms.ModelForm):
"""The admin's event form, with the version check."""
seen_version = forms.IntegerField(
widget=forms.HiddenInput, required=False
)
def __init__(self, *args, **kwargs):
"""Send the version the page is opened at."""
super().__init__(*args, **kwargs)
self.fields['seen_version'].initial = (
self.instance.version
)
def clean(self):
"""Refuse a save from an out-of-date page."""
cleaned = super().clean()
if (self.instance.pk is not None
and cleaned.get('seen_version')
!= self.instance.version):
raise ValidationError(
'This event was changed after you opened '
'this page. Reload it and make your changes '
'again.', code='stale',
)
return cleaned
In EventAdmin, use it, add 'seen_version' at the end of fields, and add two methods:
events/admin.py (in EventAdmin)
readonly_fields = ['local_start']
form = EventAdminForm
inlines = [RegistrationInline]
events/admin.py (in EventAdmin, before start_utc)
def get_object(self, request, object_id, from_field=None):
"""Lock the event while a change is saved.
The admin saves inside a transaction, so the lock
lasts until the save is committed.
"""
event = super().get_object(request, object_id,
from_field)
if event is not None and request.method == 'POST':
return Event.objects.select_for_update().get(
pk=event.pk
)
return event
def save_model(self, request, obj, form, change):
"""Count this save as a new version of the event."""
if change:
obj.version += 1
super().save_model(request, obj, form, change)
The admin already saves each change inside a transaction, so locking in get_object() holds the row until the save is committed, and the form’s check compares with the locked row.
Terminal
uv run python manage.py test events -k EditVersion
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Step 10: The design notes
Record what the code now promises. In docs/design/registration.md, delete the line “Two requests at the same moment: Chapter 33.” under “Not here”, and add above that heading:
docs/design/registration.md (before Not here)
## Requests at the same moment (Chapter 33)
- register(), publish(), cancel(), and the edit save
lock the event row (Event.locked(): select_for_update
inside atomic) and check the locked row, never the
copy a view loaded.
- Requests for one event take turns; requests for
different events do not wait for each other.
- A request waits at most LOCK_TIMEOUT (3 s), then is
told "Otahque is busy. Please try again." with
nothing changed. Only PostgreSQL's lock-not-available
error (55P03) means busy; no automatic retry.
- The same member twice: the one-active-place rule and
the inner atomic() (Chapter 31) give one place.
- Cancelling a place does not lock the event: a count
made while a place is being given back may still see
it. That can only refuse a place, never oversell.
- Proved by RaceTests (TransactionTestCase, threads,
PostgreSQL only; skipped on SQLite).
In docs/design/event-states.md, add above “Open”:
docs/design/event-states.md (before Open)
## Two organizers at once (Chapter 33)
- Event.version starts at 1 and grows by one on each
save of the edit page or the admin's event form.
- The edit page sends the version it was opened at.
The save locks the row and compares: a different
version is refused, nothing is saved, and the form
shows the event as it is now.
- Publishing and cancelling do not change the version:
the edit form has no status field, so they cannot be
undone by an edit.
and mark the open item done:
docs/design/event-states.md (in Open)
- Done (Chapter 33): a version check for two
organizers acting at once.
In docs/design/erd.md, the event gains its new column:
docs/design/erd.md (in EVENT)
bool phone_required
int version "grows by one on each edit"
}
REGISTRATION {
Step 11: Clearer full and closed states
A member who cannot register saw a plain list of reasons, and the places left were a line of small text. In registrations/templates/registrations/panel.html, replace the list of reasons with an alert:
registrations/templates/registrations/panel.html (the reasons)
The meter is decoration (aria-hidden); the sentence beside it carries the number for every reader. Otahque’s theme needs a warning colour for both, with dark text on a light background. In static/otahque/source.css, after the error colours:
One earlier test checked the exact markup of the places line. It now checks the words, so the meter’s look can keep improving. In events/tests.py, in test_pages_show_places_left:
events/tests.py (in test_pages_show_places_left)
# The words, not the markup: the meter's look may
# change from chapter to chapter (Chapter 33).
self.assertContains(response, '1 of 2 places left')
self.assertContains(
response, '<span class="places badge '
'badge-warning">Full</span>', html=True,
)
Rebuild the stylesheet and run the two apps’ tests:
Terminal
npm run build
uv run python manage.py test events registrations --parallel
Output
Found 250 test(s).
Creating test database for alias 'default'...
...
Ran 250 tests in ...s
OK
Open a full event at full width and at 390 pixels: the alert reads “You cannot register now” with “This event is full.” under it. The events list shows a short meter beside each “places left”.
Step 12: Check everything and commit
Terminal
uv run python manage.py test --parallel
Output
Found 354 test(s).
Creating test database for alias 'default'...
...
Ran 354 tests in ...s
OK
All 354 tests pass. On SQLite, the race tests are skipped with their reason, and everything else still passes:
PowerShell
# PowerShell
$env:DB_ENGINE = 'django.db.backends.sqlite3'
uv run python manage.py test registrations -k RaceTests
Remove-Item Env:DB_ENGINE
Terminal
# Git Bash, macOS, Linux, WSL
DB_ENGINE=django.db.backends.sqlite3 \
uv run python manage.py test registrations -k RaceTests
Output
Found 4 test(s).
Ran 4 tests in 0.000s
OK (skipped=4)
Terminal
uv run python manage.py makemigrations --check --dry-run
git add .
git status --short
git commit -m "Lock the last place; refuse stale edits"
Output
No changes detected
M docs/design/erd.md
M docs/design/event-states.md
M docs/design/registration.md
M events/admin.py
M events/forms.py
A events/migrations/0008_version.py
M events/models.py
M events/templates/events/edit.html
M events/templates/events/places.html
M events/tests.py
M events/views.py
M registrations/templates/registrations/panel.html
M registrations/tests.py
M static/otahque/site.css
M static/otahque/source.css
[master 3e9c903] Lock the last place; refuse stale edits
15 files changed, 625 insertions(+), 53 deletions(-)
create mode 100644 events/migrations/0008_version.py
When something goes wrong
Table 33.1 — Diagnosing locks and race tests
Symptom
Likely cause
Recovery
Race test passes without the lock
Written as a TestCase, or no meeting point after the count
Use TransactionTestCase and meet_after_counting()
DoesNotExist inside a thread
TestCase: the rows were never committed
TransactionTestCase
TransactionManagementError
select_for_update outside atomic()
Call locked() inside transaction.atomic()
A test hangs
A thread waits on something never set
Every wait has a timeout; check finished.set() in finally
Test database cannot be removed
A thread kept its connection open
connection.close() in the thread's finally
Groups missing in a race test
TransactionTestCase emptied the tables
Give permissions directly, as organizer() does
Everyone is told "busy"
A transaction holds the row for long
Keep work inside locked() short; nothing slow under the lock
Stale-edit message on every save
The page does not send version
The hidden input in edit.html
Race tests skipped
DB_ENGINE is empty: SQLite
check_environment.py; set the DB_* lines
No recovery here touches your data: the race tests create and empty their own tables in the test database.
Work through Table 33.2 from the folder that holds manage.py.
Table 33.2 — Verification checklist for Chapter 33
Check
Command or action
Expected result
Starting point
test --parallel
Found 343 test(s); OK
A row lock by hand
Two psql windows, FOR UPDATE
The second waits until the first commits
Race test fails first
test registrations -k RaceTests, before Step 4
First has 2: 'place'
Race test passes
The same, after Step 4
One place and ['full']
Busy
The busy test, after Step 6
['busy'] within the limit
Stale copies
test registrations -k StaleCopy
3 tests OK
Capacity floor
The capacity test, after Step 8
Never more places than capacity
Stale edit
Open the edit page in two tabs; save both
The second: "your changes were not saved"
Admin
The same in the admin
"Reload it and make your changes again"
All tests
test --parallel
Found 354 test(s); OK
SQLite
RaceTests with DB_ENGINE for SQLite
OK (skipped=4)
No migration waiting
makemigrations --check --dry-run
No changes detected
Full event
Open it at 390 and 1280 px
"You cannot register now"; no sideways scroll
Committed
git status --short
No output
Not verified
macOS, Linux; two processes
Readers on those systems
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 32 checkpoint with a reader’s data, against a PostgreSQL 18.3 server made for the check. The two psql windows of the Custom Way were run as two psql processes. The race tests use threads in one process; two separate server processes, as in production, were not tested here (Chapter 66). In the printed outputs the project folder is shortened to ....
Que. 3 register() was already inside transaction.atomic() in Chapter 31. Why did that not stop the clinic from being oversold?
Flip to check your answerFold answer back
Answer. A transaction keeps its own changes together; it does not stop another transaction from reading at the same time. Under READ COMMITTED, each request’s count saw only committed places, so both saw one left before either inserted. The row lock makes the second request wait until the first has committed, so its count sees the first place.
Que. 4 Why does register() check event, the row from locked(), and not self?
Flip to check your answerFold answer back
Answer. self is the copy the view loaded at the start of the request. By the time the lock is granted it may be cancelled, edited, or full. The locked row is the newest committed version, and nobody can change it until the transaction ends, so checks on it stay true until the insert.
Que. 5 locked() turns an OperationalError into “busy” only when its cause has the code 55P03. What would go wrong if it caught every OperationalError?
Flip to check your answerFold answer back
Answer. A lost connection or a server shutting down would also be shown as “Otahque is busy. Please try again.” The member would retry for ever and nobody would see the real fault in the logs. Only the expected error becomes a friendly answer, as with IntegrityError in Chapter 31.
Que. 6 Sam opens the edit page at version 4. Raj publishes the event. Sam saves. Is Sam’s save refused?
Flip to check your answerFold answer back
Answer. No. Publishing does not change the version, because the edit form has no status field: Sam’s save cannot undo Raj’s publish. The version grows only with saves of the edit page and the admin’s event form, the two places that write the form’s fields.
Mini-Challenge
Que. 7 delete_draft() still trusts its copy. If Raj publishes a draft while Sam has its delete page open, Sam’s confirmation deletes a published event. Write a test in registrations/tests.py that shows it, watch it fail, then make delete_draft() read the locked row like publish().
Flip to check your answerFold answer back
Answer. The test, at the end of registrations/tests.py:
registrations/tests.py (add at the end)
class DeleteDraftTests(TestCase):
"""Deleting reads the event again, too."""
def test_delete_sees_a_publish_made_since(self):
event = soon()
Event.objects.filter(pk=event.pk).update(
status=Event.Status.DRAFT, description='Notes.'
)
organizer(event)
draft = Event.objects.get(pk=event.pk)
Event.objects.get(pk=event.pk).publish()
with self.assertRaises(ValidationError):
draft.delete_draft()
self.assertTrue(
Event.objects.filter(pk=event.pk).exists()
)
Before the change it fails: the copy still says “draft”, and the published event is deleted. In events/models.py, replace delete_draft():
events/models.py (replace delete_draft())
def delete_draft(self):
"""Delete a draft nobody registered for.
Reads the status under the lock, like publish().
"""
with transaction.atomic():
event = self.locked()
if event.status != self.Status.DRAFT:
raise ValidationError(
'Only a draft can be deleted.'
)
if event.registrations.exists():
raise ValidationError(
'This draft has registrations, so it '
'is kept.'
)
event.organizer_assignments.all().delete()
event.delete()
Terminal
uv run python manage.py test registrations -k DeleteDraft
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
What We Learned
A transaction keeps changes together; it does not stop others from reading at the same time.
Under READ COMMITTED each statement sees what was committed before it began, so “count, then insert” can race.
select_for_update() inside atomic() locks a row until commit; other requests for the same row take turns, and plain reads and other rows are not affected.
Every check after the lock reads the locked row, never a copy loaded earlier.
SET LOCAL lock_timeout bounds the wait; only the lock-not-available error becomes “busy”, and there is no hidden retry.
A race test needs TransactionTestCase, one connection per thread, and a meeting point placed after the count; then it fails every time without the fix.
TransactionTestCase empties the tables after each test, including rows a data migration made.
A version number refuses a save from a page that is out of date; the lock and the version solve different problems and can work together.
Key terms
Use Table 33.3 to explain this chapter’s ideas in your own words.
Table 33.3 — Key terms from Chapter 33
Term
Meaning
Race
A result that depends on which of two requests runs first.
Isolation level
The rule for what one transaction sees of another.
READ COMMITTED
Each statement sees what was committed before it began.
Row lock
A hold on one row that makes other writers and lockers wait.
Pessimistic locking
Making others wait, in case of a conflict.
Optimistic locking
Letting everyone work, and refusing a conflicting save at the end.
Version number
A count of saves, sent with a page and compared at save time.
Lock timeout
The longest a request waits for a lock before it gives up.
TransactionTestCase
A test case that commits, then empties the tables.
Barrier
A meeting point where threads wait for each other.
Readiness checkpoint: you are ready for Chapter 34 when the race test failed before Step 4 and passes now, all 354 tests pass with --parallel, the race tests are skipped on SQLite, makemigrations --check --dry-run prints No changes detected, a second save from an old edit page is refused, a full event shows “You cannot register now”, and the commit is made.
Git Commit
Your Chapter 33 work was committed in Step 12, with the message “Lock the last place; refuse stale edits”. It holds Event.locked() with its time limit and the “busy” reason; register(), publish(), and cancel() reading the locked row; the edit page saving under the lock with a version check; the version field and its migration; the admin’s version check; the race, busy, capacity, stale-copy, and version tests; the alert and the places meter with the warning colour; and the updated design notes.
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to debugging and to choices under load. They are extension questions, not a gate to the next chapter. Practice files are run with uv run python manage.py shell -c "exec(open('NAME').read())" and deleted afterwards; each undoes its own changes.
L1 (Junior): What does a transaction guarantee, and what does it not?
What the interviewer is testing: Can you tell atomicity from isolation?
Flip to check your answerFold answer back
Perfect answer: A transaction guarantees that its changes are kept or undone together: if a later step fails, the earlier ones are rolled back, and other transactions never see half of it. It does not guarantee that what it read stays true while it works. Other transactions run at the same moment, and under PostgreSQL’s default, READ COMMITTED, each statement sees whatever was committed before it began. A decision based on an earlier read, such as “one place left”, can be wrong by the time it is acted on, unless something, such as a row lock, makes others wait.
Table 33.4 — What a transaction does and does not give
Question
Transaction alone
With a row lock
All or nothing?
Yes
Yes
Others see half a change?
No
No
A read stays true until commit?
No
Yes, for the locked row
Behind the scenes:
a transaction (summary)
atomic() all changes kept, or all undone
READ COMMITTED each statement sees committed data
row lock others wait for this row until commit
Code proof:l1_atomic.py undoes a change when a later step fails, and asks PostgreSQL for the isolation level:
l1_atomic.py (practice file; delete it afterwards)
"""Show what a transaction keeps, and what it reads."""
from django.db import connection, transaction
from events.models import Event
event = Event.objects.get(title='Python meetup')
before = event.capacity
try:
with transaction.atomic():
Event.objects.filter(pk=event.pk).update(
capacity=before + 9
)
raise RuntimeError('a later step failed')
except RuntimeError:
pass
after = Event.objects.get(pk=event.pk).capacity
print('undone after the failure:', after == before)
with connection.cursor() as cursor:
cursor.execute('SHOW transaction_isolation')
print('isolation level:', cursor.fetchone()[0])
Output
undone after the failure: True
isolation level: read committed
Common mistakes:
Believing atomic() alone stops two requests from both seeing one place.
Turning on SERIALIZABLE for everything without handling the errors it raises.
Follow-up the interviewer might ask:
What does REPEATABLE READ change? (Every statement sees the data as at the transaction’s first statement; a conflicting update raises an error instead of waiting.)
Does the lock block someone who only views the event page? (No: plain reads are never blocked by a row lock.)
L2 (Mid-Level): Predict the result of two registrations for the last place, without a lock
What the interviewer is testing: Can you step through an interleaving and predict it exactly?
Flip to check your answerFold answer back
Perfect answer: Both get a place. Each request counts the active places and sees none for the other, because the other’s insert is either not done or not committed. Both pass the “full” check, both insert, and both commit. The one-active-place rule does not help, because it is one place per member, and they are different members. The event ends with two places for a capacity of one. The test makes this happen every time by meeting after the count.
Figure 33.4 — Predicting the unlocked race.
Behind the scenes:
the interleaving (summary)
Sai counts 0 Raj counts 0
Sai inserts Raj inserts
2 places, capacity 1
Code proof: the race test of Step 3, run before the lock:
Output
AssertionError: Element counts were not equal:
First has 2, Second has 1: 'place'
First has 0, Second has 1: ['full']
Common mistakes:
Expecting the database to refuse the second place: no rule compares a count with capacity.
Expecting the second request to see the first’s uncommitted insert.
Follow-up the interviewer might ask:
Could a CHECK constraint stop it? (Not on a count across rows; a counter column with a CHECK could, at the price of a second copy of the count.)
What changes with three requests? (The same: each counts before any insert, so all three get places.)
L3 (Senior): Defend locking the event row instead of keeping a counter column
What the interviewer is testing: Can you weigh two correct designs and pick one for this product?
Flip to check your answerFold answer back
Perfect answer: A counter column, such as places_taken, updated with F() and limited by a CHECK constraint, also prevents overselling, and it can be faster under heavy load. But it is a second copy of a fact the registrations already hold: every place given, cancelled, or moved by an administrator must keep it in step, forever. Locking the event row keeps one source of truth, the rows themselves, and puts the rule in one method. Otahque’s events take tens of registrations, not thousands per second, and the lock is held for milliseconds. The decision is recorded with a trigger to revisit it: Chapter 66 measures lock waits under load.
Figure 33.5 — Locking the row the decision belongs to.
Behind the scenes:
two designs (summary)
counter column fast, a second copy to keep in step
row lock one source of truth, requests take turns
Otahque row lock; measure in Chapter 66
Code proof:l3_sql.py shows the two statements register() sends first, then undoes everything:
l3_sql.py (practice file; delete it afterwards)
"""Show the SQL register() sends first, then undo it."""
from django.core.exceptions import ValidationError
from django.db import connection, transaction
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from accounts.models import User
from events.models import Event
event = Event.objects.get(title='Leeds meetup')
soni = User.objects.get(email='soni@example.org')
with (transaction.atomic(),
CaptureQueriesContext(connection) as seen):
try:
event.register(soni, timezone.now())
except ValidationError as error:
print('answer:', error.messages)
transaction.set_rollback(True)
for query in seen:
sql = query['sql']
if 'lock_timeout' in sql or 'FOR UPDATE' in sql:
print(sql if len(sql) < 50 else sql[:24] + ' ... '
+ sql[-24:])
Output
answer: ['You already have a place.']
SET LOCAL lock_timeout = '3s'
SELECT "events_event"."i ... = 7 LIMIT 21 FOR UPDATE
Common mistakes:
Locking the registration rows instead of the event: a new place has no row yet to lock.
Locking the whole table: every event’s registrations would wait for each other.
Follow-up the interviewer might ask:
When would you choose the counter? (When measurements show lock waits dominate, as with ticket sales at very high volume.)
What about ON CONFLICT in PostgreSQL 19? (It handles duplicates of one key, not a count against capacity.)
L4 (Staff): A race test always passes, even with the lock removed. Diagnose it
What the interviewer is testing: Can you find why a test proves nothing?
Flip to check your answerFold answer back
Perfect answer: First, check the test’s base class. In a TestCase nothing is ever committed, so a second thread cannot see the test’s event: it fails inside the thread, and if the assertion only checks that “at most one place” exists, it passes. Second, check where the threads meet. If they start together but nothing makes them overlap, one usually finishes before the other counts, and the test passes by timing. The fix is TransactionTestCase, one connection per thread, and a meeting point right after the count. Then remove the lock and confirm the test fails: a test that has never failed has not been proved.
Figure 33.6 — Diagnosing a race test that cannot fail.
Behind the scenes:
a race test (summary)
TestCase never commits: threads see nothing
no meeting point overlap by luck
TransactionTestCase + meeting after the count: certain
Code proof:l4_testcase.py is the race test’s setup written as a TestCase. Save it in registrations/, run it as a test, and delete it:
registrations/l4_testcase.py (practice file; delete it afterwards)
"""Practice: the race test written as a TestCase."""
from django.test import TestCase
from events.models import Event
from registrations.tests import at_once, soon
class InsideOneTransactionTests(TestCase):
"""A TestCase never commits, so threads see nothing."""
def test_another_thread_looks_for_the_event(self):
event = soon(capacity=1)
print('another thread sees the event:', at_once(
lambda: Event.objects.filter(pk=event.pk).exists()
))
Terminal
uv run python manage.py test registrations.l4_testcase
Output
Found 1 test(s).
another thread sees the event: [False]
Ran 1 test in 0.051s
OK
Common mistakes:
Adding time.sleep() to make the race likely: slower, and still luck.
Never running the test without the fix, so nobody knows it can fail.
Follow-up the interviewer might ask:
Why does TransactionTestCase remove the groups? (It empties every table after each test, and nothing makes the groups again; only content types and permissions are recreated.)
How would you test two real processes? (Two runserver workers and concurrent HTTP requests, in Chapter 66.)
L5 (Lead): Defend “busy, try again” with no retry loop, and say where SERIALIZABLE would be right
What the interviewer is testing: Can you choose failure behaviour under load, and know when a stronger tool fits?
Flip to check your answerFold answer back
Perfect answer: A wait without a limit lets one stuck request hold every other request for the same event, and a website should answer quickly even when the answer is “not now”. So the wait is limited to three seconds, and then the member is told Otahque is busy, with nothing changed. A hidden retry loop would hide that the system is overloaded, repeat work, and can make a pile-up worse; a person pressing the button again is a natural, visible retry. SERIALIZABLE isolation is the right tool when a rule spans many rows that no single row can stand for, such as “no organizer runs two events at overlapping times”. Then PostgreSQL detects conflicts itself, and every caller must be ready to retry a serialization failure. For one event’s capacity, the event row stands for the rule, so a row lock is simpler. Chapter 66 measures before anything changes.
Figure 33.7 — Bounded waiting, and when to reach for SERIALIZABLE.
Behind the scenes:
failure under load (summary)
wait at most LOCK_TIMEOUT, this transaction only
then "busy", nothing changed, no retry loop
later measure in 66; SERIALIZABLE for multi-row rules
Code proof:l5_timeout.py shows that the limit lasts one transaction and is gone after it:
l5_timeout.py (practice file; delete it afterwards)
"""Show that the lock's time limit lasts one transaction."""
from django.db import connection, transaction
from events.models import Event
def lock_timeout():
"""Return the connection's lock_timeout now."""
with connection.cursor() as cursor:
cursor.execute('SHOW lock_timeout')
return cursor.fetchone()[0]
event = Event.objects.get(title='Python meetup')
with transaction.atomic():
event.locked()
print('inside the transaction:', lock_timeout())
print('after it:', lock_timeout())
Output
inside the transaction: 3s
after it: 0
Common mistakes:
Setting lock_timeout for the whole server, which PostgreSQL’s documentation advises against.
Retrying automatically after a timeout without a limit or a delay.
Follow-up the interviewer might ask:
Why three seconds? (Long enough for many turns of a millisecond lock, short enough for a person; Chapter 66 checks it with measurements.)
What would the admin show if it timed out? (The admin does not set the limit; it waits, which is acceptable for one administrator and is stated in the design note.)
Next: Chapter 34, Testing fundamentals and first-release acceptance, where every test moves into packages, the race test becomes the proof of PR-3, and Otahque meets its first continuous-integration run.