Skip to content

How it works

unicep has two pieces:

  • Provider: the adapter for one CEP service. It makes the HTTP call and converts the response to the Address object.
  • Unicep: takes a list of providers, puts a circuit breaker on each one and tries them one by one until somebody answers.

Your app calls Unicep, which tries Provider 1, then Provider 2 and so on, each with its own circuit breaker, and always returns the same Address object.

  1. The CEP is validated (01310100 or 01310-100). If it is invalid, InvalidCepError is thrown without making any request.
  2. If the cache is on and the CEP is in it, the address comes back immediately.
  3. Providers are tried in the order you passed them. One with an open circuit is skipped.
  4. Each attempt has a timeout. With retry on, the same provider is retried before moving on to the next one.
  5. The first one to answer wins, and the result carries its name in provider.

Each provider has its own circuit breaker, which counts consecutive failures:

State What it means
closed Normal. Requests go through.
open After failureThreshold failures in a row (3 by default), the provider is skipped without making a request.
half-open After resetTimeoutMs (30 seconds by default), one trial request decides whether the circuit closes or opens again.

That way a service that is down does not slow down your lookups: unicep goes straight to the next one.

What happened Counts against the breaker? What unicep does
Network error, timeout, HTTP 5xx or 429, invalid response Yes Tries the next provider
“CEP not found” No Tries the next provider, because coverage differs between services
Cancellation through an AbortSignal No Stops and rejects with the abort reason

If every provider that answered said “not found”, the error is CepNotFoundError. If none could answer, it is AllProvidersFailedError, with one error per provider. See Errors.

unicep.status();
// [
// { name: 'viacep', circuit: 'closed' },
// { name: 'brasilapi', circuit: 'open' },
// ...
// ]

This is what the status page uses to show each provider in real time.