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

📚 Interview question

What do Aspire service defaults give you? Walk through AddServiceDefaults and MapDefaultEndpoints: the OpenTelemetry, health check, service discovery and HTTP resilience set-up, and what you would change before production.

The Aspire ServiceDefaults project: ConfigureOpenTelemetry with OTLP export, default health checks and the /health and /alive endpoints, service discovery, the standard resilience handler, and production hardening.

Intermediate Theory Intermediate cloud-native dotnet-aspire health-checks opentelemetry resilience service-defaults

🎯 Key points

  • ServiceDefaults is a normal class library you own (IsAspireSharedProject), not a black-box package; each service calls builder.AddServiceDefaults()
  • ConfigureOpenTelemetry adds logging, ASP.NET Core, HttpClient and runtime instrumentation and exports over OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set
  • AddDefaultHealthChecks registers a 'self' check tagged live; MapDefaultEndpoints maps /health (all checks) and /alive (live-tagged)
  • The template only maps the health endpoints in Development, because exposing them publicly leaks information; production needs a deliberate choice
  • ConfigureHttpClientDefaults adds AddStandardResilienceHandler (rate limiter, total timeout, retry, circuit breaker, attempt timeout) and AddServiceDiscovery to every HttpClient
  • Retries on non-idempotent calls can duplicate work: tune or disable per client
  • Before production: health endpoints behind internal ingress or auth, sampling, filtering health-check traces, Azure Monitor exporter if needed, resilience tuned per dependency

⏱ 30-second answer

Service defaults is a shared class library that each service calls with builder.AddServiceDefaults(). It is code you own, generated by the template:

  • OpenTelemetry: logs, traces and metrics with ASP.NET Core, HttpClient and runtime instrumentation, exported over OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set.
  • Health checks: a self check; MapDefaultEndpoints() maps /health (readiness) and /alive (liveness), only in Development by default.
  • Every HttpClient gets service discovery and the standard resilience handler (timeouts, retries, circuit breaker).

It is a starting baseline, not a finished production configuration. Before production each service tunes retries for non-idempotent calls, decides how health endpoints are exposed, registers its own ActivitySource and Meter names, and sets sampling.

🗣 Full answer (senior)

How I would answer this in an interview

"Service defaults is the project the Aspire template creates next to the AppHost. Every service references it and calls builder.AddServiceDefaults() and, for web apps, app.MapDefaultEndpoints(). The key thing is that it's a plain class library in my repo, not a NuGet package, so it's the team's baseline and we're expected to edit it.

It does four things. First, ConfigureOpenTelemetry turns on OpenTelemetry logging, tracing with ASP.NET Core and HttpClient instrumentation, and metrics including runtime metrics, and adds the OTLP exporter only if OTEL_EXPORTER_OTLP_ENDPOINT is set, which the AppHost does for the dashboard. Second, AddDefaultHealthChecks registers a self check tagged live, and MapDefaultEndpoints maps /health for all checks and /alive for just the live ones, which line up with readiness and liveness probes. Third and fourth, ConfigureHttpClientDefaults adds service discovery and AddStandardResilienceHandler to every HttpClient, so every outbound call gets a rate limiter, a total timeout, retries with jittered backoff, a circuit breaker and a per-attempt timeout.

The mistake I see is shipping these defaults unchanged. The template only maps health endpoints in Development, so teams either forget probes in production or expose /health publicly. And the standard handler retries POSTs on transient errors, which can double-charge a payment if the downstream isn't idempotent. Service defaults are a good starting baseline, but each service still has to own the final settings."


What each part configures

Method Adds Production notes
ConfigureOpenTelemetry() Logging with formatted messages and scopes; tracing for ASP.NET Core and HttpClient; metrics for ASP.NET Core, HttpClient, runtime Add sampling; filter /health and /alive from traces; add your own ActivitySource and Meter names
AddOpenTelemetryExporters() OTLP exporter if OTEL_EXPORTER_OTLP_ENDPOINT set; commented-out Azure Monitor option Choose OTLP to a Collector or the Azure Monitor distro
AddDefaultHealthChecks() self check tagged live Add dependency checks to readiness only
MapDefaultEndpoints() /health, /alive Mapped only when IsDevelopment(); decide on exposure
ConfigureHttpClientDefaults AddStandardResilienceHandler(), AddServiceDiscovery() Tune per client; disable retries for non-idempotent calls

