Skip to content

Database Query Profiling: A Systematic Optimization Guide

Systematic profiling for PostgreSQL and MongoDB: how to find the queries driving latency and infrastructure cost, and which fixes actually move them.

Ayhan Sipahi Ayhan Sipahi

In a SaaS product, slow database queries often show up on the infrastructure bill before anyone reads a query plan. Product searches taking 8 seconds and dashboards stalling for 45 seconds are symptoms, not root causes. Adding servers suppresses the symptoms while compounding the bill. Profile first, and scale only the part that profiling cannot explain. On PostgreSQL that means pg_stat_statements plus EXPLAIN; on MongoDB it means the database profiler plus an explain plan on the pipeline.

Symptoms in a Multi-Tenant SaaS#

Consider a multi-tenant SaaS platform running both PostgreSQL (for transactional data) and MongoDB (for analytics and document storage). On paper the architecture looks solid. In practice, product search takes 8 seconds per query during peak traffic, and dashboard analytics queries take 45 seconds or more to load, which makes the feature unusable in front of a customer.

Both numbers are symptoms. They say a request is slow. They say nothing about which plan, which index, or which collection scan produced the delay, and that answer only comes from instrumenting the databases themselves.

The Failed MongoDB Migration#

A common failure mode: migrating a core product catalog from PostgreSQL to MongoDB under the assumption that NoSQL handles scale better and document storage fits API responses naturally.

A few months in, with a visibly larger AWS bill, the pattern reveals itself. SQL thinking carried into a NoSQL world means complex joins executed in application memory instead of in MongoDB aggregation pipelines, and query performance ends up worse than it was before the move.

Database technology migrations don’t magically fix poorly designed queries. Understanding access patterns first, then choosing the right tool, avoids this expensive detour.

The Profiling Setup#

The next step is instrumenting both engines so that slow work leaves a record.

PostgreSQL Profiling Stack#

pg_stat_statements and auto_explain both load at server start. pg_stat_statements needs shared memory, so adding it to shared_preload_libraries takes a server restart; a configuration reload is not enough. Its view then exists only in databases where the extension has been created. Skip either step and the ranking query below fails because pg_stat_statements does not exist:

-- Takes effect after a server restart; keep any libraries already listed
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements,auto_explain';

-- After the restart, in each database you want to query
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

On a managed service where ALTER SYSTEM is not available, set the same parameter through the provider’s parameter settings.

Enabling detailed query logging captures everything taking more than 100ms:

-- Enable comprehensive query logging
ALTER SYSTEM SET log_min_duration_statement = 100;
ALTER SYSTEM SET log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h ';
ALTER SYSTEM SET log_checkpoints = on;
ALTER SYSTEM SET log_connections = on;
ALTER SYSTEM SET log_disconnections = on;
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();

These settings have a cost. Every statement over 100ms lands in the log, and log_connections with log_disconnections add lines for every connection that opens and closes. On a busy system with short-lived connections, that means disk IO on the database host and a larger bill wherever the logs are shipped. When the volume gets too high, raise log_min_duration_statement to a ceiling that is always logged and let log_min_duration_sample with log_statement_sample_rate log only a fraction of the statements between 100ms and that ceiling.

Then pg_stat_statements reveals the real picture:

-- Find the resource hogs
SELECT 
    substring(query, 1, 100) as query_start,
    calls,
    total_exec_time,
    mean_exec_time,
    rows,
    100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS cache_hit_percent
FROM pg_stat_statements 
ORDER BY total_exec_time DESC 
LIMIT 20;

On PostgreSQL 12 and earlier those columns are named total_time and mean_time; the rename landed with pg_stat_statements 1.8.

Ranking by total time rather than by worst single call is what makes this list useful. The top entry is usually a query that looks harmless in isolation: a few hundred milliseconds, called tens of thousands of times, with a cache hit ratio low enough to show that nearly every call reaches storage. In the catalog case the top entry is the category search: a sequential scan over a 50-million-row products table on every call.

pg_stat_statements names the statement but keeps no plan. auto_explain writes the plan of each slow statement to the log as it runs, so the log shows the plan production executed, with production parameters and production statistics:

ALTER SYSTEM SET auto_explain.log_min_duration = '500ms';
ALTER SYSTEM SET auto_explain.log_analyze = on;
ALTER SYSTEM SET auto_explain.log_buffers = on;
-- Per-node timing slows every statement, logged or not
ALTER SYSTEM SET auto_explain.log_timing = off;
ALTER SYSTEM SET auto_explain.sample_rate = 0.1;
SELECT pg_reload_conf();

