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

📚 Interview question

You run about 30 .NET services on Kubernetes and Azure. Design the logging pipeline: how logs get from the services to storage, where you enrich, filter, sample and mask them, and how you set retention by data class. Where does the OpenTelemetry Collector fit, and what are the failure modes?

Architecture of a multi-service logging pipeline: OTLP from .NET services, OpenTelemetry Collector agent and gateway tiers, enrichment with Kubernetes and resource attributes, filtering and sampling, masking personal data, routing by data class to different backends and retention, back-pressure and failure modes.

Senior Architecture Advanced kubernetes log-management logging-pipeline observability opentelemetry-collector privacy

🎯 Key points

  • Services emit via ILogger + OpenTelemetry over OTLP; no vendor SDKs or sinks in application code
  • Collector as agent (DaemonSet or sidecar) for local buffering and k8s metadata, and as a gateway Deployment for central policy
  • Processor order: memory_limiter first, then enrich (k8sattributes, resourcedetection), filter, transform/redaction, batch last
  • Defence in depth for personal data: redact at source in .NET and mask again in the collector; neither alone is enough
  • Route by data class (operational, security/audit, debug) with the routing connector to different backends and retention
  • Secure the pipeline: workload identity or managed identity for exporters, TLS and authentication on OTLP receivers, no keys in config
  • Failure modes: collector OOM, exporter queue full, backend throttling; use persistent queues, retries and alert on dropped items
  • Monitor the pipeline and its cost per service and per class; keep ids out of labels to control cardinality

⏱ 30-second answer

Services log with ILogger + OpenTelemetry and send OTLP to an OpenTelemetry Collector, never to a vendor directly. I run the Collector as an agent per node for buffering and Kubernetes metadata, and as a gateway for central policy: enrich (service, version, environment, pod), filter noise such as health checks, mask personal data (after masking at source), sample high-volume Information logs, then route by data class: operational logs to Log Analytics with 30 days, audit and security to a cheaper long-retention store, debug to a short-lived tier. I protect it with memory limits, persistent queues and alerts on dropped data. The trade-off: a pipeline gives control and vendor freedom, but it is another production system you must run and monitor.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd make the applications boring and the pipeline smart. Every service uses ILogger with message templates and the OpenTelemetry logging provider, and exports OTLP to a collector on the same node. Application code knows nothing about Log Analytics or Loki. The services also redact obvious personal data at source using Microsoft.Extensions.Compliance.Redaction, because the safest place to remove an email address is before it leaves the process.

The collector runs in two tiers. The agent, a DaemonSet, receives OTLP, adds Kubernetes metadata with the k8sattributes processor, applies a memory limiter and batches. The gateway, a scaled Deployment, is where central policy lives: drop health-check and readiness noise, a transform or redaction processor as a second line of defence for personal data, probabilistic sampling of high-volume Information logs, and the routing connector that sends each record to a pipeline by data class. Operational logs go to Log Analytics in Australia East on the Analytics plan with 30 days; audit and security events go to a separate workspace or storage with a year or more; verbose logs go to a Basic table or are dropped. For example, at [company] we [moved from Serilog sinks in each service to a gateway collector, which let us mask a leaked field across all services in one change instead of 30 releases].

The mistake I see is building the pipeline and never monitoring it, so when the backend throttles, the collector silently drops logs during the very incident you need them for. A logging pipeline is production infrastructure: it needs its own SLO, its own dashboards and its own alerts."


Architecture

Layer Responsibility Technology
Service Structured logs, trace context, redaction at source ILogger, OpenTelemetry, Microsoft.Extensions.Compliance.Redaction
Agent collector Receive, add k8s metadata, buffer, batch Collector DaemonSet (or Container Apps managed OpenTelemetry agent)
Gateway collector Filter, mask, sample, route, export Collector Deployment, HPA
Backends Store and query by class Log Analytics, storage/ADX for audit, Loki or Elastic if used

Retention by data class

Class Examples Destination Retention
Operational Requests, errors, warnings Log Analytics, Analytics plan 30 days interactive
Verbose Debug, container stdout noise Basic table or dropped 7-30 days
Security / audit Logins, permission changes, admin actions Separate workspace (or SIEM), restricted RBAC 1-7 years per policy
Business events Order placed, refund issued Event store or warehouse, not logs Per business need

Production example