Standard resilience handler (Microsoft.Extensions.Http.Resilience)

Order (outer to inner) Strategy Default
1 Rate limiter 1,000 concurrent permits
2 Total request timeout 30 s
3 Retry 3 retries, exponential backoff with jitter, starting at 2 s
4 Circuit breaker Breaks at a 10% failure ratio over 30 s (min. 100 calls), for 5 s
5 Attempt timeout 10 s per attempt

Production example

A team's order API inherited the defaults and started creating duplicate orders under load: the downstream fulfilment POST timed out at 10 s per attempt and was retried while the first attempt was still being processed. They disabled retries for that named client, added an idempotency key, and duplicates went from [around 40 a day] to zero.

🔍 What the interviewer is checking

Checks that the candidate knows exactly what service defaults configure and has the judgement to adjust them for production.

Green flags

  • Names the four areas: OpenTelemetry, health checks, service discovery, resilience.
  • Knows /health vs /alive and maps them to readiness and liveness.
  • Knows endpoints are Development-only by default and why.
  • Flags retries on non-idempotent calls.

Red flags

  • Thinks service defaults is a closed NuGet package.
  • Puts dependency checks on liveness.
  • Has no view on sampling or telemetry cost.

📚 Learn in depth

1. Why a shared project and not a package

The template marks the project with <IsAspireSharedProject>true</IsAspireSharedProject> and puts an Extensions.cs in it. Owning the source means each organisation can encode its own standards (exporters, sampling, extra health checks) without forking a package. The cost is that template improvements in new Aspire versions don't flow in automatically.

2. What happens when a service calls AddServiceDefaults

builder.AddServiceDefaults()
   |
   +-- ConfigureOpenTelemetry()
   |      logging.AddOpenTelemetry(IncludeFormattedMessage, IncludeScopes)
   |      WithMetrics: AspNetCore, HttpClient, Runtime instrumentation
   |      WithTracing: AddSource(appName), AspNetCore (filter health paths), HttpClient
   |      AddOpenTelemetryExporters(): UseOtlpExporter() if OTEL_EXPORTER_OTLP_ENDPOINT
   |
   +-- AddDefaultHealthChecks(): AddCheck("self", Healthy, tags: ["live"])
   |
   +-- Services.AddServiceDiscovery()
   +-- Services.ConfigureHttpClientDefaults(http => {
          http.AddStandardResilienceHandler();
          http.AddServiceDiscovery(); })

3. Activity, ActivitySource and your own spans

.NET doesn't depend on the OpenTelemetry SDK for tracing: the runtime's System.Diagnostics.ActivitySource creates Activity objects, and an Activity is a span (trace id, span id, parent, tags, events, status). ASP.NET Core and HttpClient already create activities; the OpenTelemetry SDK only listens to sources you register with AddSource(...). That is why custom spans silently disappear if the source name isn't registered: StartActivity returns null when nobody listens, which also makes unobserved instrumentation almost free. The same applies to Meter and AddMeter(...) for metrics. In service defaults, register a naming convention (for example AddSource("Orders.*")) so every team's custom spans get exported.

4. Health endpoints and probes

  • /alive runs only checks tagged live: is the process able to serve at all? Liveness probes restart the container when it fails, so it must not depend on the database.
  • /health runs every check: ready to receive traffic? Readiness probes remove the instance from load balancing when it fails.

The template wraps both in if (app.Environment.IsDevelopment()), because unauthenticated health output can reveal dependency names and timings. In production you either map them on a separate internal port, require a host filter, or rely on the platform probing the container directly.

5. HTTP resilience internals and what goes wrong

AddStandardResilienceHandler builds a Polly v8 pipeline as a DelegatingHandler around the primary handler. The retry strategy treats 5xx, 408, 429 and HttpRequestException (and attempt timeouts) as transient. Because the handler wraps every client, including those to non-idempotent endpoints, the failure modes are real:

