The post has been translated automatically. Original language: Russian
The request frequency limit usually appears in a hurry, after the first time when one customer posted the service. They take a round threshold, apply it to everyone, and after a week they deal with the complaints of those who are not to blame for anything.
Where they make mistakes when setting up
- The threshold is selected without data. No one has looked at the actual distribution of requests, so the limit either fails or cuts off normal work.
- The restriction applies to the address, not the client. One corporate client behind a shared address blocks the rest of the employees.
- One limit for all methods. Cheap reading and a heavy report cost differently, but they have the same quota.
- There is no useful information in the response. The client gets rejected and does not know how long to wait, so repeats immediately.
- Internal calls fall under the same limit. Own services are falling off, not external clients.
What to do
- Count the threshold from the actual load. Take a high percentile of regular traffic and leave a margin.
- Limit by client ID or access key. The address is the last option when there is nothing else.
- Divide the limits by the cost of operations. Heavy requests have a separate and smaller quota.
- In the rejection response, specify the time until the next attempt. This reduces the number of pointless repetitions more than any persuasion.
- First, turn on the monitoring mode. Count the exceedances without blocking and see who would have gone under the knife.
- Allow short bursts. A minute limit with a one-second burst tolerance cuts off the attack, but does not interfere with normal operation.
Result
Limiting the frequency of requests protects not only the service, but also the clients from each other. It works when the threshold is justified by the data, linked to the client and explains to him what to do next. Otherwise, it's just a way to turn an overload into a flood of support calls.
Do you roll out new limits in the monitoring mode or turn on the lock immediately?
Ограничение частоты запросов обычно появляется в спешке, после первого случая, когда один клиент выложил сервис. Порог берут круглый, применяют ко всем, и через неделю разбираются с жалобами тех, кто ни в чём не виноват.
Где ошибаются при настройке
- Порог выбран без данных. Никто не смотрел на фактическое распределение запросов, поэтому лимит либо не срабатывает, либо режет обычную работу.
- Ограничение применяется к адресу, а не к клиенту. Один корпоративный клиент за общим адресом блокирует остальных сотрудников.
- Один лимит на все методы. Дешёвое чтение и тяжёлый отчёт стоят по-разному, а квота у них одна.
- В ответе нет полезной информации. Клиент получает отказ и не знает, сколько ждать, поэтому повторяет сразу же.
- Внутренние вызовы попадают под тот же лимит. Отваливаются собственные сервисы, а не внешние клиенты.
Что делать
- Считайте порог от реальной нагрузки. Возьмите высокий перцентиль обычного трафика и оставьте запас.
- Ограничивайте по идентификатору клиента или ключу доступа. Адрес это последний вариант, когда ничего другого нет.
- Разделите лимиты по стоимости операций. Тяжёлым запросам отдельная и меньшая квота.
- В ответе об отказе указывайте время до следующей попытки. Это снижает число бессмысленных повторов сильнее любых уговоров.
- Сначала включайте режим наблюдения. Считайте превышения без блокировок и посмотрите, кто попал бы под нож.
- Разрешите короткие всплески. Лимит на минуту с допуском на секундный всплеск отсекает атаку, но не мешает нормальной работе.
Итог
Ограничение частоты запросов защищает не только сервис, но и клиентов друг от друга. Работает оно тогда, когда порог обоснован данными, привязан к клиенту и объясняет ему, что делать дальше. Иначе это просто способ превратить перегрузку в поток обращений в поддержку.
А вы обкатываете новые лимиты в режиме наблюдения или включаете блокировку сразу?