Growing a Django project: apps on a ladder, and a slow page made fast

TL;DR

Difficulty: Advanced

A growing Django project needs boundaries to stay easy to change and measurement to stay fast. Never use one to fix the other.

  • Put the apps on a ladder and make all three kinds of arrow point down: imports, string foreign keys and signal receivers. Import tools only see the first, so add a ten line model registry test.
  • Rules about one model live on the model; rules that span apps live in a service of the app that owns the use case. Signals only for news that must travel up.
  • Move a model between apps with SeparateDatabaseAndState and keep the table.
  • For speed: measure, then fix queries, indexes and caching in that order. In the example the day overview goes from 2,083 queries and 2.8 seconds to two queries and about 440ms.
  • Async pays only when a request waits for several outside things at once. Count your database connections, and put PgBouncer in front before a Saturday deploy counts them for you.

"The project has become slow" can mean slow to change or slow to run, and they need different cures. Here is how to keep a Django 5.0 project healthy as it grows, worked through on a chain of bicycle workshops two years after launch: apps on a ladder with checked boundaries, a model moved without moving its data, and one slow page taken from 2.8 seconds to under half a second.

The question behind this chapter

"My Django project is getting big" usually arrives with one of two complaints. Either a small change now touches five apps and breaks a sixth, or the page everyone opens first thing in the morning has become slow. They sound alike and they need different cures. Boundaries make a project easier to change. Measurement makes it faster to run. Neither one fixes the other.

This chapter does both, on the same example application the whole Django series has built. It assumes you know how a project is made of apps from how a Django project is structured and how the ORM behaves from the Django ORM done well. Everything here is written for Django 5.0 on Python 3.12, the current versions as I write, with Django 4.2 as the long term support release.

The Rails series walked the same application through the same growth in growing a Rails application without it turning into a mess. The facts are identical on purpose, so you can put the two chapters side by side.

Example: Freewheel Cycles, two years on

The example is invented. Freewheel Cycles, a chain of bicycle repair workshops in Limerick (freewheelcycles.example), runs on the Django version of the spike its developers built when they compared the two frameworks. Two years later the business looks like this. The first rows are the example's fixed facts. The last rows are my own derivations and assumptions, labelled as such.

FactValue
Workshops14 (from six)
Mechanics95 (from 38)
Repair bookings a weekabout 3,100 (from about 1,150)
Parts of the businessbookings, repairs, parts, customers, invoicing, reporting, plus a JSON API for the mechanics' app
Slowest pagethe manager's day overview, 2.8 seconds
Test suite1,380 tests, 34 of them end to end, 22 minutes in continuous integration (CI)
Developers (my assumption)four: Aisling and Cian, plus two hires in the second year
Bookings on an average day (derived)3,100 ÷ 6 opening days, about 517
Rows in the bookings table (my estimate)a little over 200,000

Niamh, the founder, brings the two classic complaints to Aisling and Cian in the same week. "Last month a change to invoices broke the stock count." And: "The day overview takes forever, and my managers open it 20 times a day." The first is a boundaries job. The second is a profiler job. The chapter takes them in that order.

A Django app is a boundary only if the arrows agree

Django's own definition of an app is modest. The reference calls an application "a Python package that provides some set of features", and the only thing that makes it part of a project is its name in INSTALLED_APPS1. Nothing in the framework stops parts from reaching into repairs, or repairs into parts. A folder is not a boundary. It becomes one when the dependencies between apps all point the same way.

Here is the idea I build the rest of this chapter on. In a Django project, one app can depend on another in three different ways, and the usual tools only see one of them.

Kind of arrowWhat it looks likeWho sees it
An importfrom parts.services import deduct_stockgrep, your editor, import checking tools
A model relationmodels.ForeignKey("bookings.Booking", ...)nobody, unless you ask Django's model registry
A signal receiver@receiver(post_save, sender=JobCard) living in partsimport tools see its import, which points the opposite way to the work

The second kind surprises people. A ForeignKey can name its target as a string, "app_label.ModelName", so models can refer to each other without importing each other. Convenient, and it means an import graph of your project misses every relation between your tables. The third is subtler: a receiver in parts imports repairs to listen to it, so the import points from parts to repairs while the work flows the other way. You read card.save() and nothing on the screen says that stock just moved.

So my rule for a growing project has two parts. Put the apps on a ladder, from the ones that depend on nothing at the bottom to the ones that read everything at the top, and make all three kinds of arrow point down. The one exception is a signal, which is the sanctioned way to send news up. A ladder is easy to draw, easy to check with a tool, and it answers the daily question "may this app use that one?" in one glance.

Example: the ladder at Freewheel

Cian draws the apps as they are after two years, with what each offers to the apps above it: its public interface. Everything else is private, even though Python cannot enforce that by itself.

Rung (top to bottom)AppOwnsPublic interface for apps above
6api, reportingno tables of their own (reporting owns a few report models)none: nothing may depend on them
5invoicingInvoice, InvoiceLineservices.issue_invoice(job_card_id), selectors.invoices_for(customer_id)
4repairsJobCard, JobCardPhoto, PartUsageservices.mark_ready(job_card_id), services.fit_part(...), selectors.board(workshop_id, day)
3bookingsBookingservices.book_slot(...), services.cancel(...), selectors.free_slots(...)
2customers, partsCustomer, Bike / Part, Supplierselectors.find_customer(...) / services.deduct_stock(...), selectors.below_reorder_level()
1workshops, notificationsWorkshop, Mechanic / Notificationselectors.open_workshops() / services.queue(kind, channel, recipient, reference_id)
0accountsUserthe user model, via get_user_model()

Two apps share a rung where they must not know each other: customers and parts have nothing to say to one another, and neither do api and reporting. Each public interface is two plain modules, services.py for things that change data and selectors.py for things that read it. The names come from the HackSoft styleguide discussed below. What matters is not the name but that there is exactly one front door per app.

New app or existing app: the decision at two years

By the third year the question is "does this new feature get its own app?". The structure chapter gave the "who would you ring" test for placing code. With a ladder, the question gets sharper, because a new app has to find a rung.

Three questions decide it, in this order:

  1. Does the feature own data that no existing app owns? If not, it belongs in the app that owns the data, however big it feels.
  2. Can it sit on one rung, importing only from below? If it needs something from an app above it, that shared piece is in the wrong place. Move it down first.
  3. Will it change for different reasons, or for different people, than its neighbours? If it changes whenever bookings change, it is part of bookings.
Tap or click to enlarge

Example: invoicing gets an app, notifications loses a foreign key

In the spike, invoices lived inside repairs, because an invoice was simply "the bill for a job card". By the second year invoicing has its own rules: VAT at 23%, credit notes, sequential numbering, a monthly export for the accountant and the VAT return to Revenue. It owns data nobody else owns, it imports from repairs (below it) and never the other way, and it changes when the accountant asks, not when the workshop lead does. Three yes answers: a new app.