Attempt 1: POST /fulfilments  --(server processing slowly)-->  attempt timeout at 10 s
Attempt 2: POST /fulfilments  --> 201 Created           (attempt 1 also completes: 201)
Result:    two fulfilments, two warehouse picks, one angry customer
  • Duplicate side effects: a timed-out attempt may still succeed on the server. Fix with Retry.DisableForUnsafeHttpMethods() or an idempotency key the server deduplicates on.
  • Retry storms: three retries across four service hops multiply load up to 4^4 = 256 times on the deepest service during an outage. Retry at one layer only and rely on the circuit breaker.
  • Timeouts that don't fit: a 30 s total timeout is longer than many callers' own budgets, so work continues after the user has given up. Set totals per client from the caller's latency budget.

Override per client with AddStandardResilienceHandler(o => ...) or RemoveAllResilienceHandlers() plus a custom pipeline.

6. OTLP and exporters

OTLP is the vendor-neutral OpenTelemetry protocol (gRPC on 4317 or HTTP on 4318 by convention; the dashboard uses its own ports). In production you usually point OTLP at an OpenTelemetry Collector, or use UseAzureMonitor() from the Azure Monitor distro to send to Application Insights.

Try it yourself

  1. Open Extensions.cs in a new Aspire solution and list everything it registers.
  2. Run the app with and without OTEL_EXPORTER_OTLP_ENDPOINT and confirm the exporter is only added when set.
  3. Create an ActivitySource("Orders.Pricing"), start a span, and confirm it only appears in the dashboard after AddSource("Orders.*").
  4. Add a SQL Server health check tagged ready and verify it affects /health but not /alive.
  5. Point a POST at an endpoint that sleeps 12 s, then returns 201, and count how many records the server creates with and without DisableForUnsafeHttpMethods().

💻 Code

A trimmed ServiceDefaults extension with the production tweaks most teams add.

// ServiceDefaults/Extensions.cs
namespace Microsoft.Extensions.Hosting;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

public static class Extensions
{
    public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
    {
        builder.Logging.AddOpenTelemetry(o => { o.IncludeFormattedMessage = true; o.IncludeScopes = true; });

        builder.Services.AddOpenTelemetry()
            .WithMetrics(m => m.AddAspNetCoreInstrumentation()
                               .AddHttpClientInstrumentation()
                               .AddRuntimeInstrumentation()
                               .AddMeter("Orders.*"))                       // our own meters
            .WithTracing(t => t.AddSource(builder.Environment.ApplicationName)
                               .AddAspNetCoreInstrumentation(o =>
                                   o.Filter = ctx => !ctx.Request.Path.StartsWithSegments("/health")
                                                  && !ctx.Request.Path.StartsWithSegments("/alive"))
                               .AddHttpClientInstrumentation());

        // Only export when an endpoint is configured (the AppHost sets it locally).
        if (!string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]))
            builder.Services.AddOpenTelemetry().UseOtlpExporter();

        builder.Services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

        builder.Services.AddServiceDiscovery();
        builder.Services.ConfigureHttpClientDefaults(http =>
        {
            http.AddStandardResilienceHandler(o => o.Retry.DisableForUnsafeHttpMethods()); // no POST retries by default
            http.AddServiceDiscovery();
        });

        return builder;
    }

    public static WebApplication MapDefaultEndpoints(this WebApplication app)
    {
        // Production: probes reach these on the internal network; RequireHost limits exposure.
        app.MapHealthChecks("/health").RequireHost("*:8081");
        app.MapHealthChecks("/alive", new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") })
           .RequireHost("*:8081");
        return app;
    }
}

⚠ Common mistakes

  • Mistake: Treating service defaults as a package you can't change. Why it is wrong: It's source in your repo designed to be edited; leaving it generic means missing sampling, custom sources and safe retries. Instead: Own it as the team's platform baseline and review changes like any shared code.
  • Mistake: Shipping without health endpoints because they're only mapped in Development. Why it is wrong: Container Apps or Kubernetes probes then hit nothing or fall back to TCP checks that miss real failures. Instead: Map them deliberately for production, on an internal port or with host filtering.
  • Mistake: Exposing /health with detailed output on the public ingress. Why it is wrong: It leaks dependency names and timings and is a cheap DoS target if checks hit the database. Instead: Keep it internal and keep public responses minimal.
  • Mistake: Putting the database check on /alive. Why it is wrong: A database blip makes the orchestrator restart every instance, turning a dependency outage into a full outage. Instead: Dependency checks go on readiness only.
  • Mistake: Leaving retries on for non-idempotent POSTs. Why it is wrong: A timeout followed by a retry can create duplicate orders or payments. Instead: DisableForUnsafeHttpMethods() or idempotency keys.
  • Mistake: Not adding your own ActivitySource and Meter names. Why it is wrong: Custom spans and metrics are created but never exported, so they don't appear anywhere. Instead: Register them with AddSource and AddMeter.
  • Mistake: Tracing health-check requests. Why it is wrong: Probes every few seconds flood traces and cost money in Application Insights. Instead: Filter health paths in the ASP.NET Core instrumentation.

