ReinDBby Bandlei

2. Set up your toolkit

Brett Rosenblatt · Database tuning guide v1.3 · PDF

You can't tune what you can't see, and you can't prove a fix without history. Set the toolkit up before the next incident, not during it.

2.1What a complete toolkit covers

CapabilityWhat it gives youTypical sources
HistoryLow-overhead measurements of statements, waits and resources, kept for weeksThe engine's statement statistics and history stores, snapshot repositories, a monitoring product
Live viewWho is running what right now, who blocks whom, what sessions wait onSession, lock and transaction views
Plan inspectionEstimated and actual plans with real row countsThe engine's explain facilities and actual (runtime) plans
Platform metricsCPU, memory, storage latency and throughput, network, cloud limitsOS tools, node_exporter, Amazon CloudWatch, Azure Monitor, Google Cloud Monitoring
Change recordDeployments, parameter changes and schema changes, with timestampsCI/CD logs, change tickets, dashboard annotations
Alerting and reportingNotifications for real deviations, and reports for regular reviewAlert manager, monitoring product, scheduled reports

No single tool covers all six well. Aim for full coverage with as little overlap as possible, and make sure every source uses the same clock (UTC is easiest) so you can line events up during an incident.

2.2What the engine gives you for free

Every major engine ships with serious instrumentation, and it comes in the same five families everywhere:

  • Statement statistics: cumulative calls, time, rows and I/O for each normalized statement, since the last restart or reset.
  • Live activity: the sessions, what each one is running and waiting on, and who blocks whom.
  • Plans: the estimated plan, and the actual plan with real row counts and timings.
  • Waits and time accounting: where the time goes, by wait event or class, for the whole instance and for each session.
  • Logs and traces: slow statements, lock waits, deadlocks and temp spills, captured one execution at a time.

Learn these first: commercial tools read the same sources. The table maps the families to each engine.

EngineStatement historyLive activityPlansWaits and extras
PostgreSQLpg_stat_statements extensionpg_stat_activity, pg_locks, pg_blocking_pids()EXPLAIN (ANALYZE, BUFFERS), auto_explainwait_event in pg_stat_activity (point in time); pg_wait_sampling extension for history; pg_stat_io (16+); table and index statistics views
MySQLperformance_schema statement digests; sys schema viewsperformance_schema.threads, SHOW PROCESSLIST, sys.innodb_lock_waitsEXPLAIN, EXPLAIN ANALYZE (8.0.18+), optimizer traceperformance_schema wait events (some instruments are off by default); slow query log; pt-query-digest from Percona Toolkit
SQL ServerQuery Store (2016+); sys.dm_exec_query_statssys.dm_exec_requests, sys.dm_exec_sessions, sys.dm_os_waiting_tasksActual execution plans; plans in Query Storesys.dm_os_wait_stats; per-query waits in Query Store (2017+); Extended Events (the default system_health session records deadlocks)
Oracle, no packsV$SQL, V$SQLSTATSV$SESSION, V$LOCK, V$TRANSACTIONDBMS_XPLAN.DISPLAY_CURSOR, V$SQL_PLAN_STATISTICS_ALLV$SYSTEM_EVENT, V$SESSION_EVENT, V$SYS_TIME_MODEL; SQL trace (event 10046) with TKPROF; Statspack for history

2.3Know what you're licensed to use

Some performance features cost extra, depend on the edition, or exist only on certain platforms. On some engines, querying a licensed view counts as use of the feature, even from a script or a monitoring tool. Before you build the toolkit, list what your editions and contracts actually include, and make everything else hard to use by accident.

2.4Turn on the instrumentation you'll need

Several of the most useful sources are off by default, or need a restart to enable. Turn them on during a quiet change window, not in the middle of an incident. Whatever the engine, you want the same things switched on: statement statistics sized for your workload, I/O timing, logs of slow statements, lock waits and temp spills, a history of statements and plans that outlives the cache, and application names on every connection.