After centralising policy in a gateway collector for [30] services, we dropped [35%] of volume (health checks and duplicate framework logs), masked email addresses that had leaked from [two] services within an hour of discovery, and kept audit logs for [two] years at storage prices. The pipeline itself was alerted on otelcol_exporter_send_failed_log_records and queue size.

🔍 What the interviewer is checking

Checks whether the candidate can design observability infrastructure for many services with privacy, cost and reliability in mind.

Green flags

  • OTLP from services, policy in a collector, agent and gateway tiers.
  • Knows processor order and the memory limiter.
  • Masks at source and in the pipeline.
  • Routes by data class with different retention.
  • Monitors the pipeline itself and plans for back-pressure.

Red flags

  • Vendor SDKs hard-coded in every service.
  • Samples or drops audit logs.
  • No idea what happens when the backend is down.

📚 Learn in depth

1. The path of a log record

[.NET service]
 ILogger -> OTel LoggerProvider -> BatchLogRecordProcessor -> OTLP/gRPC :4317
                                                              |
[Node]                                                        v
 Agent collector: otlp receiver -> memory_limiter -> k8sattributes -> batch -> otlp exporter
                                                              |
[Gateway]                                                     v
 otlp receiver -> memory_limiter -> filter -> transform/redaction -> probabilistic_sampler
               -> routing connector --+--> logs/ops   -> batch -> azuremonitor (Analytics)
                                      +--> logs/audit -> batch -> azuremonitor (audit workspace)
                                      +--> logs/debug -> batch -> otlphttp (cheap store) or drop

2. Why two tiers

  • The agent is close to the workload: cheap local hop, adds pod, namespace and node metadata, and absorbs short backend blips.
  • The gateway centralises policy, holds credentials to backends (with workload identity, not keys), and scales independently.
  • For tail sampling of traces you need all spans of a trace on one gateway instance, which is what the load-balancing exporter is for; logs usually don't need that, but they share the infrastructure.

3. Processor order matters

  1. memory_limiter first, so an overload is refused early rather than crashing the collector.
  2. Enrichment (k8sattributes, resourcedetection) before filters that depend on those attributes.
  3. Filtering before masking and sampling, so you don't spend CPU on records you will drop.
  4. batch last before the exporter.

4. Masking: defence in depth

At source, .NET's redaction framework classifies properties (for example a [PersonalData] attribute you define) and redacts them in [LoggerMessage] logs. In the collector, the transform processor (OTTL replace_pattern) and the redaction processor catch what slipped through, such as emails in exception messages. Masking in the collector alone is too late for anything logged to stdout and scraped elsewhere.

Under the Privacy Act 1988, logs with personal information must be protected (APP 11) and destroyed when no longer needed; a leaked log store can be an eligible data breach under the Notifiable Data Breaches scheme. Retention by class is how you meet that without losing audit trails.

5. Failure modes and back-pressure

Failure Symptom Mitigation
Backend throttling (HTTP 429) Exporter retries, queue grows sending_queue with persistent storage (file_storage extension), retry with backoff
Collector out of memory Pod restarts, data loss memory_limiter, resource limits, HPA on CPU/memory
Gateway down Agents buffer, then drop Multiple replicas, PodDisruptionBudget
Bad config deploy All logs stop Config validated in CI (otelcol validate), canary rollout
App exporter queue full BatchLogRecordProcessor drops records Size the queue, alert on drops

The collector exposes its own metrics (otelcol_receiver_refused_log_records, otelcol_exporter_send_failed_log_records, otelcol_exporter_queue_size). Scrape them and alert.

6. Azure options

On AKS you can run the collector yourself; Azure Container Apps offers a managed OpenTelemetry agent that exports to Application Insights or OTLP endpoints. Data Collection Rules with transformations in Azure Monitor can also filter and reshape data at ingestion, which is useful when you can't run a collector.

Try it yourself

  1. Run the collector-contrib image locally with the config below and send logs from an ASP.NET Core app.
  2. Log an email address and confirm the transform processor masks it.
  3. Stop the backend and watch otelcol_exporter_queue_size grow; then enable file_storage and restart the collector.
  4. Add the routing connector and send records with data.class = audit to a separate exporter.

💻 Code

Service side: OTLP export, resource attributes and redaction at source.

