Home / Azure

AzureCheat sheetAdvanced

Log Analytics KQL performance at scale: a cheat sheet for slow queries, timeouts, result limits and throttling

Make KQL fast on multi-terabyte workspaces. Filter order, has vs contains, join and summarize patterns, materialize, and LAQueryLogs to find the queries that burn CPU or get throttled.

Deepak Bhardwaj8 min read

Applies toAzure Monitor Logs (Log Analytics workspaces, Analytics table plan), Azure CLI with the log-analytics extension. Query limits change; check the current Azure Monitor service limits.

A dashboard tile times out, an alert rule fails with a query error, or an automation account gets 429s from the query API. On a workspace that ingests terabytes a day, KQL that works on a sample becomes a full scan. This sheet lists the patterns that matter, roughly in order of impact, and shows how to find the expensive queries already running.

What Log Analytics penalises

Symptom Usual cause Fix
Query times out or takes minutes Wide time range, or the time filter applied late Put where TimeGenerated first; narrow the range
High CPU on a simple-looking query contains, regex or parse over a large text column Use has and has_any (term index); filter first, parse after
"Query result exceeds limit" Returning raw rows to a client summarize or take; export with data export if you need everything
Join takes forever or fails on memory Large table on the left, or no pre-aggregation Small side on the left; summarize both sides first; hint.strategy=shuffle
Same subquery is slow and runs twice let expression used several times Wrap it in materialize()
429 or "too many requests" from the API Concurrency or rate limits per user or app Stagger schedules, cache results, batch workspaces into one query
Cross-workspace query is slow Fan-out over many workspaces or regions Fewer workspaces per query; filter inside each workspace()

Filter order: time first, then terms

The engine prunes data shards by TimeGenerated before anything else. Make it the first operator, and use a literal range, not a computed one:

// Good
Syslog
| where TimeGenerated between (datetime(2026-11-16 08:00) .. datetime(2026-11-16 09:00))
| where Computer has "vm-app"
| where SyslogMessage has "segfault"

// Slow: everything is read before the time filter applies
Syslog
| extend Day = startofday(TimeGenerated)
| where Day == datetime(2026-11-16)

String operators: pick the indexed one

Operator Uses term index Notes
has, has_any, has_all Yes Matches whole terms; the default choice
==, in, in~ Yes Exact match; in~ is case-insensitive
startswith, endswith Partly Better than contains
contains, !contains No Substring scan of every row
matches regex No The most expensive; run it last, on few rows

has matches terms of three or more characters split on non-alphanumerics. has "10.40.2.15" works because the whole IP is a term. has "40.2" does not match the way contains would.

AzureDiagnostics
| where TimeGenerated > ago(1h)
| where Category == "AzureFirewallNetworkRule"
| where msg_s has_any ("Deny", "deny")
| parse msg_s with Protocol " request from " SrcIp ":" SrcPort " to " DstIp ":" DstPort *
| summarize Denies = count() by SrcIp, DstIp, DstPort
| top 20 by Denies

The parse runs only on rows that survived both the time filter and the has_any.

Shape early: project and summarize before you join

let failing = AppRequests
    | where TimeGenerated > ago(6h) and Success == false
    | summarize Failures = count() by OperationId;
AppDependencies
| where TimeGenerated > ago(6h)
| project OperationId, Target, DurationMs
| join kind=inner failing on OperationId
| summarize P95 = percentile(DurationMs, 95), Failures = sum(Failures) by Target

Rules that apply to joins:

  • Put the smaller table on the left. The default innerunique join also removes duplicates from the left side, which can hide rows. Say kind=inner when you mean it.
  • When both sides are large and the join key has high cardinality, add hint.strategy=shuffle.
  • For lookups against a small dimension table (a watchlist, or a list of VMs), lookup is cheaper than join.

Reuse expensive subqueries with materialize()

let hot = materialize(
    Perf
    | where TimeGenerated > ago(1d)
    | where ObjectName == "Processor" and CounterName == "% Processor Time" and InstanceName == "_Total"
    | summarize AvgCpu = avg(CounterValue) by Computer, bin(TimeGenerated, 15m));
