Rate limiting fun
I was talking with a few of the guys at work, and the concept of rate limiting came up. In particular, being able to limit the number of operations a particular user can do against the system. The actual scenario isn't really important, but the idea kept bouncing in my head, so I sat down and wrote a quick test case.
Nitpicker corner: This is scratchpad code, it isn't production worthy, tested or validated.
The idea is probably best explained in code, like so:
private SemaphoreSlim _rateLimit = new SemaphoreSlim(10); public async Task HandlePath(HttpContext context, string method, string path) { if (await _rateLimit.WaitAsync(3000) == false) { context.Response.StatusCode = 429; // Too many requests return; } // actually process requests }
Basically, we define a semaphore, with the maximum number of operations that we want to allow, and we wait on the semaphore when we are starting the operation.
However, there is nothing that actually releases the semaphore. Here we get into design choices.
We can release the semaphore when the request is over, which effectively gives us rate limiting in terms of concurrent requests.
The more interesting approach from my perspective was to use this:
_timer = new Timer(state => { var currentCount = 10 - _rateLimit.CurrentCount; if (currentCount == 0) return; _rateLimit.Release(currentCount); }, null, 1000, 1000);
Using this approach, we are actually limited to 10 requests a second.
And yes, this actually allows more concurrent requests than the previous option, because if a request takes more than one second, we'll reset its count on the timer's tick.
I actually tested this using gobench, and it confirmed that this is actually serving exactly 10 requests / second.
Comments
why to limit the server rate? this is depends on the hardware, if a user wants to limit the request rate, he should do this on his app and not on the db. I don't see any advantage of request limiting, unless you want to avoid ddos attack, but again, this shouldn't be on the database side.
Uri, Because for my purpose that is what we need. The rate limit is for the db access itself
https://github.com/damianh/LimitsMiddleware
João, this is nice, thanks! Do you know anything similar to limit outgoing http requests, or tasks in general? Similar to Oren's but production ready.
Very clever!
Comment preview