fix: Melhoria de desempenho com uso de indices no endpoint fetchInstance#2568
fix: Melhoria de desempenho com uso de indices no endpoint fetchInstance#2568iagocotta wants to merge 1 commit into
Conversation
Reviewer's guide (collapsed on small PRs)Reviewer's GuideAdds 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 tableerDiagram
Instance {
string id
string clientName "INDEX Instance_clientName_idx"
string token "INDEX Instance_token_idx"
string number "INDEX Instance_number_idx"
}
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- For PostgreSQL, consider using
CREATE INDEX CONCURRENTLYin a separate migration to avoid taking write locks onInstanceduring index creation in large/production tables. - If
clientName,token, ornumberare 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| 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"); |
There was a problem hiding this comment.
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.
Resumo
Adiciona três índices ausentes na tabela
Instanceque 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 telefoneSem 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.sqlVerificação
Após aplicar a migration, use
EXPLAIN ANALYZE(PostgreSQL) ouEXPLAIN(MySQL) para confirmar que os índices estão sendo utilizados:Summary by Sourcery
Add database indexes to improve query performance for instance lookups by client name, token, and phone number.
Build: