YARP — Reverse Proxy
YARP (Yet Another Reverse Proxy) is a Microsoft library for building high-performance, programmable reverse proxies and API gateways directly in .NET using ASP.NET Core middleware. This guide connects the programming model to production decisions, failure modes, security, testing, performance, deployment, and operations.
Overview
Unlike infrastructure proxies such as NGINX or managed services such as Azure API Management, YARP runs inside a .NET application and integrates with the full ASP.NET Core pipeline — dependency injection, authentication, rate limiting, OpenTelemetry, and custom middleware all apply. Routes and clusters are configured in appsettings.json or loaded dynamically from a database or service registry. Request and response transforms allow header manipulation, path rewriting, query modifications, and claim forwarding. YARP is an excellent fit for the Backend for Frontend pattern, internal API gateways in Modular Monolith decomposition, and migration facades in Legacy Modernisation. The central design goal is building a programmable .NET reverse proxy with explicit routes, clusters, transforms, health, load balancing, resilience, authentication boundaries, and dynamic configuration. YARP proxies HTTP traffic and exposes extensibility; upstream and downstream services still own business authorization, data rules, contracts, and workload-specific resilience. Teams should begin with a concrete user outcome and quality-attribute scenario, choose the smallest architecture that satisfies it, and record the operational owner. A catch-all proxy can become an unbounded trust bridge that forwards spoofed headers, retries unsafe requests, hides unhealthy destinations, or centralizes fragile business logic. A production design therefore needs explicit limits, identity, cancellation, telemetry, evaluation, recovery, and a safe change path. The dedicated sample keeps external infrastructure optional so readers can inspect the governing mechanics locally, then maps those mechanics to the hosted services and controls required in a real environment.
What you will learn
- Explain the purpose and boundaries of YARP — Reverse Proxy without confusing the tool with the whole architecture.
- Decide when YARP — Reverse Proxy is appropriate and when a simpler design is safer.
- Design the core contracts, ownership, data flow, and failure behavior for building a programmable .NET reverse proxy with explicit routes, clusters, transforms, health, load balancing, resilience, authentication boundaries, and dynamic configuration.
- Apply authentication, authorization, validation, privacy, and least privilege at every trust boundary.
- Test normal behavior, negative paths, dependency failure, recovery, and operational signals.
- Deploy incrementally with observable acceptance criteria, rollback, and accountable ownership.
- Run and extend the dedicated YARP Route Policy Lab sample.
Prerequisites
- .NET 10, C# async programming, dependency injection, configuration, and structured logging.
- The domain and platform fundamentals referenced by YARP — Reverse Proxy.
- Basic security, testing, observability, and continuous-delivery concepts.
- A .NET 10 SDK to run YARP Route Policy Lab; no paid cloud account is required for its default path.
When to use YARP — Reverse Proxy
Good fit
- Use YARP — Reverse Proxy when building a programmable .NET reverse proxy with explicit routes, clusters, transforms, health, load balancing, resilience, authentication boundaries, and dynamic configuration directly addresses a measured product or operational need.
- Use it when a named team can own the contracts, data, deployment, telemetry, cost, and incident response.
- Introduce it behind a narrow boundary and prove the riskiest assumption with a production-shaped experiment.
Choose another approach when
- Avoid YARP — Reverse Proxy when the same outcome is available through a smaller in-process or managed capability.
- Do not adopt it only for résumé value, diagram symmetry, or a vendor checklist.
- Do not proceed without a threat model, failure policy, observability, and an exit or rollback path.
Key concepts
A route matches an incoming request by path, host, or header and maps it to a cluster — a named group of destination backends with load balancing, health checks, and session affinity settings.
Request and response transforms modify headers, paths, query strings, and the request body before forwarding or after receiving the upstream response — configurable in JSON or code.
YARP distributes traffic across cluster destinations using round-robin, least-requests, power-of-two, or random strategies and actively or passively monitors destination availability.
Routes and clusters can be reloaded at runtime from any IProxyConfigProvider implementation — a database, Consul, or a custom control plane — without restarting the proxy process.
Routes, clusters, and transforms is a first-class design concern for building a programmable .NET reverse proxy with explicit routes, clusters, transforms, health, load balancing, resilience, authentication boundaries, and dynamic configuration.
Destination health and proxy resilience is a first-class design concern for building a programmable .NET reverse proxy with explicit routes, clusters, transforms, health, load balancing, resilience, authentication boundaries, and dynamic configuration.
Architecture
Inbound traffic hits the YARP middleware pipeline, which matches a route, applies transforms, forwards to the selected cluster destination, and returns the upstream response through the response transform chain.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
YARP is registered as middleware, routes are declared in configuration, and a custom transform forwards the authenticated user's claims to the upstream service as a trusted header.
using Yarp.ReverseProxy.Transforms;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(ctx =>
{
ctx.AddRequestTransform(async transform =>
{
var userId = transform.HttpContext.User
.FindFirst("sub")?.Value;
if (userId is not null)
transform.ProxyRequest.Headers
.TryAddWithoutValidation("X-User-Id", userId);
await Task.CompletedTask;
});
});
builder.Services.AddAuthentication("Bearer").AddJwtBearer();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapReverseProxy();
app.Run();Testing strategy
Test YARP — Reverse Proxy as a behavior and operational boundary, not only as a library call.
- Unit-test deterministic policy, validation, mapping, and error classification.
- Use contract tests for provider, protocol, platform, and downstream boundaries.
- Run integration tests with realistic serialization, configuration, identity, cancellation, and dependency behavior.
- Exercise the primary failure: A catch-all proxy can become an unbounded trust bridge that forwards spoofed headers, retries unsafe requests, hides unhealthy destinations, or centralizes fragile business logic.
- Load-test representative and adversarial inputs while observing latency, errors, saturation, and cost.
- Keep a versioned acceptance suite that protects behavior during dependency and configuration changes.
Security considerations
Treat YARP — Reverse Proxy input, dependencies, credentials, output, and administrative controls as separate trust boundaries.
- Authenticate the caller and workload; authorize the operation and resource at the system that performs it.
- Validate type, size, count, format, tenant, and allowed values before expensive or consequential work.
- Use short-lived identity and least privilege; keep secrets out of source, logs, prompts, packages, and client storage.
- Classify data, minimize collection and retention, redact telemetry, encrypt in transit and at rest, and support deletion policy.
- Require explicit approval and idempotency for external side effects; audit actor, intent, policy decision, and outcome.
- Patch and inventory dependencies, pin trusted sources, scan artifacts, and restrict outbound destinations.
Performance and scalability
Optimize the end-to-end user outcome within downstream capacity and cost limits.
- Measure p50, p95, p99, throughput, failures, saturation, queue time, payload size, and cost together.
- Set end-to-end deadlines and propagate cancellation instead of stacking independent timeouts.
- Bound concurrency, queues, retries, payloads, fan-out, and caches so overload cannot grow without limit.
- Cache only when identity, freshness, privacy, invalidation, and failure semantics are explicit.
- Batch or stream only when the workload and user latency target justify the complexity.
- Capacity-test dependency degradation and recovery because retry and replay traffic often dominate peak load.
Deployment and operations
Promote an immutable, observable change through environments with compatibility and rollback evidence.
- Keep environment configuration external, validated at startup, and free of long-lived credentials.
- Provision dependencies, identity, network policy, dashboards, alerts, and budgets through reviewed automation.
- Use additive contracts and mixed-version compatibility before removing old behavior.
- Deploy with canary or staged exposure, health gates, graceful shutdown, and automated rollback signals.
- Record version and configuration in telemetry; retain runbooks, ownership, recovery targets, and escalation paths.
- Rehearse dependency loss, restore, credential rotation, region or device failure, and data recovery where applicable.
Common problems and fixes
The local sample works but production behavior differs
Likely cause: Provider, identity, network, limits, data, or configuration assumptions were hidden.
Fix: Compare effective configuration and correlated dependency telemetry, then reproduce the smallest differing boundary.
Latency rises sharply under load
Likely cause: Concurrency, fan-out, retries, queues, or a downstream quota is unbounded.
Fix: Inspect saturation and queue time, stop retry amplification, apply backpressure, and reduce work per request.
A request succeeds twice or creates duplicate effects
Likely cause: The caller retried after an ambiguous result and the operation was not idempotent.
Fix: Use a stable operation ID, persist the outcome with the effect, and return the recorded result on replay.
Sensitive information appears in telemetry
Likely cause: Raw inputs, outputs, headers, or exceptions were logged without classification and redaction.
Fix: Stop the leak, restrict and rotate access as needed, redact by default, and test the telemetry schema.
A dependency upgrade changes behavior
Likely cause: Application semantics depended on provider-specific defaults or an untested protocol detail.
Fix: Pin or roll back, compare release notes and contract traces, then update the acceptance suite before retrying.
Operators cannot explain a failed user outcome
Likely cause: Logs, metrics, traces, version, and business identifiers are not correlated.
Fix: Add end-to-end correlation and a dashboard that links the user journey to dependency and deployment signals.
Best practices
- Centralise cross-cutting concerns — authentication, rate limiting, correlation ID injection, and request logging — in the YARP middleware pipeline rather than duplicating them in every upstream service.
- Use the dynamic configuration provider pattern to reload routes and clusters from a database or service registry at runtime, enabling zero-downtime topology changes without a proxy restart.
- Apply path-strip transforms at the proxy rather than requiring upstream services to understand gateway-prefixed paths — each service should be independently addressable without the proxy prefix.
- Monitor YARP's built-in metrics for request rate, error rate, and destination health alongside upstream service telemetry so the proxy itself is not a blind spot in the observability picture.
- Match routes narrowly by host, path, method, and policy; reject ambiguous ownership and strip client-supplied forwarding or identity headers.
- Use active and passive health, bounded timeouts, safe retry policy, destination capacity, and graceful configuration changes based on measured traffic.
Production checklist
- The need for YARP — Reverse Proxy, alternatives, owner, constraints, and exit criteria are recorded.
- Contracts, data ownership, trust boundaries, limits, and compatibility policy are explicit.
- Identity, least privilege, validation, privacy, redaction, audit, and side-effect approval are enforced.
- Timeout, cancellation, retry, backpressure, idempotency, fallback, and recovery behavior are tested.
- Logs, metrics, traces, cost, quality, business outcomes, dashboards, alerts, and runbooks identify version and owner.
- Capacity, dependency failure, restore, rollback, credential rotation, and incident response are rehearsed.
- Lifecycle, deprecation, data retention, dependency patching, and operational cost have named owners.
Common interview questions
When would you choose YARP over Azure API Management?
YARP is a good fit when the gateway logic is complex enough to need code, when deep ASP.NET Core middleware integration is required — custom auth, claim transforms, feature flags — or when a managed gateway's cost, latency, or networking constraints are not acceptable. APIM is better when a managed service, a developer portal, a built-in policy engine, and multi-region capabilities are needed without writing and operating gateway code.
What is the Backend for Frontend pattern and how does YARP support it?
Backend for Frontend creates a dedicated gateway per client type — web, mobile, third-party — each exposing the exact API shape that client needs, aggregating and transforming upstream responses. YARP supports this by letting each BFF be a .NET application with its own route configuration, transforms, and authentication policy, all sharing common middleware through the ASP.NET Core pipeline.
How does YARP handle upstream service discovery in a dynamic environment?
A custom IProxyConfigProvider implementation reads destination addresses from any source — a database, Consul, Kubernetes endpoints, or an Azure App Configuration store — and returns a new configuration on each poll. YARP watches for configuration changes and reloads routes and clusters without restarting, enabling dynamic registration and deregistration of upstream services.
What is the difference between a YARP route and cluster?
A route matches an incoming request and selects policy; a cluster groups destination endpoints and load-balancing or health behavior.
Where should authorization occur?
The edge can enforce coarse policy, but the destination must authorize the operation and resource because it owns the business trust decision.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
YARP Route Policy Lab
A .NET 10 YARP policy model that performs ordered route matching, strips spoofable headers, selects healthy destinations, and rejects unsafe retries.
- Run
dotnet run --project src/YarpRoutePolicyLab- Test
dotnet run --project src/YarpRoutePolicyLab -- --self-test