Skip to main content
Why CacheeHow It Works
All Verticals5G TelecomAd TechAI InfrastructureFraud DetectionGamingTrading
PricingDocsBlogSchedule DemoLog InStart Free Trial
← Back to Blog

GraphQL Caching Strategies for Modern APIs

December 22, 2025 • 8 min read • API Performance

GraphQL's flexibility is its greatest strength—and its biggest caching challenge. Unlike REST where each endpoint has a single response, GraphQL queries can request any combination of fields. Here's how to cache effectively.

Why GraphQL Caching Is Different

REST caching is straightforward: cache by URL. GraphQL sends everything to one endpoint with varying query bodies. Traditional HTTP caching doesn't work.

You need a multi-layer approach:

  1. Client-side normalized cache (Apollo, Relay)
  2. CDN/edge caching for persisted queries
  3. Server-side response caching
  4. Resolver-level caching (DataLoader)

Layer 1: Client-Side Normalized Caching

Apollo Client and Relay automatically normalize and cache query results:

// Apollo Client setup with cache
import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
    uri: '/graphql',
    cache: new InMemoryCache({
        typePolicies: {
            User: {
                keyFields: ['id'],  // How to identify cached entities
            },
            Product: {
                keyFields: ['sku'],
            }
        }
    })
});

This means if you fetch a user in Query A, and Query B also needs that user, Apollo serves it from cache automatically.

Layer 2: Persisted Queries for CDN Caching

Convert POST requests with query bodies into GET requests with query IDs:

// Without persisted queries (not cacheable by CDN)
POST /graphql
{ "query": "{ user(id: 1) { name email } }" }

// With persisted queries (cacheable!)
GET /graphql?id=abc123&variables={"id":1}

// Server maps ID to query
const persistedQueries = {
    'abc123': '{ user(id: $id) { name email } }'
};
Performance gain: Persisted queries are typically 10x faster because CDNs can cache the response, and you're sending less data over the wire.

Layer 3: Server-Side Response Caching

Cache full query responses by hashing the query + variables:

async function executeQuery(query, variables, context) {
    // Generate cache key from query + variables
    const cacheKey = `gql:${hash(query)}:${hash(variables)}`;

    // Check cache
    const cached = await cache.get(cacheKey);
    if (cached) return cached;

    // Execute query
    const result = await graphql(schema, query, null, context, variables);

    // Cache based on response hints
    const ttl = getMinTTL(result);  // Scan response for cache directives
    if (ttl > 0) {
        await cache.set(cacheKey, result, { ttl });
    }

    return result;
}

Layer 4: DataLoader for N+1 Prevention

DataLoader batches and caches database requests within a single request:

import DataLoader from 'dataloader';

// Create loader per request
function createLoaders() {
    return {
        user: new DataLoader(async (ids) => {
            const users = await db.query(
                'SELECT * FROM users WHERE id = ANY($1)',
                [ids]
            );
            // Return in same order as requested
            return ids.map(id => users.find(u => u.id === id));
        }),

        products: new DataLoader(async (ids) => {
            // Similar batching for products
        })
    };
}

// In resolver
const resolvers = {
    Order: {
        user: (order, _, { loaders }) => {
            return loaders.user.load(order.userId);
        }
    }
};

If a query fetches 50 orders, DataLoader batches all 50 user lookups into one database query.

Cache Directives in Schema

Define caching rules directly in your GraphQL schema:

type Query {
    # Highly cacheable - rarely changes
    categories: [Category!]! @cacheControl(maxAge: 3600)

    # User-specific - shorter cache
    me: User @cacheControl(maxAge: 60, scope: PRIVATE)

    # Real-time data - no cache
    livePrice(symbol: String!): Price @cacheControl(maxAge: 0)
}

type Product {
    id: ID!
    name: String! @cacheControl(maxAge: 600)

    # Inventory changes frequently
    stockCount: Int! @cacheControl(maxAge: 30)
}

Invalidation Strategies

The hardest part of GraphQL caching is invalidation. Options:

  1. Time-based (TTL): Simple but may show stale data
  2. Entity-based: Track which entities are in each cached response
  3. Event-driven: Invalidate on mutations
