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

📚 Interview question

How does a service find the address of another service it needs to call? Explain service discovery with DNS, Kubernetes Services, and .NET's Microsoft.Extensions.ServiceDiscovery (as used by Aspire), compare client-side and server-side discovery, and tell me what breaks when discovery goes wrong.

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.

Mid-Level Theory Intermediate aspire distributed-systems dns kubernetes microservices service-discovery

🎯 Key points

  • Instances come and go, so callers resolve a logical name instead of a fixed IP
  • Server-side discovery: caller hits a stable address (Kubernetes ClusterIP Service, load balancer) that routes to healthy instances
  • Client-side discovery: the client gets a list of endpoints and load-balances itself (gRPC round_robin, multiple endpoints in Microsoft.Extensions.ServiceDiscovery)
  • Kubernetes: Service name resolves via cluster DNS (orders.default.svc.cluster.local) to a virtual IP; readiness probes control membership
  • Microsoft.Extensions.ServiceDiscovery is a general .NET library (Aspire uses it but doesn't require it): AddServiceDiscovery, URIs like https+http://catalog, endpoints from configuration or DNS SRV, composes with the HttpClient resilience handler
  • Long-lived connections (HTTP/2, gRPC) pin to one pod behind a ClusterIP; use headless Services with client load balancing or a mesh
  • Stale addresses: OS resolver and DNS TTL caching plus pooled connections; set SocketsHttpHandler.PooledConnectionLifetime
  • Monitor discovery: per-instance request spread, endpoint counts and readiness changes

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 as catalog.shop.svc.cluster.local and 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.ServiceDiscovery is the library Aspire uses. I call AddServiceDiscovery(), add it to my HttpClient, and use a URI like https+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, HttpClient pools connections, so without PooledConnectionLifetime a 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."


Client-side vs server-side

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

Discovery mechanisms

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

Failure modes

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

Production example

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.

🔍 What the interviewer is checking

Checks practical understanding of how services find each other and the failure modes in Kubernetes and .NET.

Green flags

  • Distinguishes client-side and server-side discovery with examples
  • Explains ClusterIP per-connection balancing and the gRPC pinning problem
  • Knows Microsoft.Extensions.ServiceDiscovery / Aspire naming
  • Mentions PooledConnectionLifetime and readiness probes

Red flags

  • Hard-coded URLs per environment
  • Creates HttpClient per request
  • Thinks DNS alone guarantees even load

📚 Learn in depth

1. Why discovery exists

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.

2. Kubernetes server-side discovery

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.

3. Client-side 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.

4. Microsoft.Extensions.ServiceDiscovery

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.
  • URI schemes: 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.
  • Aspire's AppHost injects the configuration entries for each referenced project, so local runs and deployed runs use the same names.

5. DNS caching and pooled connections

.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.

6. Service meshes

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.

Try it yourself

  1. In a kind or AKS cluster, deploy 3 replicas behind a ClusterIP and call it from a gRPC client in a loop; log the pod name in each reply. Then switch to a headless Service with round_robin.
  2. Create an Aspire AppHost with two projects and inspect the injected services__catalog__https__0 environment variable.
  3. Change a DNS record while a client with and without PooledConnectionLifetime is running; observe which one follows.
  4. Break the readiness probe and watch the pod disappear from kubectl get endpointslices.

💻 Code

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" ] }
  }
}

⚠ Common mistakes

  • Mistake: Hard-coding hostnames or localhost ports per environment. Why it is wrong: breaks on every move and drifts between environments. Instead: logical names resolved by discovery.
  • Mistake: New HttpClient per request to pick up DNS changes. Why it is wrong: socket exhaustion under load. Instead: IHttpClientFactory or PooledConnectionLifetime.
  • Mistake: gRPC through a ClusterIP Service and expecting even load. Why it is wrong: one HTTP/2 connection pins to one pod. Instead: headless Service with client balancing, or an L7 proxy or mesh.
  • Mistake: Readiness probe that returns 200 before warm-up or after shutdown starts. Why it is wrong: traffic arrives at pods that can't serve it. Instead: honest readiness, graceful shutdown and draining.
  • Mistake: Making readiness depend on every downstream service. Why it is wrong: one dependency outage removes all pods from discovery. Instead: readiness checks only what this instance needs to serve.
  • Mistake: Allowing https+http in production. Why it is wrong: silent fallback to plain HTTP. Instead: AllowedSchemes = ["https"] outside development.
  • Mistake: Not monitoring discovery itself. Why it is wrong: uneven load, flapping readiness or a shrinking endpoint list show up only as vague latency. Instead: dashboards for per-pod request rate and CPU skew, ready endpoint counts (EndpointSlices) and readiness transitions, with an alert on skew.
  • Mistake: Using the same discovery path for external callers and internal services. Why it is wrong: internal names and endpoints leak, and you lose edge controls. Instead: external traffic through ingress or an API gateway (WAF, auth, rate limits); internal traffic through cluster DNS or the mesh.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions load balancers or gRPC pinning Why: Checks L4 vs L7 balancing and why gRPC can land on one pod.
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

  2. When: Candidate mentions DNS or stale addresses Why: Checks they can diagnose DNS incidents in Kubernetes.
    How to answer

    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:

    • Stale endpoint after failover: DNS changed, but HttpClient kept pooled connections to the old IP. Fix with PooledConnectionLifetime.
    • Slow or failing lookups in Kubernetes: ndots:5 makes each external name try several search domains first, and UDP conntrack races cause occasional 5-second delays.
    • Split-horizon / private endpoints: the name resolves to a public IP from one network and a private IP from another.

    Diagnose with dig/nslookup from the same pod, check TTLs, and look at the DNS phase of the HTTP timing.

  3. When: Candidate mentions readiness probes controlling discovery Why: Checks they avoid cascading removal of all pods when a dependency fails.
    How to answer

    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.

    • Check local prerequisites; handle dependency failures in the request path with timeouts, circuit breakers and fallbacks.
    • Exceptions: a dependency that belongs to this instance only (a sidecar, a per-pod cache warm-up), or a prerequisite without which the instance can serve nothing at all and the failure is instance-specific.
    • Liveness is narrower still: only a stuck process.

    The trade-off is against the SLO: serving degraded responses usually costs less error budget than having zero ready pods.

🛠 Real-world problems: how you handle them

gRPC traffic pinned to one pod behind a ClusterIP Service
Situation
A [pricing] gRPC service on [6] AKS pods served checkout at [~2,000] requests/second at peak during a [sale event].
Signals
One pod at ~85% CPU and the rest under 10%; p99 latency ~900 ms at peak; HPA didn't help because average CPU stayed low; timeouts in checkout logs.
Investigation
Per-pod request rate in Prometheus/Grafana and Application Insights showed one pod taking nearly all calls; `kubectl get svc` confirmed a ClusterIP Service; reviewed the client: one long-lived `GrpcChannel` multiplexing all calls over one HTTP/2 connection.
Resolution
Immediate: restarted the client pods to redistribute connections and scaled out. Real fix: a headless Service and `RoundRobinConfig` in `Grpc.Net.Client` with a `dns:///` address, so each call is balanced across all pod IPs.
Prevention
A dashboard alert on per-pod request-rate skew; a checklist item for any new gRPC dependency; a load test in the pipeline that verifies distribution across replicas.

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.

↩ Usually asked after

More in Microservices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me