EngineSettingWhyCost and notes
PostgreSQLshared_preload_libraries = 'pg_stat_statements', then CREATE EXTENSION pg_stat_statementsStatement historyNeeds a restart; small overhead
PostgreSQLtrack_io_timing = onI/O time per statement and per tableCheck timer overhead with pg_test_timing; usually low on modern hardware
PostgreSQLlog_lock_waits = on, log_temp_files = 0, log_min_duration_statement or auto_explain.log_min_durationEvidence of lock waits, temp spills and slow statementsLog volume; start with a threshold such as 1 s
PostgreSQLtrack_functions = 'pl', pg_stat_statements.track = 'all'Visibility into functions and the statements inside themSmall overhead
MySQLperformance_schema = ON (the default) with statement digest consumers enabled (the default)Statement historyFixed memory; for very varied workloads check performance_schema_digests_size
MySQLslow_query_log = ON, long_query_time = 1, log_slow_extra = ON (8.0.14+)Evidence for individual executionsLog volume
SQL ServerQuery Store ON with OPERATION_MODE = READ_WRITE and QUERY_CAPTURE_MODE = AUTOStatement and plan history that survives restarts, and plan forcingOn by default for new databases in SQL Server 2022; size MAX_STORAGE_SIZE_MB so it never flips to read-only
SQL Serverblocked process threshold (s) of 10 to 20, plus an Extended Events session for blocked_process_reportEvidence of blocking after the factDeadlocks are already in system_health
OracleSTATISTICS_LEVEL = TYPICAL (the default)Time model, advisories, timed statisticsUse ALL only per session while diagnosing
OracleHourly Statspack snapshots, if you don't license the Diagnostics PackHistoryPurge old snapshots regularly
AllModule and application names set by the applicationLets every tool attribute time to a feature or serviceFree; see Chapter 9

2.5Monitoring accounts with least privilege

Monitoring needs to read performance views, not business data. Give it exactly that: a dedicated login, the engine's built-in monitoring role or a short list of view grants, no write access, and no access to application tables. Keep its password in a secrets store and rotate it like any other service credential.

2.6Cloud and managed databases: what changes

Managed services run the same engines, so the method in this guide holds. What changes is your reach. You trade host access and some control for automation, and you inherit the provider's limits and defaults. Expect these differences:

  • No host access. There is no operating system shell and no full superuser (SYSDBA, sysadmin or a PostgreSQL superuser). Logs and trace files come through the provider's console, API or helper procedures.
  • Settings through the provider. Parameters change in parameter groups, flags or server parameters. The defaults are the provider's, some values are fixed, and static ones need a reboot (Chapter 11).
  • Features from a menu. Only approved extensions, plugins and options are available, and some only through an option group or a higher tier.
  • Platform limits. Storage throughput and IOPS are provisioned or tied to the instance size, burst credits can run out, and the instance class caps network and log throughput. Rule these out before you tune a statement (Chapter 5).
  • Provider monitoring. Amazon CloudWatch Database Insights, Azure's Query Performance Insight and Cloud SQL Query Insights read the same engine statistics and keep them longer. Know what each tier keeps, for how long, and what it costs.
  • License included or brought. The instance price either includes the license or you bring your own, and that decides which editions and paid features you may use.
  • Provider maintenance. Minor version upgrades and maintenance windows can change plans. Annotate them like any other change (Chapter 12).
  • Different storage underneath. Some services replace the engine's storage layer (Amazon Aurora and Google AlloyDB, for example), so advice about checkpoints, flushing and log sizing may not apply.

2.7Beyond the built-ins: choosing a monitoring tool

Built-in views are deep but local: one database at a time, short memory, and no idea what is normal. A monitoring tool earns its place by adding history, comparison and reach. Judge candidates on these points:

  • Coverage. All your engines and platforms, including managed services such as RDS and Aurora.
  • Footprint. Read-only access with minimal grants, low overhead, and nothing installed inside the database if your security team objects to agents.
  • History. At least two to four weeks kept, so baselines are meaningful.
  • Comparison. It knows what normal looks like for each hour, instead of relying only on static thresholds.
  • Depth. Statement-level drill-down, plan history and wait breakdown, not just server charts.
  • Licensing awareness. It stays within the features you're licensed for, and says clearly when it would use a paid one, such as Oracle's Diagnostics and Tuning Packs.
  • Integration. Exports to your observability stack (Prometheus and Grafana, for example) and alerting that reaches your on-call process.
  • Reviewable output. Findings explained in plain terms, and fixes delivered as scripts your team can test, rather than changes made silently in production.
  • Security and deployment. Credential handling, an audit trail, redaction of literals, and a deployment model that fits (hosted, in your cloud account, or on premises).
CategoryExamplesStrengths and limits
Built into the engineQuery Store, pg_stat_statements, performance_schema, V$ views and StatspackFree and deep; one database at a time; little history or comparison unless you persist it
Vendor consolesOracle Enterprise Manager (performance pages need the packs), SQL Server Management Studio reports, cloud provider consolesClose to the engine; usually tied to one vendor or one cloud
Open-source stacksPrometheus with exporters and Grafana; Percona Monitoring and Management; pgBadger; pt-query-digestFlexible and free to run; you build and maintain the dashboards, the alert rules and the baselines yourself
Commercial database monitoringCross-engine products from observability and database tool vendorsBroad coverage and polish; agents, pricing and lock-in vary
ReinDBDrift monitoring for PostgreSQL, MySQL, SQL Server and OracleLearns normal per database and hour, flags drift with evidence, writes fix scripts; read-only; exports to Grafana

This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.