I
I
ivandao2021-04-08 13:11:56
Software design
ivandao, 2021-04-08 13:11:56

How to deal with a large number of requests?

The user has a certain amount of funds in the database. At the request of the front, you increase this amount by 10 rubles and you cannot increase it more, but if you immediately execute 1000 requests by the bot, the amount will increase by 10 thousand rubles and will be closed only after some time. How to fix it?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Dmitry Shitskov, 2021-04-08
@Zarom

Use a transaction and take a table row write lock before incrementing the value

S
StiflerProger, 2021-04-08
@StiflerProger

Simply do each request in transaction with "select for update".
1. Immediately after receiving the request, you put the "select for update" block.
2. You validate the data. You check the payment in another table, etc.
3. You add 10 rubles to the user.
If your user can even after that add 100 rubles to himself 1000 times, then the problem is in step #2.
Those. your moment with "it cannot be increased more" should be checked in step #2.

D
Developer, 2021-04-08
@samodum

but if the bot immediately executes 1000 requests, then the amount will increase by 10 thousand rubles

This is possible if the code was written by a junior and poured into a product without a lead review. But if a junior has such rights to CI / CD, then there are questions for management and admins

I
Ivan Shumov, 2021-04-08
@inoise

Queues. Essentially there are 2 options:

  • Simple. We create a queue and process all operations sequentially in it with one handler without scaling. Suitable for starting at light loads
  • Complicated. To the simple version, we add the Kafka word and partitioning by the client key so that commands from one client fall into one topic partition. You need to have more experience, but it scales well on large volumes

S
Sergey Sokolov, 2021-04-08
@sergiks

add a sign / column to the database "can not be updated anymore".
When updating, check this sign and set it to the “basta” position:

UPDATE accounts 
SET money = money + 10, isUpdateable = false
WHERE id = :uid 
  AND isUpdateable = true
A successful update closes the shop.
In the question, it was worth clarifying, of course, what kind of "base" is - all of a sudden it's not SQL, but a Redis cluster on many nodes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question