api-gatewayrate-limitingocelot

Ocelot Rate Limiting


I've been using Ocelot lately to build an API Gateway. Are rate limits based on the requester client id? Because i've been asked to build an api gateway in an architecture that will look like this

enter image description here

And all the requests will have the same id since they are passing through the proxy. I can however, identify the different requesting clients using an header token. So my question is: can i limit the number of request made by a client using the header token rather than the request id? Thanks in advance.


Solution

  • You could use Ocelot as a Rate Limiter based on ClientId.

    "RateLimitOptions": {
    "DisableRateLimitHeaders": false,
    "QuotaExceededMessage": "Customize Tips!",
    "HttpStatusCode": 999,
    "ClientIdHeader" : "MY-CLIENT-ID"
    }
    

    The last line in Ocelot's rate limiting documentation refers to this:

    ClientIdHeader - Allows you to specifiy the header that should be used to identify clients. By default it is “ClientId”

    You could also implement your own middleware and use Ocelots rate limitng. So You could be able to read other Headers and get your customized client-id:

    Just take a look at default rate limiting middleware provided by Ocelot: ClientRateLimitMiddleware.cs

    public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext, RateLimitOptions option)
        {
            var clientId = "client";
            if (httpContext.Request.Headers.Keys.Contains(option.ClientIdHeader))
            {
                clientId = httpContext.Request.Headers[option.ClientIdHeader].First();
            }
    
            return new ClientRequestIdentity(
                clientId,
                httpContext.Request.Path.ToString().ToLowerInvariant(),
                httpContext.Request.Method.ToLowerInvariant()
                );
        }