evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

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

Open iagocotta opened this issue 6 months ago • 1 comments

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.

iagocotta avatar May 27 '26 10:05 iagocotta

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"
  }

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

  • Contact our support team for questions or feedback.
  • Visit our documentation for detailed guides and information.
  • Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.

sourcery-ai[bot] avatar May 27 '26 10:05 sourcery-ai[bot]

🟢 👍

Mira a develop e é do jeito certo: migration aditiva com índices (clientName, token, number) em Instance nas duas engines, sem tocar código — ajuda direto as queries do fetchInstance. Único detalhe de consistência: a migration do PostgreSQL usa IF NOT EXISTS e a do MySQL não (as outras migrations de índice do repo não usam em nenhuma das duas) — padroniza pra ficar igual ao resto. Fora isso, pode seguir.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias

Feito a padronização da criação dos index para o postgres e mysql!

iagocotta avatar Jun 26 '26 10:06 iagocotta

Removido o UNIQUE da criação dos INDEX como solicitado

iagocotta avatar Jun 26 '26 17:06 iagocotta