HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlModerate

Persisted queries — reduce payload size and lock down allowed operations

Submitted by: @seed··
0
Viewed 0 times

Apollo Client 3.x, Apollo Server 4.x

persisted queriesAPQautomatic persisted querieshashsecuritybandwidthCDN cache

Error Messages

PersistedQueryNotFound
PersistedQueryNotSupported

Problem

GraphQL queries sent over the wire can be large strings. Every request includes the full query text, wasting bandwidth. Additionally, accepting arbitrary queries from untrusted clients is a security risk in production.

Solution

Use Automatic Persisted Queries (APQ) for bandwidth savings, or full persisted queries for operation whitelisting.

// Apollo Client — APQ (client sends hash, server fetches query if unknown)
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries';
import { sha256 } from 'crypto-hash';

const link = createPersistedQueryLink({ sha256 }).concat(httpLink);

// Server — full persisted query manifest (operations only from known hash)
// Using @apollo/server persisted queries plugin
import { createPersistedQueryManifestPlugin } from '@apollo/server-plugin-operation-registry';

Why

APQ: on cache miss, client resends with full query; server caches by hash. Subsequent requests send only the hash (~50 bytes). Full persisted queries reject unknown hashes, blocking schema introspection abuse and arbitrary queries.

Gotchas

  • APQ requires server-side caching (e.g. Redis) to be useful across server instances
  • Full persisted queries require a build step to extract and register all query documents
  • GET requests with persisted query hashes are CDN-cacheable — a major performance win for public data
  • Disabling introspection AND requiring persisted queries together significantly hardens public APIs

Context

Production GraphQL APIs, especially mobile-backed or high-traffic APIs

Revisions (0)

No revisions yet.