Errors and Rate Limits
This page covers the error format, common error codes, rate limiting, and query complexity limits for the Foir API.
A missing record is not an error
Read this first, because it decides how you write every other read.
When you ask for a record that does not exist, the field resolves to null and there is no errors array at all:
{
"data": {
"page": null
}
}That is a successful response. Nothing has gone wrong: the page was unpublished, or deleted, or the slug was mistyped. Check the field for null and render your own 404.
The same applies to a record you are not allowed to see, and to a reference pointing at a record that has since been deleted. Both resolve to null without an error.
An errors array therefore means something has actually failed, and you can treat it that way. Do not wrap a read in try/catch to turn a missing record into null — the catch that swallows the miss also swallows the rate limits, the timeouts and the outages, and your site will serve empty pages instead of telling you it is broken.
Error format
Errors that are errors come back in the standard GraphQL error format, in the errors array alongside any partial data:
{
"errors": [
{
"message": "Rate limit exceeded",
"path": ["page"],
"extensions": {
"code": "RATE_LIMITED",
"requestId": "8f3a1c2b7d4e5069",
"retryAfter": 1800
}
}
],
"data": {
"page": null
}
}Each error object contains:
| Field | Type | Description |
|---|---|---|
message | String | Human-readable error description |
path | [String] | GraphQL path to the field that caused the error |
extensions.code | String | Machine-readable error code |
extensions.requestId | String | Correlation id. Quote it in a support request |
extensions.stepUp | String | Present with code STEP_UP_REQUIRED: proof (a change to the user’s factors needs a fresh proof), second_factor (the organization requires a second factor) or sign_in_method (sign in again with a method the organization accepts) |
extensions.stepUpUrl | String | Present with proof and second_factor: Fóir’s hosted step-up page. Send the user there with return_to added to its query, and retry when they come back. Its token, minted for the user’s session alone, is in the fragment |
extensions.lookupConflict | Object | Present when a write was refused because another record already holds its key on one of the model’s lookups: model, lookup (the lookup’s name) and keyBy (the fields it is keyed by). Code FAILED_PRECONDITION |
Branch on extensions.code, never on message. The codes are stable; the wording is not.
The full set of machine-readable extensions.code values is:
| Code | Meaning |
|---|---|
INVALID_ARGUMENT | Input was malformed or failed validation |
NOT_FOUND | A mutation named a resource that does not exist. Reads do not use this: see a missing record is not an error |
ALREADY_EXISTS | A conflicting resource already exists: moving a record onto a natural key another record holds, creating a second row of a singleton model, or registering an organization that is already registered. A create never fails this way — see natural keys are advisory on create |
FAILED_PRECONDITION | The request is valid but not allowed in the current state |
STEP_UP_REQUIRED | The signed-in user’s session must prove more before the request can succeed: see extensions.stepUp and extensions.stepUpUrl. The SDK’s stepUpRequired(error) reads both |
PERMISSION_DENIED | The caller, a key or a signed-in user, lacks a permission the operation needs |
UNAUTHENTICATED | The request is missing valid authentication |
RATE_LIMITED | The rate limit has been exceeded |
HOST_RATE_LIMITED | A field read live from another service could not be answered because that service refused the read for rate. See a live field whose host refuses |
HOST_UNAVAILABLE | A field read live from another service could not be answered because that service could not answer (a 502, 503 or 504). See a live field whose host refuses |
TIMEOUT | The request timed out |
UNAVAILABLE | The service is temporarily unavailable |
CANCELED | The request was canceled |
INTERNAL | An unexpected server error occurred |
Common Error Codes
UNAUTHENTICATED
The request is missing a valid API key or the key is invalid.
{
"errors": [{
"message": "Authentication required",
"extensions": { "code": "UNAUTHENTICATED" }
}]
}Common causes:
- Missing
x-api-keyheader - API key is invalid, expired, or deleted
- API key has been disabled in the dashboard
Resolution: Verify your API key is correct and active. Check that the x-api-key header is included in your request.
PERMISSION_DENIED
The caller lacks a permission the operation needs: a key by its scopes, a signed-in user by their role.
{
"errors": [{
"message": "missing required scope: records:write:order",
"extensions": { "code": "PERMISSION_DENIED" }
}]
}Common causes:
- API key lacks the required scope (e.g., attempting
records:writewith a read-only key) - A visitor attempting a write through a publishable or a server key
- A signed-in user whose role does not grant it
A user’s token that doesn’t verify is not refused: the request is served as nobody and says so. See When a user token is rejected.
Resolution: Check the scopes assigned to your API key in the dashboard, and the role of the signed-in user. A write from your app comes from the user’s role or from an operation, never from an admin key: see App architecture.
NOT_FOUND
A mutation named a resource that does not exist.
{
"errors": [{
"message": "Record not found",
"extensions": { "code": "NOT_FOUND" }
}]
}Reads do not produce this code. A read for a record that is not there resolves the field to null with no errors array, because for a read that is an ordinary answer rather than a failure. If a read returns null when you expected content, the usual causes are:
- The record ID or natural key does not exist
- The record has been deleted
- The model key is wrong
- The record is unpublished and was read without preview (request drafts with
preview: trueusing a key that holds thedrafts:readscope) - The record belongs to another user, and your key may not see it
INVALID_ARGUMENT
The input data was malformed or failed validation.
{
"errors": [{
"message": "Validation failed: 'title' is required",
"extensions": {
"code": "INVALID_ARGUMENT"
}
}]
}Common causes:
- Required fields are missing
- Field values do not match the expected type
- Field values violate validation rules (e.g., max length, pattern)
RATE_LIMITED
The API key has exceeded its rate limit. Rate-limited requests are rejected with HTTP status 429:
{
"errors": [{
"message": "Rate limit exceeded",
"extensions": {
"code": "RATE_LIMITED",
"requestId": "8f3a1c2b7d4e5069",
"retryAfter": 1800
}
}]
}extensions.retryAfter is the number of seconds until the window resets, the same value as the Retry-After header. It is never less than 1, so honouring it always waits.
The response also carries the standard X-RateLimit-* headers.
A read past the limit may come back 200, from cache
There are three outcomes for a read on /graphql, not two.
| Where you are | What happens |
|---|---|
| Under the ceiling | Resolved normally. |
| Over the ceiling, inside the burst band | Refused with 429 and RATE_LIMITED, as above. |
| Over the ceiling and past the burst band | Not refused. If a cached body for that exact request exists, it is served with HTTP 200 and X-Foir-Stale: true. If there is none, you get the 429. |
The stale body is whatever was last stored for your query, variables and identity. It is not refreshed by being served — serving stale does not extend how long it stays servable — so it will not get older and older forever, but it is not current either, and a caller sitting past the band can keep receiving the same body while newer content exists.
X-Foir-Stale is not readable from browser JavaScript. It is not in the CORS exposed-header list, so response.headers.get('X-Foir-Stale') returns null cross-origin even though the header is on the wire. A server-side caller can read it; a storefront running in the browser cannot, and has no way to tell a stale 200 from a fresh one. If that distinction matters to you, the signal to watch is X-RateLimit-Remaining reaching zero, which is exposed.
This exists so a site that has overrun its limit serves its last-known content rather than empty pages. It is a cushion, not a licence: content stops updating for as long as you stay past the band.
A live field whose host refuses
A field read live from another service (a price from a store, say) can fail because that service refused the read for rate, or could not answer. The same cushion applies. If the API still holds an answer for that exact request, it is served with HTTP 200 and X-Foir-Stale: true rather than the error. If it holds none, the field fails with HOST_RATE_LIMITED or HOST_UNAVAILABLE in extensions.code, and the rest of the response is resolved as usual.
Any other failure of a live field is an ordinary error, and is never answered stale.
A project with many uncached reads at once
Every project shares the platform, so each one runs a bounded number of reads that miss the cache at the same moment. Past that, its next reads wait their turn for up to two seconds. A read still waiting after that is answered from the last copy held for it, with HTTP 200 and X-Foir-Stale: true, or, when there is none, refused with 429, RATE_LIMITED and Retry-After: 1. A write that cannot get a turn is refused the same way.
Reads served from the cache never wait, however many there are. This only touches a site that sends a burst of reads nothing has cached yet, and the answer is the usual one: retry after the second, and compose the reads.
A read that arrives while the same read is being refreshed
When a cached read expires, the next request for it fetches it fresh. A request for the same read that arrives during that fetch is answered at once from the copy that just expired, with X-Foir-Stale: true, instead of waiting for it. A request carrying an X-Foir-Write-Token from a write newer than that copy waits for the fresh answer instead, so you still see your own write (see Caching).
Resolution: back off for retryAfter seconds and retry. This is the one failure worth handling deliberately, because the alternative is a site that serves empty pages while the API is fine. Retry on RATE_LIMITED as you would on a 5xx, and if you are hitting the limit regularly, cache the reads that do not change per request before asking for a higher one.
Rate limiting
API requests are rate-limited per API key. Rate limits protect the platform from abuse and keep usage fair across projects.
Your limit comes from your plan
Every key in a workspace is limited at the ceiling that workspace’s plan allows, and the number applies to each of your keys rather than being shared between them. Upgrading raises it for every key at once.
| Plan | Requests per hour, per key |
|---|---|
| Free | 10,000 — 2.8 per second sustained |
| Entry | 10,000 |
| Starter | 100,000 |
| Pro | 500,000 |
| Enterprise | 5,000,000; a contract may set a higher one |
Free is a plan to start on with no card, and the plan a workspace moves to when it stops paying.
X-RateLimit-Limit on any response is the ceiling you are actually on.
The unit is one HTTP request, not one record. A page that reads its content in a single composed query costs 1; the same page reading its navigation, footer, banner and body in four separate calls costs 4. That difference is the usual reason a site reaches the limit, and composing the reads is usually cheaper than raising it.
Requests at once
Apart from the hourly ceiling, a workspace can only have a few dozen requests running at the same moment. An application working within its plan won’t get near that. The limit is there so a runaway loop or a burst of slow queries can’t take over a whole server.
A request over it is refused straight away with RATE_LIMITED, the same code as the hourly ceiling, and it isn’t queued. Wait a moment and send it again. The SDK’s retry already does this.
Rate limit headers
Every API response includes rate limit headers:
| Header | Description | Example |
|---|---|---|
X-RateLimit-Limit | Maximum requests allowed per window | 10000 |
X-RateLimit-Remaining | Requests remaining in the current window | 9847 |
X-RateLimit-Reset | Unix timestamp when the window resets | 1743523200 |
Retry-After | On a 429 only: seconds to wait before retrying | 1800 |
Handling rate limits
Log X-RateLimit-Remaining so you find out you are approaching the ceiling before you hit it. Hitting it takes a whole site down, and a site that has been throttled looks exactly like a site with no content:
const remaining = Number(response.headers.get("X-RateLimit-Remaining"));
const limit = Number(response.headers.get("X-RateLimit-Limit"));
if (remaining < limit * 0.2) {
logger.warn("foir rate limit low", { remaining, limit });
}Staying under the limit
- Cache the reads that do not change per request. Navigation, footers, banners, design tokens and UI copy change when an editor changes them, not when a visitor arrives. Caching those with a short TTL removes most of the traffic most sites generate.
- Compose queries. One GraphQL document that selects everything a page needs costs one request; the same data fetched field by field costs one each.
- Batch writes with
batchRecordOperationsinstead of individual mutations. - Use webhooks or subscriptions for change notifications instead of polling.
Do not spread the load across several API keys to get around the ceiling. The limit is there to keep one project from degrading the platform for everyone, and working around it makes the problem it is protecting you from harder to see.
Query Complexity Limits
To prevent expensive queries from degrading performance, Foir enforces limits on query complexity.
Limits
| Limit | Default | Description |
|---|---|---|
| Max depth | 24 | Maximum nesting depth of a query |
| Max complexity | 10000 | Maximum number of selected fields in a query |
| Max aliases | 1000 | Maximum number of field aliases in a single query |
How Complexity Is Calculated
Complexity is simply the total number of fields selected across the entire query. Every field counts as one, regardless of whether it returns a single value, a reference, or a list. The complexity limit is a flat cap on that total field count — there is no per-field weighting and list fields are not multiplied. The defaults are sized for content reads, where a single page can legitimately select hundreds of fields across its sections.
A simple query like this selects only a few fields, so its complexity is low:
query {
page(naturalKey: "home") {
_id
}
}The same read through the data client is not a cheap query, because complexity is counted on the document the server compiles and complete-by-default compiles a whole-record selection whatever the call looked like:
const page = await foir.page.findUnique({ naturalKey: 'home' });A query that selects many fields across many sections counts toward the cap one field at a time:
query {
products(first: 50) {
edges {
node {
_id
title
category {
_id
name # each selected field adds 1 to the total
}
}
}
}
}The same shape through the data client:
const products = await foir.product.findMany({
first: 50,
include: { category: true },
});include is where a data-client read gets expensive. Each included relation contributes every scalar on the related model, not the two fields above, and nesting is capped at three levels. If a data-client read trips the cap, omit the fields you do not render or drop an include — narrowing the selection is not available to you.
Complexity Headers
Responses include headers showing the computed complexity:
| Header | Description |
|---|---|
X-GraphQL-Max-Complexity | Maximum number of selected fields allowed per query |
X-GraphQL-Max-Depth | Maximum nesting depth allowed per query |
X-GraphQL-Max-Aliases | Maximum number of field aliases allowed per query |
Reducing Complexity
If your query exceeds complexity limits:
- Remove unnecessary fields — only request the fields you need, since every selected field counts toward the total
- Avoid deep nesting — flatten your query or split into multiple requests to stay under the depth limit
- Split large queries — fetch in multiple smaller requests rather than one query that selects everything
- Use pagination — fetch smaller pages of results rather than large batches
- Select referenced records sparingly — only pull the fields you actually use from nested references
Client-side: a selection the server stripped
Not every failure comes from the server. The SDK raises one of its own, and it is the one most likely to be mistaken for a missing feature.
When the server cannot serve part of a document it removes the offending selections and returns the rest. That is deliberate — it is what lets a client written against an older schema keep working — but three of the reasons mean the document is wrong rather than the schema having moved: a field that does not exist on the type, sub-selections on a scalar, and sub-selections missing where the type requires them.
For those, the SDK throws a FoirRequestError rather than handing back a response with the field quietly absent:
[foir] the server could not serve part of this query and returned the rest without it:
pages.titel on Page (unknown_field). Those selections do not exist on the schema this
project is serving. Pass strict: false to get the partial answer instead of this error.The error carries prunedSelections — the list of what was stripped, each with its path, its reason and the parent type where the server named one. It does not carry partialData: that belongs to the separate errors-plus-data branch, which this throw happens before.
Each entry is a FoirPrunedSelection: path, reason, and type when the server named the parent type. The type is exported beside FoirRequestError from @foir/sdk/data, @foir/sdk/client, @foir/sdk/server and @foir/sdk/app, so a catch block can name what it caught:
import { FoirRequestError, type FoirPrunedSelection } from '@foir/sdk/data';
try {
await foir.raw(query);
} catch (err) {
if (err instanceof FoirRequestError && err.prunedSelections) {
const paths = err.prunedSelections.map((s: FoirPrunedSelection) => s.path);
console.error('fix these selections:', paths);
}
throw err;
}Any other reason means the schema moved under a document that was right when it shipped, for example a fragment on a type that no longer exists or a variable nothing uses (dead_type_condition, dead_fragment_spread, unreferenced_fragment, unused_variable). The SDK returns the answer for those and logs one warning naming each stripped selection:
[foir] selections stripped from this query: pages.hero on Page (dead_type_condition)With strict: false, the three document errors are logged the same way instead of thrown.
This only arises on hand-written documents — foir.raw and @foir/sdk/client. A generated selection cannot name a field that does not exist. See options.strict for opting out, and for the opposite switch on partial responses.
HTTP status codes
The GraphQL endpoint returns these HTTP status codes:
| Status | Description |
|---|---|
200 | The request was served. It may still carry field-level errors in the response body, and a null field is a normal result |
400 | Malformed request (invalid JSON, missing query) |
401 | Missing or invalid authentication |
403 | The credential may not make this request |
429 | Rate limit exceeded |
500 | Internal server error |
A rejection at any of these statuses carries the same JSON body as a GraphQL error, with the same extensions.code, so one code path handles both. GraphQL returns 200 even when there are field-level errors, so check the errors array as well as the status.
Error handling example
A robust pattern for API clients. Note what it does not do: it never turns an error into null. A missing record already arrives as null in data, so the only thing a catch-all would achieve is hiding the failures you need to see.
async function foirRequest(query, variables) {
const response = await fetch("https://api.foir.dev/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.FOIR_API_KEY,
},
body: JSON.stringify({ query, variables }),
});
const result = await response.json();
const error = result.errors?.[0];
const code = error?.extensions?.code;
// Throttled. Back off and retry rather than rendering an empty page: the
// content is fine, you are just asking for it too fast.
if (response.status === 429 || code === "RATE_LIMITED") {
const retryAfter =
error?.extensions?.retryAfter ??
Number(response.headers.get("Retry-After")) ??
60;
throw new FoirRateLimited(retryAfter, error?.extensions?.requestId);
}
if (code === "UNAUTHENTICATED") throw new FoirUnauthenticated(error.message);
if (code === "PERMISSION_DENIED") throw new FoirForbidden(error.message);
if (code === "INVALID_ARGUMENT") throw new FoirInvalidQuery(error.message);
if (error) {
// Unavailable, timed out, or an internal fault. Quote the requestId if
// you get in touch about it.
throw new FoirError(error.message, code, error.extensions?.requestId);
}
if (!response.ok) {
throw new FoirError(`HTTP ${response.status}`);
}
// A missing record is here, as null. It is not an error and never was.
return result.data;
}Then, at the point you render:
const { page } = await foirRequest(PAGE_QUERY, { slug });
if (!page) {
return renderNotFound(); // genuinely absent
}
return renderPage(page);If foirRequest throws, let it. A 500 tells you the site is broken; a 404 on every route tells you nothing, and is what you get if you catch here instead.
The @foir/sdk client does all of this for you, including retry that honours Retry-After, and is worth using in preference to hand-rolling the above.