M
M
mitaichik2017-08-18 02:10:48
MySQL
mitaichik, 2017-08-18 02:10:48

How to lock row in db while reading?

Hello!
There is a table, for example, of generated promotional codes. When registering a user, I need to give him a free promotional code, and mark in the table of promotional codes that he is already taken by this user.
Problems arise when several users register at the same time - a situation is possible when they simultaneously receive the same promotional code, and the last user registers in the promotional code itself.
How to avoid this?
I see several solutions, but all of them are kind of clumsy: use redis with its incr which contains the id of the next free promotional code (they are auto-increment), you can make a queue with one worker to receive a free promotional code, you can generally create a separate fpm pool with a single php-fpm process (this is sadomaso of course) or limit the queue for a user registration request in nginx.
But surely there is some simple way?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2017-08-18
@mitaichik

why generate them in advance at all?
You can make a little bit random generator during registration and the promo code is ready.
If you discard the options from the category promo_code_{user_id}
Well, or select select for update to lock the line
https://dev.mysql.com/doc/refman/5.7/en/innodb-loc...
but this is an option through the ass as a whole -then.

S
SagePtr, 2017-08-18
@SagePtr

As an option, first mark the nearest free promotional code, and only then read it and give it to the user.

H
Hatik, 2017-08-18
@Hatik

Maybe the Before Update trigger will do? in the promotional code, look for the presence of the user, if there is, then make the select again and issue another promotional code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question