django-DefectDojo icon indicating copy to clipboard operation
django-DefectDojo copied to clipboard

[performance] API ?prefetch= serializes related objects per entry: /api/v2/findings/?limit=100&prefetch=test goes from 122 to 423 queries

Open Ludocius opened this issue 4 weeks ago • 0 comments

Description

The API ?prefetch= feature (dojo/api_v2/prefetch) is meant to save round-trips, but _Prefetcher._prefetch() serializes the related object per entry: for each finding it does getattr(entry, "test") and runs the full TestSerializer.to_representation() on that single instance. The nested serializer touches the test's many-to-many fields (notes, files, finding_groups, tags), and because those instances were not fetched through a queryset with prefetch_related, every one of them is a fresh query. Prefetching therefore adds 3 queries per finding instead of removing any.

Test setup: official image defectdojo/defectdojo-django:2.50.1 + defectdojo-nginx:2.50.1, upstream docker-compose.yml (Postgres 17.6, Redis 7.2, 4 uWSGI processes x 4 threads), Docker Desktop on Windows 11. Data: 6,000 findings created through /api/v2/import-scan/ (two Generic Findings Import reports of 3,000 findings, one endpoint each) plus 30 empty products. Query counts come from django.test.utils.CaptureQueriesContext around django.test.Client requests executed inside the uwsgi container; load numbers from hey -z 20s -c 20 against nginx; memory/CPU from docker stats.

Measured on /api/v2/findings/?limit=100:

  • without prefetch: 122 queries, 238 ms wall (100 of them are the vulnerability_id N+1 already reported in #16652)
  • &prefetch=test,risk_acceptance: 423 queries, 694 ms wall -- +100 dojo_finding_group, +100 dojo_notes, +100 dojo_fileupload (one of each per finding, for the same two Test rows)
  • throughput of the plain endpoint under hey -c 20: 5.5 req/s, p50 3.06 s, p90 5.07 s

PoC

[API findings limit=100] GET /api/v2/findings/?limit=100
   HTTP 200 | 122 SQL queries | SQL time 40 ms  | wall 238 ms
     100 x  SELECT ... FROM "dojo_vulnerability_id" WHERE finding_id = ?
[API findings prefetch] GET /api/v2/findings/?limit=100&prefetch=test,risk_acceptance
   HTTP 200 | 423 SQL queries | SQL time 134 ms | wall 694 ms
     100 x  SELECT ... FROM "dojo_vulnerability_id" ...
     100 x  SELECT ... FROM "dojo_finding_group" ...
     100 x  SELECT ... FROM "dojo_notes" ...
     100 x  SELECT ... FROM "dojo_fileupload" INNER JOIN "dojo_test_files" ...

DD-PERF-PREFETCH

Before / After

Before (prefetcher.py)

for field_to_fetch in fields_to_fetch:
    field_value = getattr(entry, field_to_fetch, None)          # one related instance per entry
    ...
    field_data = extra_serializer(many=many).to_representation(field_value)
    for data in field_data_list:
        self._prefetch_data[field_to_fetch][data["id"]] = data

After: collect the related ids for the whole page first, fetch them once with the related model's own M2M prefetches, serialize once

def prefetch_page(self, entries, fields_to_fetch):
    for field in fields_to_fetch:
        related_model = entries[0]._meta.get_field(field).related_model
        ids = {pk for entry in entries for pk in _related_pks(entry, field)}   # FK -> {entry.<field>_id}, M2M -> values_list("pk")
        serializer = self._find_serializer(related_model)
        qs = related_model.objects.filter(pk__in=ids).prefetch_related(
            *[f.name for f in related_model._meta.many_to_many])              # notes, files, tags, finding_groups ...
        self._prefetch_data[field] = {obj.pk: serializer().to_representation(obj) for obj in qs}

PrefetchListMixin.list() then calls prefetch_page(page, fields) once instead of _prefetch(entry, fields) per entry. Nested objects are deduplicated automatically (the two Test rows are serialized twice instead of 100 times) and the query count becomes O(fields), not O(rows x M2M).

Measured on the 2.50.1 image (commit 8292998); the same code is present on dev at 237458c. Links above point to both.

Ludocius avatar Nov 07 '26 04:11 Ludocius