With log_analyze on, PostgreSQL instruments every statement, including the ones that finish under the threshold and never reach the log. Turning log_timing off lowers that cost and still keeps the actual row counts, which are what the estimate check below needs. The sample rate limits explaining to about one statement in ten.

MongoDB Profiling Configuration#

For MongoDB, enabling the profiler captures operations over 100ms:

// Record operations slower than 100ms (level 1; level 2 records everything)
db.setProfilingLevel(1, { slowms: 100 });

// Rank query shapes by the total time they consume
db.system.profile.aggregate([
  { $group: {
      _id: {
        ns: "$ns",
        op: "$op",
        // MongoDB 8.0 adds planCacheShapeHash; earlier versions write only queryHash
        shape: { $ifNull: ["$planCacheShapeHash", "$queryHash"] }
      },
      count: { $sum: 1 },
      avgDuration: { $avg: "$millis" },
      maxDuration: { $max: "$millis" },
      totalDuration: { $sum: "$millis" }
    }
  },
  { $sort: { totalDuration: -1 } },
  { $limit: 10 }
]);

Grouping by $command.find looks tempting, but that field holds the collection name, and aggregate commands do not carry it at all. The plan cache shape hash groups operations that share a filter, sort and projection whatever their parameter values, so ten thousand calls of the same lookup collapse into one row. Ranked by total duration, one shape often dominates. A query operation on orders with a large $in filter near the top, repeated on every dashboard load, points to an application-level join: the service pulls documents in and merges them in its own memory while MongoDB’s aggregation framework sits unused.

The Missing Composite Index#

During peak shopping traffic, product search performance degrades badly, and users abandon carts because results take 8 seconds or more to load.

PostgreSQL logs point at the root cause:

-- The killer query (simplified)
SELECT p.*, c.name as category_name 
FROM products p 
JOIN categories c ON p.category_id = c.id 
WHERE p.active = true 
  AND p.category_id = $1 
  AND p.price BETWEEN $2 AND $3 
ORDER BY p.rating DESC, p.created_at DESC;

The EXPLAIN plan shows a sequential scan across 50 million products for every search, although separate indexes on category_id and price exist. That pairing is a clue in itself. When a category matches a few thousand rows, the planner normally reads it through a bitmap scan on the category_id index. A sequential scan means the planner expects the filter to match a large share of the table. EXPLAIN (ANALYZE, BUFFERS) shows whether that expectation is wrong, because every plan node prints its estimated row count next to the actual one. The products node of such a plan has this shape (an illustrative excerpt):

Seq Scan on products p  (cost=0.00..2334127.00 rows=2412000 width=212) (actual time=0.041..7912.338 rows=3180 loops=1)
  Filter: (active AND (category_id = 42) AND (price >= '20'::numeric) AND (price <= '80'::numeric))
  Rows Removed by Filter: 49996820
  Buffers: shared hit=21894 read=1312233

The planner expected 2.4 million rows and got 3,180. An estimate off by three orders of magnitude usually has one of three causes, and each has a check:

  • Stale statistics. A bulk import or a backfill changes the distribution before the next auto-analyze runs. last_analyze, last_autoanalyze and n_mod_since_analyze in pg_stat_user_tables show how old the statistics are, and a manual ANALYZE products refreshes them.
  • A skewed column. The planner keeps a most-common-values list and a histogram per column, capped at 100 entries each by default. When a few large categories dominate, a small category falls outside the list and gets an averaged estimate. ALTER TABLE products ALTER COLUMN category_id SET STATISTICS 1000 followed by ANALYZE gives the column a larger sample.
  • A generic plan. The query takes $1. A prepared statement runs its first five executions with custom plans, then may switch to a generic plan that ignores the actual category value. Running SET plan_cache_mode = force_custom_plan in a session and repeating the EXPLAIN shows whether the generic plan is the cause.

If the estimate is accurate and the category really holds a large share of the table, the sequential scan is the right plan for that filter, and only an index that also narrows by price changes it.

Fixing the estimate first also shows how much work is left for an index. Once the planner knows the category is small, it switches to a bitmap scan on category_id, which still visits every row in the category and checks price and active one row at a time. A composite index narrows the read to the matching price slice.

CREATE INDEX CONCURRENTLY builds the index without blocking writes, so no maintenance window is required. It cannot run inside a transaction block, and a failed build leaves an invalid index behind that has to be dropped:

CREATE INDEX CONCURRENTLY idx_products_category_price_rating 
ON products (category_id, price, rating DESC, created_at DESC) 
WHERE active = true;

