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.
Service defaults is a shared class library that each service calls with builder.AddServiceDefaults(). It is code you own, generated by the template:
HttpClient and runtime instrumentation, exported over OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set.self check; MapDefaultEndpoints() maps /health (readiness) and /alive (liveness), only in Development by default.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.
"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,
ConfigureOpenTelemetryturns on OpenTelemetry logging, tracing with ASP.NET Core andHttpClientinstrumentation, and metrics including runtime metrics, and adds the OTLP exporter only ifOTEL_EXPORTER_OTLP_ENDPOINTis set, which the AppHost does for the dashboard. Second,AddDefaultHealthChecksregisters aselfcheck taggedlive, andMapDefaultEndpointsmaps/healthfor all checks and/alivefor just the live ones, which line up with readiness and liveness probes. Third and fourth,ConfigureHttpClientDefaultsadds service discovery andAddStandardResilienceHandlerto everyHttpClient, 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
/healthpublicly. 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."
| 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 |
| 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 |
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.
Checks that the candidate knows exactly what service defaults configure and has the judgement to adjust them for production.
Green flags
/health vs /alive and maps them to readiness and liveness.Red flags
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.
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(); })
.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.
/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.
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
Retry.DisableForUnsafeHttpMethods() or an idempotency key the server deduplicates on.Override per client with AddStandardResilienceHandler(o => ...) or RemoveAllResilienceHandlers() plus a custom pipeline.
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.
Extensions.cs in a new Aspire solution and list everything it registers.OTEL_EXPORTER_OTLP_ENDPOINT and confirm the exporter is only added when set.ActivitySource("Orders.Pricing"), start a span, and confirm it only appears in the dashboard after AddSource("Orders.*").ready and verify it affects /health but not /alive.DisableForUnsafeHttpMethods().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;
}
}
/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./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.DisableForUnsafeHttpMethods() or idempotency keys.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.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 |
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:
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.
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.
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.
Last updated 23 Nov 2026.