📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Customers report that checkout failed for some of them in the last hour. Using KQL in Application Insights (Log Analytics), show how you would find which operations are failing, how the failures break down by result code and exception, and how you would follow one failed request across services by its trace id.

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.

Mid-Level Coding Intermediate application-insights incident-response kql log-analytics log-management observability

🎯 Key points

  • Workspace tables: AppRequests, AppDependencies, AppExceptions, AppTraces (the classic Application Insights query names are requests, dependencies, exceptions, traces)
  • Start narrow: time range first, then filter by role (AppRoleName) and operation, then summarize
  • Failure rate = failed / total by OperationName and bin(TimeGenerated, 5m), rendered as a timechart
  • With sampling on, each row stands for ItemCount items: use sum(ItemCount), not count(), for volumes and rates
  • Break down by ResultCode, ExceptionType/ProblemId and AppRoleName to separate one bad dependency from a general outage
  • OperationId is the W3C trace id; union the tables on OperationId to rebuild one request across services, if every service propagates context
  • AppDependencies with Success == false shows which downstream (Target) failed and its DurationMs
  • Compare with a baseline, then save the query as a log search alert with threshold, action group and runbook link

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 OperationName in 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 by ResultCode: 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 ProblemId and ExceptionType, and at AppDependencies where Success == false grouped by Target, so I can see whether, say, the payment provider started timing out at 14:02. Then I pick one failed request and follow it: its OperationId is the W3C trace id, so a union of 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."


Tables you need

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

Incident question to query

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can actually answer an incident question from telemetry, not just name the tool.

Green flags

  • Knows the App* tables and key columns.
  • Computes a failure rate by operation and time bucket.
  • Uses OperationId as the trace id to follow one request.
  • Checks dependencies and compares with a baseline.
  • Turns the query into an alert with an owner and runbook.

Red flags

  • Free-text search over everything.
  • Can't explain how logs from two services are correlated.
  • Alerts on raw counts.

📚 Learn in depth

1. How the data is shaped

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.

2. KQL building blocks

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.

3. Structured properties

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.

4. From query to alert

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.

5. Cost and limits

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.

Try it yourself

  1. Run the failure-rate query on your own Application Insights resource and pin it to a dashboard.
  2. Pick one failed request and rebuild its path with the union query.
  3. Use make-series and series_decompose_anomalies on request count for the last 14 days.
  4. Turn the dependency failure query into a log search alert with a test action group.

💻 Code

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
}

⚠ Common mistakes

  • Mistake: Searching all traces for the word "error" over 30 days. Why it is wrong: It scans huge volumes, is slow and returns noise. Instead: Filter by time and role first, then summarise structured columns.
  • Mistake: Using 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.
  • Mistake: Alerting on a raw failure count. Why it is wrong: It fires at peak traffic and misses failures at night. Instead: Alert on the failure rate with a minimum request count.
  • Mistake: Ignoring AppDependencies. Why it is wrong: Most incidents are a downstream timing out, which only shows there. Instead: Break failures down by dependency Target and ResultCode.
  • Mistake: Assuming every service shares the OperationId. Why it is wrong: A service without OpenTelemetry instrumentation, a custom HttpClient handler or a message consumer that ignores 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.
  • Mistake: Parsing values out of Message with regex. Why it is wrong: It is slow and breaks when the wording changes. Instead: Log with message templates and query Properties.
  • Mistake: Concluding something is abnormal without a baseline. Why it is wrong: Some failure rate is normal, and 2% might be every Monday. Instead: Compare with the same window last week or use make-series.
  • Mistake: Not saving the query. Why it is wrong: The next incident starts from scratch. Instead: Save it to a workbook or turn it into an alert with a runbook. For one request, the portal's transaction search and end-to-end transaction view give the same picture visually.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions OperationId or trace id correlation Why: Checks how the trace id gets into every log line
    How to answer

    Two mechanisms work together.

    • Log scopes: 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.
    • Distributed tracing: each request runs inside an 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.

  2. When: Candidate queries Properties.OrderId Why: Checks why structured properties make queries possible
    How to answer

    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.

  3. When: Candidate mentions Basic logs or query cost Why: Checks awareness of query cost on different table plans
    How to answer

    All four store structured logs and let you search them, but they differ in how much they index, which drives cost.

    • Application Insights / Log Analytics: fully managed, indexes every field, queried with KQL, correlated with traces and metrics. You pay per GB ingested; Basic and Auxiliary table plans and archive cut the cost of noisy or long-retention data.
    • Seq: small, self-hosted, excellent developer experience for structured logs; free for one user.
    • Elasticsearch / OpenSearch: inverted index on fields, powerful full-text search, but you run (or pay for) a memory-hungry cluster.
    • Grafana Loki: indexes only labels, stores chunks in object storage: cheapest at high volume, slower for free-text searches.

    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.

🛠 Real-world problems: how you handle them

Checkout failures traced to a payment gateway timeout with KQL
Situation
[Online retailer] checkout API on .NET [10], [~300] requests per second at peak, during a [sale event]; failures cost revenue every minute.
Signals
Customer complaints on social media, the support queue spiking, and an Application Insights smart detection email for failure anomalies.
Investigation
KQL on AppRequests showed POST /checkout failure rate at [11%] from [14:02]; ResultCode was 500. AppDependencies grouped by Target showed timeouts to the payment gateway with DurationMs at 10,000. Following one OperationId confirmed the gateway call was the last span before the exception.
Resolution
Immediate: switched traffic to the secondary payment gateway with a feature flag. Long-term: reduced the HttpClient timeout with a circuit breaker and fallback, and agreed an SLA conversation with the provider.
Prevention
A log search alert on payment dependency failure rate above [5%] for 5 minutes paging the checkout on-call, with a runbook link; the queries saved in a checkout workbook.

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].

↩ Usually asked after

More in Log Management

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me