The idea is the following:
2 or more users request at the same time to create a resource.
I want the code to handle those requests like this: . add users to a queue and order them by timestamp. . create user resource (ONE USER AT A TIME TO AVOID DUPLICATES). . free user and then repeat the process with next user.
I've been thinking on using Socket or Atomic Locks but I'm not sure how to do it.
CodePudding user response:
I can think of 2 approaches to solve this problem:
User does not need the result of whatever you are doing in one request-response cycle:
- Make a unique Laravel job (under the hood unique jobs use atomic locks in databases like redis or memcahced)
- Return some promise as the response(What HTTP 202 status is meant for)
- When the job is done send some notification(Maybe use websockets) to the user. Alternatively polling is an option.
User needs the result of the action in the response but can wait for other users to finish what they are doing:
I can see this happening when you have a document on which multiple users are collaborating on and you don't want them accidentally overriding each others edits and you cant be bothered to use some sort of diffing like diff-match-patch to allow real-time collaboration.
- Implement a custom lock in redis(https://redis.io/docs/manual/patterns/distributed-locks/). Don't forget a reasonable lifetime so you don't run into a deadlock.
- On request check the lock if it is available, lock it, do whatever you have to do and when you are finished unset the lock. If the lock is not available either tell the user to wait and try again or just delay the request(using sleep). The second option is not ideal, don't use it unless you really have to.