Slow initial API response times for relational queries in Sanity

7 replies
Last updated: Jun 5, 2023
Hello. I am experiencing very slow api response times the first time a “relational” query is run, with subsequent executions being much faster. I’m wondering how I can speed up the initial fetch from the api. More info in the thread 👇
Jun 5, 2023, 5:15 PM
I have ~2k
Page
documents, and ~200
Author
documents in my dataset.Each
Page
has an array of references to authors, here is an example of the structured data:
"authors":[
  0:{
    "_type":"reference"
    "_key":"d72d8dea4382"
    "_ref":"5f1dd94c-2515-4391-8cf5-aeac8d0c3eb9"
  }
]
I query for all the pages given an author ID with the following groq query using the @sanity/client npm package.

export const getPagesByAuthor = async (
  authorId: string,
): Promise<Array<Page>> => {
  const start = new Date().getTime()
  const query = `*[
    _type == 'page'
    && !(_id in path("drafts.**"))
    && references(authors, $id)
  ]`
  const params = {id: authorId}
  const res = await sanity.fetch(query, params)
  const end = new Date().getTime()
  console.log(`getPagesByAuthor took ${end - start}ms`)
  return res
}
The first time this query is run for a given authorId, it takes ~8 seconds on our production dataset
using the CDN client. Subsequent invocations take ~100ms. Why is this? Is there a better way to write this “relational” groq query so that initial response time is faster?
Jun 5, 2023, 5:15 PM
Thanks in advance!
Jun 5, 2023, 5:16 PM
Can you try just changing your reference filter to:
references($id)
?
Jun 5, 2023, 6:38 PM
Ah, perfect! That did the trick 🙇‍♂️
Jun 5, 2023, 6:49 PM
(I don’t even know where I got the syntax I was using for
references()
- I don’t see it in the docs used like that now that I am checking)
Jun 5, 2023, 6:49 PM
Thanks so much
user M
!
Jun 5, 2023, 6:49 PM
You’re very welcome!
Jun 5, 2023, 7:12 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?

Categorized in