// Track entities in cached responses
async function cacheWithTracking(cacheKey, result, ttl) {
    // Extract entity IDs from response
    const entities = extractEntities(result);
    // e.g., ['User:1', 'Product:42', 'Product:43']

    // Store response
    await cache.set(cacheKey, result, { ttl });

    // Track which cache keys contain each entity
    for (const entity of entities) {
        await cache.sadd(`entity:${entity}:keys`, cacheKey);
    }
}

// When entity changes, invalidate all related cache keys
async function invalidateEntity(entityType, entityId) {
    const cacheKeys = await cache.smembers(`entity:${entityType}:${entityId}:keys`);
    await cache.del(...cacheKeys);
}

GraphQL caching made simple

Cachee.ai automatically handles GraphQL response caching with intelligent invalidation.

Start Free Trial

Related Reading

The Numbers That Matter

Cache performance discussions get philosophical fast. Here are the actual measured numbers from production deployments running on documented hardware, so you can compare against your own infrastructure instead of trusting marketing copy.

The compounding effect matters more than any single number. A 28-nanosecond L0 hit means your application spends almost zero time on cache lookups in the hot path, leaving the CPU free for the actual business logic that generates revenue.

When Caching Actually Helps

Caching isn't free. It introduces a consistency problem you didn't have before. Before adding any cache layer, the question to answer is whether your workload actually benefits from caching at all.

Caching helps when three conditions hold simultaneously. First, your reads dramatically outnumber your writes — typically a 10:1 ratio or higher. Second, the same keys get read repeatedly within a window where a cached value remains valid. Third, the cost of computing or fetching the underlying value is meaningfully higher than the cost of a cache lookup. Database queries that hit secondary indexes, RPC calls to slow upstream services, expensive computed aggregations, and rendered template fragments all qualify.

Caching hurts when those conditions don't hold. Write-heavy workloads suffer because every write invalidates a cache entry, multiplying your work. Workloads with poor key locality suffer because the cache wastes memory storing entries that never get reused. Workloads where the underlying fetch is already fast — well-indexed primary key lookups against a properly tuned database, for example — gain almost nothing from caching and inherit the consistency complexity for no reason.

The honest first step before any cache deployment is measuring your actual read/write ratio, key access distribution, and underlying fetch latency. If your read/write ratio is below 5:1 or your underlying database is already returning results in single-digit milliseconds, the engineering time is better spent elsewhere.

Memory Efficiency Is The Hidden Cost Lever

Throughput numbers get the headlines but memory efficiency determines your monthly bill. A cache that stores the same hot data in less RAM lets you run a smaller instance class — and on AWS that's the difference between profitable and breakeven for a lot of services.

Redis stores each key as a Simple Dynamic String with 16 bytes of header overhead, plus dictEntry pointers in the main hashtable, plus embedded TTL metadata. For 1KB values, per-entry overhead lands around 1100-1200 bytes once you account for hashtable load factor and slab fragmentation. At a million keys, that's roughly 1.2 GB of resident memory just for the data.

Cachee's L1 layer uses sharded DashMap entries with compact packing — a 64-bit key hash, value bytes, an 8-byte expiry timestamp, and a small frequency counter for the CacheeLFU admission filter. Per-entry overhead lands at roughly 40 bytes of structural data on top of the value itself. For the same million-key workload, that's about 13% smaller resident memory. On AWS ElastiCache pricing, that gap is the difference between needing a cache.r7g.large versus a cache.r7g.xlarge for borderline workloads.

What This Actually Costs

Concrete pricing math beats hypothetical. A typical SaaS workload with 1 billion cache operations per month, average 800-byte values, and a 5 GB hot working set currently runs on AWS ElastiCache cache.r7g.xlarge primary plus a read replica — roughly $480 per month for the two nodes, plus cross-AZ data transfer charges that quietly add another $50-150 per month depending on access patterns.

Migrating the hot path to an in-process L0/L1 cache and keeping ElastiCache as a cold L2 fallback drops the dedicated cache spend to $120-180 per month. For workloads where the hot working set fits inside the application's existing memory budget, you can eliminate the dedicated cache tier entirely. The cache becomes a library you link into your binary instead of a separate service to operate.

Compounded over twelve months, that's $3,600 to $4,500 per year on a single small workload. Multiply across a fleet of services and the savings start showing up in finance team conversations. The bigger savings usually come from eliminating cross-AZ data transfer charges, which Redis-as-a-service architectures incur on every read that crosses an availability zone.