Free audit

View Audit Scope
MySQLQuery, indexing, and InnoDB optimization

MySQL Performance Tuning & Query Optimization

JusDB provides MySQL performance tuning, query optimization, and InnoDB buffer pool tuning for production databases on Amazon RDS, Aurora, Cloud SQL, Azure, and self-managed Linux. Engineers profile slow query digests with EXPLAIN ANALYZE and pt-query-digest, design composite B-tree indexes, eliminate lock contention, and measure latency against a baseline.

The first 30-minute call covers your databases, current ownership, and required coverage. No production access is needed. Or request a free audit of one database instance.

  • NDA before access
  • Read-only by default
  • Written scope before work starts

MySQL bottleneck diagnostics

Select a bottleneck class

Slow Query Digests & Full Scans

CPU & IOPS spike

Queries missing composite covering indexes force InnoDB to scan millions of clustered primary key pages or spill temporary sort buffers to disk.

We rank digests by total execution time using pt-query-digest and sys.statement_analysis, then verify covering index plans with EXPLAIN ANALYZE.

Inspect the diagnostic symptom table

Diagnostics run read-only against performance_schema, sys, and slow query logs before any change is proposed.

Core profiling stack
pt-query-digest, EXPLAIN ANALYZE, performance_schema, sys schema, and Percona PMM
Engines and versions tuned
MySQL 5.7, 8.0, 8.4 LTS, and 9.7 LTS on RDS, Aurora, Cloud SQL, Azure Flexible Server, Percona Server, and Linux
Verification standard
Results depend on the workload; we baseline before and measure after each approved change.

Selected clients

  • Innoviti
  • Blitz
  • Freecharge
  • Nango
  • Recochain
  • Screen Facts
  • Nexora
  • WeCredit

Production bottlenecks we resolve

What causes MySQL performance bottlenecks in production?

Most MySQL latency spikes trace back to six storage-engine or optimizer symptoms: unindexed filesorts, buffer pool thrashing, row and gap lock contention, History List Length bloat, redo log checkpoint stalls, and thread concurrency saturation.

MySQL performance bottleneck symptoms, what is happening inside InnoDB, and where JusDB engineers start
Diagnostic symptomWhat is usually happeningWhere we start
filesort & full table scansCPU saturates while query latency climbsHigh-frequency SELECT statements lack a composite index matching the WHERE and ORDER BY clauses, forcing InnoDB to scan millions of pages and spill sort buffers to disk.Rank top digests via sys.statement_analysis and pt-query-digest, run EXPLAIN ANALYZE on a replica, and design a single covering B-tree index.
InnoDB mutex & buffer pool churnDisk read IOPS stays high despite ample server RAMinnodb_buffer_pool_size is left at cloud defaults or split poorly across instances, causing frequent LRU evictions and semaphore waits under concurrent reads.Measure Innodb_buffer_pool_reads vs read requests, inspect SHOW ENGINE INNODB STATUS mutex waits, and size the buffer pool to 70% to 80% of RAM.
ERROR 1213 deadlocks & gap locksConcurrent checkouts or batch updates fail with lock timeoutsTransactions acquire row locks in inconsistent orders, or a non-indexed WHERE predicate locks wide next-key gaps under REPEATABLE READ isolation.Parse LATEST DETECTED DEADLOCK and performance_schema.data_locks, add the missing index to narrow lock scope, and align transaction lock order.
Undo tablespace & History List Length bloatQueries slow down progressively over hours or daysAn uncommitted transaction or reporting query holds an old MVCC read view open, preventing InnoDB purge threads from cleaning undo log history.Inspect trx_mysql_thread_id in information_schema.innodb_trx, tune innodb_purge_threads, and enforce max_execution_time and idle session timeouts.
Redo log checkpoint stallsPeriodic write freezes every few minutes under heavy ingestinnodb_redo_log_capacity (or innodb_log_file_size) is too small for the write rate, forcing synchronous furious flushing when checkpoint age hits the high-water mark.Check Innodb_log_waits and checkpoint age, size redo log capacity for 1 hour of peak writes, and tune innodb_io_capacity_max to match storage IOPS.
Thread concurrency saturationhundreds of active threads contend on internal queuesApplication pools open thousands of direct connections without multiplexing, exhausting per-thread memory buffers and causing context-switch thrashing.Audit performance_schema.threads and memory_summary_global_by_event_name, deploy ProxySQL connection multiplexing, and bound innodb_thread_concurrency.

