Covers building a gateway with YARP (Yarp.ReverseProxy): configuration-based routes and clusters, path transforms, load balancing policies, active and passive health checks, timeouts, and applying ASP.NET Core authorisation and rate limiting per route.
YARP is Microsoft's reverse proxy toolkit, shipped as the Yarp.ReverseProxy NuGet package and run as ASP.NET Core middleware. You define routes (what to match: path, host, headers) that point at clusters (a set of destinations plus policies). Transforms rewrite the request on the way through, such as stripping /api or adding headers. Each cluster picks a destination with a load balancing policy (PowerOfTwoChoices by default) and keeps the list healthy with active probes and passive failure detection.
Because it is ASP.NET Core, the gateway reuses normal authentication, authorisation, rate limiting and CORS middleware, attached per route by policy name. The trade-off: you get full C# control and one stack for the team, but you now run, scale and patch the gateway yourself, which a managed service like API Management would do for you.
"YARP is a reverse proxy library from Microsoft that runs inside an ASP.NET Core app. I call
AddReverseProxy().LoadFromConfig(...)andMapReverseProxy(), and the proxy becomes an endpoint in the normal pipeline. Configuration has two parts. Routes say what to match, for example/api/orders/{**catch-all}on a given host, and which cluster to send it to. Clusters hold the destinations, the backend addresses, plus policies: load balancing, health checks, session affinity and HTTP client settings like timeouts.On the way through I use transforms. Typical ones are
PathRemovePrefixso the backend doesn't need to know about the gateway's/apiprefix, adding a correlation header, and YARP already addsX-Forwarded-For,-Proto,-Hostand-Prefixby default. For load balancing the default is power of two choices: pick two destinations at random and send to the one with fewer in-flight requests, which beats round robin when instances are uneven. Active health checks call each destination's/health/readyon an interval; passive health checks watch real traffic and take a destination out after transport failures, then bring it back after a reactivation period.The nice part is that cross-cutting concerns are just ASP.NET Core. I validate JWTs once at the gateway with
AddAuthentication().AddJwtBearer(), then putAuthorizationPolicyandRateLimiterPolicyon each route. The mistake I see is gateways growing business logic: calling three services and merging the responses in a transform. That turns the gateway into a fragile monolith that every team has to release through. I keep it to routing, auth, limits and headers."
| Concept | What it holds | Example |
|---|---|---|
| Route | Match rules + ClusterId + per-route policies + transforms | /api/orders/{**catch-all} → orders |
| Cluster | Destinations + load balancing + health checks + HttpClient config | orders with 3 destinations |
| Destination | One backend address | http://orders-1:8080/ |
| Transform | Request or response rewrite | PathRemovePrefix: /api |
| Policy | Behaviour | Use when |
|---|---|---|
PowerOfTwoChoices (default) |
Two random picks, fewer active requests wins | General purpose |
LeastRequests |
Scans all, fewest active requests | Small clusters, uneven request cost |
RoundRobin |
In order | Identical instances, cheap requests |
Random |
Uniform random | Rarely; testing |
FirstAlphabetical |
Always first healthy | Active/passive failover |
| Active | Passive | |
|---|---|---|
| How | Periodic probe to a health path | Observes real proxied requests |
| Detects | Down or not-ready instances before traffic hits them | Failures under real load |
| Cost | Extra requests every interval | None |
| Recovery | Next successful probe | After ReactivationPeriod |
A gateway in front of [six] internal services on Container Apps replaced a hand-written forwarding controller. With passive health checks on, a replica that started returning connection resets during a bad deploy was ejected within seconds; gateway 5xx stayed under [0.1%] while the bad revision was rolled back, compared with about [8%] errors in the previous incident without the gateway.
Checks hands-on YARP knowledge: the route and cluster model, health and load balancing behaviour, and keeping the gateway thin by reusing ASP.NET Core middleware.
Green flags
Red flags
HttpClient by handKestrel → UseRouting → UseAuthentication → UseAuthorization → UseRateLimiter
→ MapReverseProxy endpoint
└─ proxy pipeline: session affinity → load balancing → passive health
└─ IHttpForwarder → SocketsHttpHandler → destination
Each YARP route becomes a real ASP.NET Core endpoint with metadata, which is why AuthorizationPolicy or RateLimiterPolicy on a route works with the normal middleware. The default MapReverseProxy() adds the session affinity, load balancing and passive health check steps; you can pass a lambda to insert your own middleware into the proxy pipeline.
IHttpForwarder copies the request to an outgoing HttpRequestMessage, streams the body without buffering, and streams the response back. It uses one shared HttpMessageInvoker per cluster over SocketsHttpHandler, so connection pooling, HTTP/2 multiplexing and keep-alive work across requests. WebSockets and gRPC (HTTP/2) are proxied too. Request activity timeout defaults to 100 seconds.
Built-in transforms cover paths (PathPrefix, PathRemovePrefix, PathPattern), query strings, headers, X-Forwarded-* and Forwarded. By default YARP does not copy the client's Host header (the destination's host is used) unless you set RequestHeaderOriginalHost. Custom transforms are C# via AddTransforms.
LoadFromConfig(IConfiguration): appsettings or Azure App Configuration; reloads on change.LoadFromMemory(routes, clusters): build in code, update via InMemoryConfigProvider.Update.IProxyConfigProvider: for example, read destinations from Kubernetes or a database.Microsoft.Extensions.ServiceDiscovery.Yarp resolves logical names (as .NET Aspire does).Active: a timer per cluster sends GET to destination + Path every Interval; the ConsecutiveFailures policy marks it unhealthy after a threshold (default 2). Passive: the TransportFailureRate policy tracks failed proxied requests over a window and marks the destination unhealthy, then restores it after ReactivationPeriod. Load balancing only picks from healthy destinations; if none are healthy, YARP falls back to all of them rather than failing every request.
RateLimiterPolicy of 10 requests per 10 seconds on one route and confirm 429.appsettings.json while running and confirm it reloads without restart.bombardier or k6 and compare p99 latency direct vs through the gateway.A small gateway: config-driven routes, JWT validation, per-route rate limiting and a custom header transform.
// Program.cs (.NET 10, package Yarp.ReverseProxy 2.x)
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Yarp.ReverseProxy.Transforms;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o => builder.Configuration.Bind("Jwt", o));
builder.Services.AddAuthorizationBuilder()
.AddPolicy("authenticated", p => p.RequireAuthenticatedUser());
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Partition by user so one client cannot starve the rest.
o.AddPolicy("per-client", ctx => RateLimitPartition.GetTokenBucketLimiter(
ctx.User.Identity?.Name ?? ctx.Connection.RemoteIpAddress?.ToString() ?? "anon",
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 100,
TokensPerPeriod = 100,
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
QueueLimit = 0
}));
});
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(ctx =>
{
// Pass a correlation id so backend logs line up with gateway logs.
ctx.AddRequestTransform(t =>
{
t.ProxyRequest.Headers.TryAddWithoutValidation(
"X-Correlation-Id", t.HttpContext.TraceIdentifier);
return ValueTask.CompletedTask;
});
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapReverseProxy(); // default pipeline: affinity, load balancing, passive health checks
app.Run();
The routes and clusters live in configuration, so they can change without a redeploy:
{
"ReverseProxy": {
"Routes": {
"orders": {
"ClusterId": "orders",
"AuthorizationPolicy": "authenticated",
"RateLimiterPolicy": "per-client",
"Match": { "Path": "/api/orders/{**catch-all}" },
"Transforms": [ { "PathRemovePrefix": "/api" } ]
}
},
"Clusters": {
"orders": {
"LoadBalancingPolicy": "PowerOfTwoChoices",
"HealthCheck": {
"Active": { "Enabled": true, "Interval": "00:00:10", "Timeout": "00:00:05",
"Policy": "ConsecutiveFailures", "Path": "/health/ready" },
"Passive": { "Enabled": true, "Policy": "TransportFailureRate",
"ReactivationPeriod": "00:01:00" }
},
"HttpRequest": { "ActivityTimeout": "00:00:30" },
"Destinations": {
"orders-1": { "Address": "http://orders-1:8080/" },
"orders-2": { "Address": "http://orders-2:8080/" }
}
}
}
}
}
/health that checks the database. Why it is wrong: A database blip marks every instance unhealthy at once. Instead: Probe a readiness endpoint that reflects the instance's own ability to serve.UseAuthentication / UseAuthorization before MapReverseProxy. Why it is wrong: The route's AuthorizationPolicy has nothing to evaluate and requests are rejected or, worse, policies are misread. Instead: Order middleware as in any ASP.NET Core app.RemoteIpAddress when the gateway is itself behind Front Door. Why it is wrong: Every request shares the edge's IP, so one limit applies to everyone. Instead: Configure forwarded headers first or partition by user or API key.ActivityTimeout per cluster based on the backend's real latency.Authorization header to every backend unchanged. Why it is wrong: Backends may accept tokens not meant for them. Instead: Validate audience at the gateway and, where needed, exchange for a downstream token.YARP is the right choice when a .NET team needs routing logic that config files can't express, wants one language and toolchain, or needs a gateway that runs anywhere (AKS, Container Apps, on-premises). It is the wrong choice when the requirement is a developer portal, subscription keys, monetisation or policy-as-config for non-developers; that is API Management's job. I also check whether the platform ingress already does what is needed: Container Apps ingress and the Kubernetes Gateway API cover simple path routing without any code.
Two migrations come up often. YARP to API Management happens when internal APIs become partner-facing products: keys, quotas, a portal and an audit trail for non-engineers. Then API Management sits at the edge and YARP either disappears or stays as an internal router. API Management to YARP (for internal traffic) happens when latency or per-call cost hurts on chatty service-to-service calls; teams keep API Management for external consumers and route internal calls through YARP or plain service discovery. Timeouts must be layered so each hop is shorter than the one in front of it (for example Front Door 60 s > gateway 30 s > backend HttpClient 10 s), otherwise the outer layer gives up first and the inner work is wasted. CORS is owned in one place: either CorsPolicy on the YARP route or the backend, never both.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| YARP | Custom C# routing, auth, transforms; .NET team | Run, scale and patch yourself | Only need simple path routing |
| Azure API Management | External API products, keys, portal, policies | Tier cost (higher tiers for VNet) | Low-latency internal service-to-service |
| Ingress / Gateway API | Path and host routing inside AKS | Low, part of the cluster | Need per-request logic in C# |
| Front Door | Global edge, WAF, CDN | Per-request and base fee | Internal-only traffic |
I measure the gateway's own overhead with Application Insights or OpenTelemetry: the gap between gateway request duration and backend dependency duration should be a few milliseconds at p99.
An API gateway is a single entry point in front of your services that routes requests and applies cross-cutting concerns: TLS termination, token validation, rate limiting and quotas, request ids, IP filtering, header rewriting and sometimes caching. Azure API Management is a managed gateway with XML policies, products and subscriptions, a developer portal and analytics; YARP is a .NET reverse-proxy library you host yourself and extend in C#. A backend-for-frontend (BFF) is a gateway per client (web, mobile) that aggregates and shapes data for that client. The danger is a smart gateway: business rules and orchestration in policies become untested, hard-to-version logic owned by nobody. Keep the gateway thin and services authoritative.
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.
Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.
Register limiters with builder.Services.AddRateLimiter, add app.UseRateLimiter() after routing and authentication, then attach named policies to endpoints with RequireRateLimiting("name") or [EnableRateLimiting]. For fairness use RateLimitPartition.GetTokenBucketLimiter (or fixed/sliding window) keyed by the API key, user id or tenant so one client can't exhaust another's quota. Set RejectionStatusCode = 429 (the default is 503) and use OnRejected to copy the lease's RetryAfter metadata into the Retry-After header with a ProblemDetails body. The catch: the middleware keeps state in memory per process, so with several instances the effective limit multiplies; contractual limits belong in a shared store or the gateway.
How to tell it (STAR)
**S:** At [company] our YARP gateway fronted [six] APIs on Container Apps, and after one deploy checkout errors jumped to about [8%]. **T:** I was [on call] and needed to stop the errors and make sure a single bad instance could never do that again. **A:** In Application Insights I joined gateway requests to dependency calls and saw every failure going to one destination. Our config had no health checks and pointed at replica addresses, so YARP kept choosing a dying replica. I removed it through App Configuration, which YARP reloaded live, then changed destinations to the internal service name and turned on passive and active health checks with a 30-second timeout. **R:** Errors dropped back under [0.1%] within [two minutes], and in the next [three] bad deploys the gateway ejected failing instances automatically with no customer-visible impact.
Last updated 23 Nov 2026.