I am building an offline-first mobile app that synchronises its data to a nodejs server. (I am using graphql with Apollo server if its relevant). The mobile app stores a queue of mutations that were made while it was offline and when it goes online, it sends all the mutations to the server. They are sent in the correct order thanks to apollo-link-serialize, but they don’t wait for the previous mutation to finish.
If I make an object while offline and then change one of its properties, sometimes the server processes the change mutation before the create mutation, resulting in an error.
I am looking for a way to make the server process requests from a single user serially, not in parallel.
I could just make a global variable where I would manually queue requests from each user and execute them only when the previous one finishes, but it doesn’t sound like the proper solution.
>Solution :
It sounds like you should perhaps create a work-queue per user so you can process requests related to a particular user in FIFO order. The work-queue can just be an array of objects where each object describes a request (desired action, associated data, parameters, etc…).
Whenever a request comes in for a user, you check if there’s a queue for that user already. If so, add the request to the end of the queue. If not, create the queue and start working on that first request.
Whenever you finish a request, remove it from the queue and see if there are any other requests in that user’s queue. If so, you grab the next one and start processing it. If not, remove the queue.
The queue could be in the user’s server-side session so it’s easy to associate with the user.
For completeness, you may have to handle the case of multiple browsers accessing the server on behalf of the same user. You can either prevent that situation entirely (logging out other sessions for that user) or you have to share the same server-side session among all clients representing the same user.