Technical scope

What does a MySQL performance tuning engagement cover?

We tune the entire query path from application connection pooling and SQL execution plans down to InnoDB buffer pool pages, redo log flushing, and B-tree index structures.

  • Slow query digest and execution plan rewrites

    We rank every query family by total execution time and rows examined, then refactor the SQL or join order so the optimizer chooses a low-cost index path.

    • Top-N digest ranking across slow query logs and Performance Schema
    • Before-and-after iterator timing captured with EXPLAIN ANALYZE

    pt-query-digest · EXPLAIN ANALYZE

  • InnoDB buffer pool and I/O capacity sizing

    We align InnoDB memory structures, dirty-page flushing, and redo log capacity with your actual working set and underlying NVMe or cloud block storage.

    • Right-sized buffer pool instances, change buffering, and LRU scan depth
    • Redo log capacity and background page cleaner calibration for steady writes

    innodb_buffer_pool_size · innodb_io_capacity

  • Row lock, gap lock, and deadlock mitigation

    We trace lock wait chains and deadlock graphs in production so concurrent transactions stop blocking one another during peak traffic.

    • Next-key and gap lock analysis for REPEATABLE READ and READ COMMITTED
    • Transaction retry safety and lock-order alignment with your developers

    performance_schema.data_locks

  • Online composite indexing and schema optimization

    We design high-selectivity composite and covering B-tree indexes and deploy them online without stalling production reads or writes.

    • Column prefix order tuned for equality, range, and ORDER BY predicates
    • Non-blocking index rollouts with explicit metadata lock wait guards

    gh-ost · ALGORITHM=INPLACE

  • Connection multiplexing and thread concurrency

    We prevent connection storms and per-thread OOM crashes by placing a connection pooler in front of MySQL and bounding per-session memory.

    • ProxySQL read/write splitting and connection multiplexing configuration
    • Safe sizing for sort_buffer_size, join_buffer_size, and max_connections

    ProxySQL · Thread Pool

    Explore MySQL Router and routing
  • Continuous telemetry and redundant index pruning

    Every extra secondary index slows down INSERT, UPDATE, and DELETE statements. We drop unused and duplicate indexes and wire up ongoing telemetry.

    • Safe removal of duplicate and zero-hit indexes using invisible index tests
    • Dashboards for p95 query latency, buffer pool churn, and HLL growth

    PMM · sys.schema_unused_indexes

InnoDB parameter calibration

How do InnoDB tuning parameters differ by workload?

Copying a generic my.cnf template from a blog post often starves writes or risks out-of-memory kills. We calibrate InnoDB memory, redo log capacity, and flushing parameters to your specific workload profile.

InnoDB configuration parameters compared across Write-Heavy OLTP, Read-Heavy Catalog, and Mixed Multi-Tenant SaaS workloads
InnoDB parameter groupWrite-Heavy OLTPRead-Heavy CatalogMixed Multi-Tenant SaaS
innodb_buffer_pool_size & instances70% to 75% of RAM across 8 to 16 instances to keep hot index and undo pages resident during high-concurrency writes.75% to 80% of RAM with innodb_old_blocks_pct=37 and innodb_old_blocks_time=1000 so large scans do not evict hot lookup pages.70% of RAM paired with strict per-thread buffer caps so tenant connection spikes never trigger the Linux OOM killer.
innodb_redo_log_capacitySized for 1 hour of peak redo generation (often 16 GB to 64 GB) so background page cleaners flush smoothly without sync stalls.4 GB to 8 GB baseline; read-heavy workloads generate fewer dirty pages and prioritize fast crash recovery.8 GB to 32 GB to absorb tenant batch imports and webhook bursts without triggering furious checkpoint flushing.
innodb_io_capacity / io_capacity_maxSet to 50% / 80% of provisioned NVMe or EBS io2/gp3 IOPS so dirty pages flush continuously behind the scenes.Conservative background flush rates (e.g., 1000 / 2000) to preserve storage IOPS headroom for cache-miss reads.Calibrated to baseline cloud volume burst credits with adaptive flushing enabled.
innodb_flush_log_at_trx_commit & sync_binlog1 and 1 for full ACID durability, paired with group commit and fast NVMe/EBS latency (<1 ms write commit).1 and 1 on primaries; replicas can relax flush frequency during bulk catalog rebuilds if re-seedable.1 and 1 on financial/core ledgers; binlog group commit tuned to batch concurrent tenant commits.
transaction_isolation & lockingREAD COMMITTED or tightly indexed REPEATABLE READ to eliminate gap locks on high-velocity order and ledger tables.REPEATABLE READ with covering composite indexes so multi-column filter and sort queries never touch base table rows.Tenant-prefixed composite indexes (tenant_id, status, created_at) so queries never scan across tenant boundaries.

