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

Serverless Function Caching Patterns

December 22, 2025 • 7 min read • Serverless

Serverless functions have unique caching challenges: cold starts, ephemeral state, and pay-per-invocation pricing. The right caching strategy can cut costs by 80% and eliminate cold start latency. Here's how.

The Serverless Caching Challenge

Traditional caching assumes persistent processes. Serverless breaks this assumption:

You need external caching (Redis, CDN) plus smart connection reuse.

Pattern 1: Connection Reuse

Establish connections outside the handler to reuse across warm invocations:

// AWS Lambda - Reuse database and cache connections

// These persist across warm invocations
let redisClient = null;
let dbPool = null;

async function getRedis() {
    if (!redisClient) {
        const Redis = require('ioredis');
        redisClient = new Redis(process.env.REDIS_URL);
    }
    return redisClient;
}

async function getDB() {
    if (!dbPool) {
        const { Pool } = require('pg');
        dbPool = new Pool({
            connectionString: process.env.DATABASE_URL,
            max: 1  // Single connection per Lambda instance
        });
    }
    return dbPool;
}

exports.handler = async (event) => {
    const cache = await getRedis();
    const db = await getDB();

    // Use cache and db...
};
Cost savings: Connection reuse reduces cold start overhead by 50-200ms and eliminates repeated connection establishment costs.

Pattern 2: Edge Caching (CDN)

Cache responses at the edge for static or semi-static data:

// Vercel Edge Function with caching headers
export const config = { runtime: 'edge' };

export default async function handler(req) {
    const cacheKey = new URL(req.url).pathname;

    // Check if we can serve from cache
    const cached = await fetch(`https://cache.example.com/${cacheKey}`);
    if (cached.ok) {
        return new Response(await cached.text(), {
            headers: {
                'Content-Type': 'application/json',
                'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300',
                'X-Cache': 'HIT'
            }
        });
    }

    // Generate response
    const data = await generateData();

    // Cache for next time
    await cacheResponse(cacheKey, data);

    return new Response(JSON.stringify(data), {
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300',
            'X-Cache': 'MISS'
        }
    });
}

Pattern 3: Cloudflare Workers KV

Cloudflare's edge key-value store for low-latency caching:

// Cloudflare Worker with KV caching
export default {
    async fetch(request, env) {
        const url = new URL(request.url);
        const cacheKey = `cache:${url.pathname}`;

        // Try KV cache first
        let data = await env.CACHE_KV.get(cacheKey, 'json');

        if (!data) {
            // Fetch from origin
            const response = await fetch(env.API_ORIGIN + url.pathname);
            data = await response.json();

            // Cache in KV (60 second TTL)
            await env.CACHE_KV.put(cacheKey, JSON.stringify(data), {
                expirationTtl: 60
            });
        }

        return new Response(JSON.stringify(data), {
            headers: { 'Content-Type': 'application/json' }
        });
    }
};

Pattern 4: In-Memory Cache for Warm Functions

Cache frequently accessed data in function memory:

// Global cache (survives across warm invocations)
const memoryCache = new Map();
const CACHE_TTL = 60000; // 1 minute

function getCached(key) {
    const cached = memoryCache.get(key);
    if (cached && Date.now() < cached.expiry) {
        return cached.value;
    }
    return null;
}

function setCached(key, value, ttl = CACHE_TTL) {
    memoryCache.set(key, {
        value,
        expiry: Date.now() + ttl
    });

    // Limit cache size
    if (memoryCache.size > 1000) {
        const oldest = memoryCache.keys().next().value;
        memoryCache.delete(oldest);
    }
}

exports.handler = async (event) => {
    const key = `config:${event.tenantId}`;

    // Check memory cache first (fastest)
    let config = getCached(key);

    if (!config) {
        // Check Redis (fast)
        const redis = await getRedis();
        config = await redis.get(key);

        if (!config) {
            // Database (slowest)
            config = await db.query('SELECT * FROM config WHERE tenant_id = $1', [event.tenantId]);
            await redis.set(key, JSON.stringify(config), 'EX', 300);
        }

        setCached(key, config);
    }

    return config;
};

Pattern 5: Pre-warming Critical Paths

Keep functions warm for critical paths:

// CloudWatch scheduled event to keep Lambda warm
// Run every 5 minutes

exports.warmHandler = async (event) => {
    if (event.source === 'aws.events') {
        // This is a warming invocation
        console.log('Warming invocation - keeping connections alive');

        // Touch connections to keep them alive
        const redis = await getRedis();
        await redis.ping();

        return { statusCode: 200, body: 'Warmed' };
    }

    // Regular invocation logic...
};

Cost Optimization

Caching reduces serverless costs in multiple ways:

Serverless caching made simple

Cachee.ai integrates with Lambda, Vercel, and Cloudflare for automatic edge caching with zero config.

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.