Cache components

From motormetrics/motormetrics · View interactive version

Cache components is an AI agent skill from the GitHub repository motormetrics/motormetrics. Ensure 'use cache' is used strategically to minimize CPU usage and ISR writes. Use when creating/modifying queries to verify caching decisions align with data update patterns and cost optimization.

How to use this skill

Skill file

Cache Components Skill

This Skill ensures strategic use of Next.js 16 Cache Components to minimize CPU usage and ISR write overhead while maximizing cost efficiency.

When to Activate

Core Philosophy: Cache Strategically, Not Universally

NOT every query needs "use cache". Apply caching only when:

✅ Good Caching Candidates:

❌ Poor Caching Candidates:

CPU & ISR Cost Analysis

Why Strategic Caching Matters:

Without caching:

With well-planned caching (cacheLife("max") with 30-day revalidation):

With poorly-planned caching (short revalidation periods, granular tags):

Implementation Checklist

1. Evaluate Caching Necessity

Before adding "use cache", ask:

2. Correct Cache Pattern (When Caching Is Justified)

import { CACHE_TAG } from "@web/lib/cache";
import { cacheLife, cacheTag } from "next/cache";

export const getCarRegistrations = async () => {
  "use cache: remote";  // remote: shared Vercel Data Cache, not per-instance memory
  cacheLife("max");  // 30-day revalidation for monthly data
  cacheTag(CACHE_TAG.CARS);  // Domain-level tag, NOT per-query

  return db.query.cars.findMany({
    // ... query logic
  });
};

3. Cache Tag Strategy

Use domain-level tags (from src/lib/cache.ts):

Why domain-level?

4. Cache Life Profile

Project uses custom "max" profile (next.config.ts):

cacheLife: {
  max: {
    stale: 2592000,      // 30 days - client cache
    revalidate: 2592000, // 30 days - automatic regeneration
    expire: 31536000,    // 1 year - cache expiration
  },
}

When to use cacheLife("max"):

When NOT to use caching:

Common Patterns

✅ Good: Static Monthly Data

export const getLatestCOE = async (): Promise<COEResult[]> => {
  "use cache: remote";
  cacheLife("max");  // Monthly updates = perfect fit
  cacheTag(CACHE_TAG.COE);

  return db.query.coe.findFirst({
    orderBy: desc(coe.month),
  });
};

Why this works: COE data updates 2x/month, 30-day cache = ~2 regenerations/month.

❌ Bad: User-Specific Data

// DON'T DO THIS
export const getUserPreferences = async (userId: string) => {
  "use cache";  // ❌ Wrong! User-specific data shouldn't be cached globally
  cacheLife("max");
  cacheTag(CACHE_TAG.USERS);

  return db.query.users.findFirst({ where: eq(users.id, userId) });
};

Why this fails: Each user needs their own data, global caching creates stale/wrong results.

❌ Bad: Frequently Changing Data

// DON'T DO THIS
export const getBlogViewCount = async (postId: string) => {
  "use cache";  // ❌ Wrong! View counts change on every page view
  cacheLife("max");
  cacheTag(CACHE_TAG.POSTS);

  return db.query.analytics.count({ where: eq(analytics.postId, postId) });
};

Why this fails: 30-day cache on data that changes every minute = stale data.

✅ Good: Write Operations (No Caching)

export const createPost = async (data: PostInput) => {
  // NO "use cache" - write operations should never be cached
  const result = await db.insert(posts).values(data);

  // Invalidate cache AFTER write
  revalidateTag(CACHE_TAG.POSTS);

  return result;
};

Revalidation Strategy

Prefer manual revalidation over automatic:

// In API route or workflow after data import
import { revalidateTag } from "next/cache";
import { CACHE_TAG } from "@web/lib/cache";

// After monthly LTA data import completes
revalidateTag(CACHE_TAG.CARS);  // Immediate cache refresh
revalidateTag(CACHE_TAG.COE);

Benefits:

Validation Checklist

When reviewing query functions, verify:

  1. Caching is justified: Does this reduce CPU more than ISR overhead?
  2. Correct imports: cacheLife, cacheTag from next/cache, CACHE_TAG from @web/lib/cache
  3. Appropriate profile: cacheLife("max") for monthly data
  4. Domain-level tags: Using CACHE_TAG.*, not granular per-query tags
  5. No caching of: User-specific data, frequently changing data, write operations

Tools Used

Target Directories

Performance Impact

Strategic Caching (monthly data with 30-day revalidation):

Over-Caching (caching everything with short revalidation):

Under-Caching (no caching at all):

Related Documentation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.