🏛 Senior insight: trade-offs

Service defaults are a platform contract in code. In a larger organisation I'd turn it into an internal package once it stabilises, so twenty services don't each drift with their own copy, but only after the first few services have shaped it.

Setting Template default What I change Why
Health endpoints Development only Internal port or host filter in all environments Probes need them; public doesn't
Retries All methods Disable for unsafe methods; idempotency keys Avoid duplicates
Sampling None (everything) Parent-based ratio, or tail sampling in a Collector Cost at scale
Exporter OTLP if env var set OTLP to Collector, or Azure Monitor distro Vendor choice and filtering
Option When it fits Cost When not to
Copy per repo One or two services Drift over time Many teams and services
Internal NuGet package Many services, stable standards Versioning and release process Early, while still changing weekly

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions /health and /alive Why: Checks ASP.NET Core health check details
    How to answer

    Health checks are a built-in ASP.NET Core feature that lets an orchestrator, load balancer or monitor ask the app "are you OK?" over HTTP. You register checks with builder.Services.AddHealthChecks(), each one an IHealthCheck that returns Healthy, Degraded or Unhealthy, and expose them with app.MapHealthChecks("/health"). By default Healthy and Degraded return 200 and Unhealthy returns 503. Degraded means "still serving, but something non-critical is slow or down" (a cache, an optional feature), so the instance stays in rotation while you get a signal.

    Dependency checks (SQL Server, Redis, Service Bus) come from AddDbContextCheck<T>() or the community AspNetCore.HealthChecks.* packages, each with a short timeout. With tags and a Predicate you expose two endpoints:

    • Liveness: no dependencies, just "the process is responsive".
    • Readiness: "I can serve traffic now", including critical dependencies.

    The trade-off: more checks give more truth but make the endpoint slower and make it easier for a shared dependency to take every instance out at once.

  2. When: Candidate maps endpoints to probes Why: Checks how probe settings cause or prevent outages
    How to answer

    Kubernetes runs three probes per container. A liveness failure makes the kubelet restart the container. A readiness failure removes the pod from the Service's endpoints so it gets no traffic, with no restart. A startup probe disables the other two until it passes, so slow starts aren't killed.

    The timing fields decide speed: the kubelet acts after failureThreshold consecutive failures, roughly periodSeconds × failureThreshold (defaults 10 s × 3), and each attempt fails if it exceeds timeoutSeconds (default 1 s).

    Bad probes cause outages: a database check in liveness restarts every pod during a database blip; a 1-second timeout kills pods that are just busy under load, which pushes more load onto the rest; readiness tied to a shared dependency leaves the Service with zero endpoints. The trade-off is detection speed versus false positives.

  3. When: Candidate mentions custom spans or AddSource Why: Checks Activity and ActivitySource knowledge
    How to answer

    Activity is .NET's span type and ActivitySource is the factory that creates them, the equivalent of an OpenTelemetry Tracer. They live in System.Diagnostics, so libraries can emit spans without referencing OpenTelemetry at all. You call source.StartActivity("name", ActivityKind.Internal) inside a using, add tags (attributes), events and a status, and disposing it records the duration.

    StartActivity returns null when nothing is listening or the sampler drops the span, which is why you write activity?.SetTag(...). The OpenTelemetry SDK only listens to sources registered with AddSource("MyCompany.Orders"). Activity.Current is stored in an AsyncLocal, flows across await, and becomes the parent of the next activity.

    The trade-off: the API is free when tracing is off, but you must name sources consistently or your spans silently go nowhere.

↩ Usually asked after

More in .NET Aspire

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me