Sanity GROQ 查詢緩慢或逾時的成因與修正方法
Sanity GROQ query slow or timing out? Causes and the fix path
Sanity GROQ 查詢在大型列表中變慢或間歇逾時,常見原因包括投影過大、巢狀引用及 offset 分頁,文章並列出修正與驗證方法。其他成因包括過濾掃描整個數據集,以及同一個重型查詢重複執行。建議按頁面精簡投影、改用遊標分頁、減少解參照並標記快取讀取,再比較 Vision 查詢耗時、回應大小、請求時間及建置時間。
If your Sanity GROQ query is slow, or fails intermittently on a large listing page, the content is rarely the problem. The query is. It worked with 40 documents during the build and now does far too much work on a dataset with thousands. This post covers the symptoms, what they cost if you leave them, and the fix path I follow.
Symptoms of a slow GROQ query
These are the signs I see on sites where queries have outgrown the original schema:
- A listing or archive page that was fast at launch now takes seconds to render, and gets worse with every batch of new content.
- Builds slow down as the number of pages grows, even though no page changed.
- Occasional errors on one route only, usually a listing, search, or category page, while single-document pages are fine.
- Studio list views and Vision runs for the same query feel sluggish too, which tells you it is the query and not Next.js.
- Response bodies in the megabytes for a page that shows twelve cards.
If only the first page of a listing is slow, suspect the projection. If page 40 is slower than page 1, suspect offset pagination. If everything is slow, suspect the way the schema forces joins.
What it costs to ignore
A slow query hits you in three places. First, time to first byte on dynamic routes, which drags down LCP. Second, build time, because every statically generated page pays the same query cost. Third, your API usage: slow, heavy queries tend to be retried, refetched, and duplicated across components. I have covered that last effect in why Sanity API requests explode on Next.js sites.
The quieter cost is editorial. Once a listing query starts timing out, someone adds a workaround such as a hardcoded list or a cache that never invalidates, and the content team stops trusting the site.
Cause 1: the projection pulls whole documents
The most common mistake is a listing that expands everything because the same fragment is reused on every page.
// Broken: listing query that expands references and returns full bodies
*[_type == "post"] | order(publishedAt desc) {
...,
author->,
categories[]->,
related[]->{ ..., author-> },
body
}
A card needs a title, slug, date, image, and maybe an author name. Returning body as Portable Text for every post means shipping the whole article text just to render a headline. The fix is a purpose-built projection per view, which I describe in GROQ conditional projections.
Cause 2: nested joins multiply the work
Every -> dereference is a lookup. One level on twelve documents is fine. Three levels on a hundred documents, with arrays of references inside each, becomes thousands of lookups per request. The pattern usually comes from a schema where relationships were modelled for editor convenience rather than for the pages that read them. If that sounds familiar, modelling references to avoid N+1 queries and structuring schemas to avoid query waterfalls go deeper.
The practical rule: dereference only the one or two fields the view shows, and never dereference inside a reference you already dereferenced on a listing.
Cause 3: offset pagination on a large set
Slicing with a large start index forces the query to order and skip everything before it. The deeper the page, the slower it gets, and archive pages at the bottom of a blog are the first to time out. Cursor pagination keeps the cost flat.
// lib/sanity/queries/posts.ts
import { defineQuery } from "next-sanity";
export const POSTS_PAGE_QUERY = defineQuery(`
*[
_type == "post" &&
defined(slug.current) &&
(
publishedAt < $lastPublishedAt ||
(publishedAt == $lastPublishedAt && _id > $lastId)
)
] | order(publishedAt desc, _id asc) [0...12] {
_id,
title,
"slug": slug.current,
publishedAt,
"imageUrl": mainImage.asset->url,
"authorName": author->name
}
`);
// app/blog/page.tsx (fetch helper)
import { client } from "@/lib/sanity/client";
import { POSTS_PAGE_QUERY } from "@/lib/sanity/queries/posts";
export async function getPostsPage(
lastPublishedAt: string = "9999-12-31T00:00:00Z",
lastId: string = ""
) {
return client.fetch(
POSTS_PAGE_QUERY,
{ lastPublishedAt, lastId },
{ next: { tags: ["post"] } }
);
}
The first page passes a far-future date, and every following page passes the last item's publishedAt and _id. The _id tiebreaker matters: without it, posts sharing a timestamp get skipped or repeated.
Cause 4: filters and text matching that scan everything
A filter that starts with _type == is the cheapest thing you can give the query. Filters that rely on match across several fields, or on computed values, or that call references() across the whole dataset, make the query evaluate far more than it needs to. On-site search built this way is the typical casualty. If search is a core feature, send it to a search service or use embeddings rather than stretching GROQ. I have written up both approaches in syncing Sanity to Algolia and semantic search with Sanity embeddings.
Cause 5: the same heavy query runs repeatedly
Even a reasonable query hurts if layout, page, and metadata each run it separately, or if nothing is tagged for caching. Wrap shared reads in one function, tag them, and let revalidation on publish do the invalidating instead of fetching fresh on every request. The webhook side is in Sanity webhook revalidation with tag batching.
How to verify the fix
- Paste the original query into the Vision tool in Studio and note the time and response size.
- Change one thing at a time: trim the projection, then remove nested dereferences, then switch to cursor pagination. Note the numbers after each change.
- Log the duration around
client.fetchin the route and compare production-like data, not a ten-document dev dataset. - Run a build and compare total time. A listing that was queried once per page should now be a handful of small requests.
- Check deep pages, not just page one.
If the payload is still large after this, the schema is the issue, and that is a restructure rather than a query tweak. I cover how to do that safely in restructuring a Sanity schema on a live site.
What to ask a developer
- Which specific queries are slow, and what are their timings before and after?
- Will you give each view its own projection, or keep one shared fragment?
- How will you paginate, and what happens to page 50?
- Do you need schema changes, and if so, how will live content be migrated without downtime?
- How will queries be cached and revalidated after a publish?
A developer who answers with measurements is worth more than one who proposes a new CMS. For broader diagnosis, see how to find the cause of a slow Sanity website and what a fix costs.
Work I do
Query profiling and cleanup is part of the Performance and Sanity audit, which starts from $800. Details are on the services page.
來源:DEV Community · dev.to