Hands-on KQL for incident questions in workspace-based Application Insights: failure rate by operation over time, breakdown by result code, exception and role, joining requests, dependencies, exceptions and traces by OperationId (the W3C trace id), and turning the query into an alert.
I start from AppRequests for the time window and compute the failure rate by OperationName in 5-minute bins, rendered as a timechart, to see which endpoint broke and when. Then I break failures down by ResultCode, AppRoleName and, from AppExceptions, by ProblemId/ExceptionType, and check AppDependencies for the downstream Target that failed. To follow one request, I take its OperationId, which is the W3C trace id, and union requests, dependencies, exceptions and traces filtered on it, ordered by time. Finally I compare with a baseline and save the useful query as an alert. The trade-off: KQL lets you answer almost anything, but only if the telemetry is structured and correlated in the first place.
"I work from the outside in. First, is it real and how big? I query AppRequests for the last two hours, filter to the checkout role, and summarise the failure rate by
OperationNamein 5-minute bins as a timechart. That tells me which operation broke and the exact start time, which I can line up with deployments. Then I break the failures down byResultCode: a wall of 500s points at our code or a dependency, 401s at an expired secret or token, and 429s or 503s at throttling.Next, why? I look at AppExceptions for the same window grouped by
ProblemIdandExceptionType, and at AppDependencies whereSuccess == falsegrouped byTarget, so I can see whether, say, the payment provider started timing out at 14:02. Then I pick one failed request and follow it: itsOperationIdis the W3C trace id, so aunionof requests, dependencies, exceptions and traces filtered on that id, sorted by time, shows the whole path across services. For example, at [company] this kind of query [showed that only orders over a certain amount failed, because they went through a fraud-check service whose certificate had expired].The mistake I see is starting with free-text search over traces for the word 'error' across all time, which is slow, expensive and noisy. A senior habit is to narrow by time and dimension first, compare with a baseline, and turn the query that found the problem into the alert that would have caught it."
| Workspace table | Classic name | Key columns |
|---|---|---|
| AppRequests | requests | TimeGenerated, Name, OperationName, Success, ResultCode, DurationMs, OperationId, AppRoleName |
| AppDependencies | dependencies | Target, DependencyType, Name, Success, ResultCode, DurationMs, OperationId |
| AppExceptions | exceptions | ExceptionType, ProblemId, OuterMessage, OperationId |
| AppTraces | traces | Message, SeverityLevel (0 Verbose to 4 Critical), Properties, OperationId |
| Question | Query shape |
|---|---|
| Which operation is failing, since when? | summarize countif(not(Success))/count() by OperationName, bin(TimeGenerated, 5m) |
| What kind of failure? | summarize count() by ResultCode |
| Which exception? | AppExceptions summarize count() by ProblemId |
| Which dependency? | AppDependencies where Success == false summarize by Target |
| What happened to this request? | union all tables where OperationId == ... order by TimeGenerated |
| Is this normal? | Same query with ago(7d) offset, or make-series |
During a [Black Friday] incident, the failure rate on POST /checkout jumped from [0.2%] to [11%] at [14:02]. Grouping AppDependencies by Target showed every failure was a timeout to the payment gateway with DurationMs pinned at 10,000, our HttpClient timeout. We failed over to the secondary gateway in [6 minutes], and the query became a log alert on dependency failure rate above [5%] for 5 minutes.
Checks whether the candidate can actually answer an incident question from telemetry, not just name the tool.
Green flags
Red flags
Browser -> API (AppRequests: OperationId=abc, Id=span1)
|-- SQL (AppDependencies: OperationId=abc, ParentId=span1)
|-- HTTP -> Payments (AppRequests: OperationId=abc, ParentId=span2)
|-- exception (AppExceptions: OperationId=abc)
With OpenTelemetry, OperationId is the 32-hex-character W3C trace id and Id/ParentId are span ids. That shared id is what makes cross-service queries possible; without trace propagation you are matching on timestamps and guesswork.
| Operator | Purpose |
|---|---|
where |
Filter early, time first, so less data is scanned |
summarize ... by bin(TimeGenerated, 5m) |
Aggregate into time buckets |
countif, percentile, dcount |
Failure counts, latency percentiles, distinct users |
extend |
Computed columns, e.g. tostring(Properties.OrderId) |
join kind=inner / union |
Combine tables on OperationId |
make-series + series_decompose_anomalies |
Baselines and anomaly detection |
render timechart |
Visualise |
Putting the time filter first matters: Log Analytics partitions by time, so where TimeGenerated > ago(2h) is the single biggest performance lever.
With message templates, logger.LogWarning("Payment declined for {OrderId}", id) lands in AppTraces with Properties.OrderId. You query it with tostring(Properties.OrderId) instead of parsing strings with regex. That is why structured logging is a prerequisite for fast incident queries.
A log search alert runs a query on a schedule (for example every 5 minutes over the last 5 minutes) and fires when a threshold is crossed. It needs: the query, the threshold, an action group (who is paged: the checkout on-call via [PagerDuty/Opsgenie/Teams]) and a runbook link in the alert description. Prefer alerting on the failure rate, not a raw count, so it scales with traffic.
Queries on Analytics tables are free; queries on Basic and Auxiliary tables are billed per GB scanned, so the same query can cost money if traces live in a Basic table. Query results are capped (500,000 rows by default in the portal), so summarise before you return rows.
union query.make-series and series_decompose_anomalies on request count for the last 14 days.The queries I run in order during a checkout incident (workspace-based Application Insights). ItemCount makes the numbers correct when sampling is on: a sampled row with ItemCount = 5 represents five requests.
// 1. Which operations are failing, and since when?
AppRequests
| where TimeGenerated > ago(2h)
| where AppRoleName == "checkout-api"
| summarize Total = sum(ItemCount), Failed = sumif(ItemCount, Success == false)
by OperationName, bin(TimeGenerated, 5m)
| extend FailureRate = round(100.0 * Failed / Total, 2)
| where Total > 20 // ignore tiny buckets
| project TimeGenerated, OperationName, FailureRate
| render timechart
// 2. What kind of failure, and which downstream?
let window = ago(1h);
AppRequests
| where TimeGenerated > window and Success == false and AppRoleName == "checkout-api"
| summarize Requests = sum(ItemCount) by ResultCode
| order by Requests desc;
AppDependencies
| where TimeGenerated > window and Success == false
| summarize Failures = sum(ItemCount), p95Ms = percentile(DurationMs, 95) by Target, DependencyType, ResultCode
| order by Failures desc
// 3. Follow one failed request across services by its trace id (OperationId)
let traceId = toscalar(
AppRequests
| where TimeGenerated > ago(1h) and Success == false and OperationName == "POST /checkout"
| top 1 by TimeGenerated desc
| project OperationId);
union AppRequests, AppDependencies, AppExceptions, AppTraces
| where TimeGenerated > ago(1h) and OperationId == traceId
| project TimeGenerated, Type, AppRoleName, Name, Target, ResultCode, DurationMs,
ExceptionType, Message, OrderId = tostring(Properties.OrderId)
| order by TimeGenerated asc
// 4. Sanity check: are some services missing from traces? (broken propagation shows up as orphan roots)
AppRequests
| where TimeGenerated > ago(1h)
| summarize Roots = countif(isempty(ParentId)), Total = count() by AppRoleName
| extend RootShare = round(100.0 * Roots / Total, 1) // a backend service with ~100% roots is not receiving traceparent
The structured property queried above comes from a message template in C#:
namespace Checkout;
public sealed class CheckoutHandler(ILogger<CheckoutHandler> logger)
{
public void Declined(Guid orderId, string reason) =>
logger.LogWarning("Payment declined for {OrderId}: {Reason}", orderId, reason); // Properties.OrderId
}
count() when sampling is enabled. Why it is wrong: Each stored row can represent several real items, so counts are understated, and rare failures may be missing from the sample entirely. Instead: Use sum(ItemCount) for volumes and rates, keep failed requests and exceptions out of sampling where your SDK allows it, and use metrics (which are pre-aggregated, not sampled) for alerting on rates.traceparent starts a new trace, so the union silently shows half the story. Instead: Check for orphan root requests per role and fix propagation before you rely on cross-service queries.Properties.make-series.KQL skill during an incident is mostly discipline: time range first, one question per query, aggregate before you list, and always ask "compared with what?" Seniors also invest before incidents happen: consistent AppRoleName values, structured properties for business ids and saved queries linked from runbooks.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Ad-hoc KQL in the portal | Novel incidents | Free on Analytics tables | Repeated questions: save them |
| Workbooks | Shared incident views per service | Free | One-off investigations |
| Log search alerts | Conditions you can express as a query | Per alert rule evaluation | Simple metric thresholds (use metric alerts, faster and cheaper) |
| Transaction search / end-to-end view | Following one request visually | Free | Aggregate questions |
I measure it by time to identify the failing component in incident reviews.
Two mechanisms work together.
using (logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = id })) adds properties to every log inside the block, flowing across await via AsyncLocal. ASP.NET Core already opens a scope per request with RequestId and RequestPath.Activity whose trace id comes from the incoming W3C traceparent header or is created new. With ActivityTrackingOptions (on by default in the Generic Host) every log carries TraceId and SpanId. HttpClient propagates traceparent automatically; message queues need it copied into message properties (the Azure Service Bus SDK does this).So the trace id is your correlation id; add business ids as properties. The trade-off: custom correlation headers are easy but don't interoperate with tracing tools.
Structured logging records an event: a constant message template plus named properties, instead of a pre-built string. In logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", id, ms), the provider gets the template and the values separately, so OrderId and ElapsedMs become queryable fields (Application Insights customDimensions, OpenTelemetry attributes, Seq properties).
With string interpolation ($"Order {id} placed") the provider only sees a finished string: no properties, a different message every time, and the string is built even when the level is disabled. Analyser CA2254 warns about this.
The trade-off: templates take discipline in naming, but they turn logs from text you grep into data you can filter, group and alert on.
All four store structured logs and let you search them, but they differ in how much they index, which drives cost.
I choose by team size, volume, existing cloud and who runs it, and I ship logs with OpenTelemetry so the choice stays reversible. The trade-off is index everything and query fast versus index little and pay less.
How to tell it (STAR)
**S:** During a [sale], checkout started failing for about [one in ten] customers. **T:** As [on-call], I had to find the cause fast. **A:** I used KQL to chart failure rate by operation, which pinned the start to [14:02], then grouped failed dependencies by target and saw the payment gateway timing out. I followed one trace id to confirm it, and we switched to the secondary gateway via a feature flag. **R:** We were back to normal in [6 minutes], and I turned the query into an alert that caught the next gateway problem [before customers noticed].
Last updated 23 Nov 2026.