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

[performance] GET /api/v2/test_imports/ serializes every Test_Import_Finding_Action inline: 7.5 s / 830 KB for 2 imports, 20 concurrent requests time out and push uWSGI to 2.2 GB

Open Ludocius opened this issue 4 weeks ago • 1 comments

Description

GET /api/v2/test_imports/ serializes every Test_Import_Finding_Action of every import inline (test_import_finding_action_set = TestImportFindingActionSerializer(many=True)), with no limit and no way to opt out. One Test_Import row carries one action per finding of the import, so a page of 100 imports of medium-size scans (thousands of findings each) serializes hundreds of thousands of nested objects per request.

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 with only 2 test imports in the database (3,000 findings each):

  • single request: HTTP 200 | 26 SQL queries | SQL time 741 ms | wall 7,487 ms | body 830 KB
  • hey -z 20s -c 20: 0 successful responses, all 20 in-flight requests hit the client's 20 s timeout
  • the uwsgi container went from 446 MiB to 2.19 GiB RSS and 378 % CPU during those 20 s, and the memory was not released afterwards (uWSGI workers keep the peak)

With a realistic history (hundreds of imports, limit=100 default page), this endpoint is effectively unusable and is an easy way for any API user to pin all uWSGI workers.

PoC

[API test_imports] GET /api/v2/test_imports/?limit=100
   HTTP 200 | 26 SQL queries | SQL time 741 ms | wall 7487 ms | body 830 KB
### hey -z 20s -c 20  /api/v2/test_imports/?limit=100
[20]  Get http://nginx:8080/api/v2/test_imports/?limit=100: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
ddaudit-uwsgi-1 cpu=52.35%  mem=446.5MiB   (before)
ddaudit-uwsgi-1 cpu=378.54% mem=2.193GiB   (after)

DD-PERF-TESTIMPORTS

Before / After

Before

class TestImportSerializer(serializers.ModelSerializer):
    test_import_finding_action_set = TestImportFindingActionSerializer(
        many=True, read_only=True,
    )

    class Meta:
        model = Test_Import
        fields = "__all__"

After: the list returns counts per action (annotated in bulk), the actions themselves live behind a paginated sub-resource

class TestImportSerializer(serializers.ModelSerializer):
    finding_action_counts = serializers.SerializerMethodField()

    class Meta:
        model = Test_Import
        fields = "__all__"

    def get_finding_action_counts(self, obj) -> dict:
        # populated by the viewset annotation, no per-row query
        return {"created": obj.created_count, "closed": obj.closed_count,
                "reactivated": obj.reactivated_count, "untouched": obj.untouched_count}


class TestImportsViewSet(...):
    def get_queryset(self):
        actions = Test_Import_Finding_Action.objects.filter(test_import=OuterRef("pk"))

        def count(action):
            return Coalesce(Subquery(actions.filter(action=action).values("test_import")
                                     .annotate(c=Count("id")).values("c")), Value(0))

        return get_authorized_test_imports(Permissions.Test_View).annotate(
            created_count=count(IMPORT_CREATED_FINDING), closed_count=count(IMPORT_CLOSED_FINDING),
            reactivated_count=count(IMPORT_REACTIVATED_FINDING), untouched_count=count(IMPORT_UNTOUCHED_FINDING))

    @action(detail=True, methods=["get"], url_path="finding_actions")
    def finding_actions(self, request, pk=None):
        qs = self.get_object().test_import_finding_action_set.select_related("finding").order_by("id")
        page = self.paginate_queryset(qs)
        return self.get_paginated_response(TestImportFindingActionSerializer(page, many=True).data)

Keeping the nested list only when the client asks for it (?prefetch=test_import_finding_action_set) is an alternative that preserves backwards compatibility.

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

Hi @Ludocius , I'd like to take this issue and work on optimizing it. I'll be opening a Pull Request soon with a fix. Thanks!

AbdaullahAG avatar Nov 07 '26 11:11 AbdaullahAG