Django Race Conditions: Enforcing business constraints

This is the second post in a series on handling race conditions in Django. This edition centers on race conditions around your business logic.

As with the first post, this assumes we’re using PostgreSQL for our database, and the common data model we’ll be using is:

class Organization(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)

class Project(models.Model):
    organization = models.ForeignKey(
        Organization, related_name="projects", on_delete=models.CASCADE
    )
    name = models.CharField(max_length=200)
    slug = models.SlugField()

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["organization", "slug"],
                name="unique_project_slug_per_org",
            ),
        ]

Enforcing business constraints

At some point your web application is going to need to enforce some business constraints. A simple one could be that an organization can’t have more than three projects (or maybe they need to pay $ to have more).

One implementation is to add a check within our form’s clean() method:

MAX_PROJECTS = 3


class LimitedProjectForm(ProjectForm):
    def clean(self):
        organization = self.instance.organization
        if (
            self.instance._state.adding
            and organization.projects.count() >= MAX_PROJECTS
        ):
            raise ValidationError(
                "An organization can have at most %(max)s projects.",
                code="too_many_projects",
                params={"max": MAX_PROJECTS},
            )
        return super().clean()

Which works well, unless we have multiple projects being created concurrently. Which is kind of the point of this series!

To handle this type of race condition, we can acquire a lock on the row for the organization. But that is, umm, aggressive. You’ll see in a minute.

class LimitedProjectForm(ProjectForm):
    def clean(self):
        organization = self.instance.organization
        if self.instance._state.adding:
            # Other queries that update or lock this organization will wait.
            Organization.objects.select_for_update(no_key=True).get(pk=organization.pk)
            if organization.projects.count() >= MAX_PROJECTS:
                raise ValidationError(
                    "An organization can have at most %(max)s projects.",
                    code="too_many_projects",
                    params={"max": MAX_PROJECTS},
                )
        return super().clean()


def project_create_limited(request, org_slug):
    organization = get_object_or_404(Organization, slug=org_slug)
    form = LimitedProjectForm(request.POST or None, organization=organization)
    if request.method == "POST":
        # form.is_valid() takes the lock in LimitedProjectForm.clean() and
        # it's held until this block exits, after form.save().
        with transaction.atomic():
            if form.is_valid():
                project = form.save()
                messages.success(request, f"Created project {project.name}.")
                return redirect(request.path)
    return render(
        request,
        "myapp/project_form.html",
        {"form": form, "organization": organization},
    )

I included the view to show that we need to wrap the logic in a transaction.atomic() block to actually lock the organization row with select_for_update1. This lock is a binary semaphore, a fancy term for controlling access across multiple processes. The lock itself is a signal that a project is being created, and we need to make sure there are no other requests trying to create a project. This guarantees us that when we check the number of projects created, it’s the correct count2. If you’re curious, the no_key=True argument tells PostgreSQL to acquire a weaker lock that allows inserts of rows to other tables that reference the organizations table. Since Organization is a tenant model, we may have another model similar to Project, like Rule. We don’t want this lock to interfere with Rule inserts.

While this approach works, it’s not great. Any other query that seeks to update that organization row will need to wait until this request completes. This means a request as simple as someone updating the organization’s name would be blocked by this. While that’s a fairly unexpected workflow, your business case will likely be different.

Another scenario where this approach breaks down is if you have multiple business constraints you want to enforce (who would have guessed?!). Perhaps you have multiple types of projects, and organizations have different limits for each. Acquiring a lock on the organization row would mean requests to create each type of project would have to wait for the other create requests to process first, even though they aren’t actually competing.

Extending that further, a Rule model could have its own constraints. Maybe the org can only have three Rule instances too. But if we use a lock on the Organization row there too, now creating a project blocks creating a rule and vice versa. That’s probably undesirable.

Before using select_for_update, consider what other aspects of your application will be impacted by the change.

Advisory locks allow locks outside of rows

An alternative to locking the organization row to limit the number of projects would be to use an advisory lock. Advisory locks allow the application to define a key for the lock, and PostgreSQL makes queries attempting to use that same key wait. This means we can define a custom lock for individual constraints, avoiding the problem we saw of using a lock on the Organization row to control things.

The package django-pglock provides a nice interface for us to use in a Django project. We can swap out our earlier usage of select_for_update() with pglock.advisory(...).acquire() in LimitedProjectForm. The view from the previous example stays the same; its transaction.atomic() block is what the lock is held within.

import pglock


class LimitedProjectForm(ProjectForm):
    def clean(self):
        organization = self.instance.organization
        if self.instance._state.adding:
            # Held until the transaction commits.
            pglock.advisory(f"create-project:{organization.pk}", xact=True).acquire()
            if organization.projects.count() >= MAX_PROJECTS:
                raise ValidationError(
                    "An organization can have at most %(max)s projects.",
                    code="too_many_projects",
                    params={"max": MAX_PROJECTS},
                )
        return super().clean()