The plan now reads only the slice of the index that matches the category and the price range, where it used to scan 50 million rows. Run the same EXPLAIN (ANALYZE, BUFFERS) again and compare actual time and buffer counts with the first run, then watch the endpoint’s p95 latency through the next traffic peak. Together they show how much latency the change moved on your data. The sort stays in the plan: price is a range predicate, so the index returns its rows ordered by price before rating, and PostgreSQL still sorts what comes back. That sort now runs only over rows that match both the category and the price range, so it stays cheap while that set is small. Removing it altogether takes a different column order, (category_id, rating, created_at, id, price) (built below for the paginated query), because only equality predicates may precede the sort columns. That shape reads the category in rating order and filters price from the index entries, so it earns its keep mainly when the query carries a LIMIT.

The search query above carries none, which is a defect of its own. It returns every matching row with every column of products, so the response grows with the category. A search endpoint should return a page. Keyset pagination keeps every page as cheap as the first: the client sends back the sort key of the last row it received, and the query seeks past it. The row comparison needs a unique tiebreaker, so id joins the sort, and it assumes rating and created_at are NOT NULL:

SELECT p.id, p.name, p.price, p.rating, p.created_at, c.name AS category_name
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.active = true
  AND p.category_id = $1
  AND p.price BETWEEN $2 AND $3
  AND (p.rating, p.created_at, p.id) < ($4, $5, $6)  -- omit on the first page
ORDER BY p.rating DESC, p.created_at DESC, p.id DESC
LIMIT 50;

The order-first index for this query puts the tiebreaker in the key. PostgreSQL scans an ascending index backward to produce the descending order and uses the row comparison as an index condition:

CREATE INDEX CONCURRENTLY idx_products_category_rating_page
ON products (category_id, rating, created_at, id, price)
WHERE active = true;

Keeping price as the last key column lets the scan reject rows outside the price range from the index entry, without visiting the table.

With LIMIT 50 the two indexes compete. The price-first index reads every row in the price slice and keeps the top 50 in a bounded sort. The order-first index walks the category in rating order and stops once 50 rows pass the price filter. It wins when the price range is wide and loses when the range is narrow and the matching rows sit deep in the rating order. Run EXPLAIN (ANALYZE, BUFFERS) with a wide and a narrow price range on production-like data, and keep the index whose buffer counts stay low for both. Keep only one of them unless both show up in real plans, because each one adds write cost.

The trade-off sits on the write path. Every product insert or update now maintains one more index, and the partial index still pays that cost whenever the active flag or any indexed column changes. Measure the write latency delta on your own workload before shipping the index; a read win only counts if the write budget absorbs it.

Moving Joins into the Aggregation Pipeline#

PostgreSQL is only half the picture. Analytics on the MongoDB side often stays slow after the SQL side is fixed, and a dashboard that needs 30 seconds or more to load is one users abandon.

The root cause is often how the application thinks about data. A Node.js application doing this:

// The wrong way - application-level joins
const users = await User.find({ active: true });
const userIds = users.map(u => u._id);
const orders = await Order.find({ userId: { $in: userIds } });
const analytics = users.map(user => {
  // ObjectIds are objects: === would compare references and never match
  const userOrders = orders.filter(o => o.userId.equals(user._id));
  const totalRevenue = userOrders.reduce((sum, o) => sum + o.total, 0);
  return {
    userId: user._id,
    totalRevenue,
    orderCount: userOrders.length,
    avgOrderValue: userOrders.length > 0 ? totalRevenue / userOrders.length : 0
  };
});

That loads potentially millions of documents into application memory and joins them in JavaScript, so the cost scales with the size of the collections rather than with the size of the result. The filter inside the map adds a second problem: every user walks the full order list. The comparison needs .equals() (or String() on both sides) even here, because userId and _id are ObjectId instances and === only matches the same object.

Running the same work in the aggregation pipeline keeps it next to the data. Start from orders, because the result is one row per user with three numbers:

// The right way - aggregate on the orders side, then attach users
const analytics = await Order.aggregate([
  { $group: {
      _id: "$userId",
      totalRevenue: { $sum: "$total" },
      orderCount: { $sum: 1 },
      avgOrderValue: { $avg: "$total" }
    }
  },
  { $lookup: {
      from: "users",
      localField: "_id",
      foreignField: "_id",
      as: "user"
    }
  },
  { $match: { "user.active": true } },
  { $project: { _id: 0, userId: "$_id", totalRevenue: 1, orderCount: 1, avgOrderValue: 1 } }
]);

