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

SQL Server Log Reuse Wait Truncation Guard

Read log_reuse_wait_desc and the log used percentage, alert Slack, run BACKUP LOG where it helps, then re-read to confirm the log can truncate.

Categories
DataInfrastructure

A database in FULL recovery whose log has never been backed up cannot truncate. Nothing reclaims the inactive part of the log, so the file grows on every autogrowth step until the volume fills. Then every write in that database fails with error 9002 and the application stops. The database is online and healthy right up to that point, which is why nobody sees it coming. The fix is a log backup, the one piece of routine maintenance that was never set up.

sys.databases.log_reuse_wait_desc names the reason the log cannot truncate. When it reads LOG_BACKUP a log backup clears it. When it reads ACTIVE_TRANSACTION, REPLICATION, ACTIVE_BACKUP_OR_RESTORE or AVAILABILITY_REPLICA a log backup does nothing. Running one anyway just hides the real holder for another hour.

This blueprint reads both numbers that matter, the reason and how full the log already is. It routes on the reason. It alerts Slack with the whole picture. When you allow it and a human approves the run, it takes a real BACKUP LOG on the databases held by LOG_BACKUP only. Then it re-reads log_reuse_wait_desc and the used percentage and fails the run if the log still cannot truncate.

This blueprint was created by zkasuran.

Safety

  • Only ONLINE, writable user databases in FULL or BULK_LOGGED recovery 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. A SIMPLE recovery database is never touched, since its log truncates at every checkpoint.
  • Read-only by default. dry_run is true and auto_remediate is false, so a normal run only reads 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.
  • Only the rows whose reason is LOG_BACKUP carry a statement. A log held by anything else is reported and left alone, so the flow never pretends a backup helped.
  • backup_dir must be a real directory the SQL Server service account can write. BACKUP LOG ... TO DISK = 'NUL' would truncate the log while throwing the records away, 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.
  • The loop has concurrencyLimit: 1, so two log backups never write at once.
  • Each BACKUP LOG runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query, because BACKUP cannot run inside an explicit transaction.
  • A log backup taken by this flow is part of the real log chain. If a scheduled backup job also runs, point backup_dir at the same place so the files stay together.

How it works

  1. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) joins log_reuse_wait_desc from sys.databases to sys.dm_db_log_stats(database_id) for every eligible database. It keeps the rows where the reason is not NOTHING, the log file is at least min_log_size_mb and active_log_size_mb / total_log_size_mb is at or over used_pct_threshold. Each row carries its reason, its used percentage, the megabytes written since the last log backup, a plain sentence saying what clears that reason. A LOG_BACKUP row also carries a BACKUP LOG statement built in T-SQL with QUOTENAME.
  2. targets (io.kestra.plugin.core.output.OutputValues) splits the rows into the ones a log backup fixes and the ones it does not. It builds the quoted name list for the re-read from the fixable rows only. summary (io.kestra.plugin.core.log.Log) logs every finding with its reason and sizes.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs that no eligible database has a log that cannot truncate and is at or over the threshold.
    • findings: alert posts the reasons and the counts to Slack.
      • reason_split warns with one line per database that a log backup cannot help. Otherwise it confirms that every finding is fixable by a log backup.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • backup_scope runs only when at least one finding is held by LOG_BACKUP. When none is, no_backup_target says so and nothing is executed, not even the pause.
      • 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 one BACKUP LOG per database.
      • after_state reads the reason, the sizes and the used percentage back and state_log logs before and after side by side.
      • reverify returns the databases whose log still cannot truncate and is still at or over the threshold. verify_result fails the run through io.kestra.plugin.core.execution.Fail if there are any. That read does not ask for LOG_BACKUP, because that is the value the fix moves: a log that flipped to ACTIVE_TRANSACTION and stayed full is still a log that cannot truncate.
      • declined logs the findings untouched when the approval was refused.
  4. errors posts a Slack alert when the audit cannot run, a backup is rejected or the re-read fails the run.

What you get

  • The reason the log cannot truncate, next to how full the log already is. One of those numbers on its own tells you nothing. A log at 20 percent with LOG_BACKUP is a backup job to set up next week. The same reason at 98 percent is an outage this afternoon.
  • Routing on the reason, so a database held by an open transaction or a lagging replica is named and left alone instead of being handed a backup that cannot help it.
  • A real log backup to a real file, which keeps the log chain usable, rather than a truncate that throws the records away.
  • A second read of log_reuse_wait_desc and the used percentage that fails the run when the log still cannot truncate, so a log held by a second reason is never reported as fixed.
  • log_since_last_log_backup_mb per database, which says how much of the log a backup is about to free.
  • A Slack alert on the findings and a separate alert on failure.

Who it's for

  • DBAs who inherited databases someone set to FULL recovery without ever adding a log backup job, which is the most common way a SQL Server volume fills.
  • Platform teams who want the 9002 error caught while the log is at 80 percent instead of at 100.
  • Teams running replication, change data capture or Always On, where the reason is often not LOG_BACKUP and a backup would be the wrong move.
  • Anyone evaluating the SQL Server plugin who wants an example that reads a dynamic management function, routes on what it found and gates the write.