Free Engineering Calculator

Estimate safe innodb_buffer_pool_size and per-thread memory limits before editing my.cnf

Model total MySQL memory pressure across max_connections, sort_buffer_size, and innodb_redo_log_capacity in your browser.

Open MySQL Config Optimizer

How JusDB MySQL tuning compares with cloud advisors and generic MSPs

Tuning Vector
JusDB MySQL Performance Tuning
Cloud Managed (AWS / GCP)Traditional IT MSPIn-House DIY Team
Query Plan & Execution ForensicsEXPLAIN ANALYZE and optimizer trace deep-dives, compound covering index design, and line-by-line query refactoring.High-level query digests showing CPU spikes without identifying missing composite indexes or filesort stages.Superficial query rewrite advice without inspecting optimizer cost matrices or temporary disk tables.Adding single-column indexes reactively, ballooning index storage and degrading INSERT/UPDATE throughput.
InnoDB Buffer Pool & Memory OptimizationRigorous innodb_buffer_pool_size and instances tuning, dirty page flushing rate calibration (innodb_io_capacity_max), and LRU cache hit optimization (>99%).Automated cloud recommendations suggest purchasing larger RAM instances instead of tuning buffer pool memory allocation.One-size-fits-all generic my.cnf settings copied from online templates without workload profiling.Default buffer pool sizing starving application queries and causing excessive disk I/O thrashing.
Locking Contention & Deadlock ResolutionInnoDB row lock and gap lock contention analysis, isolation level adjustments (READ COMMITTED vs REPEATABLE READ), and deadlock graph elimination.Deadlock metrics displayed as simple counters without transaction sequence tracing or index locking fixes.Advising developers to retry transactions on deadlock rather than fixing underlying lock order conflicts.Unresolved lock waits snowballing during traffic spikes, exhausting available database worker threads.
Temporary Table & Filesort RemediationEliminating disk-based temporary tables and filesort operations by tuning tmp_table_size, max_heap_table_size, and optimizing ORDER BY/GROUP BY index prefixes.Generic disk write alerts without identifying which specific analytical queries are spilling to disk.Increasing global buffer parameters blindly, risking Linux kernel OOM killer crashes under high concurrency.Ignoring disk spill warnings until high storage latency brings application response times to a crawl.
Redo Log & Checkpoint StallsCalibrating innodb_redo_log_capacity and page flushing algorithms to eliminate sharp checkpoint write stalls during high write bursts.Provisioning expensive provisioned IOPS (gp3/io2) to mask underlying flush latency and log write waits.Outdated innodb_log_file_size configurations that throttle high-throughput write workloads.Severe periodic application latency spikes during checkpointing left undiagnosed and attributed to network lag.
Empirical Performance VerificationDocumented before-and-after query latency percentiles (p95/p99), buffer cache hit evidence, and zero-regression verification under production load.No before/after performance benchmarking or SLA guarantees on query latency improvements.Subjective user feedback used as the only measure of performance tuning success.Tuning adjustments deployed directly to production without baseline telemetry or rollback plans.

Interactive remediation walkthrough

How an unindexed query digest stalls InnoDB concurrency

Step through three states of a real OLTP bottleneck to see how a missing composite index triggers disk filesorts, buffer pool churn, and replica lag, and how online index remediation clears all three.

From full-partition filesort to covering B-tree index

Select a state to inspect query routing, primary CPU, buffer pool hit ratio, and replica lag.

Application & ProxySQL query path

Application workers fire 420 req/s of an unindexed order-lookup query; threads pile up in Sending data and Waiting for row lock.

p95 = 1,840 ms · 88% CPU
  • Primary (Writer)

    Scans 4.8M rows per checkout query + sorts on disk

    CPU 88% · 140 active threads

  • InnoDB Buffer Pool

    Working set evicted by full-table scans

    89.4% hit ratio · Disk read churn

  • Read Replica 01

    Applier stalls behind wide gap locks and unbatched writes

    47s replica lag

Without a composite index on (account_id, status, created_at), InnoDB scans the entire account partition, creates an on-disk filesort, and holds wide gap locks that block concurrent updates.

