Infrastructure
Azure Monitor Logs: diagnose a KQL join explosion before raising query limits
A production runbook for isolating KQL join cardinality, time-window and execution-plan problems before optimizing, canarying or rolling back an Azure Monitor log query.
An Azure Monitor scheduled query rule that normally finishes in seconds starts timing out after a deployment. The new KQL correlates failed requests with dependency errors. Each table is modest on its own, but the join produces millions of intermediate rows because the same operation identifier appears several times on both sides.
Raising a query limit or widening the evaluation interval may hide the first symptom while making every later execution more expensive. This runbook treats the problem as an execution-shape incident. It freezes one failing window, measures both sides of the join, proves the multiplication factor, then canaries a bounded query. The result is one of three decisions: promote the optimized query, keep the alert on its previous version, or redesign the correlation contract before it returns to production.
Freeze the query and one representative window
Do not edit the production rule in place while investigating. Export the deployed scheduled query rule, its scope, frequency, lookback window, threshold, dimensions and actions. Preserve the previous known-good query and one failed evaluation time in UTC. If the rule is paging repeatedly, contain notification noise without deleting the rule or its history.
Create a small incident ledger. The query text alone is insufficient: the same KQL can behave differently with a longer window, a broader workspace scope or a changed ingestion pattern.
incident: INC-OBS-20261112-03
rule_id: /subscriptions/.../providers/Microsoft.Insights/scheduledQueryRules/api-failure-correlation
evaluation_utc: 2026-11-12T14:10:00Z
frequency: PT5M
window: PT30M
scope:
- workspace-prod
query_revision: alert-api-v17
previous_revision: alert-api-v16
containment:
production_query_changed: false
action_group_temporarily_routed: incident-only
evidence:
- deployed_rule_json
- exact_query_text
- source_row_counts
- join_key_cardinality
- canary_evaluations
rollback_owner: observability-on-call Keep a fixed startTime and endTime for every diagnostic query. Relative expressions such as ago(30m) make two runs consume different data and can disguise whether an optimization helped. Record ingestion delays as well: a quiet recent window is not a valid performance canary.
Measure each side before joining
Run the left and right expressions separately with the exact production filters. Count rows, distinct join keys and keys with repeated values. A join is dangerous when both sides contain several rows for the same key: five request rows joined to eight dependency rows create forty rows for that key before later filters or aggregations run.
let startTime = datetime(2026-11-12T13:40:00Z);
let endTime = datetime(2026-11-12T14:10:00Z);
let FailedRequests =
AppRequests
| where TimeGenerated between (startTime .. endTime)
| where Success == false
| project OperationId, RequestTime=TimeGenerated, Name, ResultCode, AppRoleName;
let FailedDependencies =
AppDependencies
| where TimeGenerated between (startTime .. endTime)
| where Success == false
| project OperationId, DependencyTime=TimeGenerated, Target, DependencyType=Type, ResultCode;
union
(FailedRequests
| summarize RowsPerKey=count() by OperationId
| summarize Rows=sum(RowsPerKey), Keys=count(), RepeatedKeys=countif(RowsPerKey > 1)
by Side="requests"),
(FailedDependencies
| summarize RowsPerKey=count() by OperationId
| summarize Rows=sum(RowsPerKey), Keys=count(), RepeatedKeys=countif(RowsPerKey > 1)
by Side="dependencies") For a more useful distribution, summarize by OperationId, then inspect maximum rows per key and percentiles. Also count empty keys. Joining on an empty or fallback value can collapse unrelated events into one enormous group. If the identifier is reused across retries, batches or services, it may not be a safe correlation key without time and resource constraints.
Check whether the query filters after the join when it could filter before it. Project only required columns before the join. This does not fix a logically many-to-many relationship, but it reduces scanned and shuffled data while the relationship is corrected.
Prove the multiplication factor
Estimate the output without executing the full production join. Count rows per key on each side, join those compact summaries, and multiply the counts. This separates source growth from join amplification.
let startTime = datetime(2026-11-12T13:40:00Z);
let endTime = datetime(2026-11-12T14:10:00Z);
let LeftCounts =
AppRequests
| where TimeGenerated between (startTime .. endTime)
| where Success == false and isnotempty(OperationId)
| summarize LeftRows=count() by OperationId;
let RightCounts =
AppDependencies
| where TimeGenerated between (startTime .. endTime)
| where Success == false and isnotempty(OperationId)
| summarize RightRows=count() by OperationId;
LeftCounts
| join kind=inner RightCounts on OperationId
| extend EstimatedRows = LeftRows * RightRows
| summarize
MatchedKeys=count(),
EstimatedJoinRows=sum(EstimatedRows),
WorstKeyRows=max(EstimatedRows),
P95KeyRows=percentile(EstimatedRows, 95)
| extend Amplification = todouble(EstimatedJoinRows) / todouble(MatchedKeys) Then inspect the worst keys. Determine whether repetition is expected, caused by retries, or introduced by a parsing fallback. A high multiplication factor is not primarily a capacity problem. It is evidence that the query has not stated which event on one side should match which event on the other.
Use the query statistics and execution details available in Logs to compare scanned data, result rows and duration on the same fixed window. Do not declare success from a faster run over cached or incomplete data. Repeat the comparison across a normal window and a known peak window.
Choose the correlation contract before the operator
The correct repair depends on the intended relationship:
- If one request needs only the presence of a failed dependency, reduce dependencies to one row per operation before joining.
- If one canonical dimension table enriches events, use a lookup-shaped relationship only after proving the right side is unique and small.
- If both event streams must retain multiple rows, add a bounded time relationship and aggregate immediately after correlation.
- If the alert needs counts rather than event pairs, aggregate each side first and join the aggregates.
innerunique deduplicates the left side on the join key; it is not a universal fix and can discard meaningful left-side events. materialize() can avoid recomputing a bounded intermediate expression, but materializing an oversized set merely moves the pressure. Shuffle hints can distribute a large aggregation or join; they do not repair ambiguous keys.
For this incident, the alert needs one record per failed request with dependency evidence. Reduce the dependency stream to a stable per-operation summary before the join.
let startTime = datetime(2026-11-12T13:40:00Z);
let endTime = datetime(2026-11-12T14:10:00Z);
let FailedRequests =
AppRequests
| where TimeGenerated between (startTime .. endTime)
| where Success == false and isnotempty(OperationId)
| project OperationId, RequestTime=TimeGenerated, Name, RequestCode=ResultCode, AppRoleName;
let DependencySummary =
AppDependencies
| where TimeGenerated between (startTime .. endTime)
| where Success == false and isnotempty(OperationId)
| summarize
DependencyFailures=count(),
Targets=make_set(Target, 10),
DependencyCodes=make_set(ResultCode, 10),
FirstDependencyFailure=min(TimeGenerated),
LastDependencyFailure=max(TimeGenerated)
by OperationId;
FailedRequests
| join kind=inner DependencySummary on OperationId
| where FirstDependencyFailure between (RequestTime - 1m .. RequestTime + 5m)
| summarize
FailedRequests=count(),
DependencyFailures=sum(DependencyFailures),
Targets=make_set(Targets, 20)
by bin(RequestTime, 5m), AppRoleName, Name, RequestCode The time bounds must reflect the telemetry contract, not a convenient number copied from this example. If clocks, sampling or delayed ingestion make the relationship unreliable, the alert should use a more stable identifier or separate signals rather than pretending the join is exact.
Canary the rule, not only the ad hoc query
An interactive query can succeed while the scheduled rule still fails because scope, window, managed identity, dimensions or evaluation frequency differ. Create a canary scheduled query rule with the optimized KQL, the same production scope and lookback, and no broad action group. Give its alert instances a distinct name.
Run the old and canary rules through at least one peak-like window. Compare evaluation completion, matched cohorts, alert state transitions and false negatives against a frozen set of known incidents. Include negative cases: a failed request without a failed dependency, repeated dependencies for one operation, an empty operation ID and late telemetry.
gates:
inputs:
fixed_windows_replayed: 3
peak_window_included: true
empty_join_keys_excluded: true
semantics:
expected_positive_cases_match: true
expected_negative_cases_match: true
unexplained_cohort_delta: 0
execution:
estimated_amplification_bounded: true
evaluations_completed: 12
failed_evaluations: 0
duration_within_budget: true
operations:
canary_action_isolated: true
previous_rule_exported: true
rollback_tested: true
decision: promote_canary Promotion means replacing the production query while preserving the exported prior revision, then watching several complete evaluation cycles. Do not simultaneously increase the window or add dimensions; that would make the evidence ambiguous.
Rollback restores the previous query, scope, frequency, window and dimensions as one versioned unit. Verify that evaluations complete and that one known positive case still alerts. If telemetry volume has permanently outgrown the old rule, rollback is containment only: keep the canary isolated and redesign the signal before increasing limits.
Conclusion
A KQL join incident is rarely solved by giving the query more room. First prove how many rows exist per key on both sides and what relationship the alert actually needs. Reduce or aggregate before correlation, bind the time and resource scope, then test the complete scheduled rule under representative load.
The production decision stays narrow: promote a semantically equivalent query with bounded amplification, restore the known-good rule, or hold the alert until the correlation contract is redesigned. Limits become a capacity decision only after the query shape is explainable.