The post has been translated automatically. Original language: Russian
The buyer clicks "Pay". The loading wheel turns for 20 seconds. He presses it again. Two debit notifications arrive a minute later. The store sees one order, the bank sees two payments, and support receives an angry email.
This is a double write-off. The bank is rarely to blame here. More often, the duplicate is created by the system itself: the application, the network, or its own repeats of the service. Let's look at where it appears and how to stop it in the code.
Where does the double appear
Human repetition. Double click, the "Back" button and resend the form, refresh the page at the payment step. This is the most understandable case, but not the most frequent.
Timeout. The store has sent a request and is waiting for a response for 30 seconds. There is no response, and the code repeats the request. But the first request could have reached the bank and passed. Only the answer was lost. A timeout does not mean a failure. It means "status unknown".
Repeats within the system. In a microservice architecture, services communicate via queues and HTTP clients with automatic replays. Most message brokers guarantee delivery "at least once". This means that sooner or later the payment service will receive the same command "debit 15,000 ₸" twice.
Repetitions are inevitable. You cannot ensure that the request is never repeated. You can make sure that repeating it doesn't change anything. This property is called idempotence: the operation gives one result, no matter how many times you perform it.
The key to idempotence
The client assigns a unique key to each payment attempt and transmits it with the request. Many payment APIs accept it in the Idempotency-Key header. The server operates according to three rules:
- The key arrived for the first time: perform the operation, save the key and the result.
- The key is already there, the operation is completed: return the saved result and do not debit the money again.
- The key is already there, the operation is still in progress: answer "in processing" and do not start the second one.
The customer clicked the button twice and received one receipt. He won't notice anything else.
Where they usually make mistakes
The key is created anew with each request. Then there is no protection. The key must be created once, before the first shipment, and stored together with the payment attempt. It is convenient to link it with the order number and the attempt number.
They do not verify the contents of the request. The same key arrived, but with a different amount. This is not a repeat, but an error in the client's code. The server stores the fingerprint of the request: amount, currency, recipient. If there is a mismatch, it returns an error, not the old response.
The race of two queries. Two identical requests arrived with a difference of 5 milliseconds. Both checked the database and did not find the key. Both went to copy. Checking the key and writing it must be a single atomic operation: a unique index in the database or a lock. The second request receives the response "already being processed".
They remember a temporary error. The server has saved the response "no connection to the bank" and returns it for all replays. The payment is stuck forever. You need to save the final result. It is better not to remember a temporary error so that the replay can pass.
The key lives too little. The mobile application can repeat the request in a few minutes when the connection returns. The key retention period must cover all replay scenarios. These are usually hours, not seconds.
The key is at every joint
The payment goes through a chain: the application, the store's server, the payment provider, the store's bank, the payment system, and the buyer's bank. The key protects only the joint where it is being checked. The store's server may be idempotent. However, if the request to the provider is repeated without a key during the timeout, a duplicate will appear at a lower level.
Therefore, each participant passes on their unique transaction number to the next one. You can only repeat the request with the same number. Sometimes the next participant does not know how to recognize repetitions. Then, before repeating, you need to request the operation status by number. If the money is debited, you cannot repeat it. If the operation is not found, you can.
What to do if the status is unknown
- Do not repeat the write-off blindly.
- Request the status by operation number. If there is no response, repeat the status request after a pause.
- Show the honest status of "payment is being verified" to the buyer. The error message prompts him to pay again, for example with another card.
- Rely on daily reconciliation. She catches what online checks have missed and finds duplicates by order number and amount.
- To cancel or return the found duplicate automatically. Do not wait for the customer's complaint.
Two write-offs that didn't happen
Sometimes they managed to cancel the double, but the buyer still sees two amounts in the banking application. The second amount is a lock on a cancelled operation. The buyer's bank will withdraw it later, the timing depends on the bank. It is useful for the store's support to know this difference. Then she won't make an unnecessary refund and create a new discrepancy.
A short checklist for the developer
- Block the payment button after clicking. This removes some of the duplicates, but does not solve the network problem.
- Create an idempotence key once per payment attempt.
- Store the key, the fingerprint of the request, and the final result.
- Check and write the key atomically.
- Consider the timeout to be an unknown status, not a failure.
- Request the status before repeating to the external system if it does not recognize repetitions by itself.
- Make message handlers from the queue idempotent: one event can arrive twice.
- Perform reconciliation every day and disassemble duplicates automatically.
Double write—off is the usual behavior of a distributed system without idempotence. At the start of the project, protection costs one table and several checks. Once launched, duplicates cost money, support time, and customer trust.
Покупатель нажимает «Оплатить». Колесо загрузки крутится 20 секунд. Он нажимает ещё раз. Через минуту приходят два уведомления о списании. Магазин видит один заказ, банк видит два платежа, поддержка получает злое письмо.
Это двойное списание. Банк здесь виноват редко. Чаще дубль создаёт сама система: приложение, сеть или собственные повторы сервиса. Разберём, где он появляется и как его остановить в коде.
Где появляется дубль
Повтор со стороны человека. Двойной клик, кнопка «Назад» и повторная отправка формы, обновление страницы на шаге оплаты. Это самый понятный случай, но не самый частый.
Таймаут. Магазин отправил запрос и ждёт ответа 30 секунд. Ответа нет, и код повторяет запрос. Но первый запрос мог дойти до банка и пройти. Потерялся только ответ. Таймаут не значит отказ. Он значит «статус неизвестен».
Повторы внутри системы. В микросервисной архитектуре сервисы общаются через очереди и HTTP-клиенты с автоматическими повторами. Большинство брокеров сообщений гарантирует доставку «хотя бы один раз». Значит, сервис оплаты рано или поздно получит одну и ту же команду «списать 15 000 ₸» дважды.
Повторы неизбежны. Нельзя добиться, чтобы запрос никогда не повторялся. Можно добиться, чтобы повтор ничего не менял. Это свойство называют идемпотентностью: операция даёт один результат, сколько раз её ни выполняй.
Ключ идемпотентности
Клиент присваивает каждой попытке оплаты уникальный ключ и передаёт его с запросом. Многие платёжные API принимают его в заголовке Idempotency-Key. Сервер работает по трём правилам:
- Ключ пришёл впервые: выполнить операцию, сохранить ключ и результат.
- Ключ уже есть, операция завершена: вернуть сохранённый результат и не списывать деньги повторно.
- Ключ уже есть, операция ещё идёт: ответить «в обработке» и не запускать вторую.
Покупатель нажал кнопку дважды и получил один чек. Больше он ничего не заметит.
Где обычно ошибаются
Ключ создают заново при каждом запросе. Тогда защиты нет. Ключ нужно создать один раз, до первой отправки, и хранить вместе с попыткой оплаты. Удобно связать его с номером заказа и номером попытки.
Не сверяют содержимое запроса. Пришёл тот же ключ, но с другой суммой. Это не повтор, а ошибка в коде клиента. Сервер сохраняет отпечаток запроса: сумму, валюту, получателя. При несовпадении он возвращает ошибку, а не старый ответ.
Гонка двух запросов. Два одинаковых запроса пришли с разницей в 5 миллисекунд. Оба проверили базу и не нашли ключ. Оба пошли списывать. Проверка ключа и его запись должны быть одной атомарной операцией: уникальный индекс в базе или блокировка. Второй запрос получает ответ «уже обрабатывается».
Запоминают временную ошибку. Сервер сохранил ответ «нет связи с банком» и отдаёт его на все повторы. Платёж застревает навсегда. Сохранять нужно итоговый результат. Временную ошибку лучше не запоминать, чтобы повтор мог пройти.
Ключ живёт слишком мало. Мобильное приложение может повторить запрос через несколько минут, когда вернётся связь. Срок хранения ключа должен перекрывать все сценарии повторов. Обычно это часы, а не секунды.
Ключ на каждом стыке
Платёж проходит цепочку: приложение, сервер магазина, платёжный провайдер, банк магазина, платёжная система, банк покупателя. Ключ защищает только тот стык, где его проверяют. Сервер магазина может быть идемпотентным. Но если запрос к провайдеру при таймауте повторяется без ключа, дубль появится уровнем ниже.
Поэтому каждый участник передаёт следующему свой уникальный номер операции. Повторять запрос можно только с тем же номером. Иногда следующий участник не умеет распознавать повторы. Тогда перед повтором нужно запросить статус операции по номеру. Если деньги списаны, повторять нельзя. Если операция не найдена, можно.
Что делать, если статус неизвестен
- Не повторять списание вслепую.
- Запросить статус по номеру операции. Если ответа нет, повторить запрос статуса через паузу.
- Показать покупателю честный статус «платёж проверяется». Сообщение об ошибке подталкивает его оплатить ещё раз, например другой картой.
- Опираться на ежедневную сверку. Она ловит то, что пропустили онлайн-проверки, и находит дубли по номеру заказа и сумме.
- Найденный дубль отменять или возвращать автоматически. Не ждать жалобы покупателя.
Два списания, которых не было
Иногда дубль успели отменить, а покупатель всё равно видит в банковском приложении две суммы. Вторая сумма — это блокировка по отменённой операции. Банк покупателя снимет её позже, сроки зависят от банка. Поддержке магазина полезно знать эту разницу. Тогда она не сделает лишний возврат и не создаст новое расхождение.
Короткий чек-лист для разработчика
- Блокировать кнопку оплаты после нажатия. Это убирает часть дублей, но не решает проблему сети.
- Создавать ключ идемпотентности один раз на попытку оплаты.
- Хранить ключ, отпечаток запроса и итоговый результат.
- Проверять и записывать ключ атомарно.
- Считать таймаут неизвестным статусом, а не отказом.
- Запрашивать статус перед повтором к внешней системе, если она сама не распознаёт повторы.
- Делать идемпотентными обработчики сообщений из очереди: одно событие может прийти дважды.
- Проводить сверку каждый день и разбирать дубли автоматически.
Двойное списание — обычное поведение распределённой системы без идемпотентности. На старте проекта защита стоит одной таблицы и нескольких проверок. После запуска дубли стоят денег, времени поддержки и доверия покупателей.
Comments 0
Newest Popular