NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior79 views

В Django API список транзакций стал отвечать заметно медленнее после роста таблицы до 8 миллионов строк. Проведи по механизму: почему индекс может не помочь и что ты первым проверишь в плане выполнения запроса через `EXPLAIN ANALYZE`.

Practice

Asked at

AI answer

First, I would reproduce the slow query with representative parameters and inspect the actual plan, for example in PostgreSQL:

EXPLAIN (ANALYZE, BUFFERS) ...;

ANALYZE actually executes the query, so this is important to keep in mind on a heavily loaded production database. In the plan, I would first compare the planner’s estimates with the actual row counts and time at each node. Then I would check:

  • Whether a Seq Scan is being used instead of an index, and how many rows it filters out. An index may not help if the condition is not very selective and the query returns most of the table; in that case, a sequential scan is cheaper.
  • Whether there is an Index Scan/Bitmap Index Scan, how many pages are read, and what the Buffers (hit/read) values are. An index lookup can be slow because of the large number of table accesses needed to fetch rows.
  • Whether the index is being hindered by an expression or type cast in the condition (WHERE), a mismatched column order in a composite index, or a sort or join that is not covered by the appropriate index.
  • How much the estimated rows differ from the actual row count, how many times a node is executed (loops), and whether there are expensive Sort or Join operations, or many repeated accesses caused by a correlated subquery.

If the estimates differ significantly from reality, I would check whether the statistics are up to date (ANALYZE). I would also review the query and its parameters, including pagination and fetching related objects in Django. Simply having an index is not enough: it needs to match the filter, sort order, and actual selectivity of the query.