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

SQL Server tempdb Data File Balance Guard

Detect skewed tempdb data file sizes behind PFS and GAM page latch contention, level them up with ALTER DATABASE behind an approval, then re-read.

Categories
DataInfrastructure

tempdb does not round robin its allocations. It picks the data file with the most free space, proportionally, which is the whole reason several files help at all. The moment the files are different sizes that proportional choice collapses back onto one file. A single 20 GB data file behaves the same way under load as eight files where one is 20 GB and the rest are 8 MB. The allocation bitmaps in that one file become the hot pages.

What you see is sessions queueing on PAGELATCH_UP against pages like 2:1:1, 2:1:3 or 2:3:905768, which are the PFS, GAM and SGAM pages of tempdb file 1. Throughput falls as concurrency rises. No query plan shows it and no index will fix it, because the wait is on a latch, not a lock.

The fix has been the same advice for twenty years, several equally sized tempdb data files, so almost nobody checks whether the instance in front of them still matches it. Files drift apart after a one off manual grow. A restore or a migration lands tempdb on one file. Someone raises autogrowth on file 1 only.

This blueprint reads every tempdb data file from tempdb.sys.database_files, which holds the current size (sys.master_files keeps only the startup size for tempdb), measures the size skew between the largest file and the smallest, compares the file count against a floor, then alerts Slack. When you allow it and a human approves the run, it grows every smaller file up to one common size with ALTER DATABASE tempdb MODIFY FILE, adds files with ADD FILE to reach the floor, leaves one fixed FILEGROWTH on all of them, then reads tempdb.sys.database_files again and fails the run if tempdb is still skewed or still short of files.

This blueprint was created by zkasuran.

Safety

  • Only tempdb is read and only tempdb is changed. Every query reads tempdb.sys.database_files filtered to type_desc = 'ROWS'. Every statement names tempdb explicitly. No user database and no other system database is in range. The tempdb log file is out of range too.
  • Read-only by default. dry_run is true and auto_remediate is false, so a normal run only measures and alerts.
  • A change 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.
  • Files are only ever grown, never shrunk. Reaching one common size by raising the small files is online and reversible at the next restart. Shrinking a tempdb data file is a different operation with a different risk profile: it may release nothing at all while the file is in use. It also needs DBCC SHRINKFILE rather than MODIFY FILE. So the target size is the largest current file, floored at min_file_size_mb.
  • Growing a file writes and zeroes real disk at the moment the statement runs. Check free space on the tempdb volume first. Prefer a quiet window on a large jump.
  • The remediation loop has concurrencyLimit: 1, so two file changes never overlap on tempdb.
  • Each statement runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query. ALTER DATABASE cannot run inside an explicit transaction, so this is never a Queries task with transaction: true.

What applies immediately and what waits for a restart

  • Immediate, no restart. ALTER DATABASE tempdb MODIFY FILE (SIZE = ...) that raises a file takes effect as soon as it commits. The file is larger on disk and tempdb starts weighing it by its new free space straight away. A changed FILEGROWTH is immediate as well.
  • Immediate, but only for new allocations. ADD FILE puts the file in service at once. It does not move a single existing allocation, so a workload that already filled file 1 keeps its pages there and the proportional fill only improves as that space is freed and re-taken.
  • Only at the next restart. tempdb is recreated from the master catalog every time the instance starts, which is when the new layout becomes the starting layout rather than the current one. A size you set below a file's current size is also only honoured then.
  • What the re-verify does and does not prove. It re-reads tempdb.sys.database_files, which is the live state: file count, per file size and per file growth increment. It proves the change landed. It cannot prove the contention is gone, because allocation latch waits live in sys.dm_os_wait_stats and sys.dm_exec_requests under real load, not in a settings read. Watch PAGELATCH_UP waits on tempdb pages for that, which is listed under How to extend.

How it works

  1. state_before (io.kestra.plugin.jdbc.sqlserver.Query, read-only) lists every tempdb data file from tempdb.sys.database_files with its size in MB, its growth increment, whether that growth is a percentage and its physical path, plus the file count and the size skew as window aggregates.
  2. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) returns one row per planned action, exposed as outputs.audit.size plus outputs.audit.rows. It returns zero rows when the skew is inside skew_tolerance_pct and the file count is at or above min_file_count. A grow row carries an ALTER DATABASE tempdb MODIFY FILE statement that raises the file to the common target and sets the fixed growth. An add row carries an ALTER DATABASE tempdb ADD FILE statement, with the new file placed in the same directory as file 1. Statements are built in T-SQL with QUOTENAME.
  3. targets (io.kestra.plugin.core.output.OutputValues) splits the plan into the grow count, the add count and the target size. summary (io.kestra.plugin.core.log.Log) logs every file with its size and growth.
  4. route (io.kestra.plugin.core.flow.If):
    • clean: logs that tempdb is balanced and at or above the file floor.
    • findings: alert posts the skew, the file count and the plan 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 the grow statements first, then the add statements, one at a time.
      • after_state reads every tempdb data file back and state_log logs the before and after side by side.
      • reverify re-reads tempdb.sys.database_files and returns a row only while tempdb is still skewed, still short of files or still carrying a different growth increment on a file. verify_result branches on outputs.reverify.size and fails the run through io.kestra.plugin.core.execution.Fail if it is not zero.
      • declined logs the findings untouched when the approval was refused.
  5. 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 size skew percentage across the real tempdb data files, which is the number behind an allocation latch problem that no query plan exposes.
  • The file count against a floor you set, so a tempdb that was restored or migrated onto one file is caught as well as one that drifted.
  • A fix that only grows, so nothing depends on a shrink releasing space while tempdb is in use.
  • One fixed FILEGROWTH left on every file. tempdb grows its data files together by default since SQL Server 2016, so unequal increments pull the sizes apart again by themselves.
  • A second read of tempdb.sys.database_files that fails the run when the layout did not land, with an honest statement of what that read covers.
  • A Slack alert on the findings plus a separate alert on failure.

