Backend for Frontend (BFF) Pattern :👈 👉:Saga Pattern in .NET Core

Service Discovery and Health Checks with .net core example

πŸ” Service Discovery

Service Discovery is the process by which microservices automatically locate each other without hardcoding IP addresses or URLs.It’s especially vital in dynamic environments where services scale up/down or move across hosts.

🧩 Types of Service Discovery

  • Client-Side Discovery: The client queries a service registry (like Consul or Eureka) and decides which instance to call.
  • Server-Side Discovery: A load balancer queries the registry and routes the request to the appropriate service.

βœ… Advantages

  • πŸ”„ Dynamic resolution of service locations
  • πŸ“¦ Simplifies scaling and deployment
  • 🧠 Reduces configuration complexity
  • πŸ” Enables load balancing and failover

🚫 Challenges

  • 🧱 Requires a reliable service registry
  • πŸ› Can introduce latency if registry is slow
  • πŸ” Needs secure registration and deregistration

πŸ› οΈ Best Practices

  • 🧬 Use health checks to validate service before registration
  • πŸ” Secure registry access with authentication
  • πŸ”„ Implement retries and circuit breakers
  • πŸ“Š Monitor registry performance and service churn

Service Registration and Discovery with Consul

πŸ§ͺ Step-by-Step Example: Service Registration and Discovery with Consul

1️⃣ Install Required NuGet Package

dotnet add package Consul

2️⃣ Register Service with Consul

using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var consulClient = new ConsulClient();

var registration = new AgentServiceRegistration()
{
    ID = "my-service-id",
    Name = "MyService",
    Address = "localhost",
    Port = 5000,
    Check = new AgentServiceCheck()
    {
        HTTP = "http://localhost:5000/health",
        Interval = TimeSpan.FromSeconds(10),
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1)
    }
};

await consulClient.Agent.ServiceRegister(registration);

app.MapGet("/health", () => Results.Ok("Healthy"));
app.MapGet("/", () => "Hello from MyService!");

app.Run();
  

3️⃣ Discover Another Service

using Consul;

var consulClient = new ConsulClient();
var services = await consulClient.Agent.Services();

foreach (var service in services.Response.Values)
{
    if (service.Service.Equals("AnotherService"))
    {
        Console.WriteLine($"Found AnotherService at {service.Address}:{service.Port}");
    }
}
  

βœ… What This Does

  • Registers MyService with Consul at startup
  • Adds a health check endpoint (/health)
  • Discovers other services registered in Consul

❀️ Health Checks

Health Checks are endpoints or probes that report the status of a service to help orchestrators manage traffic and recovery.They help orchestrators (like Kubernetes or Docker Swarm) decide whether a service is healthy and should receive traffic.

🧩 Types of Health Checks

  • Liveness Probe: Is the service alive? If not, restart it.
  • Readiness Probe: Is the service ready to handle requests?
  • Startup Probe: Has the service initialized properly?

βœ… Advantages

  • 🧯 Prevents traffic to unhealthy services
  • πŸ”„ Enables auto-recovery and self-healing
  • πŸ“Š Improves observability and uptime

🚫 Challenges

  • 🐒 Poorly designed checks can cause false positives/negatives
  • πŸ”„ Frequent checks may add overhead
  • πŸ§ͺ Must reflect real service readiness

πŸ› οΈ Best Practices

  • πŸ” Keep health checks lightweight and fast
  • πŸ§ͺ Include dependencies (DB, cache) in readiness checks
  • 🧼 Separate liveness and readiness logic
  • πŸ“¦ Use standard endpoints like /health, /ready, /live
  • πŸ“Š Integrate with monitoring tools

ASP.NET Core Health Check Example

πŸ§ͺ C# Health Check Example

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

// Register health checks
builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy("Service is running"));

var app = builder.Build();

// Map health check endpoint
app.MapHealthChecks("/health");

app.MapGet("/", () => "Hello World!");

app.Run();
  

πŸ” What It Does

  • Registers a basic health check named "self"
  • Exposes a /health endpoint that returns HTTP 200 if healthy
  • Can be extended to check databases, caches, etc.

🧭 How They Work Together

Imagine a service registry like Consul:

  • A microservice registers itself with Consul.
  • Consul periodically checks the service’s health endpoint.
  • If the service fails, it’s removed from the registry.
  • Clients querying Consul only get healthy instances.

This combo ensures resilience, scalability, and fault tolerance in distributed systems.

Back to Index
Backend for Frontend (BFF) Pattern :👈 👉:Saga Pattern in .NET Core
*