Representative audit evidence

What a written MySQL query optimization finding looks like

Every tuning recommendation includes the exact query digest, the before-and-after EXPLAIN ANALYZE execution tree, the non-blocking online DDL statement, and the tested rollback command.

Example written finding from a MySQL 8.4 LTS performance auditSample deliverable

Finding #01 · Digest 0x8fa4c219

Order history lookup scans 4.8M rows and spills filesort to disk

The checkout dashboard filtered orders by account_id and status while sorting by created_at DESC. Because only a single-column index on (account_id) existed, InnoDB read 48,200 data pages per call and allocated a disk-backed sort buffer.

Measured p95 latency1,840ms → 11.4ms
Rows examined / call4.8M → 20

Illustrative specimen from a staging benchmark; results depend on the workload; we baseline before and measure after each approved change.

1. Before vs. After EXPLAIN ANALYZE execution plan

SQL · EXPLAIN ANALYZE

-- BEFORE: Filter + disk filesort over single-column idx_account (1,840 ms)
-> Limit: 20 row(s)  (actual time=1839.4..1839.6 rows=20 loops=1)
   -> Sort: orders.created_at DESC, limit input to 20 row(s)
      -> Filter: (orders.status = 'PAID')  (rows=4812040 loops=1)
         -> Index lookup on orders using idx_account (account_id=49102)

-- AFTER: Covering reverse-scan composite index (11.4 ms)
-> Limit: 20 row(s)  (actual time=0.42..11.38 rows=20 loops=1)
   -> Index lookup on orders using idx_orders_acct_status_created
      (account_id=49102, status='PAID') (reverse)

2. Online index rollout & tested rollback DDL

SQL · Online DDL + Rollback

-- Guard metadata lock wait and build composite index online
SET SESSION lock_wait_timeout = 2;
ALTER TABLE orders
  ADD INDEX idx_orders_acct_status_created (account_id, status, created_at DESC, total_cents),
  ALGORITHM=INPLACE, LOCK=NONE;

-- Instant optimizer rollback (MySQL 8.0 / 8.4 LTS invisible index toggle)
ALTER TABLE orders ALTER INDEX idx_orders_acct_status_created INVISIBLE;
-- Or full online drop if required:
ALTER TABLE orders DROP INDEX idx_orders_acct_status_created, ALGORITHM=INPLACE, LOCK=NONE;

Ways to work together

Choose a fixed-scope tuning sprint or ongoing MySQL operations

Start with a targeted MySQL performance audit and tuning sprint, or embed our database engineers alongside your application team.

Fixed-scope tuning sprintMost requested

MySQL Performance Audit & Tuning Engagement

A focused 1-to-3-week engineering sprint to baseline your workload, fix the top slow query digests, right-size InnoDB memory and I/O parameters, and verify latency gains in production.

  1. 1. Upsize vCPUsTemporarily masks unindexed full scans
  2. 2. Blind my.cnfOversized sort buffers risk OOM kills
  3. 3. Repeat spikeTable growth triggers the stall again
Ongoing embedded operations

MySQL Remote DBA & Continuous Optimization

When your team ships new features every sprint, our engineers review migrations, run online schema changes with gh-ost, and keep query plans from regressing.

Included in ongoing Remote DBA operations:

  • Weekly slow-query digest reviews and unused-index cleanup
  • Online DDL execution via gh-ost or pt-online-schema-change
  • Capacity planning, backup restore drills, and replica tuning
SLA incident escalation

MySQL Support & 24/7 Incident Response

24/7 support when lock storms, connection spikes, or replica lag hit production. SLA response times: P1 – 15 mins | P2 – 30 mins | P3 – 60 mins.

Covered under your support agreement:

  • Live Performance Schema and InnoDB deadlock triage
  • Written post-incident review with the preventive query or index fix
  • Coverage for MySQL 5.7, 8.0, 8.4 LTS, and 9.7 LTS

For procurement and security

NDA first, read-only diagnostics by default, and written scope

We profile your workload using read-only accounts first. Every index, query rewrite, or my.cnf change is benchmarked and approved by your engineering team before production rollout.Raguraman, Head of DBSRE · Allen D, Principal Engineer
  • Mutual NDA
  • Read-only baseline first
  • Written statement of work
  • Tested rollback for every DDL
  • NDA before access

    Signed before any diagnostic access. We need no database credentials for the initial scoping call.

  • Baseline-first report

    We capture pt-query-digest percentiles and Performance Schema baselines before changing a single parameter.

  • Least-privilege accounts

    Read-only SELECT and performance_schema access through your bastion or VPN, with full session logging.

  • Artifacts your team keeps

    You keep every query analysis, my.cnf diff, gh-ost runbook, and dashboard JSON. Meet the JusDB team.

