Photo by Bernd 📷 Dittrich on Unsplash
Your database is probably the first thing to degrade when traffic spikes, and the last thing your team finds out about. Most small teams discover slow queries from a customer complaint or a dashboard timeout, not from a monitoring alert. The instinct is to reach for an APM tool, but the pricing, setup overhead, and vendor lock-in often don't match what a five-person team actually needs.
This guide walks through monitoring database query performance without APM, using tools you already have access to: native database features, open source software, and a handful of scripts you can write in an afternoon.
Why APM Tools Aren't Always Necessary for Database Query Monitoring
The hidden costs of enterprise APM solutions
APM pricing is rarely just the subscription fee. Most vendors charge per host, per agent, or per GB of ingested data, and database monitoring usually sits in a separate tier from application tracing. A team monitoring three Postgres instances and two app servers can easily end up paying for capacity they don't use, just to unlock query-level visibility.
Then there's the setup cost. Agents need to be installed, tuned, and kept updated. Some APM agents add measurable overhead to query execution, which means you're paying to slow down the exact thing you're trying to speed up. And once the data lives in a vendor's platform, migrating away means rebuilding dashboards and alert rules from scratch.
What small teams actually need vs. what vendors sell
Enterprise APM suites are built for organizations with dozens of services, multiple database engines, and dedicated platform teams. They bundle distributed tracing, code-level profiling, infrastructure monitoring, and business transaction mapping into one package.
Most small teams need a much smaller slice of that: which queries are slow, which ones got slower recently, and an alert when something crosses a threshold. That's a query performance monitoring problem, not a full observability problem. Buying an entire APM suite to solve it is like buying a server rack to run a static website.
Performance monitoring gaps that don't require expensive tooling
The gaps that actually hurt small teams are usually basic: no visibility into which queries are consuming the most execution time, no historical baseline to compare against, and no alert when a query that used to take 50ms starts taking 2 seconds. None of these require distributed tracing or code-level instrumentation. They require consistent logging, a place to store the data, and a way to query it.
When DIY database monitoring makes sense
DIY monitoring makes sense when your database footprint is small enough that one or two engineers can reason about it, when you have the operational discipline to maintain scripts and dashboards, and when your incident volume doesn't justify a six-figure observability contract. If you're running a handful of Postgres or MySQL instances and a small on-call rotation, you can build monitoring database query performance without APM in a few days and maintain it with minimal ongoing effort.
It makes less sense once you have dozens of services, multiple database engines in production, and a team that needs cross-service tracing to debug issues. At that point, the math shifts, and we'll cover how to evaluate that switch later.
Native Database Monitoring Capabilities You're Already Paying For
Before installing anything new, check what your database is already tracking. Most engines ship with query performance instrumentation that's disabled by default or just never got turned on.
PostgreSQL query logs and pg_stat_statements
pg_stat_statements is the single most useful extension for monitoring database query performance without APM on Postgres. It tracks execution counts, total and mean execution time, rows returned, and cache hit ratios for every normalized query running on your instance.
Enable it with:
CREATE EXTENSION pg_stat_statements;
And add it to shared_preload_libraries in postgresql.conf, then restart the instance. Once running, you can pull your top offenders directly:
SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Pair this with log_min_duration_statement set to something like 500ms, so anything slower gets written to the log with full context. This combination alone replaces a huge portion of what teams pay APM vendors for.
MySQL slow query logs and performance_schema
MySQL's slow query log has existed for years and is still underused. Set slow_query_log = ON and long_query_time to your threshold, and MySQL will log every query exceeding it, including execution time and rows examined.
performance_schema goes further, exposing wait events, lock contention, and per-statement digest statistics through tables like events_statements_summary_by_digest. This is the same data an APM agent would otherwise scrape, except it's already sitting in your database with zero extra agents installed.
SQL Server DMVs (Dynamic Management Views)
SQL Server exposes an entire layer of Dynamic Management Views for this exact purpose. sys.dm_exec_query_stats gives you aggregated execution statistics per query plan, and joining it with sys.dm_exec_sql_text gives you the actual query text. sys.dm_os_wait_stats shows what your instance is spending time waiting on, whether that's disk I/O, locks, or network.
Teams running SQL Server often don't realize how much of their APM bill is paying for data they could pull with a scheduled job and a few DMV queries.
MongoDB profiler and system.profile collection
MongoDB's built-in profiler logs operations that exceed a configurable threshold into the system.profile collection. Enable it per-database with:
db.setProfilingLevel(1, { slowms: 100 })
From there, querying system.profile gives you execution times, query shapes, and index usage per operation, which is enough to catch missing indexes and collection scans without any external tooling.
Built-in monitoring dashboards you might be overlooking
Managed database providers often ship dashboards that go unused. RDS Performance Insights, Azure SQL's Query Performance Insight, and Cloud SQL's query insights all surface top queries, wait events, and historical trends for little to no additional cost if you're already paying for the managed instance. Check what's included before assuming you need third-party tooling.
Open Source Tools for Database Query Performance Monitoring
Once native logging is in place, open source tools help you visualize and retain that data over time.
pgAdmin and DBeaver for PostgreSQL environments
pgAdmin includes a built-in dashboard showing active sessions, locks, and server activity, and can surface pg_stat_statements data directly in its query tool. DBeaver, a free cross-platform database client, supports similar inspection across Postgres, MySQL, and SQL Server, making it a reasonable first stop for ad hoc query analysis before you build anything automated.
Percona Monitoring and Management (PMM) for MySQL/MariaDB
PMM is a free, self-hosted monitoring stack purpose-built for MySQL, MariaDB, PostgreSQL, and MongoDB. It bundles Prometheus-style metrics collection, pre-built Grafana dashboards, and query analytics into a single Docker deployment. For MySQL-heavy teams, PMM is probably the closest open source equivalent to a dedicated database APM product, and it's genuinely production-grade, not a toy project.
SolarWinds DPA alternatives in the open source space
SolarWinds Database Performance Analyzer is a common reference point for teams evaluating paid database monitoring. If you're trying to replicate its wait-time analysis without the license cost, the realistic open source combination is PMM for MySQL/Postgres, native DMVs with a Grafana front end for SQL Server, and pg_stat_statements plus Grafana for Postgres-only shops. None of these are a single drop-in replacement, but together they cover the same core use case: identifying which queries are consuming the most wait time and why.
Setting up Prometheus + node_exporter for database metrics
If you're already running Prometheus for infrastructure metrics (common if you've set up Kubernetes cluster monitoring), extending it to databases is incremental. postgres_exporter and mysqld_exporter both expose query and connection metrics in Prometheus format, and node_exporter covers the underlying host's disk I/O and memory pressure, which often explains query slowdowns that look database-specific but are actually infrastructure-level.
Grafana dashboards for visualizing query performance data
Grafana is the natural front end for all of this. Community dashboards exist for postgres_exporter and mysqld_exporter that you can import directly, giving you query throughput, latency percentiles, and connection counts without designing a dashboard from scratch. The combination of Prometheus plus Grafana is, in practice, how most teams end up monitoring database query performance without APM at a scale that actually holds up under real production load.
Custom Monitoring Scripts and Query Analysis Approaches
Native tools and dashboards cover visibility. Scripts cover automation, baselining, and alerting.
Writing SQL queries to identify slow queries from system catalogs
A simple recurring query against pg_stat_statements or performance_schema can identify regressions before they become incidents. For Postgres:
SELECT query, calls, mean_exec_time
FROM pg_stat_statements
WHERE mean_exec_time > 200
ORDER BY mean_exec_time DESC;
Run this on a schedule and store the results, and you have a rolling record of which queries are trending worse over time, not just a snapshot.
Bash and Python scripts for automated performance baseline tracking
A Python script using psycopg2 or pymysql can snapshot pg_stat_statements or performance_schema output hourly, write it to a local table or flat file, and diff it against the previous snapshot. This gives you a crude but effective baseline: if a query's mean execution time jumps 3x compared to yesterday's snapshot, flag it. This is maybe 100 lines of Python, no agents, no vendor contract.
Log parsing techniques for query analysis without agents
For teams relying on slow query logs rather than system catalogs, tools like pt-query-digest (part of Percona Toolkit) parse MySQL slow logs and produce ranked summaries of the worst offenders by total time, not just by individual slow instances. pgBadger does the same for Postgres logs, generating HTML reports with query fingerprints, execution trends, and lock statistics. Both are free, both run on a cron job, and both require nothing installed on the database server itself.
Setting up automated alerts on slow query thresholds
Once you have a script pulling query stats, alerting is just a threshold check. A basic pattern:
- Query
pg_stat_statementsorperformance_schemaevery 5 minutes. - Compare mean execution time against a stored baseline.
- If a query exceeds baseline by a defined percentage for N consecutive checks, fire a webhook.
That webhook can hit Slack, trigger a PagerDuty-style escalation, or feed into alert routing set up without PagerDuty if you're already running something lighter weight.
Integration with your existing on-call and alerting systems
Database alerts shouldn't live in a silo. Route them through the same channels you use for everything else, whether that's Slack, SMS, or a dedicated uptime monitoring tool like Uptiqr. If you haven't settled on which channel works best for which severity, it's worth reviewing how Slack, email, and SMS compare for critical alerts before wiring up database thresholds, since a slow query alert buried in a Slack channel with 200 unread messages is functionally the same as no alert at all.
Building a Database Monitoring Strategy Without APM
Tools alone don't make a monitoring strategy. You need agreement on what matters and what happens when thresholds are crossed.
Defining what metrics matter for your small team
Start narrow. Query latency (p50, p95, p99), error rate, connection pool saturation, and lock wait time cover the majority of real incidents. Resist the urge to track everything your database exposes just because it's available. More dashboards without clear ownership just become noise nobody checks.
Establishing baselines and acceptable query performance thresholds
A query that takes 800ms might be perfectly fine for a nightly report and completely unacceptable for a page load. Baselines need to be set per query or per query category, not as a single global threshold. Run your workload for a week, record the p95 execution time for your critical queries, and use that as your starting threshold, revisiting it as traffic patterns change.
Creating runbooks for common database performance issues
When an alert fires at 2am, nobody wants to start debugging from zero. Write runbooks for the failure modes you'll actually see: missing index causing a sequential scan, connection pool exhaustion, lock contention from a long-running transaction, or replication lag. Each runbook should have the diagnostic query to run first and the most likely fix. This is the same discipline covered in incident timeline documentation, applied specifically to database incidents.
Connecting database alerts to your incident response workflow
A slow query alert isn't automatically an incident. Decide upfront which thresholds trigger a page versus a ticket versus a dashboard note, and align that with whatever severity classification framework you already use. This also ties into distinguishing degraded performance from full outages, since a slow query is almost always a degradation signal before it becomes a full outage.
Cost comparison: DIY monitoring vs. enterprise APM over 12 months
A rough comparison for a team running 3 to 5 database instances:
- Enterprise APM: $1,500 to $4,000/month depending on host count and data retention, plus engineering time for agent setup and tuning.
- DIY stack (Prometheus, Grafana, exporters, custom scripts): Hosting cost for the monitoring stack itself, typically $50 to $150/month on a small VM or existing Kubernetes cluster, plus roughly 2 to 4 engineering days for initial setup and a few hours a month for maintenance.
Over 12 months, that's a difference of $15,000 to $45,000, against maybe a week of total engineering time. For teams with the in-house capability to maintain scripts and dashboards, that trade clearly favors DIY. For teams without that capacity, the calculus changes, since engineering time has a cost too.
Implementation Roadmap: Getting Started This Month
Step-by-step setup for your database platform
Postgres: Enable pg_stat_statements, set log_min_duration_statement, deploy postgres_exporter, import a community Grafana dashboard, write a baseline script.
MySQL: Enable the slow query log, turn on performance_schema consumers, deploy mysqld_exporter or PMM, run pt-query-digest on a schedule.
SQL Server: Build a scheduled job querying sys.dm_exec_query_stats, pipe results into a reporting table, visualize with Grafana via the SQL Server data source.
MongoDB: Enable the profiler at a sensible threshold, query system.profile on a schedule, alert on slow operation counts.
Integrating with existing monitoring infrastructure
If you already run Prometheus and Grafana for infrastructure or Kubernetes monitoring, add database exporters to the same stack rather than standing up a separate system. One dashboarding tool, one alerting pipeline, fewer places for things to silently break.
Common pitfalls small teams encounter and how to avoid them
The most common failure is setting up the dashboards and never setting up the alerts, so nobody looks until something breaks. The second most common is alerting on too many thresholds at once, causing fatigue and ignored pages. Start with 3 to 5 alerts tied to real business impact, and expand only once those are trusted.
Scaling your DIY approach as your team and database grows
As instance count grows, centralize exporters behind a single Prometheus federation setup rather than managing configs per-instance. As query volume grows, move from ad hoc scripts to a proper time-series retention policy so historical comparisons stay accurate instead of relying on a rolling 24-hour window.
When to reconsider APM tools and how to evaluate the switch
Reconsider APM once you need cross-service tracing (a slow query that's actually caused by an upstream service issue), once your team has grown enough that dashboard and script maintenance competes with product work, or once you're running more database engines than one or two people can reasonably keep mental models of. When evaluating, price based on your actual instance count and retention needs, not the vendor's default tier, and check whether you can export your historical data if you switch back.
FAQ
What's the difference between query monitoring and full APM?
Query monitoring focuses specifically on database-level metrics: execution time, lock waits, index usage, connection counts. Full APM adds distributed tracing across services, code-level profiling, and business transaction correlation. Most small teams need the former and are sold the latter.
Can I monitor database performance across multiple database types without APM?
Yes. Prometheus with engine-specific exporters (postgres_exporter, mysqld_exporter, MongoDB exporter) feeding a single Grafana instance gives you a unified view across engines without a unified vendor product.
How do I set up alerts for slow queries without paying for APM?
Use native logging (slow query log, pg_stat_statements) combined with a scheduled script or Prometheus alerting rule that checks execution time against a baseline, then route the alert through your existing notification channels or a tool like Uptiqr for escalation.
What should I monitor first if I'm just starting database performance monitoring?
Start with query latency percentiles and connection pool saturation. These two catch the majority of real-world performance incidents and require minimal setup on any major database engine.
Is it realistic for a small team to maintain DIY database monitoring long-term?
Yes, up to a point. Teams running a handful of instances with 2 to 3 engineers comfortable with SQL and basic scripting can maintain this indefinitely with a few hours of upkeep monthly. Once database count or team complexity grows significantly, revisit whether the maintenance burden still makes sense against a paid tool. Check Uptiqr's pricing or feature set if you want alerting and escalation handled without building that layer yourself.