perf(prisma): add missing hot-path composite indexes and cascade relations for 10k-100k+ scale

Aperta
#55 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
45/100
Tipo di issue
Funzionalità
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
postgresql, typescript
Ambito
backend, database

Direzione di ricerca

Start with packages/prisma/schema.prisma and review the listed models and their current indexes and relations. Then inspect the cited query and cleanup call sites to confirm the proposed indexes match their filters and sort order. Add the listed indexes and cascade relations, handle orphaned records in the migration, and verify the generated migration and Prisma schema.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

backend database enhancement
Problem Description

Several high-volume tables in packages/prisma/schema.prisma are missing composite indexes on hot query paths, and two tables lack onDelete: Cascade foreign keys to InstagramAccount:

Scale Impact (100 vs 10,000 vs 100,000+ Users)
  • ~100 users (1k–10k rows): Sequential table scans fit in memory and finish in < 5ms — everything works smoothly with no visible slowdown.
  • 1,000–10,000 users (500k–5M+ rows): Hot endpoints and webhook handlers scan hundreds of thousands of rows per request. DB CPU and disk I/O spike, query latency climbs to 200ms–2s+, and connection pools begin queuing under concurrent traffic.
  • 100,000+ users (10M–100M+ rows): Tables exceed PostgreSQL shared buffers and spill to disk. Webhook bursts, inbox loads, and nightly cleanup jobs take 5s–30s+, causing API timeouts, worker queue backlogs, and Meta webhook delivery failures.
Missing Indexes & Relations
  1. InstagramScheduledPost (L1036-1061):
    • Missing @@index([instagramMediaId]) — instagram-comments.service.ts:116 queries this on every incoming comment webhook across all tenants, forcing a full table scan.
    • Missing @@index([companyId, status, scheduledAt]) for scheduled post listings.
  2. Message (L548-572):
    • Missing @@index([conversationId, sentAt]) and @@index([conversationId, direction, sentAt]) — scanned/sorted on every inbox load, cron follow-up check (cron.service.ts:305), and 24-hour messaging window check (v1-messages.controller.ts:53, v1-conversations.controller.ts:66,127).
  3. Conversation (L505-546):
    • Missing @@index([instagramAccountId, archivedAt, lastMessageAt]) for paginated inbox queries (v1-conversations.controller.ts:59-63).
  4. InstagramUserProfile (L250-293):
    • Missing @@index([instagramAccountId, createdAt]) and @@index([instagramAccountId, status]) for CRM/Public API contact listing.
  5. AutomationExecution (L473-489) & ExecutionStep (L491-503):
    • Missing @@index([automationId, instagramUserId, startedAt]) (10s deduplication check in instagram-comments.service.ts:247), @@index([automationId, startedAt]), and @@index([startedAt]) (nightly purge in cron.service.ts:557-568).
    • ExecutionStep is missing @@index([executedAt]) for nightly cleanup.
  6. BackgroundJob (L348-370):
    • Missing @@index([status, completedAt]) for nightly completed job purge (cron.service.ts:572).
  7. Orphaned Records (ContactCapture L296-312 & BackgroundJob L348-370):
    • Both store instagramAccountId without an @relation(..., onDelete: Cascade) to InstagramAccount, leaving orphaned rows when an account or company is deleted.

Expected Behavior
  1. All hot-path lookups, inbox sorts, webhook media checks, and nightly purges execute as fast index scans (O(log N)) at 10k–100k+ users.
  2. Deleting an InstagramAccount automatically cascades and cleans up its ContactCapture and BackgroundJob records.
  3. Zero breaking changes to existing application queries or API contracts.

Where to Look
  • packages/prisma/schema.prisma (InstagramScheduledPost, Message, Conversation, InstagramUserProfile, AutomationExecution, ExecutionStep, BackgroundJob, ContactCapture)

Solution / Implementation Guide
  1. Add the composite @@index([...]) definitions in packages/prisma/schema.prisma for all 7 tables listed above.
  2. Add onDelete: Cascade relations on ContactCapture.instagramAccountId and BackgroundJob.instagramAccountId referencing InstagramAccount.
  3. Generate a safe Prisma migration:
    • In the migration SQL, clean up any orphaned ContactCapture / BackgroundJob rows (DELETE FROM ... WHERE "instagramAccountId" NOT IN (SELECT id FROM "InstagramAccount")) before adding the foreign key constraints.
    • Use CREATE INDEX CONCURRENTLY if applying to a large live production database to avoid locking writes.
Lingua principale
TypeScript
Stelle
2
Fork
1
Merge medio
6m
PR unite (30g)
27

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di sumamakhan761/tryinstance

Tutte le issue di sumamakhan761/tryinstance

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.