Answer the question
In order to leave comments, you need to log in
How to limit the number of requests per second in a Telegram bot?
Good afternoon.
I have a Telegram bot that gives out bonuses to people. The bonus is issued once a day. In order to receive a bonus, you need to click on the button (it doesn't matter if it's inline or regular). And now cunning people press the button dozens of times in a few seconds and receive not one, but several bonuses as a result.
The function that handles the click looks something like this:
1. Проверить, когда начислялся бонус последний раз
2. Если больше дня назад, то начислить бонус и обновить дату получения
Answer the question
In order to leave comments, you need to log in
You should not "limit the number of requests", but study what the "race condition" is.
I also noticed such a feature of behavior on bots written in Python. But there, most likely, the point is that the updater scatters the processing of incoming updates across threads, and this is where the race condition occurs. Can you look in this direction?
Put the user ID in Redis and put EX for a day :)
When you receive a request for a bonus, check the presence of the user ID in Redis using EXISTS - if not, then you did not receive it within a day. If there is - then received within a day.
It is trite to add a parameter to the session and check its presence.
Before processing the click, set it and check it before accessing the database.
Check, for example, the current date, the date of the last access and calculate the difference in the required amount of time.
Take a queue, let's say RabbitMQ or Kafka. Hang a send handler on the other end and let it check before sending how many messages it sent in the last second. If the limit is exhausted then cooldown. This, of course, will turn out to be a narrow neck, but for most tasks it should be enough. It’s not really necessary to parallel this story because the limits there are not high, but if you really want to, I can suggest completely wild options
Options:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question