Schedule icon
Query icon
Script icon
Docker icon
If icon
SlackIncomingWebhook icon
Log icon
Return icon

MySQL Table Fragmentation and Optimize Advisor

Audits MySQL InnoDB tables for storage fragmentation bloat, recommending OPTIMIZE TABLE commands to reclaim disk space.

Categories
DataInfrastructure

In active MySQL database workloads with frequent UPDATE operations and row deletions, the underlying InnoDB storage engine allocates new extents without automatically releasing unused space back to the operating system filesystem. Over months of application traffic, table data files (.ibd) accumulate substantial internal free space (DATA_FREE).

When fragmentation exceeds 30% to 50% of total table capacity, companies incur unnecessary cloud disk storage costs (e.g. AWS EBS gp3 or GCP Persistent Disk). Furthermore, fragmented B-tree index pages degrade buffer pool hit ratios and slow down table range scans.

This blueprint provides an automated storage advisor that audits MySQL information_schema.TABLES weekly, calculates exact fragmentation percentages and reclaimable megabytes, and compiles executable OPTIMIZE TABLE remediation advisories directly into your DBA team's Slack channel.

How it works

  1. Weekly Scheduled Audit: The weekly_fragmentation_audit trigger (io.kestra.plugin.core.trigger.Schedule) executes every Sunday at 04:00 UTC.
  2. Free Space Inspection: The query_table_free_space task (io.kestra.plugin.jdbc.mysql.Query) queries information_schema.TABLES for InnoDB tables with DATA_FREE > 0.
  3. Python Fragmentation Scoring: The evaluate_table_fragmentation task (io.kestra.plugin.scripts.python.Script) filters tables exceeding min_wasted_mb_threshold and fragmentation_ratio_threshold, generating fragmentation_report.json.
  4. Condition Branching: The evaluate_advisory_trigger flowable task (io.kestra.plugin.core.flow.If) evaluates whether any candidates require defragmentation.
  5. Slack Advisory Notification: If reclaimable tables are discovered, alert_dba_fragmentation_advisor (io.kestra.plugin.slack.notifications.SlackIncomingWebhook) delivers an actionable maintenance plan.
  6. Storage Manifest: The export_storage_manifest task records reclaimable disk stats for capacity planning.

Architecture diagram

flowchart TD
    A[Schedule: Weekly Sunday 04:00 UTC] --> B[query_table_free_space: MySQL]
    B --> C[evaluate_table_fragmentation: Python Storage Analyzer]
    C --> D{Fragmentation Threshold Breached?}
    D -- Yes --> E[alert_dba_fragmentation_advisor: Slack]
    D -- No --> F[log_compact_storage_status: Log]
    E --> G[export_storage_manifest: Return JSON]
    F --> G

Use cases

  • Cloud Storage Cost Optimization: Recover wasted gigabytes on AWS EBS or Google Persistent Disks caused by InnoDB data_free space.
  • Buffer Pool Performance Tuning: Defragment index and data pages to maximize MySQL buffer pool memory efficiency.
  • Proactive Database Maintenance: Generate maintenance window advisories with exact OPTIMIZE TABLE commands for DBAs.

What you get

  • Automated discovery of storage fragmentation bloat across MySQL schemas.
  • Exact quantification of reclaimable storage in megabytes.
  • Executable SQL remediation commands (OPTIMIZE TABLE) prepared in advance.
  • Zero production locks during the audit phase via non-intrusive metadata queries.

Who it is for

  • MySQL Database Administrators managing high-volume OLTP databases.
  • Cloud Infrastructure Engineers seeking to reduce cloud disk storage expenses.
  • Site Reliability Engineers optimizing database query latency and I/O efficiency.

Why orchestrate this with Kestra

Manually inspecting table fragmentation across dozens of database instances requires ad-hoc bash scripts and manual metric calculations. Kestra automates the inspection, analysis, and alerting into a scheduled, auditable workflow with zero ongoing maintenance.

Inputs

Name Type Default Description
mysql_url STRING jdbc:mysql://... JDBC URL of target MySQL instance.
mysql_username STRING db_monitor Monitoring database user.
target_schema STRING app_db Database schema name to inspect.
fragmentation_ratio_threshold FLOAT 0.30 Minimum free-to-total size ratio (e.g. 0.30 = 30%).
min_wasted_mb_threshold INT 500 Minimum wasted MB to qualify table.
slack_channel STRING #dba-maintenance Slack channel destination for alerts.

Expected outputs

  • {{ outputs.evaluate_table_fragmentation.vars.action_recommended }}: Boolean flag indicating if any table exceeded thresholds.
  • {{ outputs.evaluate_table_fragmentation.vars.total_reclaimable_mb }}: Total estimated disk space reclaimable across the schema.
  • {{ outputs.evaluate_table_fragmentation.vars.top_table }}: Name of the table with the greatest wasted space.
  • {{ outputs.evaluate_table_fragmentation.outputFiles['fragmentation_report.json'] }}: Complete JSON diagnostic report.

Prerequisites

  • MySQL server version 5.7, 8.0, or 8.4 accessible via JDBC (port 3306).
  • Database user credentials stored in Kestra secrets.
  • Slack Incoming Webhook configured for your DBA operations channel.

Secrets

  • MYSQL_PASSWORD: Password for the MySQL database user.
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook endpoint URL.

Quick start

  1. Configure MYSQL_PASSWORD and SLACK_WEBHOOK_URL in your Kestra namespace secrets.
  2. Import this flow YAML into your Kestra instance.
  3. Click Execute in the UI to perform an initial table storage inspection.
  4. Review execution outputs to inspect fragmentation percentages across your tables.

Common pitfalls and troubleshooting

  • innodb_file_per_table: Reclaiming disk space back to the host filesystem requires innodb_file_per_table=ON (enabled by default in modern MySQL). If disabled, space is reclaimed only within the shared ibdata1 tablespace.
  • Disk Space for Table Rebuild: OPTIMIZE TABLE rebuilds the table in place and requires temporary disk space approximately equal to the size of the table.
  • Maintenance Windows: While online DDL is supported in modern MySQL, rebuilding large tables generates substantial I/O and should be scheduled during off-peak maintenance hours.

How to extend

  • Add io.kestra.plugin.core.flow.EachSequential to automatically iterate through all candidate tables and execute OPTIMIZE TABLE during scheduled maintenance windows.
  • Query SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_reads' to correlate table fragmentation with cache miss spikes.
  • Export reclaimable storage metrics to Prometheus or Grafana dashboards.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.