ASP.NET - API Gateway Pattern with Ocelot or YARP in ASP.NET Core
The API Gateway Pattern is a modern architectural approach used in microservices-based applications. In this pattern, a single gateway acts as the entry point for all client requests and routes them to the appropriate backend services. Instead of clients directly communicating with multiple services, they interact with only one centralized gateway.
In ASP.NET Core, two popular tools used for implementing API Gateway functionality are:
-
Ocelot
-
YARP (Yet Another Reverse Proxy)
Both are designed to simplify routing, security, scalability, and traffic management in distributed applications.
Why API Gateway is Needed
In traditional monolithic applications, all functionalities are usually contained in a single application. But in microservices architecture, the application is divided into smaller independent services such as:
-
User Service
-
Product Service
-
Payment Service
-
Order Service
-
Notification Service
If clients communicate directly with all these services, several problems arise:
-
Complex communication logic
-
Multiple endpoints to manage
-
Security challenges
-
Increased network traffic
-
Difficult authentication management
-
Load balancing complexity
The API Gateway solves these issues by acting as an intermediary layer.
Basic Working of API Gateway
The client sends requests to the API Gateway.
The gateway then:
-
Receives the request
-
Identifies the destination service
-
Applies authentication or validation
-
Forwards the request to the target service
-
Collects the response
-
Sends the response back to the client
This creates a centralized communication mechanism.
Main Features of API Gateway
1. Request Routing
The gateway routes requests to appropriate services based on URL patterns.
Example:
-
/api/users/*→ User Service -
/api/orders/*→ Order Service -
/api/payments/*→ Payment Service
2. Authentication and Authorization
Instead of implementing authentication separately in every microservice, the gateway can centrally validate:
-
JWT Tokens
-
OAuth
-
API Keys
This reduces repetitive security implementation.
3. Load Balancing
The gateway can distribute traffic across multiple instances of the same service.
Example:
If three payment service instances exist:
-
Payment Service 1
-
Payment Service 2
-
Payment Service 3
The gateway balances incoming requests among them.
4. Rate Limiting
The gateway can restrict excessive requests from users or applications.
Example:
-
Maximum 100 requests per minute per user
This prevents abuse and protects backend services.
5. Response Aggregation
Sometimes clients need data from multiple services.
Without API Gateway:
-
Client calls multiple APIs separately
With API Gateway:
-
Gateway combines responses into one response
This improves performance and reduces client complexity.
6. Logging and Monitoring
The gateway can centrally track:
-
Incoming requests
-
Errors
-
Response times
-
Traffic analytics
This simplifies debugging and monitoring.
Ocelot in ASP.NET Core
Ocelot is an open-source API Gateway library specifically designed for ASP.NET Core applications.
It provides:
-
Request routing
-
Authentication
-
Rate limiting
-
Load balancing
-
Service discovery
-
Caching
Ocelot is configuration-driven and simple to use.
Installing Ocelot
Install the NuGet package:
dotnet add package Ocelot
Ocelot Configuration File
Ocelot mainly works using a configuration file named:
ocelot.json
Example:
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/products",
"UpstreamHttpMethod": [ "GET" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7000"
}
}
Understanding the Configuration
Downstream
Represents the actual backend service.
"DownstreamPathTemplate": "/api/products"
This is the internal service endpoint.
Upstream
Represents the public endpoint exposed to clients.
"UpstreamPathTemplate": "/products"
Clients access this URL.
Configuring Program.cs
Example:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json");
builder.Services.AddOcelot();
var app = builder.Build();
await app.UseOcelot();
app.Run();
Now the gateway routes incoming traffic automatically.
Advantages of Ocelot
Easy Configuration
Most settings are managed through JSON files.
Lightweight
Suitable for small and medium-sized microservices projects.
ASP.NET Core Integration
Works seamlessly with ASP.NET Core middleware.
Supports Authentication
Can integrate with Identity Server or JWT authentication.
Limitations of Ocelot
-
Less flexible for advanced proxy scenarios
-
Smaller ecosystem compared to enterprise gateway solutions
-
Configuration becomes large in very complex systems
YARP (Yet Another Reverse Proxy)
YARP is a modern reverse proxy library developed by Microsoft.
It is highly customizable and optimized for performance.
Unlike Ocelot, YARP is not limited to API Gateway scenarios only. It can also work as:
-
Reverse proxy
-
Load balancer
-
Edge server
-
Traffic manager
Installing YARP
dotnet add package Yarp.ReverseProxy
YARP Configuration
Example in appsettings.json:
{
"ReverseProxy": {
"Routes": {
"productRoute": {
"ClusterId": "productCluster",
"Match": {
"Path": "/products/{**catch-all}"
}
}
},
"Clusters": {
"productCluster": {
"Destinations": {
"destination1": {
"Address": "https://localhost:5001/"
}
}
}
}
}
}
Configuring Program.cs for YARP
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();
Features of YARP
High Performance
Designed for modern cloud-native applications.
Dynamic Configuration
Supports runtime updates without restarting applications.
Extensible Architecture
Developers can customize routing logic and middleware.
Microsoft Support
Developed and maintained by Microsoft.
Ocelot vs YARP
| Feature | Ocelot | YARP |
|---|---|---|
| Developed By | Community | Microsoft |
| Configuration Style | Simple JSON | Flexible Configuration |
| Performance | Good | Very High |
| Customization | Moderate | Extensive |
| Learning Curve | Easier | Slightly Advanced |
| Best Use Case | API Gateway | Reverse Proxy + Gateway |
| Cloud Native Support | Moderate | Strong |
API Gateway Security
API Gateways often handle critical security responsibilities.
Common Security Features
JWT Authentication
Validates tokens before forwarding requests.
HTTPS Enforcement
Ensures encrypted communication.
IP Filtering
Blocks unauthorized IP addresses.
Request Validation
Checks request headers, payloads, and parameters.
Service Discovery
In cloud environments, service addresses may frequently change.
API Gateways can integrate with service discovery tools like:
-
Consul
-
Eureka
-
Kubernetes DNS
This allows automatic detection of service instances.
API Gateway in Microservices Architecture
Typical flow:
Client Application
↓
API Gateway
↓
-----------------------
| User Service |
| Product Service |
| Payment Service |
| Notification Service|
-----------------------
The gateway hides internal architecture complexity from clients.
Benefits of API Gateway Pattern
Simplified Client Communication
Clients only communicate with one endpoint.
Centralized Security
Authentication and authorization are handled in one place.
Improved Scalability
Services can scale independently.
Reduced Network Overhead
Gateway can aggregate responses.
Better Monitoring
Central logging and analytics improve maintenance.
Challenges of API Gateway
Single Point of Failure
If the gateway fails, the entire system may become inaccessible.
Solution:
-
Deploy multiple gateway instances
-
Use load balancers
Additional Latency
Requests pass through an extra layer.
Solution:
-
Use optimized gateway configurations
-
Enable caching
Increased Complexity
Gateway management becomes important in large systems.
Real-World Use Cases
E-Commerce Platforms
Gateway handles:
-
Product APIs
-
Payment APIs
-
Cart APIs
-
User APIs
Banking Systems
Gateway manages:
-
Authentication
-
Transaction routing
-
Fraud monitoring
Streaming Platforms
Gateway controls:
-
Content delivery
-
User sessions
-
Subscription services
Best Practices
Keep Gateway Lightweight
Avoid heavy business logic inside the gateway.
Use HTTPS Everywhere
Secure all communication channels.
Enable Monitoring
Track gateway performance and failures.
Implement Caching
Reduce repeated backend requests.
Use Rate Limiting
Prevent traffic abuse.
Conclusion
The API Gateway Pattern is an essential component in modern microservices architecture. It simplifies communication between clients and backend services while providing centralized routing, security, monitoring, and scalability.
Ocelot is suitable for developers seeking a simpler ASP.NET Core API Gateway solution with straightforward configuration. YARP is more advanced, highly customizable, and optimized for enterprise-grade cloud-native applications.
Understanding API Gateway concepts is important for building scalable, secure, and maintainable distributed systems in ASP.NET Core applications.