Do this with AI
Install the cms-graphql skill from Contentstack agent skills. Then ask your agent:
Review this GraphQL query for my landing page, estimate its reference depth and how many entries it can fetch, and rewrite it so it stays under three reference levels and 7,500 documents, splitting it into two queries if needed.
New to this? Set up your AI workbench first.
GraphQL errors decoded: depth, cost and partial data
Contentstack's GraphQL Content Delivery API fails in two different ways. Some queries are rejected before they run, with a 422 and a code like MAX_REFERENCE_DEPTH_LIMIT_EXCEEDED. Others run, return HTTP 200, and quietly leave holes in data that are only explained in errors.
If you use Apollo, urql, graphql-request or a plain fetch from Next.js, Nuxt or Astro, both show up the same way at first: a page that renders with missing content, or a build that fails on one route. This guide decodes the errors you are most likely to see and shows how to rewrite the query for each.
What you'll learn
How to tell a rejected query from a partial result
What the depth, cost, document and page size limits are
How to rewrite queries that go too deep or fetch too much
Why the default page size is 25 and how to paginate past it
Which schema, type and branch quirks look like errors but are not
Symptoms
Code or symptom | HTTP | Example message |
|---|---|---|
MAX_REFERENCE_DEPTH_LIMIT_EXCEEDED | 422 | Max allowed nested reference depth limit is '3', but the query has '5' nested references. |
MAX_RESOLVER_COST_EXCEEDED | 422 | Max allowed cost per query is 20. Resolver cost calculated was 21. |
MAX_DOCUMENT_LIMIT_EXCEEDED | 422 | Maximum allowed documents in a single query are '7500', but the query has requested '9234' documents. |
MAX_ROOT_FETCH_LIMIT_EXCEEDED | 422 | Max allowed limit to fetch a content types is '100'. |
MAX_REFERENCE_LIMIT_EXCEEDED | 422 | Max allowed limit per reference for your organization is '100', but the query requested '120'. |
MAX_QUERIED_CONTENT_TYPE_LIMIT_EXCEEDED | 422 | Maximum allowed content types queried at a time is 'THREE' |
INVALID_BRANCH | 422 | The queried branch 'develop' is invalid. |
INVALID_LOCALE | 422 | The queried locale 'en-uk' is invalid. |
SCHEMA_BUILD_ERROR | 422 | Unable to generate GraphQL types. Check details for more info. |
RESPONSE_SIZE_TOO_BIG | 503 | Maximum response size allowed is 7 MB. |
SERVICE_UNAVAILABLE | 504 | Request timeout! |
errors[] next to data, some fields null | 200 | Failed to run query. |
A list stops at 25 items | 200 | No error |
Why it happens
Contentstack concept: The GraphQL API generates its schema from your content types on each request, and it checks every query against plan-based limits on documents, resolver cost, content types and reference depth before it runs.
That gives you two classes of errors.
Rejected before execution. The API reads the query, works out how deep it goes, how many entries it could fetch and how many database calls it needs, and compares that with the limits. If the query is over, nothing runs and you get a non-2xx status. The body has the code in extensions.errors:
{
"errors": [
{
"message": "Failed to run query.",
"extensions": {
"errors": [
{
"code": "MAX_ROOT_FETCH_LIMIT_EXCEEDED",
"message": "Max allowed limit to fetch a content types is '100'.",
"details": { "hint": "The 'all_product' argument can fetch maximum '100' content types." }
}
]
}
}
]
}Failed during execution. The query is valid and ran, but a field could not be resolved. A referenced entry is missing, or a resolver ran out of budget. You get HTTP 200, data with that field set to null, and an entry in errors with a path pointing at the field:
{
"data": {
"all_article": { "items": [{ "title": "Hello", "author": null }] }
},
"errors": [
{
"message": "Failed to run query.",
"path": ["all_article", "items", 0, "author"],
"extensions": { "errors": [{ "code": "...", "message": "...", "details": { "hint": "..." } }] }
}
]
}The status code describes the transport. The body describes the operation. A client that only checks response.ok renders the hole.
Fix it
Always read errors, even on 200
Start here, because it makes every other error visible. A small wrapper around fetch is enough:
const GRAPHQL_HOST = process.env.CONTENTSTACK_GRAPHQL_HOST ?? "https://graphql.contentstack.com";
type GqlError = {
message: string;
path?: (string | number)[];
extensions?: { errors?: { code: string; message: string; details?: { hint?: string } }[] };
};
export async function gql<T>(query: string, variables: Record<string, unknown> = {}) {
const url = `${GRAPHQL_HOST}/stacks/${process.env.CONTENTSTACK_API_KEY}?environment=${process.env.CONTENTSTACK_ENVIRONMENT}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
access_token: process.env.CONTENTSTACK_DELIVERY_TOKEN!,
},
body: JSON.stringify({ query, variables }),
});
const body = (await response.json()) as { data?: T; errors?: GqlError[] };
const details = (body.errors ?? []).map((e) => {
const inner = e.extensions?.errors?.[0];
return `${inner?.code ?? "ERROR"} at ${e.path?.join(".") ?? "query"}: ${inner?.message ?? e.message}`;
});
if (!response.ok) {
throw new Error(`GraphQL ${response.status}: ${details.join("; ")}`);
}
if (details.length > 0) {
console.warn(`GraphQL partial result: ${details.join("; ")}`);
}
return body.data as T;
}Throw on non-2xx. For partial results, decide per route: a build should usually fail, a server-rendered page can log and render what it has. Use your region's GraphQL host if your stack is not in AWS North America.
MAX_REFERENCE_DEPTH_LIMIT_EXCEEDED
Nested references can be fetched up to three levels deep. This query is four levels: page, section, card, author, company.
query {
page(uid: "blt0123456789abcdef") {
sectionsConnection {
edges {
node {
... on Section {
cardsConnection {
edges {
node {
... on Card {
authorConnection {
edges {
node {
... on Author {
companyConnection { edges { node { ... on Company { title } } } }
}
}
}
}
}
}
}
}
}
}
}
}
}
}There is no flag to raise the limit for a single query. You have three options, in this order:
Stop at the last level you need. Fetch author { system { uid } } at level three and resolve the company in a second query by UID.
Split the query by subtree. Fetch the page and its sections in one query and the cards with their authors in another. Two small queries cache better than one large one.
Change the model. Most deep chains come from modeling sections and cards as separate entries when they could be modular blocks or global fields, which come back with the entry and do not count as reference levels. Modular blocks, references or global fields? covers the trade-off.
Reference filters in where have the same three-level limit. A filter that goes deeper fails with REF_FILTER_DEPTH_EXCEEDED.
MAX_RESOLVER_COST_EXCEEDED and MAX_DOCUMENT_LIMIT_EXCEEDED
Two numbers decide whether a query is too big:
Complexity is the number of entries the query could fetch. The maximum is 7,500 documents per query. Over that, you get MAX_DOCUMENT_LIMIT_EXCEEDED.
Resolver cost is the number of database calls needed to fetch those entries and their fields. Over the allowed cost, you get MAX_RESOLVER_COST_EXCEEDED.
Both are worst-case estimates based on the limits in the query, not the data you have. A query for 100 blog posts, each with a reference connection of 75 related posts, counts as 100 + 100 × 75 = 7,600 documents, even if most posts have two related posts. It is rejected before it runs.
The fix is to lower the limits you pass, especially on nested connections:
query BlogList($skip: Int = 0) {
all_blog_post(limit: 20, skip: $skip) {
total
items {
title
url
related_postsConnection(limit: 3) {
edges {
node {
... on BlogPost { title url }
}
}
}
}
}
}20 + 20 × 3 = 80 documents. If a detail page really needs every related item, fetch them in a separate query for that one entry and paginate the connection with skip and limit.
MAX_ROOT_FETCH_LIMIT_EXCEEDED and the 25-item default
Root list queries like all_blog_post return 25 items when you pass no limit, and accept up to 100. Asking for more than 100 is rejected. Asking for nothing silently gives you 25. That second one is the bug that ships: a sitemap or generateStaticParams that builds 25 pages and nobody notices.
Paginate with skip and stop at total:
type BlogListPage = { all_blog_post: { total: number; items: { url: string }[] } };
const PAGE_SIZE = 100;
export async function getAllBlogUrls() {
const urls: string[] = [];
let skip = 0;
let total = Infinity;
while (skip < total) {
const data = await gql<BlogListPage>(
`query ($skip: Int!) {
all_blog_post(limit: ${PAGE_SIZE}, skip: $skip) { total items { url } }
}`,
{ skip }
);
total = data.all_blog_post.total;
urls.push(...data.all_blog_post.items.map((i) => i.url));
skip += PAGE_SIZE;
}
return urls;
}Keep the selection small in loops like this. A list of URLs is cheap. A list of URLs with three levels of references is where cost errors come from.
Reference connections have their own cap: up to 100 items per Reference field. Passing a higher limit returns MAX_REFERENCE_LIMIT_EXCEEDED.
Too many content types in one request
A single request can query up to three content types at the root. A fourth returns MAX_QUERIED_CONTENT_TYPE_LIMIT_EXCEEDED. Split a "home page data" query that pulls page, navigation, footer and settings into two requests, and run them in parallel.
The schema does not match my content model
The schema is generated from your content types when you query, so a model change shows up in the API right away. When it seems not to, the stale copy is usually on your side:
Codegen output. Generated TypeScript types and persisted queries are a snapshot. Regenerate them after every content type change, ideally in CI.
The wrong branch. Content type changes made on a branch only exist there. Pass the branch header with the branch UID or alias. Without it, the API reads main. A branch the delivery token is not scoped to returns INVALID_BRANCH.
Typename collisions. Content type and field UIDs become GraphQL type names. Two UIDs that only differ by special characters collide and cause SCHEMA_BUILD_ERROR. UIDs that start with a number break queries entirely. Rename the UIDs. During introspection, you can pass skip_content_type_uids to leave the broken content types out while you fix them.
Branches and aliases are covered in Safe content model changes with branches and aliases.
Type quirks
Number fields map to Float in the default schema. Do not assume Int in generated types or in variables you compare against.
Fields are nullable by default, even when they are mandatory in the content type. A required title can still be null if the entry failed to resolve. With strict type checks, mandatory fields become non-null (String!, [Edge!]!), and a missing value returns an error instead of null. Strict checks have to be enabled for your organization, and you request them with the x-graphql-strict-type-checks: true header.
Check that it worked
Send the query with curl and look at the status, the body and errors together:
curl -s -o response.json -w "%{http_code}\n" \
"https://graphql.contentstack.com/stacks/$CONTENTSTACK_API_KEY?environment=production" \
-H "access_token: $CONTENTSTACK_DELIVERY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"query":"{ all_blog_post(limit: 20) { total items { title } } }"}'
jq '{errors: [.errors[]?.extensions.errors[]?.code], count: (.data.all_blog_post.items | length), total: .data.all_blog_post.total}' response.jsonYou want 200, an empty errors list, and a count that matches what you expect for the page. For pagination, the sum of all pages should equal total.
Prevent it
Route every GraphQL request through one wrapper that reads errors on 200 and logs the code and path.
Set explicit limit values on every list and every reference connection. Never rely on the default 25.
Budget queries by multiplying limits per level before you ship them. Stay well below 7,500.
Keep reference chains at two levels in the model, so queries have room for one more when a design needs it.
Regenerate GraphQL types in CI after content model changes, and pass the branch header explicitly in non-production environments.
If you hit rate limits on top of these, Fix 429 rate limit errors covers backoff and caching.
Key takeaways
A non-2xx status means the query was rejected before it ran. The code is in extensions.errors[].code.
HTTP 200 can still carry errors[], with the failing fields set to null. Check errors every time.
References resolve up to three levels deep. Split the query or flatten the model rather than going deeper.
Complexity counts every entry a query could fetch, up to 7,500. Lower nested connection limits to stay under it and under the resolver cost.
Root lists default to 25 items and allow 100. Paginate with skip until you reach total.
Schema mismatches are usually stale codegen, a missing branch header, or colliding UIDs.
Next steps
If you query REST instead, see Nested references come back empty, or fail with error 141.
See every delivery limit side by side in Contentstack limits on one page.
Start from a working GraphQL setup with the Next.js GraphQL kickstart.
Frequently asked questions
How deep can a Contentstack GraphQL query follow references?
Three levels. A deeper query is rejected with MAX_REFERENCE_DEPTH_LIMIT_EXCEEDED before it runs.
Why do I get HTTP 200 with an errors array?
The query ran, but some fields failed to resolve. Those fields are null in data and described in errors, so always check errors before you use data.
Why does my list only return 25 entries?
25 is the default limit for root list queries. Pass limit up to 100 and paginate with skip, using total to know when to stop.
What is resolver cost?
An estimate of the database calls a query needs. Queries above the allowed cost are rejected with MAX_RESOLVER_COST_EXCEEDED.
Why are mandatory fields nullable in the generated types?
By default the schema marks fields as nullable. Strict type checks make them non-null, but they have to be enabled for your organization and requested with the x-graphql-strict-type-checks header.