Starting from users with a $lookup into orders looks closer to the SQL join, but it embeds every order of a user into one array. That intermediate document grows with the user’s order history until it hits the server’s cap (100MB by default since MongoDB 4.0.6, configurable, never below the 16MB BSON limit), and allowDiskUse does not lift it. Grouping first keeps every document small however many orders a user has. The $lookup then runs once per user against users._id, which always has an index. Users without orders drop out of the result, so the dashboard has to treat a missing user as zero. When the dashboard covers a time window, put a $match on an indexed date field before the $group so the pipeline reads only that window.

Only the projected fields cross the wire, and the work happens where the data is. Watch the 100MB per-stage memory limit on $group: since MongoDB 6.0, allowDiskUseByDefault lets a stage over the limit write temporary files to disk instead of failing, at the price of disk IO.

Continuous Performance Monitoring#

The signals worth tracking per engine are few: connections, latency percentiles per query, cache hit ratio, index usage and lock waits on PostgreSQL; operation counts, plan summaries and index usage on MongoDB. The part that catches a regression before users do is a per-query check against a baseline:

// Shared, persisted baseline: written by a release job, never by the alert path
interface BaselineStore {
  getP95(signature: string): Promise<number | undefined>;
}

type RegressionAlert = (signature: string, p95: number, baseline: number) => Promise<void>;

class QueryRegressionCheck {
  private windows = new Map<string, number[]>();

  constructor(
    private readonly baselines: BaselineStore,
    private readonly alert: RegressionAlert,
    private readonly windowSize = 200,
    private readonly threshold = 1.5,
  ) {}

  async record(query: string, durationMs: number): Promise<void> {
    const signature = normalizeQuery(query);
    const window = this.windows.get(signature) ?? [];
    window.push(durationMs);

    if (window.length < this.windowSize) {
      this.windows.set(signature, window);
      return;
    }

    // Evaluate one full window, then start the next one empty
    this.windows.delete(signature);
    const current = p95(window);
    const baseline = await this.baselines.getP95(signature);

    if (baseline !== undefined && current > baseline * this.threshold) {
      await this.alert(signature, current, baseline);
    }
  }
}

function p95(samples: number[]): number {
  const sorted = [...samples].sort((a, b) => a - b);
  return sorted[Math.ceil(sorted.length * 0.95) - 1];
}

// Replace literals so one statement with different parameters shares a signature
function normalizeQuery(query: string): string {
  return query
    .replace(/'(?:[^']|'')*'/g, "?")
    .replace(/\b\d+(?:\.\d+)?\b/g, "?")
    .replace(/\s+/g, " ")
    .trim();
}

The value sits in the signature. Normalizing parameters out of the query text makes the same statement comparable across calls, so an unindexed variant introduced in a pull request surfaces as a shifted distribution where a single slow request would stay buried in the logs. The comparison runs against a stored p95 that nothing on the alert path writes. A single slow sample (a GC pause, a lock wait) moves one window’s p95 at most and leaves the baseline where it was, so it cannot raise the bar for later regressions. Each application instance fills its own windows, and all of them compare against the same baseline. Promote a new baseline deliberately, for example from a release job after a full traffic cycle.

On PostgreSQL the same comparison can also run inside the database. Snapshot pg_stat_statements on a schedule, divide the change in total_exec_time by the change in calls for each queryid, and compare that window mean against a stored snapshot. The view covers every application instance at once, though it offers only a mean and a standard deviation, without percentiles. queryid is not stable across major versions, so take a new baseline after an upgrade.

From Query Fix to a Smaller Instance#

Query work is often what grows a database bill. A sequential scan burns IOPS and evicts useful pages from the buffer cache, a low cache hit ratio pushes reads back to storage, and both push the instance class up.

Removing the scan reverses that chain in a specific order. CPU and IO drop first. Read replicas that exist only to absorb query load become removable next. The instance class and the Atlas tier come down last, because resizing is a step function tied to a maintenance action; it does not follow the load down continuously. Measure at least one full weekly traffic cycle after the query fix before resizing anything, or you size against a load profile that no longer exists. Record the instance class, replica count, provisioned IOPS and the endpoint’s p95 before the fix as well, so the cost change can be traced to the query work.

PostgreSQL vs MongoDB: Choosing the Right Tool#

Choose by access pattern:

Use PostgreSQL when:

  • Queries join several entities, or the joins are not known up front (reporting, ad-hoc filters)
  • Invariants span several rows or tables and must hold on every write (balances, inventory counts)
  • The team reads EXPLAIN plans and writes SQL day to day