The notifications app is the opposite case, and it shows the hidden arrow. When the background tasks chapter built the "your bike is ready" letter, Notification had a foreign key to repairs.JobCard, while repairs.services imported notifications. One arrow down as an import, one arrow up as a relation: a cycle no import tool would report. Two years on, invoices want to send emails too, and they would have needed a second foreign key. The fix is to make notifications know nothing about the apps that use it:

# notifications/models.py
from django.db import models


class Notification(models.Model):
    class Channel(models.TextChoices):
        EMAIL = "email", "Email"
        SMS = "sms", "SMS"

    kind = models.CharField(max_length=40)          # "bike_ready", "invoice_issued", ...
    channel = models.CharField(max_length=10, choices=Channel)
    recipient = models.CharField(max_length=254)    # an email address or a phone number
    reference_id = models.PositiveBigIntegerField() # the id of whatever it is about
    sent_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        constraints = [
            # One message per thing, kind and channel, ever: the rule from the tasks chapter
            models.UniqueConstraint(
                fields=["kind", "reference_id", "channel"], name="one_notification_per_subject"
            ),
        ]

Notifications moved to the bottom of the ladder, and both repairs and invoicing can use it without it knowing either of them.

Moving a model between apps without moving the data

Apps are easy to create and awkward to change later, and the reason is concrete. A model's app label is baked into two places: its database table name (by default appname_modelname) and the migration history, which records every model under the app it was created in. Move the class to another folder and makemigrations concludes that you deleted one model and created another. Run that against production and it drops the table.

The tool for doing it safely is SeparateDatabaseAndState, a migration operation that lets you tell Django's model state one thing and the database another, or nothing at all2. The trick is to keep the existing table, point Django's state at the new app, and run no SQL. One more detail: Django keeps a row per model in the content types table, which the permission system and generic relations use. After the move, the old rows are stale, and remove_stale_contenttypes cleans them up, deleting anything that still depends on them, so read its list before you confirm3.

Example: customers move out of bookings

In the ORM chapter, Customer and Bike lived in bookings, because in the spike a customer only existed to book. Two years on, customers have accounts, saved bikes, marketing consent and a history across invoices. They now change for their own reasons, so Aisling gives them their own app, without touching a single row.

First the new home. The db_table option keeps the old table names:

# customers/models.py
from django.db import models


class Customer(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField(unique=True)

    class Meta:
        db_table = "bookings_customer"  # the table keeps its old name


class Bike(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="bikes")
    make = models.CharField(max_length=100)

    class Meta:
        db_table = "bookings_bike"

The new app's first migration creates the models in Django's state only:

# customers/migrations/0001_initial.py
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
    initial = True
    dependencies = [("bookings", "0029_booking_updated_at")]  # the latest bookings migration

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.CreateModel(
                    name="Customer",
                    fields=[
                        ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                        ("name", models.CharField(max_length=200)),
                        ("email", models.EmailField(max_length=254, unique=True)),
                    ],
                    options={"db_table": "bookings_customer"},
                ),
                migrations.CreateModel(
                    name="Bike",
                    fields=[
                        ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                        ("make", models.CharField(max_length=100)),
                        ("customer", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="bikes", to="customers.customer")),
                    ],
                    options={"db_table": "bookings_bike"},
                ),
            ],
            database_operations=[],  # the tables already exist: run no SQL at all
        ),
    ]

Then bookings points its foreign keys at the new home and forgets the old models, again in state only. Booking now says models.ForeignKey("customers.Customer", ...) in bookings/models.py, and the migration matches it:

# bookings/migrations/0030_move_customer_and_bike.py
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
    dependencies = [
        ("bookings", "0029_booking_updated_at"),
        ("customers", "0001_initial"),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.AlterField(
                    model_name="booking",
                    name="customer",
                    field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="bookings", to="customers.customer"),
                ),
                migrations.AlterField(
                    model_name="booking",
                    name="bike",
                    field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="bookings", to="customers.bike"),
                ),
                # Bike first, because it points at Customer
                migrations.DeleteModel(name="Bike"),
                migrations.DeleteModel(name="Customer"),
            ],
            database_operations=[],
        ),
    ]

Aisling checks three things before she opens the pull request. python manage.py sqlmigrate customers 0001 and sqlmigrate bookings 0030 both print no SQL. python manage.py makemigrations --check reports "No changes detected", so the state matches the models. And a fresh test database builds from scratch.

Two loose ends remain. Groups with the permission bookings.change_customer now need customers.change_customer, which a short data migration can copy. And the tables keep their old names, which is fine: renaming them later is one AlterModelTable operation, if anyone ever cares.

Circular imports between apps, and what they are telling you

The first symptom of a tangled project is often an error at startup: ImportError: cannot import name 'JobCard' from partially initialized module 'repairs.models' (most likely due to a circular import). Two apps import each other, and Python meets one of them half loaded.

There are four ways to make the error go away, and only one of them fixes the cause:

  • A string reference in the model. ForeignKey("parts.Part", ...) instead of importing Part. Correct for relations, and it is how Django intends cross app relations to be written.
  • An import inside the function. It works, and it hides the cycle from the next reader. I treat it as a note that says "the design is wrong here".
  • apps.get_model("parts", "Part") at call time. Useful in migrations and in truly generic code, the same smell as the previous one elsewhere.
  • Moving the shared piece down a rung. The fix. A cycle between two apps means one of them is holding something that both need, and that thing belongs below both.

Example: the reorder rule that lived in the wrong app

The import cycle at Freewheel comes from one function. parts decides which parts to reorder, and somebody added "but never reorder a part that has an open job card waiting for it", which made parts import repairs.models. Meanwhile repairs imports parts to record which part was fitted. A cycle.

The question "who owns this rule?" answers it. The rule is about demand from repairs, so it belongs to repairs, which may import parts. parts keeps a plain selector that returns what is low on stock, and repairs offers a selector for parts already reserved by open job cards. The nightly report sits in reporting, at the top, and combines the two:

# reporting/reorder.py
from parts.selectors import below_reorder_level
from repairs.selectors import reserved_part_quantities


def reorder_list():
    reserved = reserved_part_quantities()  # {part_id: quantity on open job cards}
    return [
        part
        for part in below_reorder_level()
        if part.stock_quantity - reserved.get(part.pk, 0) < part.reorder_level
    ]

No import inside a function, no get_model, and the cycle is gone because each app only imports from below.

Where the logic lives: fat models, services, or neither

A growing project has to decide where business rules live, and the Django community genuinely disagrees. It is worth hearing the three positions in their own words before choosing.

Fat models. Django's design philosophies say models should "encapsulate every aspect of an 'object'", following Martin Fowler's Active Record pattern4. James Bennett, a long standing Django contributor, argued in March 2020 that a separate service layer is "probably not what you want in Django apps": it adds indirection for a database swap that almost never happens, and it fights the ORM, generic views and forms. His advice is to put the logic on models, managers and QuerySets5.

