ReinDBby Bandlei

5. Decide what to look for

Brett Rosenblatt · Database tuning guide v1.3 · PDF

"Find the slow queries" sounds like a plan, but it hides two questions: slow by what measure, and is a query the right place to start at all? This chapter answers both, then shows how to collect the evidence, with engine notes for the details.

5.1Slow queries or overall execution time? Use three lenses

StatementCalls per hourAverage timeTotal time per hourShare of load
A: product lookup900,0004 ms3,600 s81%
B: monthly finance report245 s90 s2%
C: checkout insert30,00025 ms750 s17%

Each statement is "the problem" through a different lens:

  • Throughput lens (total time = calls × average time). Statement A costs the database the most. Making it 25% cheaper frees more capacity than making B instant. Rank by total time when the goal is lower load, lower cost or more headroom.
  • Experience lens (time per call, ideally the 95th or 99th percentile). Statement B is what finance complains about, and C sits on the path to revenue. Rank by per-call latency of user-facing statements when the goal is a better experience.
  • Regression lens (now against its own normal). A statement that used to take 4 ms and now takes 12 ms matters even if it isn't top of either list yet, because something changed: a plan, the data, or contention. Regressions are the earliest warning you get.

A good investigation uses all three. Start from the lens that matches the symptom, and check the other two before you finish.

5.2Four proven methods

  • Response-time analysis. Measure where the time goes for the task that matters, and attack the biggest component. Database time is CPU time plus wait time. Cary Millsap's Method R is the classic statement of the idea.
  • Wait-based analysis. Classify non-idle database time by wait class (CPU, I/O, locks, commit, concurrency, network) to find the dominant bottleneck.
  • USE method (Brendan Gregg). For every resource, check Utilization, Saturation and Errors. Ideal for the host and storage underneath the database.
  • RED method. For every service, track Rate, Errors and Duration. Ideal for the application in front of the database.

They complement each other: RED tells you a service is slow, response-time and wait analysis tell you whether the database is why, and USE tells you whether the hardware is the limit.

5.3What comes before statement-level tuning

Statement tuning is powerful, but it is the last layer to look at, not the first. Work from the outside in.

What comes before statement tuning: confirm it is the database, then check platform saturation, database-wide time, contention, housekeeping and workload shape, and only then tune individual statements.
What comes before statement tuning: confirm it is the database, then check platform saturation, database-wide time, contention, housekeeping and workload shape, and only then tune individual statements.
  1. Confirm the database is where the time goes. Compare the application's request time with the database time per request. Check connection pool waits, network round trips (a chatty ORM making hundreds of small calls per page), and application pauses. If the database accounts for 50 ms of a 4-second request, tune elsewhere.
  2. Check the platform for saturation and limits. CPU run queue longer than the number of cores; memory pressure or swapping; storage latency (SSD-class storage normally answers in low single-digit milliseconds or better, so sustained tens of milliseconds means trouble); cloud limits such as provisioned IOPS and throughput caps, burst credit balances on burstable volumes and instances, and per-instance network bandwidth.
  3. Look at database-wide time. Compare average active sessions with the number of CPU cores. Read the time model and the top wait classes. This tells you what kind of problem you have.
  4. Check contention. Blocking chains, lock waits, long transactions and sessions left idle inside an open transaction, deadlocks, hot rows and pages, latch and spinlock contention.
  5. Check housekeeping. Stale statistics, cleanup that has fallen behind (and the bloat it leaves), skipped maintenance jobs, undersized log files, temporary space configuration, memory settings.
  6. Check the shape of the workload. Batch jobs overlapping the online peak, connection storms after a deploy, retry storms from an unhealthy service, an ad hoc report running on the primary.
  7. Then tune statements. Take the top statements by total time and the biggest regressions, and work through their plans, indexes and code (Chapters 6 to 9).

Why this order? A perfect statement fix does nothing while storage is being throttled or a forgotten session holds a lock. And a database-wide fix, such as fresh statistics or a corrected memory setting, can fix fifty statements at once.

5.4Collecting the evidence: counters, deltas and samples

Most performance views hold cumulative counters: totals since the instance started or since the last reset. A total on its own means little. Take snapshots on a fixed interval and subtract: hourly for trends and baselines, every one to five minutes during an incident.

Counters disappear or reset more often than people expect:

  • Restarts reset most counters and caches.
  • Someone resets the statistics by hand.
  • Views built on the plan cache only show statements still in the cache.
  • Fixed-size statement tables fill up, and then evict the least-used statements or lump new ones together.
  • Persistent stores keep their data across restarts, which is one more reason to turn them on.

For "what is happening right now", sample the active sessions every second or every few seconds: who is active, what each one is running and what it waits on. Added up, the samples give you a rough active-session history for free.

Keep at least two weeks of history. Chapter 12 explains why that number matters.

5.5Where does the time go?

Every engine can answer the same three questions, and it pays to ask them in this order. How does database time split between CPU and waiting? Which waits dominate? Which statements consume the most time? If the time is mostly CPU, look for statements with high logical reads per execution, and for heavy parsing or compilation. If waits dominate, the top waits tell you where to look next (section 5.7). The engine notes show where each engine keeps the answers.

5.6From symptom to strategy

SymptomLook first atTypical fix area
Everything slow, CPU highTop statements by CPU and logical reads; parse ratesPlans and indexes; bind variables; runaway parallelism
Everything slow, CPU low, I/O waits highStorage latency; top statements by physical readsIndexes; memory sizing; storage tier or limits
Spikes at the same times every dayJobs, backups and statistics runs that overlap the peakScheduling; resource governance; batch design
One feature slow, the rest fineThat statement's plan history and statisticsPlan regression; statistics; parameter sensitivity
Intermittent timeoutsBlocking chains and lock waits; long transactionsTransaction scope; indexes on foreign keys; isolation level
Slow commitsLog, WAL or redo write latency; commit rateFaster log storage; fewer, larger commits
Gradual slowdown over weeksGrowth, bloat, statistics stalenessMaintenance; partitioning; archiving
Slow only on the replicaReplay lag; conflicts with long queriesReplica sizing; query timeouts; replica settings

5.7The same waits under different names

What sessions wait forPostgreSQLMySQLSQL ServerOracle
Single-block data readIO: DataFileReadwait/io/file/innodb/innodb_data_filePAGEIOLATCH_SHdb file sequential read
Multi-block or direct readIO: DataFileRead during scanswait/io/file/innodb/innodb_data_filePAGEIOLATCH_SH during scansdb file scattered read, direct path read
Commit and log writeIO: WALSync, IO: WALWritewait/io/file/innodb/innodb_log_fileWRITELOGlog file sync
Row lock held by another transactionLock: transactionid, Lock: tupleInnodb_row_lock_time and sys.innodb_lock_waitsLCK_M_U, LCK_M_X and other LCK_M_*enq: TX - row lock contention
Memory for a query to start(work_mem is allocated per operation)(buffers allocated per session)RESOURCE_SEMAPHORE(PGA is allocated, not queued)
Parallel query coordinationIPC: ExecuteGather(not applicable)CXPACKET, CXCONSUMERPX Deq events
Client not reading results fast enoughClient: ClientWritewait/io/socket/sql/client_connectionASYNC_NETWORK_IOSQL*Net more data to client
Hot shared memory structuresLWLock: BufferContentwait/synch/... mutexes and rw-locksPAGELATCH_* (often tempdb or last-page inserts)latch: cache buffers chains, buffer busy waits

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