hot | summarize PeakCpu = max(AvgCpu) by Computer | top 10 by PeakCpu
| join kind=inner (hot) on Computer
| project Computer, TimeGenerated, AvgCpu

Without materialize(), the let body runs once for each reference.

Aggregation choices that scale

Need Use Avoid
Distinct count over millions dcount(x) (estimate, tunable accuracy) count_distinct() or distinct then count on huge sets
Latest row per entity summarize arg_max(TimeGenerated, *) by Computer sort then take 1 per group
Top N within groups top-nested Several joins
Time series for charts make-series or summarize ... by bin() Returning raw rows to the client

arg_max(TimeGenerated, *) carries every column. On wide tables, list the columns you need instead of *.

Don't do these on big workspaces

  • search * or union *: every table is scanned. Name the tables.
  • where * has "x": every column is scanned.
  • ago(30d) on a verbose table inside an alert that runs every 5 minutes. Pre-aggregate with a summary rule, or shorten the lookback.
  • TimeGenerated > now() - 1h inside a function used by many tiles. Pass the time range as a parameter so each caller filters first.
  • Sorting millions of rows to show 20. Use top, which sorts during aggregation.

Run and measure from the CLI

WS_ID=$(az monitor log-analytics workspace show -g rg-mon -n law-prod --query customerId -o tsv)

az monitor log-analytics query -w "$WS_ID" --timespan PT1H \
  --analytics-query "Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer | where LastSeen < ago(10m)" \
  -o table

In the portal, the Query details pane under the results shows CPU time, data scanned and the age range of the data touched. Compare these before and after a rewrite.

Find the expensive and throttled queries: LAQueryLogs

Turn on query auditing on the workspace. The Audit diagnostic category writes to the LAQueryLogs table:

LAW=$(az monitor log-analytics workspace show -g rg-mon -n law-prod --query id -o tsv)
az monitor diagnostic-settings create --name law-query-audit --resource "$LAW" \
  --workspace "$LAW" --logs '[{"category":"Audit","enabled":true}]'

Top CPU consumers by caller and client app:

LAQueryLogs
| where TimeGenerated > ago(1d)
| summarize Queries = count(),
            CpuSec = sum(StatsCPUTimeMs) / 1000.0,
            DataGB = sum(StatsDataProcessedKB) / 1024.0 / 1024.0,
            P95Ms = percentile(ResponseDurationMs, 95)
          by AADEmail, RequestClientApp
| top 20 by CpuSec

Failures and throttling (status codes such as 429 and timeouts):

LAQueryLogs
| where TimeGenerated > ago(1d)
| where ResponseCode != 200
| summarize Count = count(), Example = take_any(substring(QueryText, 0, 300))
          by ResponseCode, AADEmail, RequestClientApp
| order by Count desc

Queries that scan far more history than they need:

LAQueryLogs
| where TimeGenerated > ago(1d)
| extend ScannedDays = datetime_diff('day', StatsDataProcessedEnd, StatsDataProcessedStart)
| where ScannedDays > 7
| project TimeGenerated, AADEmail, RequestClientApp, ScannedDays, StatsCPUTimeMs, QueryText
| top 50 by StatsCPUTimeMs

Tip

Alert rules and workbooks show up under their own client app values. Repeated queries with the same text every few minutes from one app are usually a dashboard on a wall screen, or an alert with a long lookback. Those are the cheapest wins.

Limits to design around

Query timeout, maximum returned rows and bytes, concurrent queries per user, and request rate per user or application are all published service limits. They change, so check the current Azure Monitor service limits page rather than hard-coding a number. Two design rules hold whatever the values:

  • Automation that polls many workspaces should run one cross-workspace query, or spread its calls over time, rather than firing parallel bursts.
  • Tables on the Basic or Auxiliary plan have a restricted KQL surface and charge per query. Keep high-frequency alert queries on Analytics tables.

Prevent it next time

  • Review the LAQueryLogs top-20 list every month. Fix or delete the worst offenders.
  • Put shared logic in saved functions that take a time range parameter, so every caller filters by time first.
  • Pre-aggregate hot dashboards with summary rules into a small table, and point the tiles at it.
  • Add a query review to alert-rule PRs: time filter first, has not contains, and no * scans.