ENGINEERING NOTE / 12 SQL SERVERPERFORMANCE
CPU Fell 67%. Reads Went Up 44%. Both Were True.
Five scalar functions per row made up most of a list procedure's CPU. Rewriting them as inline table-valued functions took the CPU down by two thirds — and put the logical reads up by almost half. The tempting explanation for that was wrong, and finding the right one meant first proving which counters could be trusted.
TABLE OF CONTENTS
The procedure behind a public listing page on a multi-tenant SQL Server was one of the more expensive things the server ran. Each tenant has its own database — a few thousand of them on one instance — and the same procedure runs in all of them. Query Store put it at about 5% of the server’s CPU over a week: about 220,000 calls, 185 ms of CPU each.
Extended Events narrowed down where the slow calls came from. Every call that took two seconds or more in a day of tracing was the same shape: an anonymous visitor opening the public list with no date filter, which asks for every record the tenant has.
- SHARE OF SERVER CPU
- ≈5%
- CALLS
- ≈220k
- CPU PER CALL
- 185 ms
Five functions per row§
The procedure builds its query dynamically, and the query calls scalar user-defined functions in its select list — three times to fetch localised text for each row, once to decide whether the row is private, and once to decide whether the current user may see it:
SELECT r.RecordId,
Content.GetLocalizedValue('Record', r.RecordId, 'Name', @Lang, @DefaultLang) AS Name,
Content.GetLocalizedValue('Record', r.RecordId, 'Location', @Lang, @DefaultLang) AS Location,
Content.GetLocalizedValue('RecordType', r.TypeId, 'Name', @Lang, @DefaultLang) AS TypeName,
Access.IsPrivate(r.RecordId, 'Record') AS IsPrivate,
Access.HasAccess(@UserId, r.RecordId, 'Record') AS HasAccess
FROM Content.Records AS r
WHERE ...
Modern SQL Server can inline a scalar UDF into the calling query, but only under a long list of conditions. Here they were not inlined, so they ran the way scalar functions always used to: once per row, each one a separate execution with its own reads, invisible to the optimizer’s costing. On the test database they accounted for more than 70% of the call’s CPU.
There was a second, smaller problem in the same text. The language, the dates and the ids were pasted into the dynamic SQL as literals rather than passed as parameters, so every combination compiled its own plan.
The rewrite§
The shape of the fix is well known: express the same logic as inline
table-valued functions and join to them with APPLY. An inline TVF is a
parameterised view; the optimizer expands it into the calling query and can
plan the lookup as a join instead of as a loop of opaque calls.
SELECT r.RecordId, nm.Value AS Name, loc.Value AS Location, tn.Value AS TypeName,
acc.IsPrivate, acc.HasAccess
FROM Content.Records AS r
OUTER APPLY Content.GetLocalizedValueTvf('Record', r.RecordId, 'Name', @Lang, @DefaultLang) AS nm
OUTER APPLY Content.GetLocalizedValueTvf('Record', r.RecordId, 'Location', @Lang, @DefaultLang) AS loc
OUTER APPLY Content.GetLocalizedValueTvf('RecordType', r.TypeId, 'Name', @Lang, @DefaultLang) AS tn
CROSS APPLY Access.HasAccessTvf(@UserId, r.RecordId, 'Record') AS acc
WHERE ...
Alongside that, the literals became sp_executesql parameters, and two
“has a published document” filters that joined to the documents table — one
row per document, then de-duplicated — became EXISTS.
The scalar functions could not simply be replaced. Dozens of other objects call them. So each TVF is a twin of its scalar function, with the same parameters and the same logic, and both carry a comment naming the other:
/* KEEP IN SYNC
Access.HasAccessTvf (inline table-valued) and Access.HasAccess (scalar)
implement the same logic. Until every caller has moved to the TVF and the
scalar function is dropped, any change to one must be made to the other. */
The first results, and the reads§
Correctness came first. The tuned procedure ran against the original across both call shapes the application uses, admin and anonymous users, status and published filters, a custom sort and a search — and a matrix of private-row access through a direct grant, a group and a nested subgroup, for a member, a non-member and an admin. No test database had row-level permissions at all, so that matrix created them inside a transaction that was rolled back. Every case returned identical values, in identical order, with identical column types.
Performance, measured with original and tuned runs alternating rather than all of one then all of the other, looked like this:
CPU ms logical reads original 3,695 318,028 TVFs only 1,227 459,478 change -67% +44%
Two thirds less CPU, and almost half as many reads again. The full-list cases were the worst: the admin “all records” case went from 103k reads to 183k.
The tempting explanation was already in the notes from the first round:
scalar function reads are not counted, so the original was always doing
those reads — the rewrite has simply moved them somewhere the counter can
see. That is a real phenomenon. SET STATISTICS IO does not report the
reads done inside scalar UDFs, and neither do the statement-level query
statistics. If the numbers above had come from either of those, the
comparison would have been between a counter that saw the lookups and one
that did not.
It is also exactly the kind of explanation that ends an investigation without finishing it. So before accepting it, the measurement had to be checked.
Proving which counter tells the truth§
The question is narrow: does this counter include the reads done by scalar functions called from the query? It can be answered directly.
A scan of a fifteen-page table, calling a scalar function once per row —
3,429 calls, with inlining disabled for the test — was run and measured two
ways at once: the session’s own counters, and an Extended Events session on
sql_batch_completed filtered to the test connection. Separately,
sys.dm_exec_function_stats reported the reads done inside the function.
table scan 15 reads sys.dm_exec_function_stats 10,423 reads (inside the function) session counters / XE batch 10,438 reads = 15 + 10,423
The batch-level counters include the function’s reads to the page. And the XE batch totals matched the session counters on every run of the comparison. The numbers in the table above were from those counters — which means the original’s function reads had been counted. The comparison was fair. The reads had really gone up.
Where the reads actually came from§
With the counter trusted, the per-table breakdown and the actual plan showed two separate causes.
Performance spools that were never reused. Seeing the lookups as joins, the optimizer put a performance spool in front of the name, location and access lookups, on the theory that the same inputs would come round again. They did not: each spool was rebuilt for every row — 3,429 rebinds, no rewinds — and the work tables added about 92,000 reads. The only spool that earned its keep was the one in front of the record-type lookup, where many rows share a type: 3,333 rewinds.
One check evaluated twice. The access function decides privacy as part of its own logic, and the procedure also called the privacy function separately to return the flag. Same question, asked twice per row: another 14,000 reads.
The localised-text TVF itself was cheaper than the scalar it replaced — 21,000 reads against 31,000. The rewrite had been right; the plan around it had added waste.
Both fixes were small. OPTION (NO_PERFORMANCE_SPOOL) on the query stops
the optimizer adding spools it expects to reuse. And the access TVF now
returns the privacy flag it has already worked out, so the procedure asks
once:
CROSS APPLY Access.HasAccessTvf(@UserId, r.RecordId, 'Record') AS acc
-- acc.HasAccess, and acc.IsPrivate from the same evaluation
...
OPTION (NO_PERFORMANCE_SPOOL);
The final version§
The same five cases against the original, same method:
CPU ms logical reads original 3,094 317,000 final 891 219,000 change -71% -31%
Then the test that matters before anything gets near production: the ten largest tenant databases on the staging server, seven cases each where the data allowed, every case compared row for row with the original, the tuned objects created alongside the originals and dropped afterwards.
- CASES IDENTICAL
- 52 / 52
- CPU
- −71%
- LOGICAL READS
- −36%
- CASES WORSE
- 0
The published-document filter case gained the most: CPU down 94% and reads
down 85%, because EXISTS stops at the first matching document instead of
joining to all of them. The anonymous “every record” shape — the one behind
the slow production calls — came down by two thirds.
The functions were tested separately as well: the TVFs against their scalar twins on about 6,500 access checks and 50,000 localised-text lookups, all identical. And the migration was rehearsed in every direction it could run: over the current state, rolled back, from the original, and re-run — every definition checked after each step.
What carries over§
Two other list procedures call the same functions per row, and they are the
next most expensive callers. They can reuse the TVFs as they are —
and they will get NO_PERFORMANCE_SPOOL from the start, because the check
for it is now part of the method rather than something rediscovered:
- Find the cost in production data, not on a hunch: Query Store for the share, Extended Events for which calls are slow and who makes them.
- Measure the original with counters that include nested work, and the function statistics alongside.
- After replacing a scalar UDF with an inline TVF, read the plan for spools that rebind on every row and never rewind.
- Prove equivalence on the real call shapes, including the permission paths that no test database happens to have data for.
- Alternate original and tuned runs, warm up first, report medians.
The rewrite itself was the easy part, and the first set of numbers was mostly right. What made it a finished piece of work was refusing the explanation that would have let the reads go unexamined — because the only way to find out it was wrong was to test it.