| 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
/healthendpoint 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.
| Backend for Frontend (BFF) Pattern :👈 | 👉:Saga Pattern in .NET Core |
Comments and Discussion