By using an advisory lock, we can limit the lock to the exact requests we want to lock on, whereas the lock on the organization row would have prevented other updates to the organization row until that transaction commits.

Since this is a custom lock we are defining, any other part of the application that creates Project instances would not be protected by this. If we wanted to enforce that (this applies to the select_for_update example too), we’d need to set up some helper or factory functions, but that’s beyond the scope of this post.

Another use for row locks: external API calls

While locking the whole organization row doesn’t work super well to limit the number of projects, that doesn’t mean row locks aren’t helpful. The advisory lock was a good fit because it was scoped to exactly what the constraint covered. A row lock can be scoped just as well when the row itself is the focus of the business constraint.

One place I’ve used this has been syncing an Event with Zoom. Without a lock, two tasks syncing the same event could both see no zoom_meeting_id and both create a meeting. By using a row lock, subsequent tasks must wait until the first one commits.

This allows us to use the appropriate API method based on the stored state of the Event. If the event has a zoom_meeting_id set, it will update the meeting in Zoom rather than create it.

This can work especially well if the model is specific to a single service, so the lock only blocks similar queries. If other parts of your application edit Event, those edits are blocked while the API request resolves and the commit occurs. Whether that’s acceptable depends on how your application is used.

An example version of this code is:

from django.db import Error, transaction
from django.tasks import task
from django.utils import timezone

from .models import Event
from .services import zoom


@task()
def sync_event(event_id: int) -> None:
    meeting = None
    try:
        with transaction.atomic():
            event = Event.objects.select_for_update(no_key=True).get(pk=event_id)
            if not event.zoom_meeting_id:
                meeting = zoom.create_event_meeting(event, timeout=5)
                event.zoom_meeting_id = meeting.meeting_id
            else:
                zoom.update_event_meeting(event, timeout=5)
            event.zoom_synced_at = timezone.now()
            event.save()
    except Error:
        if meeting is not None:
            # Clean up the created meeting that's not in the database.
            zoom.delete_event_meeting(id=meeting.meeting_id)
        raise

Testing database locks

As in the previous post, we’re also going to cover testing the race conditions. These workflows are especially difficult to reproduce in a development environment, making the tests more important. Plus, you probably want that 100% code coverage right?!

In the past when I’ve written these types of tests, I used Django’s own testing approach for select_for_update. This involves the helper methods, start_blocking_transaction and end_blocking_transaction. The general approach is to:

  1. Set up test data
  2. Start the blocking transaction
  3. Create a thread to run the blocked transaction
  4. Sleep to confirm it’s actually blocked
  5. Confirm the blocked scenario
  6. End the blocking transaction
  7. Confirm the blocked transaction is no longer blocked

It’s quite a bit, really.

def test_block(self):
    """
    A thread running a select_for_update that accesses rows being touched
    by a similar operation on another connection blocks correctly.
    """
    # First, let's start the transaction in our thread.
    self.start_blocking_transaction()

    # Now, try it again using the ORM's select_for_update
    # facility. Do this in a separate thread.
    status = []
    thread = threading.Thread(target=self.run_select_for_update, args=(status,))

    # The thread should immediately block, but we'll sleep
    # for a bit to make sure.
    thread.start()
    sanity_count = 0
    while len(status) != 1 and sanity_count < 10:
        sanity_count += 1
        time.sleep(1)
    if sanity_count >= 10:
        raise ValueError("Thread did not run and block")

    # Check the person hasn't been updated. Since this isn't
    # using FOR UPDATE, it won't block.
    p = Person.objects.get(pk=self.person.pk)
    self.assertEqual("Reinhardt", p.name)

    # When we end our blocking transaction, our thread should
    # be able to continue.
    self.end_blocking_transaction()
    thread.join(5.0)

    # Check the thread has finished. Assuming it has, we should
    # find that it has updated the person's name.
    self.assertFalse(thread.is_alive())

    # We must commit the transaction to ensure that MySQL gets a fresh
    # read, since by default it runs in REPEATABLE READ mode
    transaction.commit()

    p = Person.objects.get(pk=self.person.pk)
    self.assertEqual("Fred", p.name)

That’s clearly a lot, and it’s pretty complex. It’s also 15+ years old, and the majority of the test hasn’t changed from 2011! 🤯

Adopting that approach, we end up with something that looks like this:

import threading
import time

from django.db import DatabaseError, connection
from django.test import TransactionTestCase
from django.urls import reverse

from .models import Organization, Project