Services and selectors. The Django Styleguide published by HackSoft, a software company, takes the opposite view: "Services are where business logic lives."6 Services are functions that write, selectors are functions that read, and the guide lists the places logic should not live: views and APIs, serializers and forms, a model's save(), custom managers and QuerySets, and signals. Model properties and clean() are allowed for simple things that touch only the model's own fields.

Fat views. Nobody defends this one, and it is the most common in practice, because a view is where code starts. The problem is plain: a rule in a view is not there when the same thing happens from the admin, the JSON API, a Celery task or a management command.

My view: both written positions are right about different things, and the line between them is whose data a rule touches. A rule about one model and its own fields belongs on the model or its QuerySet, exactly as Bennett says: Booking.objects.for_day(day), job_card.can_be_collected(). A rule that changes data in two apps, or calls the outside world, belongs in a service function of the app that owns the use case, because no single model owns it. That gives you HackSoft's front door without wrapping every .filter() in a function. The front end chapter counted the doors through which a rule can be broken. That count is what makes a fat view wrong.

Example: marking a bike ready, two apps, one front door

When a mechanic marks a card ready, three things must happen: the status changes, fitted parts leave the stock, and the customer is told. Status and stock live in two apps. That makes it a service in repairs, the app that owns the use case:

# repairs/services.py
from django.db import transaction

from notifications import services as notifications
from parts import services as parts

from .models import JobCard


def mark_ready(job_card_id):
    with transaction.atomic():
        card = JobCard.objects.select_for_update().select_related("booking__customer").get(pk=job_card_id)
        if not card.can_be_marked_ready():  # a rule about the card alone: on the model
            return card
        card.status = JobCard.Status.READY
        card.save(update_fields=["status", "updated_at"])

        for usage in card.part_usages.all():
            # Down the ladder: repairs may call parts, never the other way
            parts.deduct_stock(part_id=usage.part_id, quantity=usage.quantity)

        notifications.queue(
            kind="bike_ready",
            channel="email",
            recipient=card.booking.customer.email,
            reference_id=card.pk,
        )  # writes the letter, and queues delivery on commit
    return card

The view, the admin action, the API endpoint and the mechanics' app all call mark_ready(). There is one place to read what "ready" means, and one place to test it. updated_at is in update_fields because auto_now only updates on save() with that field included, a detail that matters for caching later.

Signals: the one arrow that may point up

Django's signals let one piece of code announce that something happened and let others react, without the sender knowing who listens. The documentation is unusually blunt about them: "Signals give the appearance of loose coupling, but they can quickly lead to code that is hard to understand, adjust and debug," and where possible you should call the handling code directly7. HackSoft's guide agrees, allowing signals for things like cache invalidation but not for structuring business logic6.

On the ladder, the useful rule falls out by itself. If the receiver sits below the sender, the sender may simply import it and call it: that is an ordinary arrow pointing down, so use a function. If the receiver sits above the sender, the sender must not know it exists. That is the one case where a signal earns its place: news travelling up the ladder. The documentation also says where to connect receivers: in the ready() method of the app's configuration, from a separate module, not in models.py7. Django 5.0 added asynchronous receivers and asend(), which you will not need for this8.

Example: the stock receiver that had to go, and the one that stays

The bug in Niamh's first complaint came from a post_save receiver on JobCard, living in parts, that deducted stock whenever a card's status became "ready". When invoicing started saving job cards a second time to stamp the invoice number, the receiver ran again. Stock was deducted twice. Nothing in invoicing mentioned stock, so nobody looked there.

That receiver pointed the wrong way: parts sits below repairs, so repairs can call it directly, which mark_ready() above now does. The receiver is deleted.

The signal that stays goes up. When a text message finally fails after all its retries, the workshop board should show "customer not reached" on the card. notifications is at the bottom and must not know what a job card is, so it announces the failure, and repairs listens:

# notifications/signals.py
from django.dispatch import Signal

# Sent when a notification gives up for good. Keyword argument: notification
delivery_failed = Signal()
# repairs/receivers.py
from django.dispatch import receiver

from notifications.signals import delivery_failed

from .models import JobCard


@receiver(delivery_failed, dispatch_uid="repairs_flag_unreached_customer")
def flag_unreached_customer(sender, notification, **kwargs):
    if notification.kind == "bike_ready":
        JobCard.objects.filter(pk=notification.reference_id).update(customer_unreached=True)
# repairs/apps.py
from django.apps import AppConfig


class RepairsConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "repairs"

    def ready(self):
        from . import receivers  # noqa: F401  connects the receivers once

The import in receivers.py points down, from repairs to notifications, and the news travels up. Both kinds of arrow now agree with the ladder.

Make the ladder checked: import rules and an architecture test

A ladder on a whiteboard lasts until the first deadline. It needs a check that fails the build. For imports there is a good tool: Import Linter, a command line tool by David Seddon that checks the imports in your project against "contracts" you write in a configuration file9. Version 2.0, released on 9 January 2024, is current10. A layers contract says higher layers may import lower ones but never the reverse, indirect chains included. Two modules on the same line separated by | are independent of each other, and since 2.0 a : makes siblings that may import each other9. A forbidden contract bans specific modules.

Import Linter reads imports, so it cannot see the string references in your models. For those, Django's model registry is the source of truth: every field knows whether it is_relation and what its related_model is11. Ten lines of test turn that into a check.

Example: Freewheel's two checks

Django apps are top level packages, so each one is listed as a root package:

# .importlinter
[importlinter]
root_packages =
    api
    reporting
    invoicing
    repairs
    bookings
    customers
    parts
    workshops
    notifications
    accounts

[importlinter:contract:ladder]
name = Apps import only from apps below them
type = layers
layers =
    api | reporting
    invoicing
    repairs
    bookings
    customers | parts
    workshops | notifications
    accounts

[importlinter:contract:front-doors]
name = Other apps use services and selectors, not views or forms
type = forbidden
source_modules =
    api
    reporting
    invoicing
    repairs
forbidden_modules =
    bookings.views
    bookings.forms
    parts.views
    parts.forms

lint-imports runs in CI next to the tests. And the relations get a test of their own:

# tests/test_architecture.py
from django.apps import apps
from django.test import SimpleTestCase

# Highest rung first. An app may relate only to apps on a lower rung.
LADDER = [
    {"api", "reporting"},
    {"invoicing"},
    {"repairs"},
    {"bookings"},
    {"customers", "parts"},
    {"workshops", "notifications"},
    {"accounts"},
]
RUNG = {label: i for i, rung in enumerate(LADDER) for label in rung}