Who it's for

  • DBAs chasing a slowdown that only shows under concurrency, where the top wait is PAGELATCH_UP on a tempdb page rather than anything in a plan.
  • Platform teams who inherited instances built by someone else or restored onto new hardware, where nobody has checked the tempdb layout since.

Why orchestrate this with Kestra

This is a check nobody remembers to run and a change nobody wants to run blind. The target size depends on what the files look like right now, so the plan has to be built from a live read rather than written down once. The statements have to go one at a time against one database. A human has to say yes before real disk is written. Then somebody has to prove the layout actually changed, which is the step that gets skipped by hand. Kestra reads tempdb.sys.database_files, builds the plan from it, gates the change behind two inputs plus an approval, runs the statements serially, reads the catalog again and fails loudly when the layout did not land. 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. The container starts tempdb with 8 data files of 8 MB each on a 64 MB growth increment, which is already balanced, so it served as the healthy case. tempdb was then degraded with ALTER DATABASE tempdb MODIFY FILE to push file 1 well above the rest. A user database w35app was kept on the instance throughout with two deliberately mismatched data files (8 MB and 48 MB) on 10 percent growth, as the control for the database_id = 2 scoping. Every number below was read back with sqlcmd against sys.master_files, not from the flow log. Those runs used sys.master_files for the audit and the re-read. A later audit switched both to tempdb.sys.database_files and did not re-run them.

Run What was run Result
1 tempdev grown to 32 MB first, then the defaults plus min_file_size_mb: 8 7 flagged to grow to 32 MB at 75 percent skew. Slack said "No change applied". sqlcmd still read 32, 8, 8, 8, 8, 8, 8, 8
2 auto_remediate: true, dry_run: true the same 7 findings, still "No change applied". sqlcmd unchanged
3 auto_remediate: true, dry_run: false, pause resumed approved: false declined listed all 7. sqlcmd unchanged
4 the same, resumed approved: true 7 MODIFY FILE statements ran, reverify returned 0 rows. sqlcmd: all 8 files 32 MB, skew 75 to 0 percent, growth 64 MB on every file
5 the same inputs on the fixed instance 0 actions, clean branch, 0 percent skew
6 min_file_count: 10, approved 2 ADD FILE statements ran. sqlcmd: 8 to 10 data files, both new ones 32 MB on 64 MB growth, reverify 0 rows
7 tempdev grown to 48 MB, then skew_tolerance_pct: 90 0 actions on a tempdb at 33 percent skew, which proves the tolerance gates detection
8 the same state at tolerance 20, approved, with tempdev grown to 96 MB by another session during the pause the 9 planned grows landed at 48 MB, then reverify returned files=10 min=48MB max=96MB skew=50pct and remediation_failed failed the run. The errors block posted to Slack
9 unreachable host state_before failed on the TCP connection and the errors block posted to Slack
10 FILEGROWTH set to 10 percent on one file, tolerance 90 0 actions. That file was reported as growth=percent, which shows a growth increment on its own never triggers detection
11 the same state at tolerance 20 9 flagged at a common target of 96 MB
12 run 11 approved 9 MODIFY FILE statements ran. sqlcmd: all 10 files 96 MB, skew 50 to 0 percent, the percent growth file converted to a fixed 64 MB increment, reverify 0 rows

Across all twelve runs w35app held its mismatched 8 MB and 48 MB data files on 10 percent growth, unchanged, which is the proof that the database_id = 2 scoping held.

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 tempdb.sys.database_files, which needs the public role in tempdb. Remediation needs ALTER on tempdb. sysadmin covers both.
  • Free space on the tempdb volume for the growth the plan reports. The flow reports the target size before anything runs.
  • 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
skew_tolerance_pct 20 Flag tempdb at or over this size skew
min_file_count 4 Flag tempdb below this data file count
min_file_size_mb 64 Floor for the common target size
growth_mb 64 Fixed FILEGROWTH left on every data file
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 run it once with the defaults and read the skew and the file count out of the log.
  3. Set min_file_count from the instance. One file per logical core up to eight is the usual starting point.
  4. Set min_file_size_mb to the size each file should hold, then check free space on the tempdb volume against the target the log reports.
  5. Run with auto_remediate: true and dry_run: false and approve the pause. Plan a restart later if you want the new layout to also be the starting layout.
  6. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Join sys.dm_os_wait_stats into the audit and report the PAGELATCH_UP wait time next to the skew, so the report carries the symptom as well as the configuration.
  • Read sys.dm_db_file_space_usage to split tempdb usage into user objects, internal objects and the version store, which says whether more files is even the right answer for this workload.
  • Add a free space check on the tempdb volume from sys.dm_os_volume_stats and refuse the plan when the growth would not fit.
  • Drive many instances from one run by making url a list and looping the audit, keeping the remediation loop serial per instance.
  • Fold in a REMOVE FILE path for an instance that has too many tempdb files, remembering that it needs the file emptied first with DBCC SHRINKFILE ... EMPTYFILE and usually a restart.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.