Use MongoDB when:

  • Most reads fetch one aggregate that fits in a single document (an order with its line items, a profile with its settings)
  • The shape of those documents changes often
  • You need horizontal scaling built in
  • Aggregations run over one collection shaped for the query, the way the orders pipeline above does; pipelines that join several large collections are where the analytics problem in this example started

MongoDB has had multi-document transactions since 4.0 on replica sets and 4.2 on sharded clusters, so ACID alone does not separate the two. The difference is cost: MongoDB’s own documentation says a distributed transaction usually costs more than a single-document write and should not replace effective schema design. When most writes need a transaction, the data usually fits a relational model better.

When the answer is not obvious, default to PostgreSQL. It covers document workloads with jsonb well enough for most product catalogs, and moving a collection out of PostgreSQL later is a smaller change than moving relational data into it after the fact. Base the decision on access patterns and consistency requirements.

Effective Profiling Tools#

Evaluating database profiling tools reveals which ones deliver real value:

PostgreSQL Tools#

pgBadger for Log Analysis:

# Generate comprehensive performance reports
pgbadger -j 4 -f stderr /var/log/postgresql/postgresql-*.log \
  --prefix '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h' \
  -o /var/www/html/pgbadger.html

pgBadger turns PostgreSQL logs into actionable reports, surfacing patterns like queries that are fast individually but consume significant total time due to call frequency.

Percona Monitoring and Management (PMM): PMM’s Query Analytics keeps per-query time series with the plan attached, which is what separates a genuine regression from a traffic change. It covers both PostgreSQL and MongoDB, so one dashboard answers questions about both engines.

MongoDB Tools#

MongoDB Compass: Compass renders explain output as a tree, which makes a collection scan or an in-memory sort easy to spot without reading raw JSON. Checking a pipeline there before shipping it costs a minute.

Custom Profiling Scripts:

// Automated slow query detection
function analyzeSlowQueries() {
  return db.system.profile.aggregate([
    { $match: { millis: { $gt: 100 } } },
    { $group: {
        _id: {
          collection: "$ns",
          operation: "$op"
        },
        count: { $sum: 1 },
        avgDuration: { $avg: "$millis" },
        maxDuration: { $max: "$millis" }
      }
    },
    { $sort: { avgDuration: -1 } }
  ]);
}

Scheduled daily, this reports the slowest operations of the previous window. Note that system.profile is a capped collection: whatever is not read before it wraps is gone, so export the summary.

Common Pitfalls and How to Avoid Them#

The “Add More Indexes” Trap#

Treating indexes as a silver bullet is the common way this goes wrong: query slow, add an index; still slow, add another. Before long a hot table carries a dozen indexes, every insert maintains all of them, and the write path costs more than the reads ever saved.

Every index speeds up reads but slows down writes. Design the indexing strategy around the read/write ratio of each table, and be selective on write-heavy ones. pg_stat_user_indexes shows which indexes are never scanned; those are pure cost.

The Production Data Surprise#

An optimization that works against 10,000 uniform test records says little about 50 million production records with a skewed distribution.

The planner picks a plan from statistics. When one tenant holds most of the rows, or a status column is 99% one value, the row estimates are wrong and the plan is wrong with them, so a query that runs in 10ms locally can take orders of magnitude longer in production.

Test optimizations against production-scale data, or at least against data with similar distribution characteristics. Restoring a sanitized dump and running ANALYZE gets closer than any synthetic generator.

The Wrong Metrics Focus#

A recurring failure mode: optimizing the wrong queries by measuring database-centric metrics instead of user-facing operations. Weeks spent on overnight batch processes while user-facing search queries remain slow.

Focus on operations that directly impact user experience first. Internal reporting can be slow; user-facing operations cannot.

Start with Business Impact Measurement Prioritize the queries with the highest business impact; the slowest query is not always the most costly one. A 1-second improvement on a query hit 10,000 times per day delivers more value than a 10-second improvement on a query hit once per day.

Implement Automated Performance Testing Set up automated performance regression testing in your CI/CD pipeline. Catch performance issues during code review, before customers notice them.

When This Approach Holds#

Profiling before scaling holds when the workload is query-bound: the instance is busy, but the time goes into plans nobody has read. Scale the hardware instead when the evidence points the other way. A workload whose top queries already use their indexes, whose cache hit ratio is high, and which still saturates IOPS has exhausted what EXPLAIN can give it and needs a bigger instance. The same is true of a write-heavy table where index maintenance is already the bottleneck; there the next move is dropping indexes or partitioning the table.

The starting point is identical in both cases. Enable pg_stat_statements and the MongoDB profiler, rank by total time, and fix the top two entries before changing anything else.

References#

Related posts