def cross_app_relations():
    for model in apps.get_models():
        source = model._meta.app_label
        for field in model._meta.get_fields():
            # Forward relations only: ForeignKey, OneToOneField, ManyToManyField
            if not field.is_relation or field.auto_created or field.related_model is None:
                continue
            target = field.related_model._meta.app_label
            if target != source and source in RUNG and target in RUNG:
                yield source, target, f"{model.__name__}.{field.name}"


class LadderTest(SimpleTestCase):
    def test_model_relations_point_down_the_ladder(self):
        upward = [
            f"{name}: {source} -> {target}"
            for source, target, name in cross_app_relations()
            if RUNG[target] <= RUNG[source]
        ]
        self.assertEqual(upward, [])

On the first run the test fails with one line, Notification.job_card: notifications -> repairs, which is the hidden cycle from earlier. Once the foreign key is gone, both checks pass, and from then on any arrow that points up fails the build with a sentence that says exactly which one. Import Linter alone would never have reported that foreign key, which is the whole point of having two checks.

Performance: measure before you touch anything

Now Niamh's second complaint, which needs a different kind of work. Django's performance guide opens with the right instinct: you cannot guess where the time goes, you have to measure, and caching is "one of the final steps", not a shortcut12. The database guide says the same about queries: profile first, then optimise13.

The tools, from the laptop to production:

  • Django Debug Toolbar shows, per page, every SQL query with its time and the line that caused it, plus templates, cache calls and signals. Version 4.3.0 from February 2024 supports Django 5.014. It belongs in development only.
  • django silk records requests and their queries into the database and shows them in a small interface at /silk/, and can profile a block of code with Python's built in cProfile15. It stores request and response bodies by default, so set size limits and authentication before you let it near real traffic.
  • assertNumQueries in Django's test tools fails a test when a block of code runs a different number of queries than you state16. It turns a performance fix into a promise.
  • An application performance monitoring (APM) service in production, because no laptop looks like Saturday morning. AppSignal, Datadog, New Relic and Scout APM all instrument Django and show the slowest views, the slowest queries and how they change over time. They differ in price, depth and where they host your data, which matters for your duties under the GDPR, so compare them on those. Any of them does the measuring.

A simple model of one page's server time keeps the investigation honest. It is the same model the Rails chapter used, so the numbers can be compared:

T=nq⋅tˉq+Ttpl+TotherT = n_q \cdot \bar{t}_q + T_{\text{tpl}} + T_{\text{other}}

where TT is the total server time, nqn_q is the number of SQL queries, tˉq\bar{t}_q is the average time per query, TtplT_{\text{tpl}} is the time spent rendering templates, and TotherT_{\text{other}} is everything else, from middleware to Python object creation. Averages like tˉq\bar{t}_q are explained in Foundations: ratios and rates.

Example: profiling the day overview

The day overview lives in reporting, at the top of the ladder, because it reads from every app below. Aisling opens it locally with Debug Toolbar on and a masked copy of production data. The numbers are invented for the example and consistent with the facts above. The view:

# reporting/views.py (before)
from datetime import date

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from workshops.models import Workshop


@login_required  # the manager check is in the security chapter
def day_overview(request):
    day = date.fromisoformat(request.GET["date"]) if "date" in request.GET else date.today()
    sections = [
        # A lazy QuerySet per workshop: each runs when the template loops over it
        {"workshop": w, "bookings": w.bookings.filter(starts_at__date=day).order_by("starts_at")}
        for w in Workshop.objects.order_by("name")
    ]
    return render(request, "reporting/day_overview.html", {"day": day, "sections": sections})
<!-- reporting/templates/reporting/_booking_row.html -->
<p>
  {{ booking.starts_at|time:"H:i" }} {{ booking.customer.name }}, {{ booking.bike.make }},
  {{ booking.mechanic.display_name }}, {{ booking.job_card.get_status_display }}
</p>

The toolbar shows 2,083 queries. One for the workshops, one per workshop for its bookings, and four per booking, because each row asks for the customer, the bike, the mechanic and the job card, and each of those is a separate query the first time it is touched:

nq=1+14+4×517=2,083n_q = 1 + 14 + 4 \times 517 = 2{,}083

Here 11 counts the workshops, 1414 the per workshop booking lists, and 44 the related records of each of the 517517 bookings. At an average of tˉq=0.6 ms\bar{t}_q = 0.6\,\text{ms} per query:

nq⋅tˉq=2,083×0.6 ms≈1,250 msn_q \cdot \bar{t}_q = 2{,}083 \times 0.6\,\text{ms} \approx 1{,}250\,\text{ms}

Here nq=2,083n_q = 2{,}083 is the query count and tˉq=0.6 ms\bar{t}_q = 0.6\,\text{ms} the average time per query, so nq⋅tˉqn_q \cdot \bar{t}_q is the database share of the page.

With 1,300ms of template rendering and 250ms of everything else, the model gives exactly the 2.8 seconds Niamh complained about (Foundations: ratios and rates). Every single query is fast. There are just two thousand of them.

This is the N+1 problem, and the ORM chapter explained it from first principles. The fix is to load related records with the list. select_related() follows foreign keys and one to one relations, including the reverse side of a OneToOneField, with a SQL join in the same query. prefetch_related() fetches many to many and reverse foreign key sets with one extra query each, and joins them in Python17.

A boundary question hides here. Traversing from Booking to its job_card crosses from bookings into repairs. That is fine in reporting, which sits above both. It would not be fine inside bookings, which must not know job cards exist. The ladder tells you where a join is allowed.

Example: from 2,083 queries to two

The query moves into a selector in reporting, and it filters by a time range instead of starts_at__date, the index lesson from the ORM chapter:

# reporting/selectors.py
from datetime import datetime, time, timedelta

from django.utils import timezone

from bookings.models import Booking
from workshops.models import Workshop


def _last_change(booking):
    card = getattr(booking, "job_card", None)  # None while no card exists yet
    return max(booking.updated_at, card.updated_at) if card else booking.updated_at


def day_overview(day):
    """Workshops with their bookings for one day, in two queries."""
    start = timezone.make_aware(datetime.combine(day, time.min))
    end = start + timedelta(days=1)
    bookings = (
        Booking.objects.filter(starts_at__gte=start, starts_at__lt=end, cancelled_at__isnull=True)
        # One query with joins, instead of four more queries per booking
        .select_related("customer", "bike", "mechanic", "job_card")
        .order_by("starts_at")
    )
    by_workshop = {}
    for booking in bookings:
        by_workshop.setdefault(booking.workshop_id, []).append(booking)

    return [
        {
            "workshop": workshop,
            "bookings": by_workshop.get(workshop.pk, []),
            # Used by the cache key below: changes when a row or its job card changes
            "version": max((_last_change(b) for b in by_workshop.get(workshop.pk, [])), default=None),
        }
        for workshop in Workshop.objects.order_by("name")
    ]

