Resilient Postal Code Lookup with Automatic API Fallback, Express & Docker
Building an Express + TypeScript service with rate limiting and automatic failover from primary CEP lookup to ViaCEP, paired with React and Docker.
Anyone who builds registration forms or checkouts in Brazil knows that relying on a single public CEP API means users get stuck whenever that upstream service goes down.
In fallback-api-cep (https://github.com/rniguel/fallback-api-cep), I built a clean resilient stack with Express + TypeScript on the backend, React + Vite + shadcn/ui on the frontend, and Docker Compose orchestration.
How the Failover Works
Instead of calling third-party APIs straight from the browser, the client hits our own GET /:cep endpoint guarded by three layers:
1. Rate Limiting (`express-rate-limit`): caps requests at 30 per minute per IP.
2. Validation middleware (`validateCep`): rejects invalid formats before calling external providers.
3. Primary + Fallback providers: calls fetchFromAwesomeCep(cep) first and transparently falls back to fetchFromViaCep(cep) on failure, returning 502 only when both providers fail.
const cepRateLimiter = rateLimit({
windowMs: 60 * 1000,
max: 30,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Muitas requisições. Tente novamente em 1 minuto." },
});
router.get(
"/:cep",
cepRateLimiter,
validateCep,
async (req: Request, res: Response) => {
const { cep } = req.params;
try {
const data = await fetchFromAwesomeCep(cep);
return res.json(data);
} catch {
try {
const fallbackData = await fetchFromViaCep(cep);
return res.json(fallbackData);
} catch {
return res.status(502).json({
error:
"Não foi possível consultar o CEP no momento. Tente novamente mais tarde.",
});
}
}
}
);Normalizing the Response Contract
Because external APIs return different property names, normalizing the payload in the backend keeps the React frontend completely decoupled from whichever upstream provider succeeded.
Final Thoughts
Wrapping external lookups behind a thin, normalized BFF with automatic failover removes a common single point of failure with minimal code.
Miguel Riquelme
Front-end Engineer. Software Engineering MBA student at USP/Esalq.