dj-mercury: What a Django Test Costs the Database

PUBLISHED
28 NOV 2026
FILED UNDER
  • django
  • dj-mercury
  • testing
  • performance
  • tools

I published dj-mercury today. It counts how many trips to the database a Django test makes, and it fails the test when that count is a bug. This is how to use it, with the tests and the findings from my own company's site as the example.

It's a rewrite of the same idea as my old django-mercury-performance library. Storm Developments has taken it under its wing to use and maintain, under AGPL-3.0.

Why count round trips

On my laptop the database is on the same machine, so forty queries look free. In production every query is a round trip over a network, and the same forty are the slow page. A stopwatch on a laptop can't see that, and a count can.

The count is also the same on every machine. A test that passes on my laptop and fails on a busy CI runner teaches me to ignore it, so Mercury reports the stopwatch time and never fails a test on it.

Install

pip install dj-mercury

It needs Python 3.12 or newer and Django 5.2 or newer, and Django is its only dependency. The test helper needs no setup at all. Add "dj_mercury" to INSTALLED_APPS only if you want the mercury command, which comes up further down.

Wrap a test

Here is a real test from my site, the one that loads the blog index:

from dj_mercury import performance_monitor


class BlogIndexTests(BlogTestBase):

    def test_index_returns_200(self):
        with performance_monitor(queries=5):
            resp = self.client.get(reverse('blog:index'))
        self.assertEqual(resp.status_code, 200)

The test already existed. The only new lines are the import and the with. Everything inside the block is counted, and queries=5 says the page may make five round trips and no more.

When the block goes over, the test fails and says why:

AssertionError: Mercury FAILED: blog/tests.py:210 in BlogIndexTests.test_index_returns_200
  round trips      7 (limit 5)
  round-trip cost  at least 1.05 ms, at 0.15 ms per round trip
  stopwatch        121.4 ms on this machine, never a reason to fail
  most rows        2 from one query
  fails: 7 round trips, over the limit of 5.

The view asked for each post's tag ids with values_list, which skips the tags Django had already prefetched, so every post on the page cost one more query.

What fails with no limit written

Two things are bugs on any page, so they fail a block even when I write performance_monitor() with nothing in it.

The first is a repeated query, where the same query with different values comes from the same line of code three or more times. That is a loop asking the database once per row. Three lookups from three different lines are three decisions, and they pass.

The second is an exact duplicate, the same query with the same values sent more than once.

Everything else is reported and only fails against a limit I write. Mercury ships no limits of its own, because the right number for a page is mine to know.

The options

The README lists every option and the three places one can be written. My site uses three of them, queries above, then rows and round_trip_ms.

rows is the one I didn't expect to need. My blog post page picked its related posts by loading every published post and scoring them in Python. The query count was fine and the page still got slower with every post I wrote. I moved the scoring into the database, and the test now holds the page to two rows from any one query:

def test_the_recommendation_reads_a_fixed_number_of_rows(self) -> None:
    for n in range(12):
        self._post(f'filler-{n}', self.home, n + 1, self.tag_django)
    with performance_monitor(queries=8, rows=2):
        self.client.get(reverse(POST_DETAIL, kwargs={'slug': self.subject.slug}))

Measure your own round trip

round_trip_ms is the average delay on one round trip to your database, wherever it is hosted. Set it and Mercury multiplies it by the count, so a failure says what the page costs in production and not only how many queries it made.

To find the number, time a trivial query from the app server:

import statistics, time
from django.db import connection

times = []
with connection.cursor() as cursor:
    for _ in range(200):
        start = time.perf_counter()
        cursor.execute("SELECT 1")
        times.append((time.perf_counter() - start) * 1000)
print(f"median {statistics.median(times):.2f} ms")

Mine came back between 0.10 and 0.18 ms over six runs, because my database is a container on the same host as the app. I set round_trip_ms to 0.15. Expect about 0.5 to 2 ms inside one data centre and 10 ms or more across regions.

I took my Storm Buckets dashboard from 39 round trips to 32, and at 0.15 ms each that saves about a millisecond a load, which nobody will feel. The fixes that mattered were the loops, because a loop's cost grows with the data and a fixed handful of queries doesn't.

Run only the performance tests

python manage.py mercury
python manage.py mercury blog --output mercury-report.md

mercury reads the test files, finds the tests that use performance_monitor, prints them and runs only those through Django's own test runner. It takes the same options manage.py test takes. --output writes the run's report as Markdown, which a CI job can keep.

Hunt through the tests you already have

Wrapping tests one at a time works when I already know which page is slow. For a project that has never counted its queries, I wanted Mercury to tell me where to start.

python manage.py mercury --hunt

A hunt runs every test in the project and watches each page a test loads through Django's test client. It fails nothing. When the run ends it writes mercury-hunt.md, one entry per finding:

## repeated query, 4 times from `accounts/gates.py:47`

- seen on 995 page loads, worst on `GET /dashboard/`

```sql
SELECT ? AS "a" FROM "auth_group" INNER JOIN "auth_user_groups" ON ("auth_group"."id" = "auth_user_groups"."group_id") WHERE ("auth_user_groups"."user_id" = ? AND "auth_group"."name" = ?) LIMIT ?
```

Read an entry as this line sent this query four times while one page loaded, and 995 page loads met it. Entries are ordered by page loads, so the query every page pays for comes before the one bad page.

I ran it on my company's site, which has 10,345 tests, and it wrote 325 findings. The first one was the entry above, with the file path and the URL changed. A function that asks whether a user is in a group ran once for every dashboard check, on nearly every signed-in page. It already took an argument for callers who had read the groups, and almost none of them passed it. Now the groups are read once per request.

Then I wrapped that page's test so it stays fixed. The loop is hunt, fix the first entry, wrap the test, hunt again.

What a hunt will and won't show you

Some findings are not loops. Test data is small, so a hunt notes a query sent twice from one line, where a wrapped test waits for three.

One line can appear twice, once as a repeated query and once as an exact duplicate.

It only sees pages loaded with self.client. Code a test calls directly is not watched, and neither is the async client. A test that errors before it loads a page adds nothing.

It is a full test run. It takes as long as the suite does and it works under --parallel.

Where to get it

It is on PyPI and the source is on my company's forge.

Have comments? Add me on Mastodon and shoot me a message.