As33
@periodic/
arsenic
high_cpu
⚠️ Warning

Query or request caused high CPU consumption

Elevated CPU usage during query execution — often complex aggregations, sorts on large datasets, regex patterns, or missing indexes causing full scans.

Common Causes

  • Complex aggregation pipelines
  • Regex queries without indexes
  • In-memory sorting of large result sets
  • Missing indexes causing full collection scans

How to Fix

  1. 1.Optimize complex calculations
  2. 2.Push computation to database aggregation pipelines
  3. 3.Add indexes for sorting/filtering
  4. 4.Avoid regex queries; use text indexes

Example

typescript
// BAD — regex query causes full scan
const users = await User.find({ name: /^john/i });

// GOOD — text index for search
await User.collection.createIndex({ name: 'text' });
const users = await User.find({ $text: { $search: 'john' } });

Aggregation pipelines run on the database

Move heavy computation into MongoDB aggregation or PostgreSQL expressions rather than fetching raw data and processing it in Node.js.

Aggregation instead of in-memory processing

typescript
// BAD — fetch all, calculate in Node.js
const orders = await Order.find({ userId });
const total = orders.reduce((sum, o) => sum + o.amount, 0); // CPU in Node

// GOOD — compute on the database
const [result] = await Order.aggregate([
  { $match: { userId } },
  { $group: { _id: null, total: { $sum: '$amount' } } },
]);
const total = result?.total ?? 0;