During an interview, i got this question.
Scenario: In a database table there are entries made for common resources. Lets say column name "token". In total there are 500 tokens. One web app is using this token table. So whenever one user hits the web app URL, one token get assigned to the user. Once token assigned to user, it can not be used by other users. So for another user, if a token shows that already taken, system will try to assign another token and so on.
Problem: Now on given point of time, lets say 600 user hits the web app, how to make sure that only 500 users will get the token, rest 100 will not.
Thank you.
What you need to do is to check whether there is a free token when a request starts, take a token if there is a free one, and release it when work is done. Since the question was about a database, I think it hints at how to achieve atomicity of check and take: use transactions.
For example, you could have table with 500 rows for tokens with a procedure that would select a free token from database and, if there is one, update its row to mark it as taken. This procedure would be run in a transaction. If it ends with no free token available, then the serving thread would wait and try again after a short period of time. Releasing the token is again a trivial update of a row.
Another option would be starting with an empty table and taking a token by inserting a new row. Again, checking that there are <= 500 rows and inserting a new one must be run in a transaction to ensure atomicity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With