Zeeshan Ayyub
Zeeshan Ayyub
  • Home
  • About Us
  • Services
  • Projects
  • Blog
  • Contact Us

Unlocking Performance and Security with YARP Reverse Proxy in microservices .NET Core - Zeeshan Ayyub

    Home / Blog / Unlocking Performance and Security with YARP Reverse Proxy in microservices .NET Core
  • February 11, 2024
  • linkzeeshan.ayyub
Zeeshan Ayyub

Unlocking Performance and Security with YARP Reverse Proxy in microservices .NET Core

Let’s talk about YARP Reverse Proxy – your secret sauce for handling web traffic like a boss in the .NET Core universe. you’ve got a bustling web application, and you need something to manage all those incoming requests, right?

Enter YARP – it’s like the superhero of reverse proxies, lightweight, efficient, and highly adaptable to your needs. You want performance? Check. Security? Double check. And let’s not forget optimization – YARP’s got your back.

Think of it as your trusty sidekick, aligning perfectly with Microsoft’s mission for robust and scalable solutions. So whether you’re a startup, a big corporation, or somewhere in between, YARP’s your go-to for smoothing out those digital wrinkles and keeping your web traffic flowing smoothly.

In a nutshell, YARP Reverse Proxy in .NET Core? It’s your ticket to web traffic management done right. Trust me, you’ll wonder how you ever lived without it!

This can be solved by introducing an API gateway that acts as a reverse proxy which accepts API calls from the client application and forward them to the appropriate service.

Here’s what we will cover:

  • Explain YARP Reverse proxy 
  • Difference between Load balancer,  API gateway and reverse proxy
  • Installing and configuring and Creating API Gateway with YARP
  • Add Authentication, Rate limiting and Reverse Proxy  on the API gateway
  • YARP route configuration

Explain YARP Reverse Proxy:

YARP (Yet Another Reverse Proxy) Reverse Proxy is a component developed by Microsoft as part of .NET Core. It serves as a reverse proxy solution that allows developers to manage incoming network traffic, particularly HTTP traffic, by distributing it across multiple backend servers.

  • YARP reverse proxy addresses performance, security, scalability, and load balancing concerns.
  • It acts as an API gateway, optimizing performance by efficiently handling requests and enhancing security protocols.
  • YARP enables scalability, allowing seamless adjustment to varying traffic demands.
  • It incorporates load balancing functionalities to distribute requests evenly across backend services.
  • Integration with YARP guarantees robust performance, heightened security, scalable infrastructure, and efficient resource utilization.

Difference between Load Balancer, API Gateway and Reverse Proxy:

 Load Balancer:

A load balancer distributes incoming network traffic across multiple servers to ensure no single server is overwhelmed with too much traffic. This ensures high availability and reliability of applications.

API Gateway and Reverse Proxy:

  • Reverse proxies and API gateways serve different purposes.
  • A reverse proxy mediates between clients and servers, concealing server details and managing routing across server clusters.
  • Clients communicate exclusively with backend servers via the reverse proxy.
  • Reverse proxies efficiently handle traffic distribution across server clusters while hiding server complexities

Installing, Configuring and Creating API Gateway with YARP:

 

 Let’s start by creating a new .NET 8 application project.


First, you have to install the nuget package Yarp.ReverseProxy.

Install-Package Yarp.ReverseProxy


Authentication, Rate limiting and Reverse Proxy  on the API gateway:


Next, we need to inject the reverse proxy in Program.cs :


Code:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("authenticated", policy =>
        policy.RequireAuthenticatedUser());
});
builder.Services.AddRateLimiter(rateLimiterOptions =>
{
    rateLimiterOptions.AddFixedWindowLimiter("fixed", options =>
    {
        options.Window = TimeSpan.FromSeconds(10);
        options.PermitLimit = 5;
    });
});
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapReverseProxy();
app.Run();

YARP route configuration:

Here, we’re going to tell YARP reverse proxy how to route the incoming requests to the appropriate service.

YARP supports configuration files and settings here will be in the appsettings.json file.

YARP uses the concepts of Routes and Clusters.

Routes to represent requests patterns.

Clusters to represent the services where requests will be forwarded.

In our example we have two routes :

orders-route: which represents the pattern of the incomming requests that will be forwarded to orders-cluster.

products-route: Which represents the pattern of the incomming requests that will be forwarded to products-cluster.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ReverseProxy": {
    "Routes": {
      "users-route": {
        "ClusterId": "users-cluster",
        //"AuthorizationPolicy": "authenticated",
        "Match": {
          "Path": "/users/{**catch-all}"
        },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }
        ]
      },
      "doctors-route": {
        "ClusterId": "doctors-cluster",
        //"AuthorizationPolicy": "authenticated",
        "Match": {
          "Path": "/doctors/{**catch-all}"
        },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }
        ]
      },
      "patients-route": {
        "ClusterId": "patients-cluster",
        "RateLimiterPolicy": "fixed",
        "Match": {
          "Path": "/patients/{**catch-all}"
        },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }
        ]
      },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }
        ]
      }
    },
    "Clusters": {
      "users-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "https://localhost:44353/"
          }
        }
      },
      "doctors-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "https://localhost:44345/"
          }
        }
      },
      "patients-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "https://localhost:44355/"
          }
        }
      }
    }
  }
}

 YARP Reverse Proxy is working successfully as expected:

 

Next Post

Leave a comment

Cancel reply

Recent Posts

  • Build a .NET AI vector search app
  • Build an AI chat app with .NET
  • Executive Brief .NET 10 for Web & APIs
  • Executive Brief: .NET 10 for Web & APIs
  • Single vs. Split Queries

Recent Comments

  1. Abhiroop Santra on Build an AI chat app with .NET

Recent Post

  • October 1, 2025
    Build a .NET AI vector search app
  • September 25, 2025
    Build an AI chat app with .NET
  • September 22, 2025
    Executive Brief .NET 10 for Web & APIs

Categories

  • Blog

Tags

There’s no content to show here yet.

Archives

  • October 2025
  • September 2025
  • February 2024

Excellence decisively nay man yet impression for contrasted remarkably. There spoke happy for you are out. Fertile how old address did showing.

Solutions

  • IT Management
  • Cloud Service
  • Data Center
  • Software Development
  • Machine Learning

Contact Info

  • 5919 Trussville Crossings Pkwy, new Dusting town, Austria
  • Opening Hours: 8:00 AM – 7:45 PM
  • Phone: +123 34598768

Subscribe to Newsletter

Join our subscribers list to get the latest news and special offers.

Copyright 2024 Zeeshan Ayyub. All Rights Reserved by Trancept