#Route handler with locks
1 messages · Page 1 of 1 (latest)
@trim agate
If no response in a reasonable time, ping @Member.
To close, type !solve or byte solve.
Please include an MCVE so that we can reproduce your issue locally.
That depends what you want to achieve
I'm assuming preventing requests being processed in parallel isn't your end goal, so a few more details would be needed to answer this
It's a different thing for example if you want to do something like rate limiting, or preventing race conditions
Also depends if this needs to work in a distributed environment
I literally want to to prevent some of my route handlers from running in parallel 😄
they're writing to a 3rd party service and the access needs to be serialized, otherwise the functions step on each other toes
and I want the method fail instead of wait, so that users know what's happening
That sounds like it's potentially a huge bottleneck if you don't buffer these writes then
Anyway. That's not really Litestar specific, and I'd just use a distributed lock
e.g. with redis
@post("/")
async def handler(data: bytes, redis: Redis) -> Any:
async with redis.lock("write-lock-for-the-thing", blocking=False):
await service.write_data(data)
You can of course abstract this away with a dependency if you want, but I personally would go for the explicitness here
I mean the litestar-specific part 🙂
I was wondering if I should use guard or a dependency
Actually, this should probably just be part of the thing that writes to your 3rd party service
That way it's not the callers responsibility to ensure concurrency is handled correctly
you want my users to talk to each other and agree who is waiting for whom? 😄
As I said, I don't think that's the right approach but yeah, you could do this with a guard or something if you wanted to?
Simply put the lock snippet I posted in a guard 🤷
No
I'm saying put the lock in service.write_data
the async with will cause it to block, I want it to fail, so there are a few lines of code I don't want to duplicate