MAX_PROJECTS = 3
TOO_MANY_PROJECTS = f"An organization can have at most {MAX_PROJECTS} projects."


class ProjectLimitThreadRaceTests(TransactionTestCase):
    def test_create_race(self):
        """
        Concurrent requests to create projects wait for each other.
        """
        acme = Organization.objects.create(name="Acme", slug="acme")
        # Leave room for one more project
        for i in range(MAX_PROJECTS - 1):
            Project.objects.create(organization=acme, name=f"P{i}", slug=f"p{i}")
        url = reverse("project-create-limited", kwargs={"org_slug": "acme"})

        # The blocking transaction adds the last allowed project.
        self.start_blocking_transaction(acme)
        status = []
        # Start the blocked request in another thread
        thread = threading.Thread(target=self.run_create_project, args=(url, status))
        thread.start()

        # The request is blocked because the first request isn't
        # committed. Sleep to give it time to finish if it isn't blocked.
        time.sleep(1)
        self.assertEqual(status, [])
        self.assertFalse(acme.projects.filter(slug="anvil").exists())

        # Ending the blocking transaction commits the first request, letting
        # the second finish.
        self.end_blocking_transaction()
        thread.join(5.0)
        response = status[0]
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response.context["form"], None, TOO_MANY_PROJECTS)
        self.assertEqual(acme.projects.count(), MAX_PROJECTS)

    def run_create_project(self, url, status):
        try:
            status.append(self.client.post(url, {"name": "Anvil", "slug": "anvil"}))
        except Exception as e:
            status.append(e)
        finally:
            # This method is run in a separate thread. It uses its own
            # database connection. Close it without waiting for the GC.
            connection.close()

    def setUp(self):
        # Another connection stands in for a request adding the last
        # allowed project.
        self.new_connection = connection.copy()

    def tearDown(self):
        try:
            self.end_blocking_transaction()
        except (DatabaseError, AttributeError):
            pass
        self.new_connection.close()

    def start_blocking_transaction(self, organization):
        """Lock the organization and add the last project, without committing."""
        self.new_connection.set_autocommit(False)
        self.cursor = self.new_connection.cursor()
        self.cursor.execute(
            f"SELECT 1 FROM {Organization._meta.db_table} "
            "WHERE id = %s FOR NO KEY UPDATE",
            [organization.pk],
        )
        self.cursor.execute(
            f"INSERT INTO {Project._meta.db_table} (organization_id, name, slug) "
            "VALUES (%s, %s, %s)",
            [organization.pk, "Last", "last"],
        )

    def end_blocking_transaction(self):
        # Commit rather than roll back, so the request sees the last project.
        self.cursor.close()
        self.new_connection.commit()
        self.new_connection.set_autocommit(True)

Which I think is a good enough approach for a one-off. The usage of Thread, then managing state in the helper methods makes it complex at first glance.

If we were to need to do this in several places in our codebase, I’d want to create a RequestRace abstraction to make this easier. First, how it would be used, and then we’ll see how the sausage is made.

from django.test import TransactionTestCase
from django.urls import reverse

from myapp.models import Organization, Project
from myapp.tests.helpers import RequestRace

MAX_PROJECTS = 3
TOO_MANY_PROJECTS = f"An organization can have at most {MAX_PROJECTS} projects."


class ProjectLimitRaceTests(TransactionTestCase):

    def test_create_race(self):
        """
        Concurrent requests to create projects wait for each other.
        """
        acme = Organization.objects.create(name="Acme", slug="acme")
        # Leave room for one more project
        for i in range(MAX_PROJECTS - 1):
            Project.objects.create(organization=acme, name=f"P{i}", slug=f"p{i}")
        url = reverse("project-create-limited", kwargs={"org_slug": "acme"})

        with RequestRace() as race:
            # The first request adds the last allowed project.
            first = self.client.post(url, {"name": "Last", "slug": "last"})
            self.assertRedirects(first, url)
            # Start the blocked request
            race.start_request_in_thread(
                self.client.post, url, {"name": "Anvil", "slug": "anvil"}
            )
            race.assert_request_is_blocked()
        # Leaving the block commits the first request, letting the second
        # finish.
        response = race.wait_for_response()
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response.context["form"], None, TOO_MANY_PROJECTS)
        self.assertEqual(acme.projects.count(), MAX_PROJECTS)

This removes the need to define start_blocking_transaction and end_blocking_transaction. It also reduces our Thread surface area down to a single function, start_request_in_thread. If you’re familiar with functools.partial(), you should feel at home with this approach.

What I like about this approach is that it centers the test on the concurrent nature of your application. While one request remains uncommitted, it’s clear the other request is blocked. The most confusing part is that exiting the RequestRace() context manager’s block causes the first request to commit to the database, which then allows the blocked request to finally process.

