Query icon
OutputValues icon
Log icon
If icon
SlackIncomingWebhook icon
Loop icon
Fail icon
Schedule icon

SQL Server Index Fragmentation Rebuild Guard

Detect fragmented SQL Server B-tree indexes with a DMV query, alert Slack, then rebuild or reorganize them and re-measure to confirm.

Categories
DataInfrastructure

Fragmented indexes make SQL Server read more pages than it needs, so range scans slow down and the buffer pool fills with half-empty pages. SQL Server has no built-in job that measures fragmentation and acts on it. The usual answer is a hand-written maintenance script on SQL Server Agent that nobody reviews.

This blueprint reads sys.dm_db_index_physical_stats for the connected database, flags every clustered or nonclustered index whose avg_fragmentation_in_percent is at or above a threshold on a table past a page floor and alerts Slack. When you allow it, it rebuilds the heavily fragmented indexes and reorganizes the moderately fragmented ones, one statement at a time, then measures again and fails the run if anything is still fragmented.

This blueprint was created by zkasuran.

Safety

  • Read-only by default. dry_run is true and auto_remediate is false, so a normal run only measures and alerts.
  • A write happens only when auto_remediate is true and dry_run is false.
  • ALTER INDEX ... REBUILD cannot run inside an open transaction, so each statement runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query, never a Queries task with transaction: true.
  • ONLINE = ON keeps the index available during a rebuild but needs Developer or Enterprise edition. On Standard edition set online_rebuild to false.
  • The remediation loop has concurrencyLimit: 1, so the statements never run in parallel.

How it works

  1. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) reads sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') and joins sys.indexes, sys.objects and sys.schemas. It keeps clustered and nonclustered indexes on user tables whose page_count is at or above page_floor and whose avg_fragmentation_in_percent is at or above reorganize_threshold. For each one it picks REBUILD when fragmentation is at or above rebuild_threshold, otherwise REORGANIZE. It builds the ALTER INDEX statement with QUOTENAME so identifiers are quoted by the server.
  2. fixes (io.kestra.plugin.core.output.OutputValues) collects the per-index ALTER INDEX statements. summary (io.kestra.plugin.core.log.Log) logs the findings.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs that nothing is fragmented past the thresholds.
    • findings: alert posts the flagged indexes to Slack.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • remediate (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) runs each ALTER INDEX in turn.
      • reaudit re-measures. verify_result fails the run if any flagged index is still above the threshold.
  4. errors posts a Slack alert when the audit itself cannot run.

What you get

  • The real fragmentation of every B-tree index that is big enough to matter, with the page count and the action chosen for each.
  • Rebuild for heavy fragmentation, reorganize for moderate, from one threshold pair you control.
  • A re-measure after the change that fails the run if an index is still fragmented, so a remediation that did not land is never reported as success.
  • A Slack alert on findings and a separate alert if the audit cannot run.

Who it's for

  • DBAs who keep index maintenance in a hand-written SQL Server Agent job and want it measured, gated and verified.
  • Platform teams running SQL Server in containers or managed instances where Agent is limited or absent.
  • Teams evaluating the SQL Server plugin who want an example that reads a DMV and drives ALTER INDEX.

Why orchestrate this with Kestra

A maintenance script runs on a schedule and hopes. Kestra measures first, decides rebuild against reorganize per index, applies the change only behind two safety inputs, one statement at a time, then measures again and fails loudly if the fragmentation is still there. The Slack alert tells you what was found and whether anything was changed. The run history keeps every before and after.

Tested end to end

On Kestra 2.0.5 against SQL Server 2022 Developer Edition, with a local HTTP sink standing in for Slack. A clustered index of about 428 pages was fragmented to 38.10 percent by expanding a variable-length column across many rows.

Run Inputs Result
1 defaults, clean index 0 indexes flagged. clean branch. The engine reported 4.91 percent, below the 10 percent threshold
2 dry_run: true, index at 38.10 percent 1 index flagged, action REBUILD, Slack alert sent "No change applied". The engine still reported 38.10 percent afterwards, so dry run changed nothing
3 auto_remediate: true, dry_run: false remediate ran one ALTER INDEX ... REBUILD WITH (ONLINE = ON). reaudit returned 0 rows. The engine reported 0.84 percent, down from 38.10
4 auto_remediate: true, dry_run: false, index at 29.43 percent action REORGANIZE chosen and run, fragmentation dropped below the threshold, verified
5 same fragmented index, page_floor above its size 0 indexes flagged, clean branch. The page floor correctly excludes the index
6 unreachable server audit failed, errors block posted to Slack

Prerequisites

  • A SQL Server database you can reach over JDBC.
  • A login with VIEW DATABASE STATE for the audit, plus ALTER on the target tables (for example db_ddladmin) for remediation.
  • A Slack incoming webhook.

Secrets

  • SQLSERVER_PASSWORD: password for the login in user. The password input defaults to this secret.
  • SLACK_WEBHOOK_URL: Slack incoming webhook, used by alert and the errors block.
  • In Kestra OSS, provide each one as a base64-encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
url jdbc:sqlserver://localhost:1433;databaseName=app;encrypt=false Database to check. DB_ID() resolves this database
user sa SQL Server login
password {{ secret('SQLSERVER_PASSWORD') }} Password for the login
reorganize_threshold 10.0 Fragmentation percent at which an index is flagged
rebuild_threshold 30.0 Fragmentation percent at which an index is rebuilt rather than reorganized
page_floor 1000 Indexes smaller than this many pages are ignored
online_rebuild true Rebuild with ONLINE = ON (Developer or Enterprise edition)
auto_remediate false Allow ALTER INDEX
dry_run true Must be false for a statement to run

Quick start

  1. Add the SQLSERVER_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow, then set url to the database you want to check and set user.
  3. Run it once with the defaults and read the flagged indexes.
  4. When you are happy with the thresholds, run with auto_remediate: true and dry_run: false.
  5. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Rebuild with WITH (ONLINE = ON, RESUMABLE = ON) so a long rebuild can be paused.
  • Add a maintenance window check before the remediate gate so rebuilds only run off-hours.
  • Update statistics after a reorganize, since reorganize does not refresh them the way a rebuild does.
  • Loop over several databases on the instance by reading sys.databases first.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.