Video in progress
An external provider like SMS or payments is unreliable. How do you design failover, limits and cost across several providers?
I hide the providers behind a single internal interface, each with its own timeout, circuit breaker and quota; routing rules live in configuration. The hardest part is the "unknown outcome": sending an operation that timed out to another provider produces a duplicate, so the failover rule depends on the type of operation.
📖 Answer
Failover is relatively simple for SMS and dangerous for payments: the difference is the price of a duplicate. An OTP SMS that arrives twice is a small inconvenience. Money charged twice through two providers is an incident.
The architecture:
public interface SmsGateway {
SendResult send(SmsMessage message); // message.id is the idempotency key
}
class RoutingSmsGateway implements SmsGateway {
private final ProviderRouter router;
@Override
public SendResult send(SmsMessage m) {
for (ProviderAdapter p : router.candidatesFor(m)) { // by operator, price, health
if (p.breakerOpen() || !p.quota().tryAcquire()) continue;
try {
return p.send(m);
} catch (ProviderUnavailable e) {
continue; // couldn't connect: the next one is safe
} catch (ProviderTimeout e) {
if (m.duplicateTolerable()) continue; // OTP: a duplicate is minor harm
return SendResult.unknown(p, m); // otherwise it goes to reconciliation
}
}
return SendResult.failed(m);
}
}
The main decisions:
-
Result types. "Successful", "definitely rejected" (validation, balance: another provider will often reject it too, so failover is useless), "provider isn't working" (couldn't connect: moving to the next one is safe) and "unknown" (a timeout after the request went out). The unknown state goes to reconciliation: the status is queried from the provider or a webhook is awaited.
-
Health and routing. A circuit breaker and a business-outcome metric per provider: for SMS the share of delivery reports, for payments the share of confirmations. A provider can return "200 OK" and still not deliver the SMS, so health is judged by the outcome, not the HTTP response.
-
Quota and price. The contractual limits (N per second) are counted not locally but with a centralized limiter, because 20 pods send together. The cheap provider is primary and the expensive one is the backup; for some operators only one provider delivers. These rules are in configuration, not in code.
-
A queue. Only urgent messages like OTPs go on the synchronous path. The rest go through a queue: even if every provider is down, messages aren't lost and are sent later.
-
Accounting: which provider each message or payment went through is stored, for monthly invoices and disputes.
In payments, switching providers often involves the customer (another payment method is offered), not automatic. That is a product decision, but the architect should be the one to propose it.
Sign up to mark studied questions and save your progress.