The post has been translated automatically. Original language: Russian
In payment systems , any error in synchronous or asynchronous communication is expensive: stalled transactions, duplicate debits, status discrepancies, and support tickets. Therefore , the boundary between modules is not just a choice of protocol, but an architectural decision based on consistency, latency, and fault tolerance.
Let's look at what should happen strictly at the time of payment, and what should be put in the queue and events.
When choosing synchronous interaction
A synchronous call (REST, gRPC) is justified where the user or the calling service cannot move on without an immediate response and we are ready to wait for it within a strict timeout.:
Validation and initial verification: checking limits, real-time anti-fraud screening, checking the availability of the payment method.
Authorization/ holding of funds (if the provider responds quickly and predictably) or fixing the payment Intent in the core of the system.
Short read operations: Getting payment status, balance, or transaction details for the checkout screen.
The main risk of the synchronous path is cascading failures and blurring timeouts. If the external provider responds in 4 seconds and your timeout is 3 seconds, the money could have already been debited, but the client will receive an error.
When we go into asynchrony
An asynchronous model (message brokers, queues, webhooks, background workers) is needed where the operation is long, unreliable, or does not require blocking the client thread.:
Communication with external acquirers and banks: network delays, retrays, 3DS/redirects, asynchronous final status webhooks.
Post-processing and side effects: sending receipts and fiscalization (if the scenario and regulatory requirements allow the receipt to be generated in the background), notifications, updating analytics, accrual of cashback and bonuses, order delivery trigger.
Reconciliation reconciliation, refunds, and deferred charges: processes that must be guaranteed to complete, even if one of the related services is temporarily unavailable.
Where is the practical boundary
The working rule for the payment core is to separate "decision making and state fixation" and "execution in the outside world":
We synchronously record the intent and status: we create a payment with the PENDING or CREATED status in our Database, check the basic invariants and return a quick response to the calling service. (or we move the client to the next step).
We asynchronously move the payment through the lifecycle: the worker picks up the task from the queue, contacts the provider, processes the delays and transfers the status through PROCESSING to the final one SUCCEEDED or FAILED.
Events are sent out through the outbox and asynchronously: when the status has changed, the rest of the domains (orders, billing, notifications) will learn about it from the events, and not through a chain of synchronous requests.
Checklist: it's time to break the synchronous bundle and move on to events
A revision of the architecture is needed if at least 2-3 points coincide.:
There are more than two consecutive synchronous calls between internal services in a single payment chain.
The response time of an external bank or acquirer is unstable and regularly runs into a timeout.
The fall of a secondary module (for example, notifications or a bonus program) breaks the main payment scenario.
As the load increases, the number of suspended transactions or manual analysis of discrepancies increases.
Several independent domains need the same payment fact at once.
What kind of rake appears when switching to events
Asynchrony takes the load off the synchronous circuit, but brings new reliability requirements.:
Idempotence: a message from a broker or a webhook from a bank can arrive twice. Without idempotency There is a high risk of making a double debit, refund, or bonus accrual at the database level.
Delivery procedure (out-of-order): the SUCCEEDED event may arrive before PROCESSING, and cancellation may arrive before confirmation. The status state machine must be able to correctly reject or survive outdated events.
Loss of events between DB and broker: if you update the payment status in the database, but do not have time to send the event to the queue in case of a network outage, adjacent services will not know about the payment. The Transactional Outbox pattern saves here.
A question for colleagues from fintech and the backend: what did you encounter more often in practice — cascading timeouts on synchronous calls or duplicates and a violation of the order of events after switching to queues?
В платёжных системах любая ошибка в синхронной или асинхронной связи стоит дорого: зависшие транзакции, дубли списаний, расхождение статусов и тикеты в поддержку. Поэтому граница между модулями — это не просто выбор протокола, а архитектурное решение, завязанное на требования к консистентности, latency и отказоустойчивости.
Разберём, что должно происходить строго в момент оплаты, а что стоит уносить в очереди и события.
Когда выбираем синхронное взаимодействие
Синхронный вызов (REST, gRPC) оправдан там, где пользователь или вызывающий сервис не может двигаться дальше без немедленного ответа и мы готовы ждать его в рамках строгого таймаута:
Валидация и первичная проверка: проверка лимитов, антифрод-скрининг в реальном времени, проверка доступности платёжного метода.
Авторизация / холдирование средств (если провайдер отвечает быстро и предсказуемо) либо фиксация намерения платежа (Payment Intent) в ядре системы.
Короткие операции чтения: получение статуса платежа, баланса или деталей транзакции для экрана checkout.
Главный риск синхронного пути: каскадные отказы и размытие таймаутов. Если внешний провайдер отвечает 4 секунды, а ваш таймаут — 3 секунды, деньги могли уже списаться, но клиент получит ошибку.
Когда уходим в асинхронность
Асинхронная модель (брокеры сообщений, очереди, webhooks, фоновые воркеры) нужна там, где операция долгая, ненадёжная или не требует блокировки клиентского потока:
Общение с внешними эквайерами и банками: сетевые задержки, ретраи, 3DS/редиректы, асинхронные вебхуки о финальном статусе.
Постобработка и побочные эффекты: отправка чеков и фискализация (если сценарий и регуляторные требования позволяют формировать чек в фоне), уведомления, обновление аналитики, начисление кэшбэка и бонусов, триггер доставки заказа.
Сверки (reconciliation), возвраты (refunds) и отложенные списания (capture): процессы, которые должны гарантированно завершиться, даже если один из смежных сервисов временно недоступен.
Где проходит практическая граница
Рабочее правило для платёжного ядра — разделять «принятие решения и фиксацию состояния» и «исполнение во внешнем мире»:
Синхронно фиксируем намерение и состояние: создаём платёж со статусом PENDING или CREATED в своей БД, проверяем базовые инварианты и возвращаем быстрый ответ вызывающему сервису (или переводим клиента на следующий шаг).
Асинхронно двигаем платёж по жизненному циклу: воркер забирает задачу из очереди, обращается к провайдеру, обрабатывает ретраи и переводит статус через PROCESSING в финальный SUCCEEDED или FAILED.
События наружу — через outbox и асинхронно: когда статус изменился, остальные домены (заказы, биллинг, уведомления) узнают об этом из событий, а не через цепочку синхронных запросов.
Чек-лист: пора разрывать синхронную связку и переходить на события
Пересмотр архитектуры нужен, если совпадает хотя бы 2–3 пункта:
В цепочке одного платежа больше двух последовательных синхронных вызовов между внутренними сервисами.
Время ответа внешнего банка или эквайера нестабильно и регулярно упирается в таймаут.
Падение второстепенного модуля (например, уведомлений или бонусной программы) ломает основной сценарий оплаты.
При росте нагрузки растёт число зависших транзакций или ручных разборов расхождений.
Один и тот же факт оплаты нужен сразу нескольким независимым доменам.
Какие грабли появляются при переходе на события
Асинхронность снимает нагрузку с синхронного контура, но приносит новые требования к надёжности:
Идемпотентность: сообщение из брокера или вебхук от банка могут прийти дважды. Без idempotency key и защиты на уровне БД велик риск сделать дубль списания, возврата или начисления бонусов.
Порядок доставки (out-of-order): событие SUCCEEDED может прийти раньше PROCESSING, а отмена — раньше подтверждения. Конечный автомат статусов должен уметь корректно отклонять или переживать устаревшие события.
Потеря событий между БД и брокером: если обновить статус платежа в базе, но не успеть отправить событие в очередь при сбое сети, смежные сервисы не узнают об оплате. Здесь спасает паттерн Transactional Outbox.
Вопрос к коллегам из финтеха и бэкенда: с чем на практике сталкивались чаще — с каскадными таймаутами на синхронных вызовах или с дублями и нарушением порядка событий после перехода на очереди?
Comments 0
Newest Popular