Skip to content
Back to skills

Django Api Benchmark

ASecurity

Prove whether a Django/DRF performance change actually made an endpoint faster, by A/B-ing two git refs against one production-shaped local database. Use this skill when asked to benchmark an endpoint, measure or verify a performance fix, answer "is this actually faster", size a speedup before merging, or turn a production OTel trace into a reproducible local experiment. Also use it when a local benchmark comes back clean but production is still slow, or to ask whether an endpoint leaks memor...

  • 5 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added October 4, 2026
developmentpythongobashsqldjangogitapidatabasebackendperformance

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Pro scans all 7 files and shows the line behind each finding

Scanned October 4, 2026

npx -y skills add mitodl/agent-kit --skill django-api-benchmark --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Django Api Benchmark?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Django Api Benchmark
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/mitodl-django-api-benchmark/badge)](https://www.skillsdirectory.com/skills/mitodl-django-api-benchmark)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: django-api-benchmark
description: >
  Prove whether a Django/DRF performance change actually made an endpoint faster,
  by A/B-ing two git refs against one production-shaped local database. Use this
  skill when asked to benchmark an endpoint, measure or verify a performance fix,
  answer "is this actually faster", size a speedup before merging, or turn a
  production OTel trace into a reproducible local experiment. Also use it when a
  local benchmark comes back clean but production is still slow, or to ask
  whether an endpoint leaks memory, retains objects, or grows a worker's heap
  per request. Covers eliciting production evidence (traces, sample API
  responses), calibrating a seed to the real data shape, writing the
  benchmark's config file, reporting a defensible number, and escalating from
  latency to retention using the mitol-django-benchmark package.
license: BSD-3-Clause
metadata:
  category: python
---

# Benchmarking a Django API change

A performance PR that says "this should be faster" is a guess. This skill turns
it into a measurement: seed a **production-shaped** throwaway database, run the
same request on both git refs against **identical rows**, and attribute the
difference query by query.

The mechanics are handled by
[`mitol-django-benchmark`](https://github.com/mitodl/ol-django/tree/main/src/benchmark).
**You do not write a harness.** You write one TOML file describing the shape and
the target, run one command, and read the JSON it produces. Everything the
package enforces — refusing to measure under a profiler, seeding once across
both arms, verifying each arm ran the ref you think — is covered by its own
tests, so it is not your job to re-derive.

What is left is the part no package can do for you, and it is the part that
decides whether the number means anything:

1. **Getting the shape right.** Factory defaults are nothing like production. A
   seed that is off structurally produces a number with no bearing on the
   endpoint you care about.
2. **Not fitting the seed to the answer you want.** Calibrating against the
   query you changed is circular, and it will manufacture a confident,
   large, wrong result.
3. **Knowing what to do when the benchmark says the code is fine.** A clean
   local result against a production stall is a finding, not a dead end, and
   Step 7 is where it leads.

Related: [`drf-api-performance`](../drf-api-performance/SKILL.md) is about
*writing* fast endpoints. This is about *proving* one got faster.

## Step 0 — Install it

```bash
uv add --dev "mitol-django-benchmark[drf,factories,django,postgres]"
```

Use the `postgres2` extra instead of `postgres` on a project still using
psycopg2. Without a psycopg instrumentation extra the run still works, but the
trace pass reports that it captured no database spans and you lose per-query
attribution.

If the project has no `benchmarks/` directory yet:

```bash
ol-benchmark init --project     # benchmarks/benchmark.toml, committed
ol-benchmark init --local       # benchmarks/benchmark.local.toml, gitignored
```

`init --project` also adds this package's artifacts to the project's
`.gitignore`: `.bench/`, the local layer, and `traces/` plus `*.trace.json`.
Run it before Step 1 in a project that has not adopted the package, so the
entries are in place before you ask anyone for a production trace.

## Step 1 — Ask for the evidence

Do not start writing the seed. Ask for all of it in **one batched question**,
and say what each artifact is for — people usually have more than they
volunteer:

| Ask for | Why you need it |
| --- | --- |
| The **endpoint and exact query string**, including filter params | Filters drive join fan-out; the wrong params benchmark a different code path |
| The **two git refs** to compare (usually the branch and its merge base) | The A/B arms |
| **Production OTel traces** of real slow requests (JSON exports) | The only source of per-query timings and row-count floors. Ask for *several* — the baseline is a median, so it improves with the sample |
| **Sample production API responses** for that endpoint (2-3, different tenants/filters) | The only ground truth for the *output* shape |
| Whether they can run **read-only queries against a production replica** | Collapses the biggest guesses into facts |
| Anything they already know is slow | Their intuition is usually a good prior |

If they have no trace, the benchmark can still run, but say plainly that you
lose per-query attribution and the calibration target.

Two things to say when you ask for the traces, because both are easy to get
wrong at export time and neither is recoverable afterwards:

- **Include the server/root span**, not just database spans. A trace filtered
  to queries makes the last query's gap read as zero — and that gap is where
  serialization lives, usually the largest single cost.
- **One endpoint per set.** Traces for different routes get averaged into
  nonsense.

### Step 1b — Collect what they said they have

The answer to Step 1 tells you which artifacts **exist**. It does not hand you
any of them. Every artifact they said yes to has to arrive before Step 2, and
asking for it is a separate turn:

- For **each** trace or sample response they claimed, ask for it by name — a
  file path you can read, or pasted content. Anywhere you can read it is fine —
  offer a scratch path outside the repo so production data is never at risk of
  being committed.
- **Do not infer a path.** A trace you guessed at is worse than no trace,
  because the resulting knobs get labelled OBSERVED.
- For **replica access**, hand them the exact read-only SQL from
  [references/evidence.md](references/evidence.md) rather than asking them to
  invent queries.
- Confirm each one landed: read the file and state what you got from it (rows
  per page, span count) before moving on.

**You may not enter Step 2 with a promised artifact still outstanding.** Either
it is in hand, or they explicitly dropped it — and if they dropped it, every
knob it would have justified is a `# GUESS:`, not an `# OBSERVED:`. Offering to
"proceed with estimates and swap them in later" re-labels guesses as facts the
moment the report is written; ask again instead.

## Step 2 — Derive the target shape from the artifacts

Each artifact answers different questions. Be explicit about which, because
anything neither can answer is a **guess you must label as one**.

- **Sample responses** give you the output shape exactly: rows per page, nested
  collection sizes per row, field payload sizes. Compare these against what the
  app's factories actually produce — the gap is usually large in both directions.
- **The OTel trace** gives you the query timeline. Compute each span's duration
  *and the gap to the next span*: the span wraps `cursor.execute`, so row
  fetch, model instantiation and serialization all land in the gaps. It also
  gives **row-count floors** from `IN (%s, %s, ...)` placeholder counts, and
  per-query timings you can calibrate against.
- **Neither** can show you hidden fan-out: rows loaded and discarded, join
  multiplicity, or column payloads that are selected but never serialized.

See [references/evidence.md](references/evidence.md) for the jq to turn a trace
export into a gap-annotated timeline, and what to extract from responses.

## Step 3 — Write the benchmark file

```bash
ol-benchmark init --benchmark <name>     # benchmarks/<name>.toml
```

**This is the only file you edit.** `benchmark.toml` is a project-wide decision
and `benchmark.local.toml` belongs to whoever owns the machine; if either needs
changing, say so and ask.

What goes in it, and the full token vocabulary, is in
[references/configuring.md](references/configuring.md). The three things that
decide whether the result is worth anything:

- **Every shape dimension is a knob**, so the same benchmark re-runs at another
  shape with `--knob` and no edit, and the report can state the exact shape.
- **Each knob is annotated OBSERVED or GUESS**, in a comment naming the
  artifact that justifies it. This distinction has to survive into the report.
- **Structure before sizing.** Many tenants, children spread across parents,
  noise rows the page does not return, and whatever membership the permission
  check needs. Getting this wrong is not recoverable by tuning payload sizes.

Then check it loads before running anything destructive:

```bash
ol-benchmark validate benchmarks/<name>.toml
```

## Step 3b — Distil the traces into a committed baseline

**Never commit a raw trace, and never paste its SQL into the config or a PR.**
It carries statement literals, query strings and user identifiers. Keep the
exports outside the repository; `traces/` and `*.trace.json` are gitignored as
a backstop in any project where `init --project` has been run — check that it
has, rather than assuming, if you did not run it yourself.

Write the `[[trace.classify]]` rules first — they are what the baseline is
keyed by — then:

```bash
ol-benchmark baseline benchmarks/<name>.toml traces/*.json
```

Pass every trace you have; a glob is the expected way. That writes
`benchmarks/<name>.baseline.json` containing per-query medians, row-count
floors, and the sampled trace ids. Nothing else — no SQL, no attribute values,
no absolute timestamps. A query matching no rule is labelled `"unclassified"`
rather than by its statement, and the command warns so you can add a rule.

**Read the file before committing it.** It is a few lines, and reading it is
the review gate. `--stdout` prints without writing if you want to look first.

Then tell the drift check which query the change is meant to move:

```toml
[[trace.classify]]
label = "topics prefetch"
pattern = "book_topics"
targeted = true            # expected to differ; excluded from drift

[calibration]
baseline = "<name>.baseline.json"
drift_factor = 5
```

This step is optional — the A/B works without it — but skipping it means
nothing checks whether your seed resembles production at all.

## Step 4 — Calibrate, and be willing to falsify

Tune the seed until the **independent observables** match production.
Independent means "not affected by the change under test" — those are
legitimate calibration targets precisely because they are identical in both
arms.

Record them in the file, so the report cites them automatically:

```toml
[[calibration.observable]]
name = "rows per page"
source = "sample response"
production = 100

[calibration.floors]
children = 388          # from the trace's IN-list placeholder count
```

**Give the observables you can a `response` key.** Without one, an observable
is compared against the seed's row counts, which prove what was *created* and
not what the endpoint *returned*. With one, the report reads the value back out
of the response and flags it when it misses:

```toml
[[calibration.observable]]
name = "response bytes"
source = "sample response"
production = 96794
response = "response_bytes"   # or count, results, nested.<key>
tolerance = 0.25              # the default
```

This is the check that catches the seed that looks right and is not. A seed
whose counts all matched production once produced a 66 KB response against
production's 97 KB — two missing pieces of shape, invisible in every row count,
and only the payload size said so.

**A seed parameter that makes an *unchanged* query wildly slower than
production is falsified — discard it, however good the story was.** With a
baseline configured this is no longer only your judgement: the report computes
it, as `calibration_drift`. Without one it stays yours to check by eye.

Structural realism matters more than sizing: how rows fan out across joins
dominates how wide they are. See
[references/calibration.md](references/calibration.md) for the worked example
and the common structural mistakes.

## Step 5 — Run it, and check the benchmark before the result

```bash
ol-benchmark run benchmarks/<name>.toml --base-ref <merge-base>
```

The working tree must be clean — the runner refuses otherwise, because
otherwise the two arms are not the two refs you think.

Read `.bench/out/<name>/comparison.json`. Before quoting any delta:

1. **`verdict` is not `void`.** Void means the arms returned different
   responses; `equivalence_mismatches` says which fields. They did not do the
   same work. Find out why before anything else.
2. **`verdict` is not `inconclusive`.** That is a real answer — report it as
   one. Do not re-run until you get a number you like.
3. **`classifier_collisions` is empty.** A non-empty entry means a
   `[[trace.classify]]` label is mixing two different queries, so its median is
   meaningless. Tighten the pattern.
4. **`per_query` shows the saving where the change aims**, and nothing else
   regressed to pay for it. With a baseline, read the `production_total_ms`
   column beside it — a local number is hard to interpret alone.
5. **`calibration_drift` is empty.** An entry means a query the change does
   *not* touch does not look like production, which puts the seed shape in
   question rather than the result. Local slower than production there is the
   falsification signal: fix the seed and re-run rather than explaining it
   away. Drift never changes the verdict, so a sound A/B on a bad seed still
   reads `ok` — you have to look.
6. **`calibration_mismatches` is empty.** An entry means the *response* is a
   different size from the production sample, whatever the row counts say. Like
   drift it never changes the verdict, and like drift it means the per-query
   numbers describe a shape that is not production's.
7. **`refs.base` and `refs.branch` differ.** Identical refs means the switch
   never reached the code being measured.
8. **Re-run at a second shape** (`--knob rows=200`). A delta stable across
   shapes is the single strongest evidence you can produce locally.

[references/results.md](references/results.md) is the field-by-field guide,
including how to read the SQL-versus-gap split.

## Step 6 — Report a floor, not an estimate

Local Postgres has no network round-trip, a warm cache and no contention.
Production has all three, and they penalise larger result sets
disproportionately. Say so, every time — `comparison.json` carries the sentence
in `caveat`; do not drop it.

State in the write-up:

- The seed shape, next to the numbers.
- The execution environment, and anything it contributes to the spread — a
  benchmark sharing a pod with a live server is noisier than one in an isolated
  container, and a shared database has contention a dedicated one does not.
  See [references/environments.md](references/environments.md).
- Which inputs were **guesses**, and that they are identical across arms (so
  they move the baseline, not the delta).
- Any production signal the harness **failed** to reproduce, and what you ruled
  out.
- Per-query attribution, so a reviewer can see the saving is where the change
  aims and nothing regressed.

Do not quote a single headline number without the shape it was measured on.

## Step 7 — When the benchmark exonerates the endpoint

A clean local result against a calibrated seed is a **finding**, not a failed
run. It says the time is not being spent in the request. Say that plainly, and
then keep going, because the next question is one no A/B can answer: not what
the request costs, but what it **leaves behind**.

A worker that grows a little every request ends up spending its life near
whatever ceiling bounds it — a container limit, or a process manager's
`max-rss` recycle. That is where stop-the-world collections are longest and
where a worker can be replaced mid-request. None of it is visible in a
latency comparison, because it is a property of one commit rather than a
difference between two.

```bash
ol-benchmark memory benchmarks/<name>.toml
```

Same seed, same auth, same refusals — including the empty-response refusal,
which fires before the requests run, and the refusal of a committed
`benchmark.local.toml`, which is one developer's connection strings in the
repository whatever is being measured. The one it drops deliberately is the
dirty-tree check: single-arm, nothing to check out. The result says whether the
tree was dirty — `ref` comes back `git describe --dirty` style — and a number
measured against uncommitted changes belongs to the tree, not to the commit, so
say so when you quote it. **Do not write your own
script for this.** Every wrong answer this section exists because of came from
one: a hand-rolled measurement run under pytest, where an ORM profiler the
harness refuses inflated retention by 70%; and another against an endpoint
quietly serving an empty page, where the heap looked admirably flat.

Read the verdict first:

| Verdict | What it means | What to do |
| --- | --- | --- |
| `stable` | Neither configured rate was crossed | The growth is elsewhere. Measure another endpoint, or look outside the request path. Read it as "nothing crossed the thresholds", not as "nothing is held" |
| `high-water` | RSS grew; live objects did not | Consistent with the allocator holding freed arenas rather than retention, so **there is no holder to find** — the fix is to allocate less per request, and an over-fetch is the usual cause. Check the RSS series plateaus; retention the collector cannot enumerate reads the same way |
| `retaining` | Objects survive a forced collection | Something holds them across requests. `retained_by_type` usually names it; `holders` gives the chain up to the module or class |

Three things are worth reading even when the verdict is benign:

- **Retained types against what the response contains.** Retaining far more
  objects than the endpoint serializes means an over-fetch is being *held*,
  not merely loaded. The same rows that cost latency, made permanent.
- **`lru_caches_grown` being empty.** That is informative, not a null result:
  no `functools` cache in the process gained entries, which points at a
  hand-rolled holder. It does not clear the category — the comparison is on
  `cache_info().currsize`, so a cache whose existing values accumulate
  references looks flat.
- **The chain's last named step.** A cache keyed by `id(obj)` in a dict with
  class lifetime will not appear in any cache audit, and the walk is what
  finds it.

One limit, so a quiet result is not over-read: only GC-tracked containers are
visible, so an object held solely in a dict of untracked values has no
discoverable referrers. It fails toward saying nothing rather than toward a
false alarm. The retained set itself is exact — the baseline heap is frozen
into the permanent generation before the requests run, so what the collector
can still enumerate afterwards is what the run added.

The figures are the endpoint's own rather than the process's, which is not
free: Django's test client re-connects three signals per request and
`Signal.connect` leaves a `weakref.finalize` against the owner of each
receiver, two of which have process lifetime. Twelve objects a request, enough
on its own for a view returning a fixed string to read `retaining`. The pass
detaches each as it appears and reports the count in
`harness_finalizers_detached`; when that field is `null` it could not identify
them on the Django in use, and the figures then include the instrument. This
is also why not to hand-roll the measurement — a script that serves an
endpoint in a loop and counts objects is measuring its own client.

## What the package already refuses

You do not need to guard against these; it will not run. Knowing *why* still
matters, because the reasons shape how you read a result:

| Refused | Why it would ruin the number |
| --- | --- |
| N+1 profiler middleware (`zeal`, `nplusone`, `silk`, debug toolbar) | Hooks every ORM fetch, so the cost scales with objects hydrated — the exact variable a prefetch change moves. Inflates whichever arm loads more rows and **overstates the win** |
| A trace function installed (coverage, a profiler, a debugger) | Line tracing dwarfs the effect |
| Running under pytest | Test settings commonly enable both of the above |
| A dirty working tree | The arms would not be two refs |
| A scratch database not named `bench*` | The step drops it, and a shared cluster has real databases next to it |
| A `benchmark.local.toml` that is tracked by git | It holds one developer's cluster and credentials |
| **A response with no rows in it** | Both arms agree perfectly on nothing, so equivalence passes and the timings are real — the one wrong answer no downstream check can catch. Usually authorization failing open, which renders as a **200 carrying an empty page, not a 403**, so `expect_status` is satisfied. Refused before the timed loop |
| **A declared `nested_keys` collection that is empty in every row** | The same failure one level down: the rows are there, the thing being measured is not |
| **A remote default file storage** | A seed creating image or attachment rows uploads to whatever bucket the environment points at, and a developer environment usually holds working credentials for a real one. This is a safety refusal — the write happens during seeding, before anything is measured |

It also forces `DEBUG = False` (and records that it did), seeds once across both
arms, keeps the query-capture pass separate from the timed loop, and verifies
each arm is running the ref you think before measuring it.

## Pitfalls it cannot catch

These are judgment, which is why they are the skill's job:

| Pitfall | Why it ruins the result |
| --- | --- |
| Tuning the seed against the query you changed | Circular. Calibrate only on unchanged observables |
| Factory defaults as "realistic" | Blank rich-text fields, one related row where production has dozens |
| Every row under one tenant | Makes the filter match everything and turns an unchanged query pathological |
| Quoting a traced total as the result | Instrumentation is not free. The trace is for attribution; the uninstrumented pass is for the number |
| Extrapolating local ms to production ms | Different hardware, cache state and network. Report a floor |
| Quoting a delta from one seed shape | A result that does not hold at a second shape is a result about your seed |
| Committing a raw OTel export, or pasting its SQL into a PR | It carries statement literals, query strings and user identifiers. Only the distilled baseline is committable |
| Explaining away a drift warning | An unchanged query that does not look like production means the seed is wrong, not that the check is |
| Measuring anything in a script of your own instead of through the harness | Every refusal above is lost at once. A retention measurement written by hand and run under pytest reported 70% more growth than the truth, because `ENVIRONMENT == "pytest"` force-enabled an ORM profiler that `ol-benchmark` would have refused. If you need a measurement the harness does not offer, add it to the harness |
| Reading seed row counts as proof the seed is right | They show what was created, not what the endpoint returned. A seed can build every row correctly while a filter, a missing membership or an unattached nested collection leaves the response a fraction of production's size — with every count still agreeing |

## References

| Read this | For |
| --- | --- |
| [evidence.md](references/evidence.md) | The batched question, collecting the artifacts they said they have, reading an OTel JSON export, what a usable export needs, handling traces safely, what no artifact can tell you |
| [configuring.md](references/configuring.md) | The three config layers, seed step kinds, the `$token` vocabulary, targets, auth, query classifiers, the production baseline keys |
| [calibration.md](references/calibration.md) | What the harness now falsifies for you and what it cannot, the observables table, structural vs sizing realism, a worked falsification |
| [results.md](references/results.md) | Every output file, the verdicts, SQL versus gap, the production column, seed drift, what a classifier collision means |
| [environments.md](references/environments.md) | Choosing a backend, the local-dev cluster's namespaces and DSN, fidelity differences to disclose |
| [retention.md](references/retention.md) | The retention pass: why RSS alone cannot answer it, the three verdicts and their thresholds, reading a holder chain, how the retained set is delimited and the one limit on it, and how an over-fetch becomes a leak's multiplier |

## Resources

- [`mitol-django-benchmark`](https://github.com/mitodl/ol-django/tree/main/src/benchmark) — the package, its README and its own `AGENTS.md`
- [Write Performant APIs](https://engineering.ol.mit.edu/handbook/how-to/write-performant-apis/)
- [OpenTelemetry Python: in-memory span exporter](https://opentelemetry-python.readthedocs.io/en/latest/sdk/trace.export.html)

Files in this skill

  • SKILL.md24.3 KB
  • references/calibration.md8.4 KB
  • references/configuring.md9.8 KB
  • references/environments.md6.9 KB
  • references/evidence.md9.7 KB
  • references/results.md8.7 KB
  • references/retention.md9.8 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.