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
Addressobject. Unicep: takes a list of providers, puts a circuit breaker on each one and tries them one by one until somebody answers.
The path of a lookup
Section titled “The path of a lookup”- The CEP is validated (
01310100or01310-100). If it is invalid,InvalidCepErroris thrown without making any request. - If the cache is on and the CEP is in it, the address comes back immediately.
- Providers are tried in the order you passed them. One with an open circuit is skipped.
- Each attempt has a timeout. With retry on, the same provider is retried before moving on to the next one.
- The first one to answer wins, and the result carries its name in
provider.
Circuit breaker
Section titled “Circuit breaker”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 counts as a failure
Section titled “What counts as a failure”| 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.
Circuit state
Section titled “Circuit state”unicep.status();// [// { name: 'viacep', circuit: 'closed' },// { name: 'brasilapi', circuit: 'open' },// ...// ]This is what the status page uses to show each provider in real time.