JusDB's security practices are aligned with ISO 27001 and SOC 2 Type II, and JusDB is pursuing both certifications (see Terms, section 12). Read the stated status.

Technical FAQ

MySQL performance tuning and query optimization questions

Answers on EXPLAIN ANALYZE profiling, InnoDB buffer pool and redo log sizing, online index builds, deadlock resolution, and baseline measurement.

Still have a question?

Ask it on a scoping call. No production access needed.

Book a 30-min scoping call (opens Google Calendar in a new tab)

What causes MySQL performance bottlenecks in production?

Production MySQL bottlenecks usually stem from unindexed full table scans and disk-spilling filesorts, stale optimizer statistics, undersized InnoDB buffer pools (innodb_buffer_pool_size), small redo log capacities (innodb_redo_log_capacity) that trigger checkpoint flush stalls, gap-lock contention under REPEATABLE READ, and unbatched writes that stall replica applier threads.

How does JusDB diagnose and fix slow MySQL queries?

We profile statement digests using Performance Schema (events_statements_summary_by_digest), the sys schema, and Percona Toolkit pt-query-digest. For the top latency contributors, we inspect runtime iterator costs with EXPLAIN ANALYZE, design composite covering B-tree indexes, rewrite non-sargable predicates or correlated subqueries, and verify execution plans against a staging replica before rollout.

How do you size innodb_buffer_pool_size and innodb_redo_log_capacity safely?

On dedicated database hosts, we typically size innodb_buffer_pool_size to 70% to 80% of system RAM after accounting for OS page cache, per-connection sort/join buffers, and Performance Schema memory overhead. We size innodb_redo_log_capacity (or innodb_log_file_size on MySQL 5.7 and early 8.0) so the redo log holds at least one hour of peak write volume, preventing synchronous checkpoint stalls.

How do you add composite indexes on multi-million-row tables without locking writes?

We verify whether the index creation supports native InnoDB online DDL (ALGORITHM=INPLACE, LOCK=NONE) with bounded metadata lock timeouts (lock_wait_timeout). When an operation requires a table rebuild or replication lag control on busy primaries, we run gh-ost or pt-online-schema-change with automated replica-lag throttling.

How do you resolve ERROR 1213 InnoDB deadlocks and row lock wait timeouts?

We inspect LATEST DETECTED DEADLOCK in SHOW ENGINE INNODB STATUS along with performance_schema.data_locks and data_lock_waits. We then add missing indexes so UPDATE and DELETE statements lock only target rows rather than wide index gaps, align transaction lock acquisition order across application code paths, or evaluate READ COMMITTED isolation where appropriate.

What causes InnoDB History List Length (HLL) bloat and how do you clear it?

History List Length grows when long-running transactions or abandoned REPEATABLE READ sessions hold an old read view open, preventing InnoDB purge threads from reclaiming undo log pages. We identify and bound long transactions via innodb_trx, tune innodb_purge_threads and innodb_max_purge_lag, and configure idle transaction timeouts.

Which MySQL versions and cloud platforms do you tune?

We tune Oracle MySQL 5.7, 8.0, 8.4 LTS, and 9.7 LTS, Percona Server for MySQL, and MariaDB across self-managed Linux, Kubernetes operators, Amazon RDS for MySQL, Amazon Aurora MySQL, Google Cloud SQL, and Azure Database for MySQL Flexible Server.

How do you measure MySQL performance improvements?

Results depend on the workload; we capture a baseline before work starts and measure after each approved change. Every tuning engagement includes a written report comparing before-and-after pt-query-digest latency percentiles (p50, p95, p99), EXPLAIN ANALYZE execution costs, buffer pool hit ratios, and CPU/IOPS utilization.

Next step

Talk to a MySQL engineer about your query latency

Share your MySQL version, hosting platform, and top bottleneck symptoms. The first 30-minute call covers your databases, current ownership, and required coverage. No production access is needed. Or request a free audit of one database instance, subject to availability: mutual NDA before read-only access, a prioritized report within one week after access is ready, and no obligation.

NDA before access · read-only by default · baseline-measured changes