Section 4 of 6

Microservices Patterns

🎯 What You'll Learn

  • What are microservices
  • API Gateway pattern
  • Service discovery
  • Circuit breaker
  • Retry policies

What are Microservices?

Microservices are small, independent services that communicate over HTTP/gRPC, each responsible for a specific business capability.

Monolith vs Microservices

Aspect Monolith Microservices
Deployment Single unit Independent services
Scaling Scale entire app Scale individual services
Technology Single stack Different stacks per service
Complexity Lower Higher
Failure Entire app fails Isolated failures

API Gateway Pattern

Single entry point for all client requests, routing to appropriate microservices.

Install Ocelot Bash
dotnet add package Ocelot
ocelot.json JSON
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/products/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/products/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    },
    {
      "DownstreamPathTemplate": "/api/orders/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/orders/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}
Program.cs C#
builder.Configuration.AddJsonFile("ocelot.json");
builder.Services.AddOcelot();

var app = builder.Build();
await app.UseOcelot();

Circuit Breaker Pattern

Prevent cascading failures by stopping calls to failing services.

Install Polly Bash
dotnet add package Microsoft.Extensions.Http.Polly
Program.cs C#
using Polly;

builder.Services.AddHttpClient("ProductService", client =>
{
    client.BaseAddress = new Uri("http://localhost:5001");
})
.AddTransientHttpErrorPolicy(policy => 
    policy.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));

Retry Policy

Retry with Polly C#
builder.Services.AddHttpClient("ProductService", client =>
{
    client.BaseAddress = new Uri("http://localhost:5001");
})
.AddTransientHttpErrorPolicy(policy => 
    policy.WaitAndRetryAsync(3, retryAttempt => 
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

InvenTrack Microservices Example

OrderService calling ProductService C#
public class OrderService
{
    private readonly IHttpClientFactory _httpClientFactory;

    public async Task<Product> GetProductAsync(int productId)
    {
        var client = _httpClientFactory.CreateClient("ProductService");
        var response = await client.GetAsync($"/api/products/{productId}");
        response.EnsureSuccessStatusCode();
        
        return await response.Content.ReadFromJsonAsync<Product>();
    }
}

Key Takeaways

  • Microservices: Independent, scalable services
  • API Gateway: Single entry point (Ocelot)
  • Circuit breaker: Prevent cascading failures
  • Retry policy: Handle transient errors
  • Polly: Resilience library
  • Trade-offs: Higher complexity for better scalability