Why orchestrate this with Kestra

The decision here is not whether to run a backup, it is whether a backup is even the right action. That depends on a value you have to read first. Doing it by hand means connecting to the instance, reading sys.databases for every database, working out how full each log is, then picking the ones a backup helps. It is also the kind of check nobody does until an application is already down. Kestra reads both values, splits the findings by reason, gates the write behind two inputs and a human approval, runs one backup at a time, then reads the reason again and fails loudly if the log still cannot truncate. The Slack alert carries the reasons, so an on-call engineer knows whether this is a backup job to add or a transaction to go and find. The run history keeps every before and after.

Tested end to end

On Kestra 2.0.5 against SQL Server 2022 on Linux, with a local HTTP sink standing in for Slack. Four databases were seeded on one instance: appreuse in FULL recovery with a full backup taken and then 4200 wide rows written and no log backup ever, txreuse in FULL recovery with a log backup taken and then an open transaction left holding the log, failreuse in FULL recovery with an open transaction holding the log while its reason still read LOG_BACKUP, plus simplereuse left untouched in SIMPLE recovery. Every number below was read back with sqlcmd against sys.databases and sys.dm_db_log_stats, not from the flow log.

Run Inputs Result
1 defaults 2 flagged: appreuse LOG_BACKUP at 98.1% of a 34.0 MB log, txreuse ACTIVE_TRANSACTION at 71.5% of 16.0 MB. 1 fixable by a log backup, 1 report only. simplereuse not flagged
2 auto_remediate: true, dry_run: true the same 2 findings, the same Slack line, no .trn written. 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 LOG_BACKUP at 98.1%
4 same, resumed with approved: true one real 33.5 MB .trn written, named after the execution id. appreuse: LOG_BACKUP at 98.1% to NOTHING at 0.2%, confirmed with sqlcmd. reverify returned 0 rows. txreuse untouched
5 defaults, after run 4 1 flagged, only txreuse. appreuse is out of the findings
6 auto_remediate: true, dry_run: false on that state no_backup_target. No statement ran and the pause was never even reached, because the only finding is not fixable by a log backup
7 used_pct_threshold: 99 on the degraded instance 0 flagged, clean branch, which proves the percentage gates the detection
8 failreuse at LOG_BACKUP 72.6% with an open transaction holding its log, used_pct_threshold: 50, approved the backup ran, the reason flipped to ACTIVE_TRANSACTION, the log stayed at 71.0%, reverify returned the row and remediation_failed failed the run. The errors block posted to Slack
9 defaults with failreuse switched to BULK_LOGGED flagged as BULK_LOGGED LOG_BACKUP at 76.5%, so BULK_LOGGED is covered
10 the same state with include_bulk_logged: false failreuse dropped out and only txreuse was left, so the recovery model filter works both ways
11 unreachable host audit failed on the TCP connection and the errors block posted to Slack
12 both held transactions killed, both logs backed up by hand, then defaults 0 flagged, clean branch. txreuse read LOG_BACKUP at 0.7% at that moment and was correctly left out, because the reason on its own is not a finding

Across every run simplereuse stayed out of the findings. No statement ever ran against a database whose reason was not LOG_BACKUP. Run 8 was repeated with the transaction still writing while the backup ran: the reason then stayed LOG_BACKUP at 76.4% rather than flipping. The re-read failed the run just the same, which is why that read does not ask for a particular reason.

Prerequisites

  • A SQL Server instance you can reach over JDBC, 2016 SP2 or later for sys.dm_db_log_stats. The audit reads instance wide catalog views, so any database context works.
  • A login that can read sys.databases and sys.dm_db_log_stats (VIEW SERVER STATE plus VIEW ANY DEFINITION) or sysadmin. The remediation also needs BACKUP LOG on each target, so db_backupoperator 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
used_pct_threshold 70 Flag a log at or over this used percentage
min_log_size_mb 8 Ignore a log file smaller than this
include_bulk_logged true Also check BULK_LOGGED databases
backup_dir /var/opt/mssql/backup Directory for the log backups. Never NUL. Quotes are rejected
auto_remediate false Allow BACKUP LOG to run
dry_run true Must be false for a backup 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 reasons. Lower used_pct_threshold to see logs that cannot truncate but still have room.
  4. For the LOG_BACKUP findings, run with auto_remediate: true and dry_run: false and approve the pause. Then add a real log backup schedule, because this flow buys time rather than replacing one.
  5. Enable the daily trigger, which always runs in safe mode.

How to extend

  • Add a log_since_last_log_backup_mb floor to the audit, so a database that only wrote a few megabytes since its last backup is left for the regular schedule.
  • Read sys.dm_tran_database_transactions and sys.dm_exec_sessions in the ACTIVE_TRANSACTION branch, so the report names the session holding the log instead of only the reason.
  • Point the REPLICATION branch at sys.dm_repl_traninfo or the log reader agent history, so the report says how far behind the log reader is.
  • Alert on the trend rather than the level by writing each run's used percentage to a KV key, so a log climbing two points a day is caught before it reaches the threshold.
  • Add a second input that refuses to back up a database whose log is already over a size you consider broken, so a log that needs a shrink is handed to a human instead.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.