Reputation: 1511
I have an application that has a credit-based usage system. However with my current structure, if the user makes 2 requests in a small enough window, he can get both of these requests through and this results in a faulty system and user having minus credit value since his credits get decremented twice when the second request shouldn't have been allowed.
I wanted to make sure that a single user can only have a single request running at a given time, I tried to use express-rate-limit but that didn't fit my use case since these requests are made by google cloud functions I have set up and not the user himself.
However, I have specific user ids identifying these requests so I could have user-id specific queues that process a single user's requests one by one.
Would this be an appropriate and scalable design addressing the credit usage issue or are there better alternatives?
Upvotes: 0
Views: 2093
Reputation: 317362
You will need to use an atomic operation with whatever underlying data store you use. Since you haven't said what that is, it's not possible to give specific advice about how to proceed. Most databases provide a way to use a "transaction" that lets updates succeed only if certain criteria are met. You will want to use one of these transactions to determine if the client should be able to proceed with the update.
There is really no easy way to make Cloud Functions limit the call rate of the function, per user, in a way that scales well. This is really about the underlying storage mechanism allowing too many concurrent requests. If you didn't have to scale up the number of users, you could use Cloud Tasks to implement a queue per user, but I don't think that's really the best solution here.
Upvotes: 1