#Route handler with locks

1 messages · Page 1 of 1 (latest)

trim agate
#

What would be the most lightstarry way of blocking a selection of route handlers from concurrent execution?

latent krakenBOT
#
Notes for Route handler with locks
At your assistance

@trim agate

No Response?

If no response in a reasonable time, ping @Member.

Closing

To close, type !solve or byte solve.

MCVE

Please include an MCVE so that we can reproduce your issue locally.

south fable
#

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

trim agate
#

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

south fable
#

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

trim agate
#

I mean the litestar-specific part 🙂
I was wondering if I should use guard or a dependency

south fable
#

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

trim agate
#

you want my users to talk to each other and agree who is waiting for whom? 😄

south fable
south fable
#

I'm saying put the lock in service.write_data

trim agate
#

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

south fable
#

No, it does not

#

It will raise an exception if the lock cannot be acquired

#

That's what blocking=False does

#

It causes it to not block 😉