惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
MongoDB | Blog
MongoDB | Blog
U
Unit 42
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
L
LINUX DO - 最新话题
博客园_首页
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Privacy & Cybersecurity Law Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
C
Cisco Blogs
博客园 - 【当耐特】
阮一峰的网络日志
阮一峰的网络日志
I
Intezer
罗磊的独立博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
A
About on SuperTechFans
G
GRAHAM CLULEY
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
D
DataBreaches.Net
The Hacker News
The Hacker News
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
I
InfoQ
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 叶小钗
Project Zero
Project Zero

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Service Discovery in Modern .NET Applications and Azure
Hossein Esmati · 2026-06-26 · via DEV Community

Hossein Esmati

This article is part of the Comprehensive Guide to Microservices Architecture in .NET Core, Cloud and Azure series.

Service Discovery in Kubernetes

How Kubernetes DNS Works

Kubernetes automatically creates DNS entries for services, enabling simple name-based discovery. A service named order-service in the production namespace becomes accessible at order-service.production.svc.cluster.local. For services within the same namespace, you can use the short name order-service.

Service Definition:

apiVersion: v1
kind: Service
metadata:
  name: order-service
  namespace: production
  labels:
    app: order-service
    version: v1
spec:
  selector:
    app: order-service
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 8080
  type: ClusterIP

Native Service Discovery in .NET 9

.NET 9 introduces enhanced service discovery capabilities with improved configuration and resilience features.

Basic Configuration:

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add service discovery with .NET 9 enhancements
builder.Services.AddServiceDiscovery();

// Configure HTTP client with service discovery
builder.Services.AddHttpClient<IOrderServiceClient, OrderServiceClient>(client =>
{
    // Use service name - discovery resolves to actual endpoint
    client.BaseAddress = new Uri("http://order-service");
})
.AddServiceDiscovery()
.AddStandardResilienceHandler(); // .NET 9 resilience patterns

var app = builder.Build();

Advanced Configuration with appsettings.json:

{
  "ServiceDiscovery": {
    "Providers": {
      "Kubernetes": {
        "Namespace": "production",
        "RefreshPeriod": "00:01:00"
      }
    },
    "Services": {
      "order-service": {
        "Scheme": "https",
        "EndpointNames": ["http", "https"],
        "HealthCheckPath": "/health"
      },
      "payment-service": {
        "Scheme": "http",
        "AllowAllHosts": false
      }
    },
    "AllowAllHosts": true,
    "AllowedHosts": ["*.svc.cluster.local"]
  }
}

Service-to-Service Communication Patterns

Using Typed HTTP Clients:

public interface IOrderServiceClient
{
    Task<Order> GetOrderAsync(Guid orderId, CancellationToken cancellationToken = default);
    Task<IEnumerable<Order>> GetOrdersByCustomerAsync(Guid customerId, CancellationToken cancellationToken = default);
}

public class OrderServiceClient : IOrderServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<OrderServiceClient> _logger;

    public OrderServiceClient(HttpClient httpClient, ILogger<OrderServiceClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<Order> GetOrderAsync(Guid orderId, CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetFromJsonAsync<Order>(
                $"api/orders/{orderId}", 
                cancellationToken);

            return response ?? throw new OrderNotFoundException(orderId);
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "Failed to retrieve order {OrderId}", orderId);
            throw;
        }
    }

    public async Task<IEnumerable<Order>> GetOrdersByCustomerAsync(
        Guid customerId, 
        CancellationToken cancellationToken = default)
    {
        return await _httpClient.GetFromJsonAsync<IEnumerable<Order>>(
            $"api/orders/customer/{customerId}", 
            cancellationToken) ?? [];
    }
}

Service Registration with Resilience:

builder.Services.AddHttpClient<IOrderServiceClient, OrderServiceClient>(client =>
{
    client.BaseAddress = new Uri("http://order-service");
    client.Timeout = TimeSpan.FromSeconds(30);
})
.AddServiceDiscovery()
.AddStandardResilienceHandler(options =>
{
    // Configure circuit breaker
    options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(10);
    options.CircuitBreaker.FailureRatio = 0.5;
    options.CircuitBreaker.MinimumThroughput = 10;

    // Configure retry policy
    options.Retry.MaxRetryAttempts = 3;
    options.Retry.BackoffType = Polly.DelayBackoffType.Exponential;

    // Configure timeout
    options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(30);
});

