The post has been translated automatically. Original language: Russian
A typical picture: the user makes an application, clicks "Submit", and the page thinks. He presses it again. Then he refreshes the page. As a result, there are three identical requests in the system, the manager calls the client three times, and if it was a payment, the money is debited twice. The user didn't do anything wrong: he just didn't wait for a response.
Duplicates don't just appear because of impatient people. The mobile Internet disappeared for a second, and the application repeated the request itself. The service crashed before it could respond, and the caller sent the request again. We generally cannot guarantee that each request will arrive exactly once. But we can make sure that repetition does not create anything new. This property is called idempotence: no matter how many times you perform the operation, the result will be the same as after the first time.
We give each request a key
Before submitting the form, the client — browser or application — generates a unique key, a random string like a7f3-91c2. This key goes away with the request and does not change during repetitions. Upon receiving the request, the server first checks whether there has already been such a key. If not, it processes and remembers the key along with the response. If it was, it does not create anything and returns the same response as the first time.
Storing the key along with the result
The key and the result are recorded in the database in the same transaction as the application itself. A transaction is a group of actions that is performed entirely or not at all. If you write down the request and save the key in a separate step, there may be a failure exactly between them — and when we repeat, we will create a duplicate. Plus, we put a unique restriction on the key in the database: even if two identical requests arrive at the same time, the second one simply will not be able to register.
Dealing with "still at work"
It happens that a replay arrives while the first request is still being processed. There is no answer yet, there is nothing to give. In this case, we do not start processing a second time, but respond: "The request is already being processed, try it in a couple of seconds." The client will wait and receive the finished result. It is important that the client understands this response as a request to wait, and not as an error, otherwise it will show the user a red message "something went wrong".
We also help with the interface
Protection on the server is the main thing, but the interface can also help. After clicking, the button becomes inactive and shows "Sending...". This removes most of the accidental double clicks. But we don't rely on the interface alone: the request can be repeated by the network, application, or other service, and the button won't help.
Do not confuse a repeat with a new operation.
The key is linked to a specific action, not to the user. If a person consciously submits a second request, for example, for a different amount, this is a new operation with a new key. And if other data came with the same key, this is a client error, and we return it, rather than quietly choosing one of the options.
Where are we staying
We don't keep the keys forever: after a day or two, a repeat is unlikely, and we delete the old records so that the table doesn't grow indefinitely. We do not make keys for operations that are already safe: reading data or writing "set status X" gives the same result for any number of calls. We put full protection where duplication is expensive: payments, requests, sending documents, and notifying clients.
Bottom line: there will always be repeated requests due to people, network, and disruptions. Idempotence does not eliminate repetitions, but makes them harmless. One key per operation and one transaction, and a triple click turns into one request.
And how do your team protect themselves from duplicates — on the server, in the interface, or not yet?
Типичная картина: пользователь оформляет заявку, нажимает «Отправить», а страница думает. Он нажимает ещё раз. Потом обновляет страницу. В итоге в системе три одинаковые заявки, менеджер звонит клиенту трижды, а если это был платёж — деньги списаны дважды. Пользователь ничего плохого не сделал: он просто не дождался ответа.
Дубли появляются не только из-за нетерпеливых людей. Мобильный интернет пропал на секунду, и приложение само повторило запрос. Сервис упал, не успев ответить, и вызывающая сторона отправила запрос снова. Мы вообще не можем гарантировать, что каждый запрос придёт ровно один раз. Зато можем сделать так, чтобы повтор не создавал ничего нового. Это свойство называется идемпотентностью: сколько раз ни выполни операцию, результат будет как после первого раза.
Даём каждому запросу ключ
Перед отправкой формы клиент — браузер или приложение — генерирует уникальный ключ, случайную строку вроде a7f3-91c2. Этот ключ уходит вместе с запросом и не меняется при повторах. Сервер, получив запрос, сначала проверяет: был ли уже такой ключ? Если нет — обрабатывает и запоминает ключ вместе с ответом. Если был — ничего не создаёт и возвращает тот же ответ, что и в первый раз.
Храним ключ вместе с результатом
Ключ и результат записываем в базу в одной транзакции с самой заявкой. Транзакция — это группа действий, которая выполняется целиком или не выполняется вовсе. Если записать заявку, а ключ сохранить отдельным шагом, может случиться сбой ровно между ними — и при повторе мы создадим дубль. Плюс ставим на ключ уникальное ограничение в базе: даже если два одинаковых запроса придут одновременно, второй просто не сможет записаться.
Разбираемся с «ещё в работе»
Бывает, что повтор приходит, пока первый запрос ещё обрабатывается. Ответа пока нет, отдавать нечего. В этом случае не запускаем обработку второй раз, а отвечаем: «Запрос уже обрабатывается, попробуйте через пару секунд». Клиент подождёт и получит готовый результат. Важно, чтобы клиент понимал этот ответ как просьбу подождать, а не как ошибку, — иначе он покажет пользователю красное сообщение «что-то пошло не так».
Помогаем и в интерфейсе
Защита на сервере — главная, но интерфейс тоже может помочь. После нажатия кнопка становится неактивной и показывает «Отправляем…». Это убирает большую часть случайных двойных кликов. Но только на интерфейс мы не полагаемся: запрос может повторить сеть, приложение или другой сервис, и кнопка тут не поможет.
Не путаем повтор с новой операцией
Ключ привязан к конкретному действию, а не к пользователю. Если человек осознанно отправляет вторую заявку — например, на другую сумму, — это новая операция с новым ключом. А если с тем же ключом пришли другие данные, это ошибка клиента, и мы её возвращаем, а не тихо выбираем один из вариантов.
Где мы останавливаемся
Ключи не храним вечно: через сутки-двое повтор уже маловероятен, и старые записи удаляем, чтобы таблица не росла бесконечно. Не делаем ключи для операций, которые и так безопасны: чтение данных или запись «установить статус X» дают одинаковый результат при любом числе вызовов. Полную защиту ставим туда, где дубль стоит дорого: платежи, заявки, отправка документов, уведомления клиентам.
Итог: повторные запросы будут всегда — из-за людей, сети и сбоев. Идемпотентность не убирает повторы, а делает их безвредными. Один ключ на операцию и одна транзакция — и тройной клик превращается в одну заявку.
А как в вашей команде защищаются от дублей — на сервере, в интерфейсе или пока никак?
Comments 1
Newest Popular