Add rate limiting to the ASP.NET and C# Proxy example
This is an optional addition to the Proxy example, to protect your site and the service from traffic bursts.
Add a global rate limiter in Startup.cs and ConfigureServices(IServiceCollection services), or the equivalent in Program.cs if you have migrated to it:
using System.Threading.RateLimiting;
..
services.AddRateLimiter(limiterOptions =>
{
// When QueueLimit is reached, respond with this status code
limiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
limiterOptions.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
RateLimitPartition.GetConcurrencyLimiter(
// If you're on Optimizely DXP or behind the Cloudflare CDN, use: httpContext.Request.Headers["CF-Connecting-IP"].ToString()
// Otherwise, use an existing method to look up the user's IP. A default could be:
partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ =>
{
var path = httpContext.Request.Path.ToString().ToLowerInvariant();
if (path.StartsWith("/rest-api/rek/", StringComparison.OrdinalIgnoreCase)
|| path.StartsWith("/static/rek/", StringComparison.OrdinalIgnoreCase))
{
// Only allow two parallel ongoing requests to Rek.ai from one IP,
// queue and process the rest sequentially up to QueueLimit
return new ConcurrencyLimiterOptions
{
PermitLimit = 2,
QueueLimit = 768,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
};
}
// Determine what's appropriate for your site in general
return new ConcurrencyLimiterOptions
{
PermitLimit = 50,
QueueLimit = 768,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
};
}));
});Add this line to Startup.cs and Configure(IApplicationBuilder app, IWebHostEnvironment env) to enable the rate limiter. Typically, you add it after app.UseAuthorization():
app.UseRateLimiter();Now only two parallel ongoing requests to Rek.ai from one IP are permitted, more requests are put on queue and processed sequentially up to the QueueLimit-value where instead the HTTP status 429 is returned.