Service Discovery in Azure Container Apps

Azure Container Apps provides built-in service discovery within the same environment, eliminating the need for manual endpoint configuration.

Environment Variables Approach

Container App Configuration:

{
  "properties": {
    "environmentId": "/subscriptions/.../containerappsenvironments/production-env",
    "configuration": {
      "ingress": {
        "external": false,
        "targetPort": 8080,
        "transport": "http",
        "allowInsecure": false
      }
    },
    "template": {
      "containers": [{
        "name": "api-service",
        "image": "myregistry.azurecr.io/api-service:latest",
        "env": [{
          "name": "OrderService__Url",
          "value": "https://order-service.internal.<environment-unique-id>.azurecontainerapps.io"
        },
        {
          "name": "ASPNETCORE_ENVIRONMENT",
          "value": "Production"
        }],
        "resources": {
          "cpu": 0.5,
          "memory": "1Gi"
        }
      }]
    }
  }
}

Consuming in .NET:

services.AddHttpClient<IOrderServiceClient, OrderServiceClient>(client =>
{
    var orderServiceUrl = configuration["OrderService:Url"] 
        ?? throw new InvalidOperationException("OrderService URL not configured");
    client.BaseAddress = new Uri(orderServiceUrl);
});

Native Service Discovery in Container Apps

Azure Container Apps now supports simplified service discovery using service names directly.

var builder = WebApplication.CreateBuilder(args);

// Add Azure Container Apps service discovery
builder.Services.AddServiceDiscovery();

builder.Services.AddHttpClient<IOrderServiceClient, OrderServiceClient>(client =>
{
    // Reference by Container App name within the same environment
    client.BaseAddress = new Uri("http://order-service");
})
.AddServiceDiscovery()
.AddStandardResilienceHandler();

// For external Container Apps (different environment)
builder.Services.AddHttpClient<IPaymentServiceClient, PaymentServiceClient>(client =>
{
    client.BaseAddress = new Uri("https://payment-service.politeocean-12345678.westeurope.azurecontainerapps.io");
})
.AddStandardResilienceHandler();

Dapr Integration for Service Invocation

Dapr (Distributed Application Runtime) provides a robust service invocation model with built-in retry, tracing, and security.

Dapr Configuration:

var builder = WebApplication.CreateBuilder(args);

// Add Dapr services
builder.Services.AddDaprClient();
builder.Services.AddControllers().AddDapr();

var app = builder.Build();
app.UseRouting();
app.UseCloudEvents(); // Enable CloudEvents for pub/sub
app.MapSubscribeHandler(); // Map Dapr subscription endpoint
app.MapControllers();

Service Invocation with Dapr:

public class OrderController : ControllerBase
{
    private readonly DaprClient _daprClient;
    private readonly ILogger<OrderController> _logger;

    public OrderController(DaprClient daprClient, ILogger<OrderController> logger)
    {
        _daprClient = daprClient;
        _logger = logger;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetOrder(Guid id)
    {
        try
        {
            // Invoke customer service via Dapr sidecar
            var customer = await _daprClient.InvokeMethodAsync<Customer>(
                HttpMethod.Get,
                "customer-service", // Dapr App ID
                $"api/customers/{id}");

            if (customer is null)
            {
                return NotFound();
            }

            return Ok(customer);
        }
        catch (DaprException ex)
        {
            _logger.LogError(ex, "Failed to invoke customer service for customer {CustomerId}", id);
            return StatusCode(503, "Service temporarily unavailable");
        }
    }

    [HttpPost]
    public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
    {
        // Invoke with request/response
        var inventoryCheck = await _daprClient.InvokeMethodAsync<InventoryCheckRequest, InventoryCheckResponse>(
            HttpMethod.Post,
            "inventory-service",
            "api/inventory/check",
            new InventoryCheckRequest 
            { 
                ProductId = request.ProductId, 
                Quantity = request.Quantity 
            });

        if (!inventoryCheck.IsAvailable)
        {
            return BadRequest("Insufficient inventory");
        }

        // Process order creation...
        return CreatedAtAction(nameof(GetOrder), new { id = Guid.NewGuid() }, null);
    }
}

Dapr Component Configuration for Container Apps:

# dapr-components.yaml
componentType: state.azure.cosmosdb
version: v1
metadata:
- name: url
  value: "https://mycosmosdb.documents.azure.com:443/"
- name: masterKey
  secretRef: cosmosdb-key
- name: database
  value: "ordersdb"
- name: collection
  value: "orders"
scopes:
- order-service

API Gateway and Ingress Patterns

What is an API Gateway?

An API gateway serves as a single entry point for client requests, providing:

