# Limits and errors

> CNPJá API request limits by plan, the 429 error, timeouts, error format and codes, the trace ID and how to retry requests safely without wasting your quota.

The API limits how many requests each organization, by its plan, or each IP address under public access, sends per second and keeps in progress at the same time, sets a maximum duration for each request and answers every failure with a JSON body that always has the same shape. This page describes these limits, what each error code means and how to retry a request without unnecessary consumption. The full technical specification is in [Usage limits](https://cnpja.com/en-us/docs/api/reference#description/usage-limits) and [Error codes](https://cnpja.com/en-us/docs/api/reference#description/error-codes), in the Reference.

Organization limits other than request limits, such as lists and API keys, are in [Usage limits](https://cnpja.com/en-us/docs/billing/limits).

## Usage limits

The API currently applies two request limits, which work together and always share the same value:

- **Requests per second:** counts the requests that arrive in each second, regardless of how long they take.
- **Concurrent requests:** counts the requests in progress. Each one holds a slot from the moment it arrives until its response finishes, so slow operations, such as those that run [live queries](https://cnpja.com/en-us/docs/glossary#consulta-em-tempo-real--live-query), hold their slots longer.

With a key, the value depends on the organization's plan; without a key, it applies to each source IP address:

| Access | Requests per second | Concurrent requests |
|---|---|---|
| Free | 5 | 5 |
| Pro | 50 | 50 |
| Enterprise | As set in the contract, up to 250 | As set in the contract, up to 250 |
| Without a key | 5, per IP address | 5, per IP address |

The effective limit depends on response time: on average, the number of concurrent requests equals the requests per second multiplied by the average response time, in seconds. With responses that take 5 seconds on average, Pro's 50 concurrent requests sustain about 10 per second, and Free's 5, about 1 per second: the concurrency limit is reached well before the per-second limit.

### With a key

Limits belong to the organization: all of its keys and applications share them, across every operation, and having more keys does not raise them, as [Managing API keys](https://cnpja.com/en-us/docs/organizations/api-keys#what-it-is) explains. They follow the plan of the organization's current [usage period](https://cnpja.com/en-us/docs/glossary#período-de-uso--usage-period):

- a Pro awaiting its first payment still has Free's limit, since the plan only takes effect with the payment;
- the organization goes back to Free's limit when it goes back to Free, at the end of a cancelled subscription or through a late plan invoice, as [Late payment](https://cnpja.com/en-us/docs/billing/past-due#downgrade) explains;
- a new limit takes up to 5 seconds to apply.

### Without a key

Limits apply to each source IP address and do not count toward any organization's limits, as [Public API access, no key](https://cnpja.com/en-us/docs/api/public-access) explains.

Requests with a key also count toward the keyless limits of the IP they leave from, although only the organization's limit can reject them. So a keyless request is rejected with `429` once 5 others from the same IP, with or without a key, arrived in the same second or are in progress. If a server already sends requests with a key, use the key on all of them.

## Limit exceeded

A request over a limit is rejected with `429` and is not charged. Its `code` tells which limit was reached:

| Code | Cause | Action |
|---|---|---|
| `RATE_LIMIT_EXCEEDED` | Too many requests in the same second | Wait about a second and spread requests evenly instead of sending them in bursts |
| `CONCURRENCY_LIMIT_EXCEEDED` | Too many requests in progress | Process requests with a fixed number of parallel workers, below the limit, and resend once another request completes |

> **Important:** responses carry no rate limit headers and no `Retry-After`. Control pace and parallelism on the application side, keeping a margin below the limits, as shown in [Pacing](#pacing).

## Timeout and size

Besides the request limits, the API currently sets these duration and size limits:

| Limit | Value | When exceeded |
|---|---|---|
| Request duration | 60 seconds | `504` `REQUEST_TIMED_OUT` |
| Duration of each live query | 30 seconds | `206`, with the affected resource cached or empty, as described in [Partial success](#partial-success) |
| Request body | 50 MB, measured on the decompressed JSON | `400` `REQUEST_VALIDATION_FAILED`, without `errors` |
| Records per page in searches | From `1` to `1000` in `limit` | `400` `REQUEST_VALIDATION_FAILED` |
| Pagination cursor validity | 15 minutes between one page and the next | `400` `PAGE_CURSOR_INVALID` |

- Set the HTTP client timeout above 60 seconds, so it receives the `504` instead of closing the connection first and losing the `traceId`.
- The body is used only by operations that create or change data, such as the list operations. It can be sent compressed, as described in [Compression](https://cnpja.com/en-us/docs/api/reference#description/compression), and the 50 MB limit applies to the decompressed JSON.
- Pagination and the cursor are covered in [CNPJ search and lists in the API](https://cnpja.com/en-us/docs/api/cnpj-search). The limit on lists per organization and the one on CNPJs per list, which cause the `422` errors, are in [Organization](https://cnpja.com/en-us/docs/billing/limits#organization) and in [Lists, exports and bulk](https://cnpja.com/en-us/docs/billing/limits#lists).

## Error format

Every error response has an HTTP status of `4xx`, when the problem is in the request, or `5xx`, when the failure is on the API side, and a JSON body that always has the same shape. This request sends `company.taxRegime.view` without `company.taxRegime` in `expand`:

```http
GET /v2/establishments/37335118000180?company.taxRegime.view=DETAILED HTTP/1.1
Host: api.cnpja.com
Authorization: YOUR_API_KEY
```

The request is rejected with `400`:

```json
{
  "status": 400,
  "code": "REQUEST_VALIDATION_FAILED",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "message": "company.taxRegime.view requires company.taxRegime to be present at expand",
  "errors": [
    {
      "field": "company.taxRegime.view",
      "code": "DEPENDENCIES",
      "message": "Requires company.taxRegime to be present at expand"
    }
  ]
}
```

| Field | Content |
|---|---|
| `status` | The same HTTP status as the response |
| `code` | Stable error identifier. Base error handling on it, never on `message` |
| `message` | Human-readable description, in the response [language](https://cnpja.com/en-us/docs/api/responses) when a translation exists, and in English when it does not. It is for display only and may change without notice |
| `traceId` | Request identifier, also sent in the `trace-id` header. See [Trace ID and support](#trace-id) |
| `errors` | Validation failures, one per failed rule. When present, `message` restates only the first one |

## Validation rules

Each `errors` item has `field`, `code` and `message`. `field` is the parameter name or the property path in the body, with list positions counted from zero: `expand.0` is the first value of `expand`, and `items.2` is the third body item. `code` names the failed rule:

| Rule | When it appears |
|---|---|
| `REQUIRED` | A required value is missing |
| `FORMAT` | The value has an invalid format |
| `ENUM` | The value is outside the allowed ones |
| `DEPENDENCIES` | A combination that is not accepted, such as a parameter that configures a resource missing from `expand`, or `cursor` sent with other parameters |
| `ADDITIONAL_PROPERTIES` | An unrecognized name, such as a typo. The message does not say which one, so check the spelling of the parameters sent |

- `field` is empty on `ADDITIONAL_PROPERTIES` and when the problem is in the URL path, such as a malformed CNPJ.
- `errors` is absent when the body cannot be read, as with malformed JSON, an unsupported `Content-Type` or a body over 50 MB, and on every code other than `REQUEST_VALIDATION_FAILED`.
- On operations without query parameters, such as [Lookup company](https://cnpja.com/en-us/docs/api/reference#tag/companies/GET/v2/companies/%7bid%7d), unrecognized names are ignored instead of causing an error.

## Error codes

All codes, grouped by status. The Billing column says whether the request consumes quota and in which unit. The amounts are in the metering rules, under [What is not charged](https://cnpja.com/en-us/legal/metering#not-charged) and [What is charged even without a useful result](https://cnpja.com/en-us/legal/metering#charged-without-result).

| Status | Code | Cause | Action | Billing |
|---|---|---|---|---|
| `400` | `REQUEST_VALIDATION_FAILED` | A parameter, the path or the request body is invalid | Fix what `errors` points out or, when it is absent, the body | None |
| `400` | `PAGE_CURSOR_INVALID` | The `cursor` expired or is unknown | Restart the search from the first page, with the same parameters | None |
| `401` | `API_KEY_MISSING` | `Authorization` is missing or empty, or a public request has query parameters | Send an API key or remove the parameters from the public request | None |
| `401` | `API_KEY_INVALID` | The `Authorization` value is not a valid key, for example because it has the `Bearer` prefix | Send the full key, with no prefix, as described in [Authentication](https://cnpja.com/en-us/docs/api/authentication#header) | None |
| `401` | `API_KEY_REVOKED` | The key was revoked and will not work again | Use another active key of the organization | None |
| `402` | `CACHED_QUERY_QUOTA_EXCEEDED` | The organization used up its [quota](https://cnpja.com/en-us/docs/billing/queries-and-quotas) of [cached queries](https://cnpja.com/en-us/docs/glossary#consulta-em-cache--cached-query), with no overage budget to charge the queries beyond it, or with it suspended by a [late payment](https://cnpja.com/en-us/docs/billing/past-due#api) | Follow one of the ways out in [Quota used up](https://cnpja.com/en-us/docs/billing/quota-exhausted#ways-out) | None |
| `402` | `LIVE_QUERY_QUOTA_EXCEEDED` | The organization used up its quota of live queries, with no overage budget to charge the queries beyond it, or with it suspended by a [late payment](https://cnpja.com/en-us/docs/billing/past-due#api) | Follow one of the ways out in [Quota used up](https://cnpja.com/en-us/docs/billing/quota-exhausted#ways-out) | None |
| `402` | `OVERAGE_BUDGET_EXCEEDED` | The quota ran out, and the spend on overage queries reached the month's [overage budget](https://cnpja.com/en-us/docs/billing/packs-and-budget#overage-budget) | Follow one of the ways out in [Quota used up](https://cnpja.com/en-us/docs/billing/quota-exhausted#ways-out) | None |
| `404` | `ESTABLISHMENT_NOT_FOUND` | The CNPJ is not registered with the Receita Federal. Without a key, also when the CNPJ is not yet in cached data | Check the CNPJ. Without a key, see [Public API access, no key](https://cnpja.com/en-us/docs/api/public-access) | Live query, with a key |
| `404` | `COMPANY_NOT_FOUND` | No company with that root is in cached data, which includes an existing company not yet added to it | Check the root. To add the company, look up one of its CNPJs with Lookup CNPJ, then retry | Cached query |
| `404` | `INDIVIDUAL_NOT_FOUND` | No state or SUFRAMA registration was found for the CPF in the queried sources | Check the CPF and the requested states, as described in [State registrations in the API](https://cnpja.com/en-us/docs/api/state-registrations) | Live queries, depending on the operation |
| `404` | `ESTABLISHMENT_DOSSIER_EMPTY` | None of the certificates requested in Issue CNPJ dossier is available, as described in [Omitted certificates](https://cnpja.com/en-us/docs/api/certificates#omitted) | Request only the certificates that should exist for the CNPJ | Depending on the omitted certificates |
| `404` | `INDIVIDUAL_DOSSIER_EMPTY` | None of the certificates requested in Issue CPF dossier is available, as described in [Omitted certificates](https://cnpja.com/en-us/docs/api/certificates#omitted) | Request only the certificates that should exist for the CPF | Depending on the omitted certificates |
| `404` | `PERSON_NOT_FOUND` | No person has that ID | Use an `id` obtained from Search people or from `company.partners[].person.id` | Cached query |
| `404` | `POSTAL_CODE_NOT_FOUND` | The CEP was not found | Check the CEP and send only its 8 digits, with no punctuation | Cached query, with a key |
| `404` | `LIST_NOT_FOUND` | The list does not exist or belongs to another organization | Check the list `id` | None |
| `404` | `NOT_FOUND` | The request path or HTTP method does not exist | Check the URL, the `/v2` prefix and the method | None |
| `409` | `LIST_EXPORT_IN_PROGRESS` | Update list with `operation` while an export of the list, made in the app, is queued or running | Retry once the export finishes. Renaming still works | None |
| `422` | `LIST_LIMIT_EXCEEDED` | The organization reached its list limit | Delete unused lists before creating another | None |
| `422` | `LIST_SIZE_EXCEEDED` | Update list would leave the list over the CNPJs-per-list limit | Send fewer CNPJs or split them into more than one list | None |
| `422` | `ORGANIZATION_DEACTIVATED` | The key's organization was deactivated | Use an API key of an active organization | None |
| `429` | `RATE_LIMIT_EXCEEDED` | The requests-per-second limit was reached | Wait about a second and slow down | None |
| `429` | `CONCURRENCY_LIMIT_EXCEEDED` | The concurrent-requests limit was reached | Reduce parallelism and resend once another request completes | None |
| `500` | `UNEXPECTED_ERROR` | An unexpected failure prevented the request from completing | Retry with increasing intervals | None |
| `504` | `REQUEST_TIMED_OUT` | The request did not complete within 60 seconds | Retry with increasing intervals | None |

- `5xx` errors are not charged, even when some queries completed before the failure.
- If you receive a `code` you do not recognize, handle the error by its HTTP status.

## Not found

A `404` consumes the queries needed to conclude that the record does not exist, such as the live query that confirms a CNPJ is not registered with the Receita Federal. Therefore:

- Do not repeat a `404` right away: look it up again only when the registration may have changed.
- An identifier in the wrong format, such as a CNPJ root with lowercase letters in Lookup company or a CEP with a hyphen in Lookup CEP, is rejected with `400`, with no charge: the charged `404` is only that of an identifier in the right format that is not on record.
- Searches do not return `404` for a lack of results: with no records, the response is `200` with empty `records` and consumes a cached query, under [What is charged even without a useful result](https://cnpja.com/en-us/legal/metering#charged-without-result).

The `404` consumption of each operation is in the metering rules, under [What is charged even without a useful result](https://cnpja.com/en-us/legal/metering#charged-without-result).

## Partial success

The `206` status is not an error. On the operations that accept `maxAge`, a live query that fails or takes longer than 30 seconds does not abort the request: the other resources are delivered normally, the affected resource keeps its cached data, or comes back empty if it was never queried, and the response comes with `206`, in the same shape as a `200`. The affected resource is not charged. Treat `206` as success.

When the cached data the response relies on is missing, as on the first lookup of a CNPJ, a failure at the source makes the request fail instead of returning `206`. In that case, retry later. The concept is in [Partial result](https://cnpja.com/en-us/docs/data/freshness#partial), and how to identify the affected resource, in [Partial success (206)](https://cnpja.com/en-us/docs/api/max-age#partial).

## Trace ID and support

Every response, successful ones included, carries the `trace-id` header, which identifies the request. On error responses, the same value is in the `traceId` field. Keep it in the application logs.

```bash
curl -i https://api.cnpja.com/v2/postal-codes/01310100
```

The `-i` option prints the response headers, `trace-id` among them.

In **Settings** > **Requests**, the details of each request made with the organization's keys, including those rejected with `400` and `5xx` failures, show the same value as **Trace ID**, as described in [Track usage](https://cnpja.com/en-us/docs/billing/usage#usage-events). Public requests, made without a key, do not appear there.

When you contact us about a request, send its trace ID, as [Contact us](https://cnpja.com/en-us/docs/support/contact#trace-id) explains.

## Best practices

### Retries

Errors with status `429`, `500` and `504` are usually temporary, are not charged and can be retried unchanged, except on [operations that change data](#operations-that-change-data). A `409` clears once the list's export finishes. The others are not fixed by retrying the same request: a `400` or `401` requires fixing the request, a `402` persists until the quota or the overage budget is raised, or until the quota renews, a `422` requires adjusting the request or freeing space, and a repeated `404` can be charged again.

| Error | Wait before retrying |
|---|---|
| `409` `LIST_EXPORT_IN_PROGRESS` | Until the list's export is ready |
| `429` `RATE_LIMIT_EXCEEDED` | About a second |
| `429` `CONCURRENCY_LIMIT_EXCEEDED` | Until another in-progress request completes |
| `500` and `504` | Increasing intervals with each attempt. If the error persists, contact us and send the `traceId` |

The example below retries only temporary errors, doubles the wait on each attempt and uses a timeout above 60 seconds:

```js
const TEMPORARY = [429, 500, 504];

async function lookup(url, attempts = 5) {
  for (let attempt = 1; ; attempt++) {
    const response = await fetch(url, {
      headers: { Authorization: process.env.CNPJA_API_KEY },
      signal: AbortSignal.timeout(65000),
    });
    if (!TEMPORARY.includes(response.status) || attempt === attempts) return response;
    await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** (attempt - 1)));
  }
}

const response = await lookup('https://api.cnpja.com/v2/establishments/37335118000180');
```

### Pacing

- **Fixed parallelism:** process batches with a fixed number of parallel workers, below the concurrent-requests limit, instead of firing every request at once.
- **Headroom for other applications:** limits belong to the organization, so reserve part of them for the other applications that use other keys.
- **Faster responses:** a larger `maxAge` serves more resources from cached data, which shortens responses and frees concurrency slots sooner. See [Max age and partial success](https://cnpja.com/en-us/docs/api/max-age).
- **Fewer requests:** in searches, larger pages, with `limit` up to `1000`, take fewer requests to read a full result.

This example processes a list of CNPJs using the `lookup` function above. `PLAN_LIMIT` is the limit of the organization's plan, from the [Usage limits](#usage-limits) table, such as 5 on Free and 50 on Pro. The number of parallel workers stays at 80% of it, leaving headroom for the organization's other applications, and each worker starts at most one request per second, which keeps both concurrent requests and requests per second below the limit. When the plan changes, adjust `PLAN_LIMIT`:

```js
const PLAN_LIMIT = 5;
const CONCURRENCY = Math.max(1, Math.floor(PLAN_LIMIT * 0.8));
const queue = ['37335118000180'];

async function worker() {
  while (queue.length) {
    const taxId = queue.shift();
    const pace = new Promise((resolve) => setTimeout(resolve, 1000));
    const response = await lookup('https://api.cnpja.com/v2/establishments/' + taxId);
    console.log(taxId, response.status);
    await pace;
  }
}

await Promise.all(Array.from({ length: CONCURRENCY }, worker));
```

### Operations that change data

An operation that creates or changes data may have completed even when the response is a `500`, a `504` or never arrives. Check the resource's state before retrying:

- **Create list** is not idempotent: each request creates a new list, even with a `name` already in use. After a `500`, a `504` or no response, look for the name with [Search lists](https://cnpja.com/en-us/docs/api/reference#tag/lists/GET/v2/lists) and delete duplicates with [Delete list](https://cnpja.com/en-us/docs/api/reference#tag/lists/DELETE/v2/lists/%7blistId%7d) before retrying.
- **Update list** can be resent, since it neither duplicates nor reverts CNPJs. A repeated `ADD` can return `422` `LIST_SIZE_EXCEEDED` if the first attempt was already applied, so check `size` with [Lookup list](https://cnpja.com/en-us/docs/api/reference#tag/lists/GET/v2/lists/%7blistId%7d).
- **Delete list**, when repeated, returns `404` `LIST_NOT_FOUND` once the list is already deleted.

## Notes

- Request limits and the quota are separate controls: limits restrict pace (`429`), and the quota restricts each period's consumption (`402`), as [Quota is not a rate limit](https://cnpja.com/en-us/docs/billing/queries-and-quotas#rate-limit) explains.
- The language of `message`, including in `errors` items, follows the `Accept-Language` header, as described in [Response format](https://cnpja.com/en-us/docs/api/responses).
- Errors specific to each resource are on its page, such as [CNPJ lookup in the API](https://cnpja.com/en-us/docs/api/cnpj-lookup), [State registrations in the API](https://cnpja.com/en-us/docs/api/state-registrations) and [CNPJ search and lists in the API](https://cnpja.com/en-us/docs/api/cnpj-search).
- The terms used on this page are in the [Glossary](https://cnpja.com/en-us/docs/glossary).
