Skip to content

fix: Melhoria de desempenho com uso de indices no endpoint fetchInstance#2568

Open
iagocotta wants to merge 1 commit into
evolution-foundation:developfrom
iagocotta:fix-index-performance-fetchInstance
Open

fix: Melhoria de desempenho com uso de indices no endpoint fetchInstance#2568
iagocotta wants to merge 1 commit into
evolution-foundation:developfrom
iagocotta:fix-index-performance-fetchInstance

Conversation

@iagocotta
Copy link
Copy Markdown

@iagocotta iagocotta commented May 27, 2026

Resumo

Adiciona três índices ausentes na tabela Instance que são consultados em caminhos críticos da aplicação, mas estavam executando varredura sequencial completa na tabela.

  • clientName — filtrado em toda inicialização do servidor (loadInstancesFromDatabasePostgres) e em cada chamada a fetchInstances sem instância específica
  • token — filtrado em toda requisição autenticada a /instance/fetchInstances quando utilizado token de instância ao invés da chave global (auth.guard.ts + instance.controller.ts)
  • number — filtrado nas buscas via instanceInfoById por número de telefone

Sem esses índices, cada uma dessas queries executa um full scan na tabela Instance. Em ambientes multi-tenant com centenas ou milhares de instâncias compartilhando o mesmo banco, isso impacta diretamente o tempo de inicialização, a latência de autenticação e o tempo de resposta das buscas de instância.

Alterações

  • prisma/postgresql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sql
  • prisma/mysql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sql

Verificação

Após aplicar a migration, use EXPLAIN ANALYZE (PostgreSQL) ou EXPLAIN (MySQL) para confirmar que os índices estão sendo utilizados:

-- PostgreSQL
EXPLAIN ANALYZE SELECT * FROM "Instance" WHERE "clientName" = 'seu-client';
EXPLAIN ANALYZE SELECT * FROM "Instance" WHERE "token" = 'seu-token';
EXPLAIN ANALYZE SELECT * FROM "Instance" WHERE "number" = 'seu-numero';

-- MySQL
EXPLAIN SELECT * FROM `Instance` WHERE `clientName` = 'seu-client';
EXPLAIN SELECT * FROM `Instance` WHERE `token` = 'seu-token';
EXPLAIN SELECT * FROM `Instance` WHERE `number` = 'seu-numero';

Summary by Sourcery

Add database indexes to improve query performance for instance lookups by client name, token, and phone number.

Build:

  • Add MySQL migration to create indexes on Instance.clientName, Instance.token, and Instance.number.
  • Add PostgreSQL migration to create indexes on Instance.clientName, Instance.token, and Instance.number if they do not already exist.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 27, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds database indexes on the Instance table (for clientName, token, and number) in both PostgreSQL and MySQL migrations to eliminate full table scans on critical fetch/auth queries and improve performance of the fetchInstance-related paths.

Entity relationship diagram for new indexes on Instance table

erDiagram
  Instance {
    string id
    string clientName "INDEX Instance_clientName_idx"
    string token "INDEX Instance_token_idx"
    string number "INDEX Instance_number_idx"
  }
Loading

File-Level Changes

Change Details Files
Add matching B-tree indexes for clientName, token, and number columns on the Instance table for MySQL and PostgreSQL.
  • Create three non-unique indexes on clientName, token, and number in the MySQL migration for the Instance table.
  • Create three non-unique indexes on clientName, token, and number in the PostgreSQL migration for the Instance table, using IF NOT EXISTS to make the migration idempotent.
  • Align index naming (Instance_clientName_idx, Instance_token_idx, Instance_number_idx) across both database engines for consistency and easier query-plan inspection.
prisma/mysql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sql
prisma/postgresql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sql

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • For PostgreSQL, consider using CREATE INDEX CONCURRENTLY in a separate migration to avoid taking write locks on Instance during index creation in large/production tables.
  • If clientName, token, or number are wide VARCHAR/TEXT columns in MySQL, you may want to specify a prefix length on these indexes to reduce index size and improve write performance.
  • Double-check the main query patterns (e.g., combined filters on clientName + token) to see if a composite index would better match real-world access patterns than three separate single-column indexes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- For PostgreSQL, consider using `CREATE INDEX CONCURRENTLY` in a separate migration to avoid taking write locks on `Instance` during index creation in large/production tables.
- If `clientName`, `token`, or `number` are wide VARCHAR/TEXT columns in MySQL, you may want to specify a prefix length on these indexes to reduce index size and improve write performance.
- Double-check the main query patterns (e.g., combined filters on `clientName` + `token`) to see if a composite index would better match real-world access patterns than three separate single-column indexes.

## Individual Comments

### Comment 1
<location path="prisma/postgresql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sql" line_range="2-8" />
<code_context>
+-- CreateIndex
+CREATE INDEX IF NOT EXISTS "Instance_clientName_idx" ON "Instance"("clientName");
+
+-- CreateIndex
+CREATE INDEX IF NOT EXISTS "Instance_token_idx" ON "Instance"("token");
+
+-- CreateIndex
+CREATE INDEX IF NOT EXISTS "Instance_number_idx" ON "Instance"("number");
</code_context>
<issue_to_address>
**issue (bug_risk):** Using `IF NOT EXISTS` in migrations can hide schema drift and make future index changes harder.

This can let an index with the wrong definition (columns, collation, options) slip through, since the migration appears to succeed even though the index shape doesn’t match what you expect. Given that Prisma migrations are linear and controlled, it’s safer to omit `IF NOT EXISTS` so any mismatch fails loudly and surfaces schema drift early.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +2 to +8
CREATE INDEX IF NOT EXISTS "Instance_clientName_idx" ON "Instance"("clientName");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "Instance_token_idx" ON "Instance"("token");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "Instance_number_idx" ON "Instance"("number");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Using IF NOT EXISTS in migrations can hide schema drift and make future index changes harder.

This can let an index with the wrong definition (columns, collation, options) slip through, since the migration appears to succeed even though the index shape doesn’t match what you expect. Given that Prisma migrations are linear and controlled, it’s safer to omit IF NOT EXISTS so any mismatch fails loudly and surfaces schema drift early.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant