Simple Load Balancer in .NET Core with YARP

Introduction

Load balancing is essential in distributed systems and web applications to ensure that traffic is efficiently distributed across multiple servers or resources.

Reverse Proxy

A reverse proxy is a server that sits between client devices (e.g., browsers) and the backend servers, forwarding client requests to the appropriate server and then returning the server's response to the client.

Sticky Sessions

Sticky sessions (also known as Session Affinity) in YARP is a feature that ensures requests from a particular client are always routed to the same backend server. This is particularly important for applications that rely on server-side session data, such as when storing user state or authentication information in memory on specific servers.

YARP(Yet Another Reverse Proxy) Setup

  1. create a new ASP.NET Core web application
  2. Install the Yarp.ReverseProxy NuGet package

Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();
app.MapReverseProxy();

app.Run();

appsettings.json

{
  "ReverseProxy": {
    "Routes": {
      "api-route": {
        "ClusterId": "api-cluster",
        "Match": {
          "Path": "{**catch-all}"
        },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }         
        ]
      }
    },
    "Clusters": {
      "api-cluster": {
        "SessionAffinity": {
          "Enabled": "true",
          "AffinityKeyName": "Key1",
          "Cookie": {
            "Domain": "localhost",
            "Expiration": "03:00:00",            
            "IsEssential": true,
            "MaxAge": "1.00:00:00",            
            "SameSite": "Strict",
            "SecurePolicy": "Always"
          }
        },
          "LoadBalancingPolicy": "RoundRobin",
          "Destinations": {
            "destination1": {
              "Address": "https://localhost:7106"
            },
            "destination2": {
              "Address": "https://localhost:7107"
            }
          }
        }
      }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Destination Address: The destination address should point to the base URL of your hosted web application.

Output

Here is the console output of round-robin policy.

Load balancer

Summary

Load balancing helps in improving the scalability, performance, availability, and security of web applications and services.


Similar Articles