Two queries, whatever the number of bookings: one for the bookings with everything joined, one for the workshops. When Freewheel opens its 20th workshop, the count stays at two. A test makes sure it stays there:

# reporting/tests/test_day_overview.py
from datetime import date

from django.template.loader import render_to_string
from django.test import TestCase

from reporting.selectors import day_overview
from .factories import make_busy_day  # builds three workshops with bookings


class DayOverviewQueryTest(TestCase):
    def test_two_queries_however_busy_the_day(self):
        make_busy_day(date(2024, 5, 18), workshops=3, bookings_each=5)
        with self.assertNumQueries(2):
            sections = day_overview(date(2024, 5, 18))
            render_to_string(
                "reporting/day_overview.html", {"sections": sections, "day": date(2024, 5, 18)}
            )

The rendering sits inside the assertNumQueries block on purpose. If someone later adds {{ booking.customer.preferred_workshop.name }} to the row, the test fails before a manager ever notices. The toolbar now reads about 1,670ms: the database part dropped to around 120ms, and 110ms of that is the one bookings query.

Fix the slow query: an index, built without locking the table

The remaining bookings query reads too much of the table, because the existing index from the ORM chapter starts with the workshop, and this page asks for all workshops at once. QuerySet.explain() on realistic data shows a scan, and the answer is an index on starts_at.

On a live PostgreSQL database, a normal CREATE INDEX blocks writes to the table while it builds, and on Saturday morning that means blocked bookings. AddIndexConcurrently, from django.contrib.postgres, builds the index with PostgreSQL's CONCURRENTLY option instead, which does not lock out writes18. PostgreSQL does not allow that inside a transaction, so the migration must set atomic = False19.

Example: the index migration

# bookings/migrations/0031_booking_starts_at_idx.py
from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import migrations, models


class Migration(migrations.Migration):
    atomic = False  # CREATE INDEX CONCURRENTLY cannot run inside a transaction

    dependencies = [("bookings", "0030_move_customer_and_bike")]

    operations = [
        AddIndexConcurrently(
            "booking", models.Index(fields=["starts_at"], name="booking_starts_at_idx")
        ),
    ]

The same models.Index goes into Booking.Meta.indexes, so the state and the models agree. After the deploy, explain() shows an index scan, and the database part of the page is about 25ms. The page is at roughly 1,575ms, and almost all of what is left is template rendering.

Fix the rendering: template fragment caching, and what it cannot do

Rendering 517 rows takes time even when every row is already in memory. Django's template fragment cache stores a rendered piece of a template under a name plus any values you give it: {% cache timeout name value1 value2 %}, after {% load cache %}20. Change any of the values and you get a different key, so the old fragment is simply never read again.

Django has no equivalent of Rails' touch: true, which updates a parent's timestamp when a child changes. So the key has to carry the freshness itself, which is why the selector above computes a version from both the booking's and the job card's updated_at. One trap: auto_now fields update only on Model.save(), not on QuerySet.update()21. A bulk status change through .update() must set updated_at itself, or the page will show stale cards.

And the honest limit, as in the Rails chapter: caching saves rendering, not queries. The key needs the bookings, so the two queries still run. A cache on top of 2,083 queries would still run 2,083 queries. That is why the query fix came first.

Example: caching each workshop's section

<!-- reporting/templates/reporting/day_overview.html -->
{% load cache %}
{% for section in sections %}
  {% cache 86400 day_overview_workshop section.workshop.pk day section.version section.bookings|length %}
    <h2>{{ section.workshop.name }}</h2>
    {% for booking in section.bookings %}
      {% include "reporting/_booking_row.html" %}
    {% empty %}
      <p>No bookings yet.</p>
    {% endfor %}
  {% endcache %}
{% endfor %}

The key is the workshop, the day, the newest change and the number of bookings (so a cancellation also changes it). Cian notices a business decision hidden in it: a customer who changes their name will see the old one on today's overview until their booking changes. Niamh decides that is grand for an internal screen. The developer finds the trade off, the business decides it.

How fast is the page now? A fresh fragment costs about 2ms to fetch, a stale one about 93ms to render (1,300ms over 14 workshops). Between two views a few minutes apart, about 1.5 of the 14 fragments are stale on average:

Ttpl=12.5×2 ms+1.5×93 ms≈165 msT_{\text{tpl}} = 12.5 \times 2\,\text{ms} + 1.5 \times 93\,\text{ms} \approx 165\,\text{ms}

Here TtplT_{\text{tpl}} is the template time, 12.512.5 fresh fragments cost 2 ms2\,\text{ms} each and 1.51.5 stale ones cost 93 ms93\,\text{ms} each. That is an expected value, an average over many views (Foundations: expected value). The page total is about 25 + 165 + 250 = 440ms, down from 2,800. The 250ms of "other" is the next thing to profile, if it ever matters. Niamh's complaint is sorted.

Bar chart of server time in milliseconds for the invented Freewheel day overview in Django. Before: 2,800. After select_related: 1,670. After the starts_at index: 1,575. After template fragment caching: 440. Query count falls from 2,083 to two at the first step. Tap or click to enlarge

Four kinds of cache, one question: how stale may this be?

Django ships several caches, and a growing project usually needs more than one. The backends come built in: Redis, Memcached, the database, files and local memory, with a dummy cache for development20. The levels differ in what they store:

LevelWhat it storesUse it forWatch out for
Per site (middleware)every anonymous GET and HEAD response with status 200small public sitesanything personal, anything with forms
Per view, cache_pageone view's whole response, keyed by URL20public pages the same for everyonea page that differs by user or permission
Template fragment, {% cache %}a rendered piece of a templateexpensive pieces of personal pagesa key that misses what changes the fragment
Low level, cache.get_or_set()any picklable valuecomputed numbers, lists of idscaching whole model instances across deploys
cached_propertya value on one Python object, for that object's life22computing something twice in one requestit never expires while the object lives

The table hides the question that decides every row. Not "what is slow?" but "how stale may this be?". The answer is a business answer, and it sets the timeout or the key. One more thing worth checking: Django wraps its default template loaders in the cached loader automatically, so templates are compiled once per process. If someone set loaders by hand in TEMPLATES, they may have switched that off23.

Example: the totals at the top of the overview

Each workshop's section shows booked hours and expected takings. They are aggregate queries, and Niamh says ten minutes of delay is fine. That is a timeout, so a low level cache with a ten minute expiry fits:

# reporting/selectors.py (continued)
from django.core.cache import cache
from django.db.models import Count, Sum


def day_totals(workshop_id, day):
    key = f"day_totals:{workshop_id}:{day.isoformat()}"

    def compute():
        start = timezone.make_aware(datetime.combine(day, time.min))
        return Booking.objects.filter(
            workshop_id=workshop_id,
            starts_at__gte=start,
            starts_at__lt=start + timedelta(days=1),
            cancelled_at__isnull=True,
        ).aggregate(bookings=Count("id"), quoted=Sum("quoted_price"))

    # Ten minutes is Niamh's answer to "how stale may this be?"
    return cache.get_or_set(key, compute, timeout=600)

