Load Balancer¶
Ocelot can load balance across available downstream services for each route. This means you can scale your downstream services, and Ocelot can use them effectively.
LoadBalancerOptions Schema¶
Class: FileLoadBalancerOptions
The following is the full load balancer configuration, used in both the Route Schema and the Dynamic Route Schema.
Not all of these options need to be configured; however, the Type option is mandatory.
"LoadBalancerOptions": {
"Type": "",
"Key": "", // CookieStickySessions balancer
"Expiry": 1 // ms, CookieStickySessions balancer
}
Option |
Description |
|---|---|
|
An in-built load balancer type selected from the list of available Balancers, or a user-defined type (refer to the “Custom Balancers” section). |
|
The name of the cookie you wish to use for sticky sessions. This option is applicable only to the CookieStickySessions type. |
|
Expiration period specifies how long, in milliseconds, the session should remain sticky. This value refreshes with each request to mimic typical session behavior. Note: This option applies only to the CookieStickySessions type. |
The actual LoadBalancerOptions schema with all the properties can be found in the C# FileLoadBalancerOptions class.
Configuration¶
The following shows how to set up multiple downstream services for a static route using ocelot.json and then select the LeastConnection load balancer.
This is the simplest way to configure load balancing without using service discovery.
{
"UpstreamPathTemplate": "/posts/{postId}",
"UpstreamHttpMethod": [ "Put", "Delete" ],
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "10.0.1.10", "Port": 5000 },
{ "Host": "10.0.1.11", "Port": 5000 }
],
"LoadBalancerOptions": {
"Type": "LeastConnection"
}
}
The following shows how to set up a route using Service Discovery and then select the RoundRobin load balancer.
{
// ...
"ServiceName": "product",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
When this is set up, Ocelot will look up the downstream host and port from the Service Discovery provider and load balance requests across any available services. If you add and remove services from the Service Discovery provider [1], Ocelot should respect this and stop calling services that have been removed and start calling services that have been added.
Global Configuration [2]¶
A complete configuration consists of both route-level and global load balancing.
You can configure the following options in the GlobalConfiguration section of ocelot.json:
"Routes": [
{
"Key": "R0", // optional
"LoadBalancerOptions": {
"Type": "CookieStickySessions",
"Key": ".AspNetCore.Session",
"Expiry": 1200000 // milliseconds, 20 minutes
}
},
{
"Key": "R1", // this route is part of a group
"LoadBalancerOptions": {} // optional due to grouping
}
],
"GlobalConfiguration": {
"BaseUrl": "https://ocelot.net",
"LoadBalancerOptions": {
"RouteKeys": ["R1"], // if undefined or empty array, opts will apply to all routes
"Type": "LeastConnection"
}
}
Service Discovery dynamic routes intentionally override the global dynamic routing configuration:
"DynamicRoutes": [
{
"Key": "", // optional
"ServiceName": "my-service",
"LoadBalancerOptions": {
"Type": "LeastConnection" // switch from RoundRobin to LeastConnection
}
}
],
"GlobalConfiguration": {
"BaseUrl": "https://ocelot.net",
"DownstreamScheme": "http",
"ServiceDiscoveryProvider": {
// required section for dynamic routing
},
"LoadBalancerOptions": {
"RouteKeys": [], // no grouping, thus opts apply to all dynamic routes
"Type": "RoundRobin"
}
}
In this configuration, the RoundRobin balancer is used for all implicit dynamic routes.
However, for the “my-service” service, the load balancer type has been explicitly switched from RoundRobin to LeastConnection.
Note
1. If the RouteKeys option is not defined or the array is empty in the global LoadBalancerOptions, the global options will apply to all routes.
If the array contains route keys, it defines a single group of routes to which the global options apply.
Routes excluded from this group must specify their own route-level LoadBalancerOptions.
2. Prior to version 24.1, global LoadBalancerOptions were only accessible in the special Dynamic Routing mode.
Since version 24.1, global configuration has been available for both static and dynamic routes.
As a team, we would consider the idea of implementing such a global configuration for aggregated routes.
However, an aggregated route is essentially a combination of static routes.
Balancers¶
The available types of built-in load balancers are:
Type |
Description |
|---|---|
|
This uses a cookie to stick all requests to a specific server. More information can be found in the “CookieStickySessions Type” section. |
|
This tracks which services are dealing with requests and sends new requests to the service with the fewest (“least”) existing requests. The algorithm state is not distributed across a cluster of Ocelots. |
|
This loops through available services and sends requests. The algorithm state is not distributed across a cluster of Ocelots. |
|
This takes the first available service from configuration or Service Discovery provider. |
You must choose which load balancer to use in your configuration.
Custom Balancers [4]¶
In order to create and use a custom load balancer, you can do the following.
Below, we set up a basic load balancing configuration, and note that the Type is MyLoadBalancer, which is the name of a class we will set up to perform load balancing.
{
// ...
"DownstreamHostAndPorts": [
{ "Host": "10.0.1.10", "Port": 5000 },
{ "Host": "10.0.1.11", "Port": 5000 }
],
"LoadBalancerOptions": {
"Type": "MyLoadBalancer"
}
}
Then, you need to create a class that implements the ILoadBalancer interface. Below is a simple round-robin example:
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Responses;
using Ocelot.Values;
public class MyLoadBalancer : ILoadBalancer
{
private readonly Func<Task<List<Service>>> _services;
private static object Locker = new();
private int _last;
public MyLoadBalancer() { }
public MyLoadBalancer(Func<Task<List<Service>>> services)
=> _services = services;
public string Type => nameof(MyLoadBalancer);
public void Release(ServiceHostAndPort hostAndPort) { }
public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext context)
{
var services = await _services.Invoke();
lock (Locker)
{
_last = (_last >= services.Count) ? 0 : _last;
var next = services[_last++];
return new OkResponse<ServiceHostAndPort>(next.HostAndPort);
}
}
}
Finally, you need to register this class with Ocelot. We have used the most complex example below to show all of the data and types that can be passed into the factory that creates load balancers.
using Ocelot.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.ServiceDiscovery.Providers;
Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, MyLoadBalancer> lbFactory
= (serviceProvider, Route, discoveryProvider) => new MyLoadBalancer(discoveryProvider.GetAsync);
builder.Services
.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer(lbFactory);
However, there is a much simpler example that will work the same way:
using Ocelot.DependencyInjection;
builder.Services
.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer<MyLoadBalancer>();
Note
1. There are numerous IOcelotBuilder methods to add a custom load balancer.
The interface is as follows:
IOcelotBuilder AddCustomLoadBalancer<T>()
where T : ILoadBalancer, new();
IOcelotBuilder AddCustomLoadBalancer<T>(Func<T> loadBalancerFactoryFunc)
where T : ILoadBalancer;
IOcelotBuilder AddCustomLoadBalancer<T>(Func<IServiceProvider, T> loadBalancerFactoryFunc)
where T : ILoadBalancer;
IOcelotBuilder AddCustomLoadBalancer<T>(Func<DownstreamRoute, IServiceDiscoveryProvider, T> loadBalancerFactoryFunc)
where T : ILoadBalancer;
IOcelotBuilder AddCustomLoadBalancer<T>(Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, T> loadBalancerFactoryFunc)
where T : ILoadBalancer;
When you enable custom load balancers, Ocelot looks up your load balancer by its class name when it decides whether to perform load balancing.
If it finds a match, it will use your load balancer to load balance.
If Ocelot cannot match the load balancer type in your configuration with the name of the registered load balancer class, then you will receive an HTTP 500 Internal Server Error.
If your load balancer factory throws an exception when Ocelot calls it, you will receive an HTTP 500 Internal Server Error.
Warning
Remember, if you specify no load balancer in your Configuration, Ocelot will not attempt to load balance.