Limit the simultaneous requests served by the ASP.NET Web API

OWIN middleware to apply limits to an OWIN pipeline:

  • Max bandwidth
  • Max concurrent requests
  • Connection timeout
  • Max query string
  • Max request content length
  • Max url length
  • Min response delay

You could add a piece of OwinMiddleware along these lines (influenced by the WebApiThrottle you linked to):

public class MaxConccurrentMiddleware : OwinMiddleware
    private readonly int maxConcurrentRequests;
    private int currentRequestCount;

    public MaxConccurrentMiddleware(int maxConcurrentRequests)
        this.maxConcurrentRequests = maxConcurrentRequests;

    public override async Task Invoke(IOwinContext context)
            if (Interlocked.Increment(ref currentRequestCount) > maxConcurrentRequests)
                var response = context.Response;

                response.OnSendingHeaders(state =>
                    var resp = (OwinResponse)state;
                    resp.StatusCode = 429; // 429 Too Many Requests
                }, response);

                return Task.FromResult(0);

            await Next.Invoke(context);
            Interlocked.Decrement(ref currentRequestCount);

Alternatively you can use a git package to deal with this:



There are two nuget packages. The main one is pure owin and this has no dependencies.

install-package LimitsMiddleware

The second package provides integration with IAppBuilder, which is deprecated but provided here for legacy and compatability reasons.

install-package LimitsMiddleware.OwinAppBuilder

An vNext builder integration package will be forthcoming.


Configuration values can be supplied as constants or with a delegate. The latter allows you to change the values at runtime. Use which ever you see fit. This code assumes you have installed ‘LimitsMiddleware.OwinAppBuilder’

public class Startup
    public void Configuration(IAppBuilder builder)
        //static settings
            .MaxBandwidth(10000) //bps
            .MaxQueryStringLength(15) //Unescaped QueryString

        //dynamic settings
            .MaxBandwidth(() => 10000) //bps
            .MaxConcurrentRequests(() => 10)
            .ConnectionTimeout(() => TimeSpan.FromSeconds(10))
            .MaxQueryStringLength(() => 15)
            .MaxRequestContentLength(() => 15)
            .MaxUrlLength(() => 20)