✅ Handle one API request at a time
So i have an api controller and i need to make sure i handle only one request at a time for a specific endpoint. the reason is that sometimes the client sends a request twice and i need to make sure i only handle each one once. how can i handle one at a time so i dont run into concurrency issues?
11 Replies
im currently using an
AutoResetEvent
which should probably work fine?Handling an api request in this case would mean that the request is kept open until it is actually first in line to be processed?
Or is this a case of "client puts in a piece of work, but does not care about the response"?
Because depending on that a queue of jobs might be a better fit
I havent used AutoResetEvent in a long long time, but for async contexts a Semaphore might be a better primitive since it allows non-blocking wait
put the requests in a queue?
maybe you can checkout the rate limiting
Rate limiting middleware in ASP.NET Core
Learn how limit requests in ASP.NET Core apps
concurrency limiter might be good
or use redis with a key
check for each request if the key exists with a value of true/false
and either stop, or continue your work
You could probably do it without redis and some kind of a threadsafe lock
I'm not sure though
the problem with that approach is that two checks could be happening at the same time so not solving anything
Redis locks should be atomic though, it's designed to be single threaded to avoid collisions
But if you only have one instance then there's probably not much benefit to redis
Because you also don't need the persistence since you can't just restore a request after a crash
this example for concurrency limiter only shows for minimal apis. then how do i do RequireRateLimiter for a controller?
oh nvm
Rate limiting middleware in ASP.NET Core
Learn how limit requests in ASP.NET Core apps