The public "workshops and opening times" page is the same for everyone and changes a few times a year, so it gets @cache_page(60 * 60). The manager's page never does: it differs by user. And inside the invoice PDF code, Invoice.vat_amount is a cached_property, because the template reads it six times and it never changes while that one invoice object is in memory.

Async Django: a tool for waiting, not for computing

Django can run views as coroutines: declare the view with async def, and since Django 4.1 the ORM has an asynchronous interface, every query method with an a prefix and async for over QuerySets24. Django 5.0 added request.auser(), aget_object_or_404() and async signal receivers, and made common decorators such as never_cache and require_POST work with async views8.

The documentation is also clear about the limits, and they decide whether async helps you at all:

  • The ORM is async in interface, not yet underneath. The 4.1 release notes say the underlying database operations "remain synchronous". The async methods wrap the necessary sync_to_async() calls for you25.
  • Transactions do not work in async code. Put transactional work in a synchronous function and call it with sync_to_async()26.
  • ASGI is needed for the big win. Async views run under WSGI too, in a one off event loop per request, "with performance penalties". The real benefit of serving hundreds of open connections without threads, for streaming and long polling, needs an ASGI server, and only if no synchronous middleware sits in the stack24.

So here is my rule of thumb. Async pays when one request waits for several slow things that can wait at the same time. Without async, the waits add up. With async, the request waits about as long as the slowest one:

Tsync=∑i=1kwiTasync≈max⁡iwiT_{\text{sync}} = \sum_{i=1}^{k} w_i \qquad\qquad T_{\text{async}} \approx \max_{i} w_i

where kk is the number of independent waits in one request and wiw_i is the duration of wait ii, such as a call to another company's API (Foundations: ratios and rates). With one wait, k=1k = 1, both are the same and async buys nothing. A database query that the next query depends on is not independent either. The day overview has two dependent database queries and no outside calls, so async would not make it a millisecond faster.

Example: asking three suppliers at once

Two years on, the parts screen has a button: "check suppliers". It asks three suppliers' stock APIs whether they have a part. Each answers in about 350 to 450ms. As a normal view the waits add up to about 1.2 seconds. As an async view they overlap:

# parts/views.py
import asyncio

import httpx
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.shortcuts import aget_object_or_404

from .models import Part

SUPPLIER_STOCK_URLS = [  # invented endpoints for the example
    "https://api.supplier-one.example/stock",
    "https://api.supplier-two.example/stock",
    "https://api.supplier-three.example/stock",
]


async def supplier_stock(request, sku):
    user = await request.auser()  # new in Django 5.0
    if not user.is_staff:
        raise PermissionDenied
    part = await aget_object_or_404(Part, sku=sku)  # new in Django 5.0

    async with httpx.AsyncClient(timeout=2.0) as client:
        # The three requests wait at the same time, not one after another
        replies = await asyncio.gather(
            *(client.get(url, params={"sku": part.sku}) for url in SUPPLIER_STOCK_URLS),
            return_exceptions=True,  # one slow supplier must not sink the answer
        )

    offers = [r.json() for r in replies if isinstance(r, httpx.Response) and r.status_code == 200]
    return JsonResponse({"sku": part.sku, "in_stock": part.stock_quantity, "offers": offers})

HTTPX is a Python HTTP client with an async interface, and version 0.27 is current27. With w=350,400,450 msw = 350, 400, 450\,\text{ms}:

Tsync=350+400+450=1,200 msTasync≈450 msT_{\text{sync}} = 350 + 400 + 450 = 1{,}200\,\text{ms} \qquad T_{\text{async}} \approx 450\,\text{ms}

Here k=3k = 3 waits of w1=350w_1 = 350, w2=400w_2 = 400 and w3=450 msw_3 = 450\,\text{ms}: TsyncT_{\text{sync}} adds them, TasyncT_{\text{async}} is close to the largest (Foundations: ratios and rates).

And Freewheel does not need to move to ASGI for this. The view runs under its existing WSGI server and still overlaps the three calls inside the request. ASGI would only matter if the board started holding hundreds of connections open, which the board's htmx polling does not do.

Database connections: persistent, pooled, and counted

By default Django opens a database connection for each request and closes it at the end. CONN_MAX_AGE keeps connections open for reuse: a number of seconds, or None for no limit, and the performance guide notes that opening connections can be a significant part of request time12. Two details from the database reference matter as the project grows28:

  • Each thread keeps its own connection, so the database must accept at least as many connections as you have worker threads. Do not enable persistent connections in development, where the development server starts a thread per request.
  • CONN_HEALTH_CHECKS = True checks a reused connection once per request before using it, so a database restart does not turn into a burst of errors.

Django 5.0 has no connection pool of its own for PostgreSQL. The common answer is PgBouncer, a separate pooler that many application connections share. In its transaction pool mode, a server connection goes back to the pool after each transaction, and its default pool size is 20 connections per user and database pair29. Django's documentation says that transaction pooling needs DISABLE_SERVER_SIDE_CURSORS = True, because consecutive transactions may land on different server connections and a server side cursor from .iterator() would break28.

Example: the Saturday deploy that ran out of connections

The arithmetic is simple, and it is the part most teams never write down. The connections a Django deployment holds open with persistent connections are:

C=s⋅p⋅t+cworker+cotherC = s \cdot p \cdot t + c_{\text{worker}} + c_{\text{other}}

