Is it possible to add delay to concurrent requests in ASP.NET Web API 2?

Cenk 1,021 Reputation points
2023-12-10T13:28:56.5266667+00:00

I am using WebApiThrottle for rate limiting in my ASP.NET Web API 2 project, but I am having problems with concurrent requests. Instead of sending 429 too many requests responses, is it possible to delay concurrent requests, for example, allowing only one request per second? Here is my WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
            DateTimeZoneHandling.Local;
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional }
        );
        config.MessageHandlers.Add(new ThrottlingHandler()
        {
            Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20)
            {
                IpThrottling = true,
                EndpointThrottling = true
            },
            Repository = new CacheRepository(),
            QuotaExceededMessage = "You may only perform this action every {0} seconds."
        });

        config.MessageHandlers.Add(new RequestResponseHandler());
        config.Filters.Add(new CustomExceptionFilter());

        var resolver = config.DependencyResolver; 
        var basicAuth = (BasicAuthenticationAttribute)resolver.GetService(typeof(BasicAuthenticationAttribute));
    }
}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,922 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,015 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
343 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2023-12-10T17:17:12.0566667+00:00

    Delaying would stack up connections, and may queue up more work than the server can do. This is why throttling rejects requests, rather than delay.

    the calling client should respect the api limits.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.