Faster APIs Start With Fewer Queries
Controlling query growth by designing database access around the response contract.
One of the easiest ways to build a slow API is to let serialization trigger database queries silently.
A transaction endpoint may begin with one query. Each transaction can then reference a user, wallet, country, provider, recipient, payment method, and status history. If the serializer accesses those relationships without preloading them, a page containing 100 transactions can generate hundreds of additional queries.
This is the N+1 query problem, but the important operational detail is that it often remains invisible in development. A small local dataset responds quickly. Production data, concurrent staff requests, and distant database connections expose the real cost.
Treat the response contract as a query plan
Before changing the database query, map every field in the response to its data source. Single relationships can normally be loaded through joins, while collections should be prefetched in bounded secondary queries.
transactions = ( Transaction.objects .select_related( "user", "wallet", "country", "payment_method", ) .prefetch_related( "status_events", "provider_responses", ) ) select_related is appropriate for foreign-key and one-to-one relationships. prefetch_related is safer for one-to-many and many-to-many collections because it avoids multiplying the primary result set.
Preloading alone is not enough. A list endpoint rarely needs complete webhook bodies, provider payloads, reconciliation evidence, or every internal metadata field. Those belong on the detail endpoint. Keeping list serializers compact reduces database reads, Python object construction, serialization work, memory use, and response size.
Move aggregate work out of each row
A serializer method that counts related records or calculates a total can execute once per item. Move those calculations into annotations, a separate aggregate query, or a statistics endpoint.
Pagination must also happen before expensive serialization. Fetching thousands of records, transforming all of them, and slicing the final array defeats the purpose of pagination.
Indexes remain important for filters and ordering, especially on status, provider, country, reference, and creation time. But an index cannot compensate for requesting unnecessary data hundreds of times.
Measure query count, not only duration
Timing one query is insufficient. Track the number of queries for a representative page and verify that it remains approximately constant as the number of rows increases within the page size.
The best optimization was not a larger database server. It was making every request ask a smaller and more deliberate question.
Implementation checklist
Map serializer fields to relationships before writing the queryset. Use separate list and detail serializers. Paginate at the database boundary. Annotate repeated counts and totals. Add indexes for real filter and ordering patterns. Measure query count with realistic fixtures, and protect important endpoints with regression tests that fail when query growth returns.
原文:https://www.a8q9.cn/en/article/faster-apis-start-with-fewer-queries-e3a427.html