  • Request routing to appropriate microservices
  • Authentication and authorization enforcement
  • Rate limiting and throttling to prevent abuse
  • Request/response transformation for protocol translation
  • Caching to improve performance
  • Load balancing across service instances
  • Monitoring and analytics for observability

Azure API Management

Azure API Management provides enterprise-grade API gateway capabilities with comprehensive policy support.

Read Configure ingress for an Azure Container Apps environment

Policy Configuration:

<policies>
    <inbound>
        <base />
        <!-- Rate limiting -->
        <rate-limit-by-key calls="100" 
                           renewal-period="60" 
                           counter-key="@(context.Request.IpAddress)" />

        <!-- JWT validation -->
        <validate-jwt header-name="Authorization" 
                      failed-validation-httpcode="401" 
                      failed-validation-error-message="Unauthorized">
            <openid-config url="https://login.microsoftonline.com/{tenant-id}/v2.0/.well-known/openid-configuration" />
            <required-claims>
                <claim name="roles" match="any">
                    <value>api.read</value>
                    <value>api.write</value>
                </claim>
            </required-claims>
        </validate-jwt>

        <!-- Dynamic backend routing -->
        <choose>
            <when condition="@(context.Request.Url.Path.StartsWith("/api/orders"))">
                <set-backend-service base-url="http://order-service.production.svc.cluster.local" />
            </when>
            <when condition="@(context.Request.Url.Path.StartsWith("/api/customers"))">
                <set-backend-service base-url="http://customer-service.production.svc.cluster.local" />
            </when>
            <otherwise>
                <return-response>
                    <set-status code="404" reason="Not Found" />
                </return-response>
            </otherwise>
        </choose>

        <!-- Add correlation ID -->
        <set-header name="X-Correlation-ID" exists-action="skip">
            <value>@(Guid.NewGuid().ToString())</value>
        </set-header>
    </inbound>
    <backend>
        <base />
        <retry condition="@(context.Response.StatusCode >= 500)" 
               count="3" 
               interval="2" 
               delta="1" 
               first-fast-retry="true" />
    </backend>
    <outbound>
        <base />
        <!-- Remove internal headers -->
        <set-header name="X-Powered-By" exists-action="delete" />
        <set-header name="X-AspNet-Version" exists-action="delete" />
    </outbound>
    <on-error>
        <base />
        <set-body>@{
            return new JObject(
                new JProperty("error", context.LastError.Message),
                new JProperty("correlationId", context.Request.Headers.GetValueOrDefault("X-Correlation-ID"))
            ).ToString();
        }</set-body>
    </on-error>
</policies>

YARP - .NET Native API Gateway

YARP (Yet Another Reverse Proxy) is a highly performant, .NET-native reverse proxy toolkit ideal for building custom API gateways.

Configuration:

{
  "ReverseProxy": {
    "Routes": {
      "order-route": {
        "ClusterId": "order-cluster",
        "Match": {
          "Path": "/api/orders/{**catch-all}"
        },
        "Transforms": [
          { "PathRemovePrefix": "/api" },
          { "RequestHeader": "X-Forwarded-For", "Append": "{RemoteIpAddress}" },
          { "RequestHeader": "X-Original-Host", "Set": "{OriginalHost}" }
        ],
        "Metadata": {
          "requireAuth": "true"
        }
      },
      "customer-route": {
        "ClusterId": "customer-cluster",
        "Match": {
          "Path": "/api/customers/{**catch-all}"
        },
        "RateLimiterPolicy": "fixed",
        "AuthorizationPolicy": "authenticated"
      },
      "websocket-route": {
        "ClusterId": "notification-cluster",
        "Match": {
          "Path": "/notifications"
        }
      }
    },
    "Clusters": {
      "order-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://order-service",
            "Health": "http://order-service/health"
          }
        },
        "HealthCheck": {
          "Active": {
            "Enabled": true,
            "Interval": "00:00:10",
            "Timeout": "00:00:05",
            "Policy": "ConsecutiveFailures",
            "Path": "/health"
          }
        },
        "LoadBalancingPolicy": "RoundRobin"
      },
      "customer-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://customer-service"
          },
          "destination2": {
            "Address": "http://customer-service-2"
          }
        }
      },
      "notification-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://notification-service"
          }
        }
      }
    }
  }
}

Program.cs with Advanced Features:

var builder = WebApplication.CreateBuilder(args);

// Add YARP with service discovery
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddServiceDiscovery();

// Add authentication
builder.Services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = "https://login.microsoftonline.com/{tenant-id}/v2.0";
        options.Audience = "api://myapi";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("authenticated", policy =>
        policy.RequireAuthenticatedUser());
});

// Add rate limiting (.NET 9)
builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", opt =>
    {
        opt.Window = TimeSpan.FromMinutes(1);
        opt.PermitLimit = 100;
        opt.QueueLimit = 10;
    });

    options.AddSlidingWindowLimiter("sliding", opt =>
    {
        opt.Window = TimeSpan.FromMinutes(1);
        opt.PermitLimit = 100;
        opt.SegmentsPerWindow = 6;
    });
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();

// Map YARP routes with custom middleware
app.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.Use(async (context, next) =>
    {
        // Add custom headers
        context.Request.Headers.Append("X-Gateway", "YARP");

        await next();

        // Log response
        var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
        logger.LogInformation(
            "Proxied {Method} {Path} -> {StatusCode}", 
            context.Request.Method, 
            context.Request.Path, 
            context.Response.StatusCode);
    });
});

app.Run();

Kubernetes Ingress

Kubernetes Ingress resources manage external access to services, providing HTTP/HTTPS routing with SSL termination.

Ingress Configuration:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  namespace: production
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rate-limit: "100"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/cors-allow-origin: "https://app.company.com"
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - api.company.com
    secretName: api-tls-secret
  rules:
  - host: api.company.com
    http:
      paths:
      - path: /orders(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: order-service
            port:
              number: 80
      - path: /customers(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: customer-service
            port:
              number: 80
      - path: /payments(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: payment-service
            port:
              number: 80

Gateway API (Next Generation):

Kubernetes Gateway API provides more expressive and extensible routing capabilities.

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: api-gateway
  namespace: production
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    protocol: HTTP
    port: 80
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      certificateRefs:
      - name: api-tls-secret
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: order-route
  namespace: production
spec:
  parentRefs:
  - name: api-gateway
  hostnames:
  - "api.company.com"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /api/orders
    backendRefs:
    - name: order-service
      port: 80
    filters:
    - type: URLRewrite
      urlRewrite:
        path:
          type: ReplacePrefixMatch
          replacePrefixMatch: /

Best Practices

Health Checks

Implement comprehensive health checks for proper service discovery and load balancing.

builder.Services.AddHealthChecks()
    .AddCheck<DatabaseHealthCheck>("database")
    .AddCheck<RedisHealthCheck>("redis")
    .AddHttpClient("order-service", client =>
    {
        client.BaseAddress = new Uri("http://order-service");
    })
    .AddCheck("order-service-health");

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = _ => true,
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live")
});

Observability

Enable distributed tracing and metrics for monitoring service communication.

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddSource("OrderService");
    })
    .WithMetrics(metrics =>
    {
        metrics
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddRuntimeInstrumentation();
    });

Security Considerations

  • Always use HTTPS for external service communication
  • Implement mutual TLS (mTLS) for service-to-service communication
  • Use service mesh (Linkerd, Istio) for advanced security policies
  • Apply principle of least privilege for service accounts
  • Regularly rotate credentials and certificates
  • Implement API keys or OAuth for external API access

Summary

Service discovery is fundamental to building resilient microservices architectures. .NET 9 provides native service discovery capabilities that integrate seamlessly with Kubernetes, Azure Container Apps, and custom solutions. Combining service discovery with API gateways like YARP or Azure API Management creates a robust, scalable foundation for distributed applications.

Choose your approach based on your infrastructure:

  • Kubernetes: Use native DNS with .NET service discovery
  • Azure Container Apps: Leverage built-in service discovery or Dapr
  • Hybrid/Multi-cloud: Implement YARP or Azure API Management for unified routing

Always prioritize observability, security, and resilience patterns to ensure production-ready services.