// Program.cs (.NET 10)
using Microsoft.Extensions.Compliance.Classification;
using Microsoft.Extensions.Compliance.Redaction;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService("orders-api", serviceVersion: "1.8.2")
        .AddAttributes([new("deployment.environment.name", builder.Environment.EnvironmentName)]))
    .WithLogging(l => l.AddOtlpExporter()); // to the node-local collector

// Redact classified data before it leaves the process.
builder.Logging.EnableRedaction();
builder.Services.AddRedaction(r =>
    r.SetRedactor<ErasingRedactor>(new DataClassificationSet(DataTaxonomy.PersonalData)));

var app = builder.Build();
app.Run();

public static class DataTaxonomy
{
    public static DataClassification PersonalData { get; } = new("Orders", "PersonalData");
}

public sealed class PersonalDataAttribute() : DataClassificationAttribute(DataTaxonomy.PersonalData);

public static partial class OrderLog
{
    [LoggerMessage(Level = LogLevel.Information, Message = "Order {OrderId} placed by {Email}")]
    public static partial void OrderPlaced(this ILogger logger, Guid orderId, [PersonalData] string email);
}

Gateway collector: filter, mask, sample and route by data class.

receivers:
  otlp:
    protocols: { grpc: { endpoint: 0.0.0.0:4317 } }
extensions:
  file_storage: { directory: /var/lib/otelcol/queue }