RequestRace concurrent test helper

As promised, here is the code for the RequestRace test helper. The main thing to keep in mind with it is that it’s wrapping transaction.atomic(), then providing a more constrained interface to run a function in a separate thread.

from concurrent.futures import ThreadPoolExecutor, wait

from django.db import connection, transaction


class RequestRace:
    """
    A context manager for two requests racing each other. This wraps
    transaction.atomic().

    Needs TransactionTestCase so both threads' database connections see the
    same data.
    """

    def __enter__(self):
        # Each thread has its own database connection, so this transaction is
        # separate from the one the request in the thread uses. The view's own
        # transaction.atomic() becomes a savepoint inside it, so its locks are
        # held until the block ends.
        self._atomic = transaction.atomic()
        # Start the atomic transaction block. It ends in __exit__
        self._atomic.__enter__()
        self._future = None
        return self

    def __exit__(self, exc_type, exc, traceback):
        try:
            self._atomic.__exit__(exc_type, exc, traceback)
        finally:
            if exc_type is not None and self._future is not None:
                # The test failed part way. Let the request finish before the
                # test's tables are flushed.
                wait([self._future], timeout=5)

    def start_request_in_thread(self, func, *args, **kwargs):
        """
        Start the request by running func(*args, **kwargs), such as
        self.client.post, on a thread.
        """
        def run():
            try:
                return func(*args, **kwargs)
            finally:
                # Each thread opens its own connection.
                connection.close()

        executor = ThreadPoolExecutor(max_workers=1)
        self._future = executor.submit(run)
        # Lets the thread exit once func returns, without waiting here.
        executor.shutdown(wait=False)

    def assert_request_is_blocked(self, timeout=0.5):
        """
        Fail if the request from start_request_in_thread() finishes within the
        timeout.
        """
        done, _ = wait([self._future], timeout=timeout)
        if done:
            # Re-raise the request's error, if it had one.
            self._future.result()
            raise AssertionError("The request was not blocked.")

    def wait_for_response(self, timeout=5):
        """
        Wait for the request from start_request_in_thread() and return its
        response, re-raising its error.
        """
        return self._future.result(timeout=timeout)

Timeouts and locks

Something that I didn’t mention was timeouts with these locks, despite it being an important concept. When using locks, you need to consider what should happen when a request is blocked by another request. Should it skip, should it error, or should it wait, and for how long should it wait? These questions will depend on the context of your application.

In my experience, I’ve found that if I’m building a recurring workflow that does batch processing, skipping locked rows makes the most sense. If they are locked, that’s fine. I know they are being processed elsewhere, and they can always be picked up in a subsequent run of the workflow.

If the workflow absolutely needs an instantaneous response, I’ll lean towards erroring. Reserving a concert seat is a decent example of this. Just tell the person they can’t have that seat immediately; don’t wait an extra few seconds to see if it becomes available. Another scenario is if this workflow runs frequently, causing many requests to wait. Each request that waits requires resources, such as a database connection. If many are waiting and/or are waiting a long time, then it’s possible you could run out of connections for your entire application.

All that said, I still lean towards waiting. This is because the majority of my applications don’t run into these cases often. And when they do, it’s something that will resolve quickly. If the timeout is exceeded, I have it error noisily by using a database statement timeout. That error report acts as a signal that an investigation needs to occur into the scenario.

What’s next

This post focused on showcasing solutions for race conditions when enforcing business constraints. We saw how we can lock a single row to control the application flow or to sync data with third-party services. Though for flow control, the better approach is to use an advisory lock, as it allows you to explicitly define the boundaries on the lock. This provides you with greater control and limits the downstream effects.

When handling race conditions, though, you should consider what should happen in all cases. For each request in a race, what should happen for them? Is it reasonable to wait? Should the request error? Is there an alternative way to solve the problem without resorting to a lock? These scenarios are likely complex and most likely going to impact multiple workflows in your application. It can be challenging to process all the permutations.

The next post in this series will be about handling concurrent edits. If you’re looking for a solution here immediately, I’d suggest looking at django-concurrency. It provides some of the options I’ll be covering and more.

If you have questions or feel like I should cover another topic/scenario, please let me know!

  1. For databases that support select_for_update, Django will raise TransactionManagementError if you don’t use transaction.atomic() to wrap select_for_update. ↩

  2. This relies on Django’s default isolation level for PostgreSQL, READ COMMITTED. ↩

Photo of Tim Schilling

Written by Tim Schilling

Django 6.x Steering Council member, maintainer of django-debug-toolbar and django-simple-history, and a professional software engineer since 2009. These days, I mentor developers one-on-one.

About Mastodon GitHub Email

More on Django