Service discovery for .NET services: DNS, Kubernetes Services and kube-proxy, Microsoft.Extensions.ServiceDiscovery and Aspire, client-side vs server-side discovery, and failure modes such as stale DNS and uneven load.
Instances move, scale and restart, so callers use a logical name and a discovery mechanism maps it to healthy addresses. In server-side discovery the caller hits a stable address, such as a Kubernetes Service (cluster DNS → virtual IP → kube-proxy picks a ready pod) or a load balancer. In client-side discovery the client gets the list of endpoints and balances itself, as gRPC and Microsoft.Extensions.ServiceDiscovery (used by Aspire, URIs like https+http://catalog) can. Common failures: stale DNS in pooled connections, readiness probes that lie, and HTTP/2 or gRPC connections pinned to one pod. The trade-off: server-side is simpler for clients; client-side gives smarter balancing at the cost of logic in every client.
"In a distributed system the address of a service isn't fixed: pods restart with new IPs, autoscaling adds instances, deployments replace them. So callers use a logical name like
catalog, and service discovery turns that into healthy endpoints. There are two shapes. In server-side discovery the caller talks to one stable address and something in the middle routes: in Kubernetes a Service gets a DNS name such ascatalog.shop.svc.cluster.localand a virtual IP, and kube-proxy spreads connections over pods whose readiness probe passes. In client-side discovery the client gets the list of endpoints and picks one itself, which is what gRPC's client-side load balancing does with a headless Service.In .NET,
Microsoft.Extensions.ServiceDiscoveryis the library Aspire uses. I callAddServiceDiscovery(), add it to myHttpClient, and use a URI likehttps+http://catalog. Locally Aspire injects the endpoints as configuration, and in Kubernetes the same name resolves through DNS, so my code doesn't change between environments.The mistake I see is assuming discovery is solved once DNS works. Two things bite. First,
HttpClientpools connections, so withoutPooledConnectionLifetimea client keeps talking to an old IP after a failover. Second, HTTP/2 and gRPC multiplex everything over one long-lived connection, so behind a ClusterIP Service all traffic from a client lands on one pod and the others sit idle. Discovery isn't just finding an address; it's keeping traffic on healthy, evenly loaded instances."
| Server-side | Client-side | |
|---|---|---|
| How | Stable VIP/load balancer routes | Client gets endpoint list, chooses |
| Examples | Kubernetes ClusterIP Service, Azure Container Apps ingress, Azure Load Balancer, API gateway | gRPC with dns:/// and headless Service, Microsoft.Extensions.ServiceDiscovery with multiple endpoints |
| Client complexity | Low | Higher (resolver, balancing, health) |
| Balancing quality | Per connection (L4) or per request (L7) | Per request, can be latency-aware |
| Extra hop | Sometimes (L7 proxy) | No |
| Mechanism | What it resolves | Notes |
|---|---|---|
| DNS A/AAAA | Name → IP(s) | Simple; TTLs and client caching delay changes |
| DNS SRV | Name → host + port | Supported by Microsoft.Extensions.ServiceDiscovery's DNS SRV provider |
| Kubernetes Service (ClusterIP) | Name → virtual IP | kube-proxy balances per connection |
Headless Service (clusterIP: None) |
Name → all pod IPs | For client-side balancing |
| Configuration | Services:catalog:https:0 |
Aspire injects this locally |
| Service mesh (Istio, Linkerd) | Sidecar handles routing | Per-request L7 balancing, mTLS, retries |
| Symptom | Cause | Fix |
|---|---|---|
| Calls go to a dead IP after failover | Pooled connection never re-resolves DNS | PooledConnectionLifetime = 2–5 min (IHttpClientFactory handlers rotate too) |
| One pod at 90% CPU, others idle | HTTP/2/gRPC pinned to one pod behind ClusterIP | Headless Service + client balancing, or a mesh / L7 proxy |
| Errors right after deploy | Pod in Service before it's ready | Correct readiness probe, graceful shutdown with connection draining |
| Works locally, fails in cluster | Hard-coded localhost URLs | Logical names + discovery in every environment |
A gRPC pricing service on [6] pods showed one pod at ~85% CPU and five under 10%, with p99 latency of ~900 ms at peak. Switching to a headless Service with round_robin client-side balancing in Grpc.Net.Client spread load evenly and brought p99 to ~120 ms without adding pods.
Checks practical understanding of how services find each other and the failure modes in Kubernetes and .NET.
Green flags
Red flags
In the cloud, instances are cattle: an AKS node is drained, a pod is rescheduled with a new IP, autoscaling adds three replicas. Hard-coding addresses fails within days. Discovery is the indirection between who you want (a logical service) and where it currently runs.
Orders pod CoreDNS kube-proxy (iptables/IPVS)
| GET http://catalog/... | |
|-- resolve catalog ------>| |
|<-- 10.0.12.7 (ClusterIP)-| |
|-- TCP connect 10.0.12.7 ------------------------->| picks a READY pod
| |--> catalog-pod-2 (10.244.1.9)
The ClusterIP is virtual. Balancing happens when the TCP connection is made. Every request on that connection then goes to the same pod. With HTTP/1.1 and a connection pool that's fine; with one HTTP/2 connection it means one pod.
Endpoints (EndpointSlices) only include pods whose readiness probe passes, so the readiness probe is part of discovery.
Orders (gRPC client, round_robin)
| resolve dns:///catalog-headless -> [10.244.1.9, 10.244.2.4, 10.244.3.1]
| subchannel per address, pick per call
|--> pod A |--> pod B |--> pod C
Grpc.Net.Client supports this through GrpcChannelOptions.ServiceConfig with a RoundRobinConfig and a dns:/// address. The resolver refreshes addresses periodically and on connection failure.
A standalone library (no Aspire required) that plugs into IHttpClientFactory and YARP:
builder.Services.AddServiceDiscovery() registers resolvers: configuration (Services:catalog:https:0) by default, DNS and DNS SRV providers optionally.https+http://catalog means prefer HTTPS endpoints, fall back to HTTP only if none exist. https://_grpc.catalog selects a named endpoint.ServiceDiscoveryOptions.AllowedSchemes can restrict production to HTTPS..NET doesn't cache DNS itself beyond the OS, but SocketsHttpHandler keeps connections open indefinitely by default, so a changed DNS record is never seen on an existing connection. Set PooledConnectionLifetime (or rely on IHttpClientFactory handler rotation, default 2 minutes). Don't create a new HttpClient per request to "fix" this: that causes socket exhaustion.
Istio or Linkerd put a proxy beside each pod. Discovery, per-request balancing, retries and mTLS move out of the app. Cost: extra latency per hop (typically sub-millisecond to a few ms), memory per sidecar, and operational complexity. Azure Container Apps gives built-in discovery by app name without running a mesh yourself.
services__catalog__https__0 environment variable.PooledConnectionLifetime is running; observe which one follows.kubectl get endpointslices.Discovery for HTTP with Microsoft.Extensions.ServiceDiscovery, and client-side balancing for gRPC.
// Program.cs (Orders service)
using Microsoft.Extensions.ServiceDiscovery;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddServiceDiscovery();
builder.Services.Configure<ServiceDiscoveryOptions>(o =>
{
// In production, refuse to fall back to plain HTTP.
if (!builder.Environment.IsDevelopment()) o.AllowedSchemes = ["https"];
});
builder.Services.ConfigureHttpClientDefaults(http =>
{
http.AddServiceDiscovery(); // resolves logical names in BaseAddress
http.AddStandardResilienceHandler(); // timeouts, retries, circuit breaker
});
// Logical name, same in every environment. Endpoints come from config (Aspire) or DNS.
builder.Services.AddHttpClient<CatalogClient>(c => c.BaseAddress = new Uri("https+http://catalog"));
var app = builder.Build();
app.Run();
public sealed class CatalogClient(HttpClient http)
{
public Task<ProductDto?> GetAsync(Guid id, CancellationToken ct) =>
http.GetFromJsonAsync<ProductDto>($"/products/{id}", ct);
}
public sealed record ProductDto(Guid Id, string Name, decimal Price);
// gRPC client-side load balancing against a Kubernetes headless Service.
using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Net.Client.Configuration;
var channel = GrpcChannel.ForAddress("dns:///pricing-headless.shop.svc.cluster.local:8080", new GrpcChannelOptions
{
Credentials = ChannelCredentials.Insecure, // TLS terminated by the mesh in this example
ServiceConfig = new ServiceConfig { LoadBalancingConfigs = { new RoundRobinConfig() } }
});
// appsettings.Development.json: what Aspire injects for you, written by hand.
{
"Services": {
"catalog": { "https": [ "https://localhost:7101" ] }
}
}
localhost ports per environment. Why it is wrong: breaks on every move and drifts between environments. Instead: logical names resolved by discovery.HttpClient per request to pick up DNS changes. Why it is wrong: socket exhaustion under load. Instead: IHttpClientFactory or PooledConnectionLifetime.https+http in production. Why it is wrong: silent fallback to plain HTTP. Instead: AllowedSchemes = ["https"] outside development.Most teams on Kubernetes or Azure Container Apps should use the platform's server-side discovery and only add client-side balancing where long-lived connections need it. A mesh is worth it when you need mTLS, per-request routing and traffic shifting across many services, not for discovery alone.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Platform DNS + ClusterIP / Container Apps | HTTP/1.1 and pooled connections, most services | Per-connection balancing only | Heavy gRPC/HTTP/2 traffic |
| Client-side (gRPC round_robin, ServiceDiscovery) | gRPC, latency-sensitive calls | Logic and config in each client | Many languages to support |
| Service mesh | Dozens of services, mTLS, canary routing | Sidecar latency, memory, ops skills | Small estate, no platform team |
Measure per-pod request rate and CPU spread; uneven distribution is the tell-tale sign of a discovery or balancing problem.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
DNS maps names to records: A (IPv4), AAAA (IPv6), CNAME (alias), plus MX, TXT, SRV, NS and PTR. A client asks a recursive resolver, which walks root → TLD → authoritative servers and caches the answer for its TTL. .NET uses the OS resolver (getaddrinfo) and does not cache itself.
Typical incidents:
HttpClient kept pooled connections to the old IP. Fix with PooledConnectionLifetime.ndots:5 makes each external name try several search domains first, and UDP conntrack races cause occasional 5-second delays.Diagnose with dig/nslookup from the same pod, check TTLs, and look at the DNS phase of the HTTP timing.
Mostly no. Readiness should say whether this instance can serve traffic: started, warmed up, not shutting down. If it checks a shared database or another service, one dependency outage marks every pod unready, discovery removes them all, and a partial outage (some endpoints still worked, cached reads still worked) becomes a total one.
The trade-off is against the SLO: serving degraded responses usually costs less error budget than having zero ready pods.
How to tell it (STAR)
**S:** At [company], our [pricing] gRPC service ran on [six] pods, but during a [sale] checkout timed out while the cluster looked mostly idle. **T:** I was on call and needed to restore checkout and find the cause. **A:** I compared per-pod request rates and saw one pod taking almost all the traffic. The client used one HTTP/2 channel through a ClusterIP Service, so kube-proxy had balanced once, at connect time. I restarted the clients to spread connections, then changed the service to headless and turned on round-robin balancing in the gRPC client. **R:** Load spread evenly across all pods and p99 dropped from [~900 ms] to [~120 ms] without adding capacity.
Last updated 23 Nov 2026.