[Bug]: Heavy Database CPU & IOPS (I/O Operations per second) Spikes via COUNT(*) in DatabaseManager.getMetadata()
Author: prakharsingh-74Created Sep 27, 2026Updated Sep 27, 2026
Labelsbugneeds-triage
What's the bug?
Location
backend/src/infra/database/database.manager.ts (Lines 170–209) | Severity: HIGH
Summary
DatabaseManager.getMetadata() fetches schema metadata and record counts across all user tables in the public schema. When cache entries expire (TTL 60s) or are missing, it builds and executes a single combined UNION ALL SQL query running exact COUNT(*) selections over every un-cached table.
Flawed Implementation Code
const unionQuery = missingOrExpired
.map((tableName) =>
pgFormat(
'SELECT %L as table_name, COUNT(*) as count FROM %I.%I',
tableName,
'public',
tableName
)
)
.join(' UNION ALL ');
const queryResult = await client.query(unionQuery);
### Performance & Database Scaling Impact
In PostgreSQL, COUNT(*) requires a full sequential scan of table pages to count visible tuples under MVCC. For production databases with multi-gigabyte tables or millions of rows, executing COUNT(*) across all tables on metadata requests causes database CPU saturation, high disk IOPS, connection pool starvation, and API timeouts.
### Expected behavior
Metadata overview requests should not perform full MVCC `COUNT(*)` sequential table scans. Fast estimates should be queried from PostgreSQL catalog views (e.g., `pg_class.reltuples` or `pg_stat_user_tables.n_live_tup`) or exact counting should be refactored/opted into only when explicitly needed.
### How to reproduce
_No response_
### Environment (optional)
_No response_Source: InsForge/InsForge