processors:
  memory_limiter: { check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 20 }
  filter/noise:
    error_mode: ignore
    logs:
      log_record:
        - 'attributes["url.path"] == "/healthz"'
  transform/mask:
    log_statements:
      - context: log
        statements:
          - replace_pattern(body, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", "***@***")
  probabilistic_sampler/info: { sampling_percentage: 20 }
  batch: {}
connectors:
  routing:
    default_pipelines: [logs/ops]
    table:
      - context: log
        condition: attributes["data.class"] == "audit"
        pipelines: [logs/audit]
exporters:
  azuremonitor/ops:   { connection_string: "${env:APPINSIGHTS_OPS}",   sending_queue: { storage: file_storage } }
  azuremonitor/audit: { connection_string: "${env:APPINSIGHTS_AUDIT}", sending_queue: { storage: file_storage } }
service:
  extensions: [file_storage]
  pipelines:
    logs/in:    { receivers: [otlp], processors: [memory_limiter, filter/noise, transform/mask], exporters: [routing] }
    logs/ops:   { receivers: [routing], processors: [batch], exporters: [azuremonitor/ops] }
    logs/audit: { receivers: [routing], processors: [batch], exporters: [azuremonitor/audit] }

In practice the probabilistic sampler would sit on a separate pipeline for Information-level operational logs only, so audit events are never sampled.

⚠ Common mistakes

  • Mistake: Each service writes directly to the backend with its own sink. Why it is wrong: Changing masking, routing or vendor needs a release of every service. Instead: Export OTLP to a collector and put policy there.
  • Mistake: Masking only in the collector. Why it is wrong: Data already left the process and may be in stdout, crash dumps or another scraper. Instead: Redact at source and use the collector as a second line.
  • Mistake: Sampling audit or security logs. Why it is wrong: You lose the records you are legally or contractually required to keep. Instead: Route audit logs to their own unsampled pipeline.
  • Mistake: No memory limiter or persistent queue. Why it is wrong: A backend outage crashes the collector or drops everything during the incident. Instead: Put memory_limiter first and use file_storage-backed sending queues.
  • Mistake: Not monitoring the pipeline. Why it is wrong: Silent drops are discovered when someone needs the logs. Instead: Scrape collector metrics and alert on refused, failed and queued records.
  • Mistake: One retention period for every log. Why it is wrong: It is either too expensive or too short for audit, and keeps personal data longer than needed. Instead: Classify data and set retention per class.
  • Mistake: High-cardinality values as resource attributes or labels. Why it is wrong: Some backends (Loki, Prometheus-style stores) index them and degrade. Instead: Keep ids as log attributes, not labels.

🏛 Senior insight: trade-offs

The pipeline is where a senior encodes policy once instead of 30 times: what is noise, what is personal data, what must be kept and where. The cost is operating another critical system, so it needs ownership, configuration in Git with CI validation, and its own monitoring.

Option When it fits Cost When not to
Direct export (distro to Application Insights) Few services, one backend, small team Lowest operational cost Many teams, multiple backends, central masking needs
Agent-only collector Need k8s metadata and buffering DaemonSet resources Central policy across clusters
Agent + gateway Many services, routing by class, vendor freedom Gateway replicas and ownership Small estates
Azure Monitor DCR transformations Can't run a collector, Azure-only Per-GB processing for some tables Multi-cloud or complex routing

Security is part of the design, not an add-on: the gateway holds the only credentials to the backends, so it authenticates with AKS workload identity (a federated managed identity) rather than connection strings or keys in a ConfigMap, the OTLP receivers accept traffic only from inside the cluster (network policy, TLS, and an authenticator extension if exposed), and the audit workspace has its own restricted RBAC.

Cost needs the same systematic treatment: I tag every record with service.name and data class, publish GB per day per service and per class from the collector's metrics and the backend's usage table, and give each team a budget with an alert. Without that, one noisy service quietly pays for itself out of everyone's budget. I measure the pipeline with its own SLO, for example 99.9% of records delivered within 2 minutes, using collector metrics.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the OpenTelemetry SDK or the Azure Monitor distro Why: Checks OpenTelemetry set-up and sampling on the service side
    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.

  2. When: Candidate mentions masking personal data or the Privacy Act Why: Checks redaction and privacy obligations in depth
    How to answer

    Treat logs as a data store that attackers and too many staff can read. Never log secrets (passwords, tokens, Authorization headers, connection strings, card numbers) and keep personal information out: log identifiers like CustomerId, not names, emails or request bodies.

    Enforce it in code rather than by memory: Microsoft.Extensions.Compliance.Redaction lets you classify fields with attributes, map classifications to redactors (erase, or HMAC for a stable pseudonym) with AddRedaction, and apply them to logs with EnableRedaction. Use header allowlists in HTTP logging.

    In Australia, APP 11 requires reasonable steps to protect personal information and APP 11.2 requires destroying or de-identifying it when no longer needed, so retention matters, and a leaked log store can be a notifiable data breach. The trade-off: less detail in logs versus a smaller breach surface.

  3. When: Candidate mentions log floods or sampling Why: Checks volume control before the pipeline
    How to answer

    I treat log levels as a contract the whole team follows:

    • Information: business events and request outcomes worth keeping. Warning: handled but unexpected (a retry, a fallback). Error: an operation failed and someone may need to act. Critical: the service cannot function.
    • Debug/Trace are off in production by default (volume, CPU and payloads with personal data), but can be switched on temporarily for one category at runtime when troubleshooting.
    • Defaults: Information for our namespaces, Warning for Microsoft.*, set per category in configuration.

    To debug live, I change levels through reloadable configuration or Azure App Configuration, time-boxed and reverted. To prevent floods I use sampling or per-request buffering, log exceptions once, and alert on ingestion volume. The trade-off is detail when you need it versus cost, overhead and privacy risk all the time.

🛠 Real-world problems: how you handle them

Email addresses leaked into logs from two services
Situation
[30] .NET services on [AKS] in Australia East sending logs to Log Analytics; a security review found customer email addresses in AppTraces from [two] services.
Signals
A [quarterly privacy review] KQL query matching an email regex returned [~120,000] rows over [three] weeks; the security team raised a Privacy Act concern.
Investigation
KQL on AppTraces grouped by AppRoleName and the message template found the offending log calls (an exception message containing the request body and a debug log left at Information). Checked who had workspace access and whether data had been exported.
Resolution
Immediate: added a transform/mask rule in the gateway collector, rolled out in [an hour] for all services, and purged the affected rows with the Log Analytics purge API. Long-term: fixed the two log calls, introduced the .NET redaction framework with a PersonalData classification, and split audit logs into a restricted workspace.
Prevention
A scheduled KQL alert for personal-data patterns, a code review checklist item, an analyser rule against logging request bodies, and an ADR defining data classes and retention. Assessed against the Notifiable Data Breaches scheme with the privacy officer.

How to tell it (STAR)

**S:** A review found customer email addresses in our logs from [two] of our [30] services. **T:** I had to stop the leak, clean up and make it structurally hard to repeat. **A:** Because all services sent logs through our gateway collector, I added a masking rule there and it covered every service within [an hour]. We purged the affected data, fixed the log calls, added redaction at source with data classifications, and moved audit logs to a restricted workspace. **R:** The pattern alert has found [zero] new leaks in [six] months, and the privacy officer concluded [it was not a notifiable breach] because access was limited.

↩ Usually asked after

More in Log Management

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me