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

📚 Interview question

Your Application Insights bill has tripled in a month and API latency has risen, and both trace back to logging. How do you find exactly what is producing the volume, fix log levels, sampling and sinks, and keep costs under control without losing the data you need for incidents?

A real-world logging cost and latency incident: finding ingestion sources with KQL over _BilledSize by table, category and template, common causes (Debug left on, EF Core command logging, HTTP body logging, duplicate pipelines, health-check noise, disabled sampling), latency from synchronous or blocked log writes, fixes in levels, filters, sampling and sinks, and long-term controls such as daily caps, table plans, transformations and cost alerts.

Senior RealWorldScenario Advanced application-insights aspnet-core cost-optimisation kql logging performance

🎯 Key points

  • Measure first: union * | summarize sum(_BilledSize) by itemType, then traces by CategoryName and OriginalFormat to find the top producers
  • Usual causes: Default/category at Debug via an env var, EF Core Database.Command at Information, HTTP logging bodies, health probes, duplicate SDK + sink pipelines
  • Latency link: synchronous sinks, console logging under high volume (queue full, Wait mode), large payload formatting on the request thread
  • Fix levels per category in configuration (no deploy), filter health probes, remove duplicate pipelines
  • Sampling for traces/requests/dependencies (distro rate-limited TracesPerSecond or fixed SamplingRatio; tail sampling in a Collector to keep errors); keep metrics for rates
  • Workspace controls: daily cap as a safety net, table plans (Basic/Auxiliary for verbose logs), ingestion-time transformations, per-table retention
  • A written production logging policy: Information by default, Debug only time-boxed and per category, telemetry config changes reviewed like code
  • Prevent: cost alert on ingestion anomaly, logging guidelines, CA2254/CA1848, monthly review of ingestion by category

⏱ 30-second answer

First measure, don't guess: in Log Analytics run union * | summarize sum(_BilledSize) by itemType, then break traces down by category and message template (OriginalFormat). One or two sources usually dominate: a Debug level left on, EF Core SQL command logging, HTTP body logging, health probes, or two pipelines sending the same data.

Latency rises because logging runs on the request thread: synchronous sinks, a full console queue, or formatting large payloads.

Fix in order: levels per category (configuration, no deploy), remove duplicates and noise, sample traces while keeping metrics complete, then workspace controls: daily cap as a safety net, cheaper table plans, retention, and a cost anomaly alert. The trade-off: every gigabyte you cut must not be the one you need at 3 a.m.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd treat it as an incident with two symptoms and probably one cause. The first thing is data, not opinions: Log Analytics records the billed size of every row, so union * | summarize sum(_BilledSize) by itemType tells me whether it's traces, requests, dependencies or exceptions, and then I group traces by category name and message template, and by cloud role, over the last 30 days to see when it jumped. Almost always one or two sources are most of the bill, and the jump lines up with a deployment or a configuration change.

For example, at [company] the bill went from about [A$4,000 to A$12,000] a month. The KQL showed [70%] of ingestion was Microsoft.EntityFrameworkCore.Database.Command at Information plus our own Debug lines: someone had set Logging__LogLevel__Default=Debug on the production App Service to investigate a bug and never removed it. The latency was the same cause: at that volume the console provider's queue was filling, and the default Wait mode blocked request threads. I set the level back through configuration, which took effect without a deploy, then over the next sprint removed a duplicate Serilog Application Insights sink, filtered health probes, and set explicit trace sampling. Ingestion dropped by [about 75%] and p95 latency went back to [120] ms.

The mistake I see is reaching for the daily cap first. A cap stops the bill by stopping all ingestion, so the day you have an incident is the day you have no logs. I use a cap only as a safety net set well above normal, and fix the sources. Then I make it stay fixed: an ingestion anomaly alert, temporary verbose logging with an expiry, and telemetry config changes reviewed like code. Cost is a logging quality metric: noise you pay for is noise that hides signal."


Typical causes and fixes

Cause How it shows in KQL Fix
Default or category at Debug in prod Huge traces count at severityLevel 0–1 Reset level in config; time-box verbose logging
EF Core Database.Command at Information Category Microsoft.EntityFrameworkCore.Database.Command dominates Set to Warning; use Query Store for slow SQL
HTTP logging with bodies Large _BilledSize per row from Microsoft.AspNetCore.HttpLogging Headers allowlist, no bodies
Health probes traced and logged requests named GET /healthz dominate Filter probes in instrumentation and logging
Duplicate pipelines (SDK + Serilog sink) Identical messages twice per operation Keep one pipeline
Sampling off itemCount always 1 Distro TracesPerSecond / SamplingRatio
Chatty dependency telemetry (Redis, blob per call) dependencies table dominates Sampling, filter dependency types

Why latency rose

Mechanism Detail
Console queue full Console provider queues to a background thread; when the queue is full, the default QueueFullMode.Wait blocks callers
Synchronous sinks File or HTTP sink writing on the request thread
Formatting large objects Serialising DTOs or bodies for every request
Exporter back-pressure Very high volume increases CPU and GC in batching exporters

Production example

After the fixes, monthly ingestion went from about [900] GB to [210] GB, the bill from [A$12,000] to [A$3,100], and p95 latency from [310] ms back to [120] ms; an anomaly alert on daily ingestion has fired [twice] since, both times catching a forgotten Debug override within a day.

🔍 What the interviewer is checking

Checks whether the candidate can run a cost and performance investigation with data, fix it without losing incident visibility, and put guardrails in place.

Green flags

  • Starts with KQL on _BilledSize by table, category and template.
  • Names the usual culprits and links volume to latency on the request path.
  • Fixes levels and duplicates before sampling, and keeps metrics complete.
  • Treats the daily cap as a safety net and adds anomaly alerts and policy.

Red flags

  • Turns logging off or sets a low daily cap as the answer.
  • Cannot explain why logging affects latency.
  • No plan to stop it happening again.

📚 Learn in depth

1. Where the money goes

Workspace-based Application Insights stores data in Log Analytics tables (AppTraces, AppRequests, AppDependencies, AppExceptions, AppMetrics; the classic names traces, requests work in the Application Insights blade). You pay mainly per GB ingested (pay-as-you-go or a commitment tier), plus retention beyond the included period. Every row carries _BilledSize in bytes.

  ILogger / Activity / Meter
        │
        ▼
  provider filters (levels) ──► sampler ──► exporter batch ──► ingestion endpoint
   ↑ cheapest place to cut      ↑ traces only                   │
                                                                  ▼
                                              transformation (DCR, where supported) ──► table
                                                                                    │
                                                                    plan: Analytics / Basic / Auxiliary
                                                                    retention per table

Cut as early as possible: a log filtered by level costs nothing downstream; a log dropped by an ingestion-time transformation has already cost CPU, network and exporter time.

2. The KQL toolkit

// Which table?
union withsource = Table *
| where TimeGenerated > ago(30d)
| summarize GB = sum(_BilledSize) / 1e9 by Table
| order by GB desc

// Which category and template inside traces?
AppTraces
| where TimeGenerated > ago(7d)
| summarize GB = sum(_BilledSize) / 1e9, Rows = count()
    by Category = tostring(Properties.CategoryName), Template = tostring(Properties.OriginalFormat), AppRoleName
| top 20 by GB

// When did it start?
AppTraces
| where TimeGenerated > ago(30d)
| summarize GB = sum(_BilledSize) / 1e9 by bin(TimeGenerated, 1d), AppRoleName
| render timechart

The property names depend on the SDK or exporter version; check one row first.

3. The console provider and latency

The console logger formats on the caller's thread and enqueues the text for a background writer. stdout in containers is often slow (a pipe read by the container runtime). With very high volume the queue fills, and with ConsoleLoggerQueueFullMode.Wait (the default) the request thread waits. DropWrite avoids blocking but loses lines. The real fix is less volume.

4. Sampling and what it doesn't fix

Sampling reduces requests, dependencies and their logs (with trace-based log sampling in recent Azure Monitor exporters), but logs written outside a sampled trace, start-up and background loops, aren't affected. Metrics stay accurate because they are pre-aggregated. Sampled rows carry itemCount so counts in the portal are scaled back up.

5. Workspace-level controls

  • Daily cap: stops ingestion when reached until the next day. A safety net, never the main control.
  • Table plans: Basic and Auxiliary logs cost far less to ingest but have limited query features and charge per query; good for verbose diagnostic tables you rarely query.
  • Transformations: data collection rules can drop columns or rows at ingestion for supported tables.
  • Retention: per table; keep high-value tables longer and verbose ones briefly (also an APP 11.2 point if they contain personal information).
  • Commitment tiers: cheaper per GB at steady high volume; fix waste before committing.

6. Making verbose logging temporary

Raise a category through Azure App Configuration with a label and a reminder, or use a dynamic LoggingLevelSwitch exposed on an admin endpoint that reverts after N minutes. Never set production-wide Debug through a portal app setting without an expiry.

Try it yourself

  1. Run the table and category queries above against a test workspace and find the top three sources.
  2. Load test a demo API with k6 at Debug and at Information, and compare ingestion and p95 latency.
  3. Set the console provider's MaxQueueLength to a small number and observe request latency at high log volume with Wait versus DropWrite.
  4. Configure the Azure Monitor distro with TracesPerSecond = 1 and verify itemCount scaling in the requests table.
  5. Create an Azure Monitor alert on daily ingestion using the Usage table or a log search alert on _BilledSize.

💻 Code

The changes that typically fix this, in configuration and code.

// appsettings.Production.json: levels per category, no Debug by default
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Warning",
      "System.Net.Http.HttpClient": "Warning"
    },
    "Console": {
      "LogLevel": { "Default": "Warning" }
    }
  }
}
// Program.cs
using Azure.Monitor.OpenTelemetry.AspNetCore;
using OpenTelemetry.Instrumentation.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole();

// One pipeline to Application Insights (no extra Serilog sink, no classic SDK)
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
    o.TracesPerSecond = 5; // explicit sampling decision, documented in an ADR
});

// Don't trace or log health probes: they were [30%] of requests
builder.Services.Configure<AspNetCoreTraceInstrumentationOptions>(o =>
    o.Filter = ctx => !ctx.Request.Path.StartsWithSegments("/healthz"));

var app = builder.Build();
app.MapGet("/healthz", () => TypedResults.Ok());
app.MapGet("/orders/{id:guid}", (Guid id, ILogger<Program> logger) =>
{
    logger.LogDebug("Loading order {OrderId}", id); // filtered out in production
    return TypedResults.Ok(new { id });
});
app.Run();
# Remove the forgotten override that caused the spike (App Service)
az webapp config appsettings delete --name orders-api --resource-group rg-orders-prod \
  --setting-names Logging__LogLevel__Default

⚠ Common mistakes

  • Mistake: Using the daily cap as the fix. Why it is wrong: When it trips, all telemetry stops, often during the incident you need it for. Instead: Fix sources; keep a cap well above normal as a safety net.
  • Mistake: Guessing which logs are expensive. Why it is wrong: Intuition is usually wrong about volume. Instead: Query _BilledSize by table, category and template.
  • Mistake: Turning on Debug in production through an app setting with no expiry. Why it is wrong: It is forgotten and silently multiplies cost. Instead: Time-boxed, category-specific overrides with a reminder or automatic revert.
  • Mistake: Cutting all Information logs to save money. Why it is wrong: You lose the business events needed in incidents. Instead: Remove noise categories and duplicates first.
  • Mistake: Keeping two pipelines into Application Insights. Why it is wrong: Double ingestion for identical data. Instead: One pipeline.
  • Mistake: Treating the latency as a separate problem. Why it is wrong: High log volume costs CPU, GC and blocked threads on the request path. Instead: Profile with dotnet-trace and check console queue and sink behaviour.
  • Mistake: Committing to a higher commitment tier before cutting waste. Why it is wrong: You lock in paying for noise. Instead: Reduce volume, then size the tier.

🏛 Senior insight: trade-offs

A telemetry bill is a design review in disguise. It tells you which code is noisy, which levels nobody agreed, and which configuration changes bypass review. I fix the immediate spike quickly through configuration, then put three guardrails in place: an ingestion anomaly alert, a written logging-level policy, and a rule that verbose overrides expire. I also keep the conversation about value: if a table costs A$2,000 a month and nobody queried it in 90 days, it goes to a cheaper plan or away.

Option When it fits Cost When not to
Category level changes First fix, always None –
Trace sampling High request volume Fewer individual traces Low-traffic services where every trace matters
Basic/Auxiliary table plans Verbose data rarely queried Limited queries, per-query charge Data used in alerts and dashboards
Ingestion transformations Legacy apps you can't change quickly Data already sent; rules to maintain As a substitute for fixing the code
Daily cap Safety net only Blind spot when hit Primary cost control

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions resetting log levels per category. Why: Checks they can configure per-category levels precisely, the cheapest fix.
    How to answer

    ILogger<T> is the logging abstraction from Microsoft.Extensions.Logging. You inject it, and the category is the full name of T, so every log line says which class wrote it.

    Each call has a level: Trace, Debug, Information, Warning, Error, Critical (and None to turn a category off). In appsettings.json the Logging:LogLevel section sets a minimum level per category prefix: Default for everything, and more specific prefixes like Microsoft.AspNetCore override it, the longest matching prefix wins. Providers can have their own overrides (Logging:Console:LogLevel).

    The trade-off: verbose levels help diagnose problems but cost money and noise, so production usually runs at Information with framework categories at Warning.

  2. When: Candidate mentions sampling traces to cut cost. Why: Checks they understand sampling choices and what metrics keep accurate.
    How to answer

    OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).

    In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.

    For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.

  3. When: Candidate links log volume to request latency. Why: Checks they can profile the latency side with dotnet-trace and dotnet-counters.
    How to answer

    First I measure: Application Insights tells me which endpoint is slow and at what percentile, and whether time goes into dependencies like SQL or HTTP. Then I reproduce it on a Release build and run the Visual Studio Performance Profiler (Alt+F2): CPU Usage for hot paths, Database for query count and duration, .NET Object Allocation Tracking for GC pressure, and .NET Async for slow awaits. In an environment where I can't use Visual Studio, dotnet-counters shows live metrics like thread pool queue length and GC, and dotnet-trace captures CPU samples. I fix the biggest cause, often an N+1 query, re-measure against the baseline, and add a load test so it doesn't regress.

🛠 Real-world problems: how you handle them

Forgotten Debug override tripled telemetry cost and raised p95 latency
Situation
An orders API on [Azure App Service, Australia East, 6 instances] with workspace-based Application Insights. The monthly bill rose from about [A$4,000] to [A$12,000] and p95 latency from [120] to [310] ms over [three] weeks; finance and the product owner both escalated.
Signals
Azure Cost Management showed the Log Analytics meter driving the increase; daily ingestion up from [30] to [95] GB; `traces` table dominant; CPU up [15%]; thread pool queue length spikes in dotnet-counters during peaks.
Investigation
KQL on `_BilledSize` by table, then by category and template: [70%] from `Microsoft.EntityFrameworkCore.Database.Command` and our own Debug templates. A daily timechart showed the jump on the day an app setting `Logging__LogLevel__Default=Debug` was added in the portal during a bug investigation (found in the App Service activity log). A `dotnet-trace` capture showed request threads blocked in the console logger's queue under peak load, plus a Serilog Application Insights sink duplicating every trace.
Resolution
Immediate: deleted the app setting (levels reloaded without a deploy) and confirmed ingestion fell within an hour. Next sprint: removed the duplicate Serilog sink, filtered health probes, set EF Core command logging to Warning permanently, set explicit trace sampling, moved a verbose diagnostic table to the Basic plan and set a daily cap at [3x] normal as a safety net.
Prevention
Ingestion anomaly alert on daily GB; verbose overrides only through App Configuration with an expiry label; telemetry configuration changes reviewed in pull requests; logging-level guidelines in the team wiki; dashboard of ingestion by category reviewed monthly.

How to tell it (STAR)

**S:** At [company] our orders API's Application Insights bill tripled to about [A$12,000] a month, and at the same time p95 latency went from [120] to [310] ms. **T:** I was asked to bring the cost down quickly without losing the telemetry we relied on for incidents, and to explain the latency. **A:** I used KQL on billed size by table, category and template and found most of it was EF Core SQL logging and Debug lines, which started the day someone set a Debug override in the portal. A dotnet-trace capture showed request threads waiting on the console logger at that volume, and a duplicate Serilog sink doubling traces. I removed the override straight away, then cleaned up the duplicate pipeline, probe noise and sampling, and added an ingestion anomaly alert and an expiry rule for verbose logging. **R:** Ingestion fell by [about 75%], the bill dropped to around [A$3,100], p95 went back to [120] ms, and the alert has since caught [two] forgotten overrides within a day.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me