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

SQL Server Stale Statistics Refresh Guard

Find SQL Server statistics with a high modification counter versus rowcount, alert Slack, refresh with UPDATE STATISTICS, then re-read to confirm.

Categories
DataInfrastructure

SQL Server keeps column and index statistics so the query optimizer can estimate how many rows a predicate returns. Each statistic carries a modification_counter that counts the rows changed since it was last built. When that counter grows large relative to the table, the stored histogram no longer matches the data, the optimizer estimates the wrong row counts and it picks bad plans: a loop join where a hash join was right, a seek where a scan was right, too little or too much memory granted. Auto update statistics helps, but it can be off, it can lag on large tables and a load that bypasses it leaves the counter high.

This blueprint reads sys.stats joined through sys.dm_db_stats_properties for every user table statistic in the connected database, flags the ones whose modification_counter is at least a chosen percent of the rowcount (with a floor so small tables are ignored) and alerts Slack. When you allow it, it refreshes each flagged statistic with UPDATE STATISTICS, one statement at a time, then reads dm_db_stats_properties again and fails the run if any flagged statistic is still over the threshold.

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 reads the statistics and alerts.
  • A write happens only when auto_remediate is true and dry_run is false.
  • Each refresh runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query, never a Queries task with transaction: true. UPDATE STATISTICS does not run inside an explicit transaction.
  • The remediation loop has concurrencyLimit: 1, so the refreshes never run in parallel.
  • UPDATE STATISTICS holds a short schema lock while it rebuilds the histogram. WITH FULLSCAN reads the whole table, so leave it off on very large tables unless you need exact estimates.

How it works

  1. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) joins sys.stats to sys.objects and sys.schemas, then CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id). It keeps every user table statistic where modification_counter is at least min_modifications and at least modification_pct of the rowcount, then builds the UPDATE STATISTICS statement for each one with QUOTENAME.
  2. fixes (io.kestra.plugin.core.output.OutputValues) collects the per statistic refresh statements. summary (io.kestra.plugin.core.log.Log) logs the findings with the modification counter and rowcount for each.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs that no statistic is over the threshold.
    • findings: alert posts the flagged statistics 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 UPDATE STATISTICS in turn.
      • reaudit re-reads dm_db_stats_properties. verify_result fails the run if any flagged statistic is still over the threshold.
  4. errors posts a Slack alert when a refresh did not land or the audit cannot run.

What you get

  • Every statistic the optimizer is reading from a stale histogram, with its modification counter, the rowcount at the last update and the percent over.
  • A refresh that rebuilds each flagged statistic from the current data and resets its modification counter, so the optimizer gets current estimates.
  • A re-read of dm_db_stats_properties after the change that fails the run if a statistic is still over the threshold, so a refresh that did not land is never reported as success.
  • A Slack alert on findings and a separate alert if a refresh fails or the audit cannot run.

Who it's for

  • DBAs who turned off auto update statistics for predictable load windows and want a controlled refresh of only the statistics that drifted.
  • Platform teams chasing a plan regression who want to know which statistics are stale before they rebuild everything.
  • Teams evaluating the SQL Server plugin who want an example that reads a dynamic management function and drives UPDATE STATISTICS.

Why orchestrate this with Kestra

Refreshing every statistic on a schedule wastes IO and can still miss the one table that drifted overnight. You want to see which statistics are actually stale first, refresh only those, one at a time, then confirm the counters reset. You want the run to stop and shout if a refresh did not take. Kestra reads dm_db_stats_properties, gates the change behind two inputs, runs each UPDATE STATISTICS on its own, re-reads the function and fails loudly if anything is still stale. 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 on Linux, with a local HTTP sink standing in for Slack. A table was seeded, its statistics were fully updated, then many rows were changed with AUTO_UPDATE_STATISTICS OFF so the modification counters climbed and stayed high.

Run Inputs Result
1 defaults, two statistics over threshold 2 flagged, Slack alert "No change applied". dm_db_stats_properties still showed modification_counter 1000 and 3000, so a default run changed nothing
2 auto_remediate: true, dry_run: true 2 flagged, still "No change applied". The dry run blocked the write even with auto_remediate on
3 auto_remediate: true, dry_run: false remediate ran two UPDATE STATISTICS. reaudit returned 0 rows. dm_db_stats_properties reported modification_counter 0 for both
4 defaults, after run 3 0 flagged, clean branch
5 min_modifications: 999999 0 flagged on the degraded table, which proves the threshold gates the detection
6 unreachable server audit failed, errors block posted to Slack

Prerequisites

  • A SQL Server database you can reach over JDBC.
  • A login that can read sys.stats and run sys.dm_db_stats_properties for the audit, plus ALTER on the tables (for example db_ddladmin or table ownership) for UPDATE STATISTICS.
  • 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. The query reads the connected database
user sa SQL Server login
password {{ secret('SQLSERVER_PASSWORD') }} Password for the login
modification_pct 20.0 Flag a statistic when its modification counter is at least this percent of the rowcount
min_modifications 500 Ignore statistics with fewer modifications than this
full_scan false Refresh with a full scan instead of a sample
auto_remediate false Allow the refresh statements
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 statistics.
  4. When you are ready, run with auto_remediate: true and dry_run: false.
  5. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Limit the audit to one schema by adding a WHERE sch.name = ... filter so a shared instance is checked in parts.
  • Raise modification_pct or min_modifications to match your own staleness tolerance. Drop full_scan for faster sampled refreshes.
  • Post the modification counter and rowcount to Slack so an on-call engineer can judge urgency without opening the database.
  • 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.