where ss is the number of web servers, pp the Gunicorn worker processes per server, tt the threads per process (Gunicorn's --threads setting30), cworkerc_{\text{worker}} the Celery worker processes, and cotherc_{\text{other}} everything else: the scheduler, admin shells, monitoring. Each term is a count, multiplied or added as in Foundations: ratios and rates.

Freewheel runs two web servers with three processes and four threads each, and four on Saturday mornings. Celery has 16 worker processes, and about six other connections are open at any time. The managed PostgreSQL plan allows 75 connections (an invented figure for the example, while PostgreSQL's own default max_connections is typically 10031):

Cweekday=2⋅3⋅4+16+6=46CSaturday=4⋅3⋅4+16+6=70C_{\text{weekday}} = 2 \cdot 3 \cdot 4 + 16 + 6 = 46 \qquad C_{\text{Saturday}} = 4 \cdot 3 \cdot 4 + 16 + 6 = 70

Here s=2s = 2 or 44 servers, p=3p = 3 processes, t=4t = 4 threads, cworker=16c_{\text{worker}} = 16 and cother=6c_{\text{other}} = 6.

Seventy fits under 75. But a deploy starts the new servers before stopping the old ones, so for a minute there are eight:

Cdeploy=8⋅3⋅4+16+6=118C_{\text{deploy}} = 8 \cdot 3 \cdot 4 + 16 + 6 = 118

with s=8s = 8 for that minute and every other term unchanged.

That is the "too many connections" error Cian saw at 10.40am one Saturday. With PgBouncer in transaction mode in front of PostgreSQL, the servers can open as many client connections as they like, and PostgreSQL sees the pool: 20 connections, plus a few direct ones for migrations and admin work.

Is 20 enough? Little's law says the average number of things in a system equals the arrival rate times the time each one spends inside32. Say the Saturday peak is 40 requests a second, each holding a transaction for about 50ms on average:

L=λW=40 requestss×0.05 s=2L = \lambda W = 40\,\tfrac{\text{requests}}{\text{s}} \times 0.05\,\text{s} = 2

where LL is the average number of transactions open at once, λ\lambda the requests per second and WW the time each spends in a transaction (Foundations: ratios and rates). Two on average, so a pool of 20 has plenty of room for bursts. The lesson is that connections held open and connections in use are very different numbers.

Bar chart for the invented Freewheel example. Without a pooler, PostgreSQL holds 46 connections on a weekday, 70 on a Saturday and 118 during a Saturday deploy, against a plan limit of 75. Behind PgBouncer in transaction mode it holds about 26: a pool of 20 plus about six direct connections. Tap or click to enlarge

Read replicas with a router, and pagination that stays fast

Replicas. A read replica is a copy of the database that follows the primary and only accepts reads. Django supports several databases through the DATABASES setting and database routers: classes whose db_for_read, db_for_write, allow_relation and allow_migrate methods choose a database per query, listed in DATABASE_ROUTERS33. The documentation's own primary and replica router picks a random replica for every read, and it warns that the example does nothing about replication lag: a read straight after a write may not see it yet. Django does not route to replicas by itself. For tests, a replica entry can declare "TEST": {"MIRROR": "default"}, so tests read and write one database34.

Pagination. Any list that grows with the business needs it. Django's Paginator slices a QuerySet and calls count() to know how many pages there are35. On a few hundred thousand rows, that count and a deep OFFSET both get slower as the page number rises. For a screen people page through by hand that is fine. For the JSON API, keyset pagination, "give me the 50 after this id", stays fast at any depth.

Example: the monthly report on the replica

The monthly revenue report scans two years of invoices, about 220,000 by my estimate. Cian does not want every read in the project sent to a replica that may be a second behind. So the router only guards, and the reporting selectors ask for the replica explicitly:

# freewheel/db_routers.py
class PrimaryReplicaRouter:
    """Everything uses the primary unless a query says .using("replica")."""

    def db_for_read(self, model, **hints):
        return None  # no opinion: Django falls back to "default"

    def db_for_write(self, model, **hints):
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True  # same data on both databases

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return db == "default"  # never migrate the replica
# freewheel/settings.py (production, shortened)
DATABASES = {
    "default": env.db("DATABASE_URL"),
    "replica": {**env.db("REPLICA_DATABASE_URL"), "TEST": {"MIRROR": "default"}},
}
DATABASE_ROUTERS = ["freewheel.db_routers.PrimaryReplicaRouter"]
# reporting/selectors.py (continued)
from django.db.models.functions import TruncMonth

from invoicing.models import Invoice


def monthly_revenue(since):
    return (
        Invoice.objects.using("replica")  # a report may be a second behind
        .filter(issued_at__gte=since)
        .annotate(month=TruncMonth("issued_at"))
        .values("month")
        .annotate(net=Sum("net_amount"), vat=Sum("vat_amount"))
        .order_by("month")
    )

What may read slightly old data is now visible in the code, in the one app allowed to decide it.

Upgrading across LTS versions without a cliff

A big project upgrades less often than it should, because every upgrade touches everything. Django 5.0.6 and 4.2.13 are the current releases. Django 4.2 LTS has security support until April 2026, Django 5.0 until April 2025, and the roadmap plans 5.1 for August 2024 and 5.2 LTS for April 2025, supported until April 202836. The five years chapter did the money side. Here is the craft side.

Django's upgrade guide is short and firm: read the release notes for every version in between, resolve deprecation warnings on your current version first, with python -Wa manage.py test because Python hides them by default, and upgrade one feature release at a time. "The same incremental upgrade approach is recommended when upgrading from one LTS to the next."37 Adam Johnson's django-upgrade tool rewrites many old idioms for a target version automatically38.

Boundaries help here in a way people rarely mention. A third party package used by one app is a one app problem during an upgrade. A package used everywhere blocks the whole project until it supports the new version.

Example: Freewheel's upgrade map

Cian lists every Django related package and the apps that import it:

PackageUsed byUpgrade risk
Django REST Frameworkapi onlycontained: one app to test
Celerynotifications, parts, repairs tasksthree apps, small surface
django storagesrepairs (photos)contained
django htmxrepairs (the board)contained
a calendar widget packagetemplates in four appswide: it blocks every upgrade

The last row is the one to fix before an upgrade, not during it. Aisling wraps the widget in one template include in workshops, so the other three apps stop touching the package. Then the upgrade rule writes itself: every feature release, in its first month, after the warnings are clean, one release at a time. On that rhythm the step from 4.2 to 5.2 is two small upgrades the team has already done, not one big one it has been dreading.

Rails and Django side by side

The Rails chapter took the same application through the same growth. The tools differ, the ideas mostly do not:

JobRails 7.1Django 5.0
Unit of boundarya namespace, later a pack or an enginean app
Checking boundariespackwerkImport Linter plus a model registry test
Hidden couplingcallbacks reaching into other areassignals and string foreign keys
Moving a modelrename, a migration for polymorphic typesSeparateDatabaseAndState, same table
Profiling in developmentthe log line, rack mini profilerDjango Debug Toolbar, django silk
N+1 guardstrict_loading, BulletassertNumQueries
Eager loadingincludesselect_related, prefetch_related
Fragment cachingRussian doll with touch: true{% cache %} with a version in the key
Low level cacheRails.cache.fetchcache.get_or_set
Replicasconnects_to, automatic role switchingrouters, explicit using()
Connectionsa pool per process, sized in database.yml39one per thread, PgBouncer for pooling

Rails makes more of these decisions for you by default. Django asks you to make them, and documents the consequences clearly.

For the person paying for this

If you own a Django application two or more years old, you can judge whether it is growing well without reading the code. Ask for these, every quarter:

QuestionA healthy answer
Is there a picture of which apps may use which?yes, and a check in CI fails when someone breaks it
How long does CI take?under 10 minutes, and falling
What are the five slowest pages?named, measured, each with a plan
How many connections can the database take, and how many does the busiest hour use?both numbers, with room between them
Which Django version does it run on, and when does its support end?a date, and an upgrade planned well before it

A team that answers these without a week of preparation is in control. A proposal to split into separate services that cannot point to a measured problem here is a proposal to spend money on a feeling.

I build and look after web applications on Ruby on Rails, not Django, so for work inside a Django codebase you want a Django specialist. What I can do is help you ask the right questions before you build or rebuild. That is what the free workshop is for, and if you decide to build on Rails, my web application development page shows how I work: tests first, and the code, accounts and data stay yours.

Conclusion

A Django project that gets big needs two different kinds of work. To stay easy to change, its apps need a ladder: apps that depend on nothing at the bottom, apps that read everything at the top, and every import, every foreign key and every signal receiver pointing down, with signals kept for the one job of sending news up. Import Linter checks the imports, a ten line test checks the relations, and SeparateDatabaseAndState lets you move a model to a better app without moving a single row. Put rules about one model on that model, and rules that span apps in a service of the app that owns the use case.

To stay fast, it needs measurement first and fixes in order. Queries before indexes, indexes before caching, and caching keyed on the question "how stale may this be?". In the example that order took the day overview from 2,083 queries and 2.8 seconds to two queries and about 440ms. Async helps when a request waits for several outside things at once, and not otherwise. Connections need counting, and PgBouncer turns a Saturday deploy from an outage into a non event.

The 22 minute test suite gets its own chapter at the end of the testing series, which starts next week.

If you are planning what to build next and want the boundaries and the slow pages thought through before the first line of code, book the free workshop. The first two weeks of work are on me.

Sources

  1. 1.

    Django Software Foundation, "Applications", Django 5.0 documentation, 2023. https://docs.djangoproject.com/en/5.0/ref/applications/

  2. 2.

    Django Software Foundation, "Migration Operations" (SeparateDatabaseAndState), Django 5.0 documentation, 2023. https://docs.djangoproject.com/en/5.0/ref/migration-operations/

  3. 3.

    Django Software Foundation, "django admin and manage.py" (remove_stale_contenttypes), Django 5.0 documentation, 2023. https://docs.djangoproject.com/en/5.0/ref/django-admin/

  4. 4.

    Django Software Foundation, "Design philosophies" (Models: include all relevant domain logic), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/misc/design-philosophies/

  5. 5.

    James Bennett, "Against service layers in Django", his weblog, 16 March 2020 (updated 23 March 2020). https://www.b-list.org/weblog/2020/mar/16/no-service/

  6. 6.

    HackSoft, "Django Styleguide", GitHub. https://github.com/HackSoftware/Django-Styleguide

  7. 7.

    Django Software Foundation, "Signals", Django 5.0 documentation, 2023. https://docs.djangoproject.com/en/5.0/topics/signals/

  8. 8.

    Django Software Foundation, "Django 5.0 release notes", 4 December 2023. https://docs.djangoproject.com/en/5.0/releases/5.0/

  9. 9.

    David Seddon, "Import Linter: Contract types", Import Linter documentation, version 2.0. https://github.com/seddonym/import-linter/blob/v2.0/docs/contract_types.rst

  10. 10.

    David Seddon, "Import Linter changelog" (2.0, 9 January 2024), GitHub. https://github.com/seddonym/import-linter/blob/v2.0/CHANGELOG.rst

  11. 11.

    Django Software Foundation, "Model field reference" (attributes for fields: is_relation, related_model, auto_created), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/models/fields/

  12. 12.

    Django Software Foundation, "Performance and optimisation", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/performance/

  13. 13.

    Django Software Foundation, "Database access optimisation", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/db/optimization/

  14. 14.

    Django Debug Toolbar contributors, "Change log" (4.3.0, 1 February 2024). https://django-debug-toolbar.readthedocs.io/en/latest/changes.html

  15. 15.

    Jazzband, "django silk" README, GitHub. https://github.com/jazzband/django-silk

  16. 16.

    Django Software Foundation, "Testing tools" (assertNumQueries), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/testing/tools/

  17. 17.

    Django Software Foundation, "QuerySet API reference" (select_related, prefetch_related), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/models/querysets/

  18. 18.

    Django Software Foundation, "Database migration operations" (AddIndexConcurrently), django.contrib.postgres, Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/operations/

  19. 19.

    PostgreSQL Global Development Group, "CREATE INDEX" (building indexes concurrently), PostgreSQL 16 documentation. https://www.postgresql.org/docs/16/sql-createindex.html

  20. 20.

    Django Software Foundation, "Django's cache framework", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/cache/

  21. 21.

    Django Software Foundation, "Model field reference" (DateField.auto_now and QuerySet.update), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/models/fields/#django.db.models.DateField.auto_now

  22. 22.

    Django Software Foundation, "Django Utils" (cached_property), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/utils/

  23. 23.

    Django Software Foundation, "The Django template language: for Python programmers" (cached loader), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/templates/api/

  24. 24.

    Django Software Foundation, "Asynchronous support", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/async/

  25. 25.

    Django Software Foundation, "Django 4.1 release notes" (asynchronous ORM interface), 3 August 2022. https://docs.djangoproject.com/en/5.0/releases/4.1/

  26. 26.

    Django Software Foundation, "Making queries" (asynchronous queries), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/db/queries/

  27. 27.

    Encode, "HTTPX: Async support", HTTPX documentation, version 0.27, February 2024. https://www.python-httpx.org/async/

  28. 28.

    Django Software Foundation, "Databases" (persistent connections, transaction pooling and server side cursors), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/databases/

  29. 29.

    PgBouncer project, "PgBouncer configuration" (pool_mode, default_pool_size). https://www.pgbouncer.org/config.html

  30. 30.

    Gunicorn project, "Settings" (workers, threads), Gunicorn 22.0 documentation, April 2024. https://github.com/benoitc/gunicorn/blob/22.0.0/docs/source/settings.rst

  31. 31.

    PostgreSQL Global Development Group, "Connections and Authentication" (max_connections), PostgreSQL 16 documentation. https://www.postgresql.org/docs/16/runtime-config-connection.html

  32. 32.

    John D. C. Little, "A Proof for the Queuing Formula: L = λW", Operations Research 9(3), 1961. https://doi.org/10.1287/opre.9.3.383

  33. 33.

    Django Software Foundation, "Multiple databases", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/db/multi-db/

  34. 34.

    Django Software Foundation, "Advanced testing topics" (testing primary and replica configurations), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/testing/advanced/

  35. 35.

    Django Software Foundation, "Pagination", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/pagination/

  36. 36.

    Django Software Foundation, "Download" (supported versions and roadmap), djangoproject.com, as published in May 2024. https://www.djangoproject.com/download/

  37. 37.

    Django Software Foundation, "How to upgrade Django to a newer version", Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/howto/upgrade-version/

  38. 38.

    Adam Johnson, "django upgrade" README, GitHub. https://github.com/adamchainz/django-upgrade

  39. 39.

    Rails Core Team, "Configuring Rails Applications" (database pooling), Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/configuring.html#database-pooling

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter