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

SQL Server VLF Log Fragmentation Guard

Count VLFs per database with sys.dm_db_log_info, alert Slack, then back up, shrink and re-grow the log in one step and re-read to confirm.

Categories
DataInfrastructure

A transaction log left on a tiny autogrowth increment, the old 1 MB or 10 percent default, does not grow once. It grows in hundreds of small steps. Every one of those steps carves new Virtual Log Files into the log. A log that reached 50 GB in 1 MB pieces can hold tens of thousands of VLFs.

Nothing in normal monitoring shows it. Disk space looks fine, the log file size looks fine, no query is slow. What slows down is everything that has to walk the log end to end: crash recovery after a failover or a restart, log backups, the log reader for replication and change data capture, plus the redo queue on an Always On secondary. A database that should recover in seconds takes minutes. The first time anyone finds out is usually during an incident.

This blueprint counts the VLFs per database from sys.dm_db_log_info, reads the log file size and growth increment from sys.master_files and flags the logs that are both fragmented and still growing in steps too small to stop. It alerts Slack. When you allow it and a human approves the run, it takes a real BACKUP LOG so the log can truncate, runs DBCC SHRINKFILE on the log, re-grows it to its working size in one single ALTER DATABASE ... MODIFY FILE step and leaves a sane fixed FILEGROWTH behind. Then it reads sys.dm_db_log_info again and fails the run if the VLF count is still over the threshold.

This blueprint was created by zkasuran.

Safety

  • Only ONLINE, writable, FULL recovery user databases are considered. master, model, msdb and tempdb are excluded by name and by database_id > 4. Database snapshots are excluded by source_database_id IS NULL.
  • Read-only by default. dry_run is true and auto_remediate is false, so a normal run only counts VLFs and alerts.
  • A write happens only when auto_remediate is true, dry_run is false and a human resumes the Pause with approved: true. A pause resumed without an answer reads as a refusal.
  • backup_dir must be a real directory the SQL Server service account can write. Backing a log up to NUL would truncate the log while discarding the records, which breaks the log chain and every differential and log restore taken after it. The flow therefore takes a real destination and writes one file per database per run.
  • A shrink plus a re-grow briefly affects log availability and write throughput. The re-grow also zeroes the new log file. Run it in a quiet window.
  • The remediation loop has concurrencyLimit: 1, so two shrinks never overlap.
  • Each statement runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query. BACKUP, DBCC SHRINKFILE and ALTER DATABASE cannot run inside an explicit transaction, so this is never a Queries task with transaction: true.
  • On an Always On primary, check that the secondaries are synchronising before you shrink. A log that cannot truncate because a secondary is behind will not release space. The re-read then fails the run rather than reporting success.

How it works

  1. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) joins sys.databases to sys.master_files for the log file of every eligible database, CROSS APPLYs sys.dm_db_log_info(database_id) to count the VLFs. It keeps the rows at or over vlf_threshold. With require_small_growth on, it also requires percent growth or a fixed growth under min_growth_mb, so it flags the logs that are still fragmenting. Each row carries its own BACKUP LOG, DBCC SHRINKFILE and ALTER DATABASE ... MODIFY FILE statement, built in T-SQL with QUOTENAME.
  2. targets (io.kestra.plugin.core.output.OutputValues) collects the per database plan and the quoted name list for the re-read. summary (io.kestra.plugin.core.log.Log) logs each database with its VLF count, log size and growth increment.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs that no eligible database is over the threshold.
    • findings: alert posts the flagged logs to Slack.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • approval_gate (io.kestra.plugin.core.flow.Pause) holds the run until a human resumes it.
      • remediate (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) runs BACKUP LOG, then DBCC SHRINKFILE through the target database's own sys.sp_executesql, then one ALTER DATABASE ... MODIFY FILE (SIZE, FILEGROWTH).
      • after_state reads the size, growth and VLF count back for every touched database and state_log logs the before and after side by side.
      • reverify re-reads sys.dm_db_log_info and returns only the databases still at or over the threshold. verify_result fails the run through io.kestra.plugin.core.execution.Fail if there are any. That read ignores the growth increment on purpose, so fixing FILEGROWTH alone can never report success.
      • declined logs the findings untouched when the approval was refused.
  4. errors posts a Slack alert when the audit cannot run, a statement is rejected or the re-read fails the run.

What you get

  • A VLF count per database read from the real DMF, next to the log size and the growth increment that produced it, which is the one number normal monitoring never shows.
  • A fix that does all three parts in the right order. A shrink without a log backup releases nothing. A re-grow in small steps puts the VLFs straight back.
  • A fixed FILEGROWTH left behind, so the log stops re-fragmenting the next time it grows.
  • A second read of sys.dm_db_log_info that fails the run when the count did not come down, so a shrink blocked by an open transaction or a lagging secondary is never reported as success.
  • A Slack alert on the findings and a separate alert on failure.

Who it's for

  • DBAs who inherited databases created with the default 1 MB or 10 percent log growth and want to find the logs that are quietly slowing recovery.
  • Platform teams who measured a slow failover or a slow restart and need to know whether log fragmentation is the cause.
  • Teams running replication, change data capture or Always On, where the log reader and the redo queue walk the log and pay for every extra VLF.
  • Anyone evaluating the SQL Server plugin who wants an example that reads a dynamic management function and drives real log maintenance behind an approval.

Why orchestrate this with Kestra

The fix is a sequence where the order is the whole point. Each step can fail on its own. A backup that did not run means the shrink releases nothing. A shrink that worked means nothing if the re-grow happens in small steps. Doing it by hand on twenty databases is a long evening. Doing it blind on a schedule is how a shrink lands in the middle of a busy afternoon. Kestra reads the real VLF counts first, gates the change behind two inputs and a human approval, runs the three statements per database one database at a time, then reads the DMF again and fails loudly if the count did not come down. The Slack alert says what was found and whether anything changed. The run history keeps every before and after.

Tested end to end

On Kestra 2.0.5 against SQL Server 2022 (16.0.4295.3) on Linux, with a local HTTP sink standing in for Slack. Two FULL recovery databases were seeded and both given a full backup, so the logs really hold records. appvlf started with an 8 MB log on FILEGROWTH = 1MB and was then grown in 600 one MB steps, which took it to 607 VLFs in a 608 MB log. okvlf was left alone with a 64 MB log on FILEGROWTH = 64MB and 4 VLFs. Every number below was read back with sqlcmd against sys.dm_db_log_info and sys.master_files, not from the flow log.

Run Inputs Result
1 defaults 1 flagged: appvlf 607 VLFs, 608 MB, 1 MB growth. okvlf not flagged. Slack alert said "No change applied". sqlcmd still read 607
2 auto_remediate: true, dry_run: true still 1 flagged, still "No change applied". The dry run blocked the write with auto_remediate on
3 auto_remediate: true, dry_run: false, pause resumed with approved: false declined logged the findings. sqlcmd still read 607 VLFs, 608 MB, 1 MB growth
4 same, resumed with approved: true, target_log_mb: 256, filegrowth_mb: 64 BACKUP LOG wrote a real 8.1 MB .trn, DBCC SHRINKFILE ran, one ALTER DATABASE MODIFY FILE re-grew it. reverify returned 0 rows. sqlcmd: 607 to 12 VLFs, 608 MB to 256 MB, 1 MB to 64 MB growth. okvlf untouched at 4 VLFs
5 defaults, after run 4 0 flagged, clean branch
6 re-fragmented to 456 VLFs, then shrink_target_mb: 800 (above the current 700 MB size) with approved: true the shrink released nothing, the re-grow added one VLF, reverify returned appvlf at 457 and remediation_failed failed the run. The errors block posted to Slack. The growth increment had been fixed to 64 MB by then, which is exactly why the re-read ignores growth
7 defaults on that state 0 flagged. The log is still fragmented but no longer growing in small steps, so it is out of scope for the default audit
8 require_small_growth: false on the same state 1 flagged: appvlf 457 VLFs, 750 MB, 64 MB growth. okvlf still not flagged
9 require_small_growth: false, vlf_threshold: 100000 0 flagged on the same fragmented instance, which proves the threshold gates the detection
10 require_small_growth: false, auto_remediate: true, dry_run: false, approved: true 457 to 13 VLFs, 750 MB to 256 MB. reverify returned 0 rows
11 unreachable host audit failed on the TCP connection and the errors block posted to Slack

Across all eleven runs okvlf stayed at 4 VLFs, 64 MB and a 64 MB growth increment. The three remediation runs each wrote their own log backup file named after the execution id.

Prerequisites

  • A SQL Server instance you can reach over JDBC. The audit reads instance wide catalog views, so any database context works.
  • A login that can read sys.databases, sys.master_files and sys.dm_db_log_info (VIEW SERVER STATE plus VIEW ANY DEFINITION) or sysadmin. Remediation also needs BACKUP LOG and ALTER DATABASE on each target, so db_backupoperator plus db_owner is enough, as is sysadmin.
  • A directory on the server the SQL Server service account can write, for the log backups.
  • 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 SQL Server instance to check
user sa SQL Server login
password {{ secret('SQLSERVER_PASSWORD') }} Password for the login
vlf_threshold 200 Flag a log at or over this VLF count
min_growth_mb 64 A growth increment under this counts as too small
require_small_growth true Flag only logs that are still fragmenting
backup_dir /var/opt/mssql/backup Directory for the log backups. Never NUL
shrink_target_mb 8 Size DBCC SHRINKFILE aims for
target_log_mb 2048 Size the log is re-grown to in one step
filegrowth_mb 512 Fixed FILEGROWTH left on the log
auto_remediate false Allow the statements to run
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, set url and user, then set backup_dir to a directory the SQL Server service account can write.
  3. Run it once with the defaults and read the VLF counts. Set require_small_growth: false to see every fragmented log, including ones whose growth was already fixed by hand.
  4. Pick target_log_mb from the size the log actually reaches between backups, then run with auto_remediate: true and dry_run: false and approve the pause.
  5. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Size target_log_mb per database by reading used_log_space_in_percent from sys.dm_db_log_space_usage in the audit, instead of using one number for the instance.
  • Check log_reuse_wait_desc in the audit and skip a database whose log cannot truncate yet, so the run reports rather than attempting a shrink that will not release anything.
  • Post the before and after VLF counts to Slack so an on-call engineer sees the gain without opening the database.
  • Point backup_dir at the same share your regular log backups use, so the files the flow writes stay part of one chain.
  • Add a second Pause after the audit on an instance where every database needs its own sign off.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.