fix: Melhoria de desempenho com uso de indices no endpoint fetchInstance
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 afetchInstancessem instância específicatoken— filtrado em toda requisição autenticada a/instance/fetchInstancesquando utilizado token de instância ao invés da chave global (auth.guard.ts+instance.controller.ts)number— filtrado nas buscas viainstanceInfoByIdpor 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.sqlprisma/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.
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.Reviewer's guide (collapsed on small PRs)
Reviewer's Guide
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.
prisma/mysql-migrations/20260527000000_add_index_instance_client_name_token_number/migration.sqlprisma/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 reviewon 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 issueto create an issue from it. - Generate a pull request title: Write
@sourcery-aianywhere in the pull request title to generate a title at any time. You can also comment@sourcery-ai titleon the pull request to (re-)generate the title at any time. - Generate a pull request summary: Write
@sourcery-ai summaryanywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment@sourcery-ai summaryon the pull request to (re-)generate the summary at any time. - Generate reviewer's guide: Comment
@sourcery-ai guideon the pull request to (re-)generate the reviewer's guide at any time. - Resolve all Sourcery comments: Comment
@sourcery-ai resolveon 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 dismisson 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 reviewto 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.
🟢 👍
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
Feito a padronização da criação dos index para o postgres e mysql!
Removido o UNIQUE da criação dos INDEX como solicitado