Advanced

Como Projetar e Implementar Estratégias de Cache com Claude Code

Aprenda a projetar e implementar estratégias de cache usando o Claude Code. Inclui exemplos práticos de código e orientação passo a passo.

Vantagens de Usar Claude Code para Design de Estratégias de Cache

Sem um design cuidadoso, o cache pode levar à exibição de dados desatualizados ou desperdício de memória. O Claude Code analisa os padrões de acesso a dados da sua aplicação e pode propor e implementar estratégias de cache otimizadas.

Implementação de Cache Redis

> Implemente uma camada de cache com Redis.
> Com invalidação de cache, gerenciamento de TTL e pattern cache-aside.
// src/lib/cache.ts
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL!);

interface CacheOptions {
  ttl?: number;      // em segundos
  prefix?: string;
}

export class CacheService {
  private defaultTTL = 300; // 5 minutos

  async get<T>(key: string, options?: CacheOptions): Promise<T | null> {
    const fullKey = this.buildKey(key, options?.prefix);
    const data = await redis.get(fullKey);
    if (!data) return null;

    try {
      return JSON.parse(data) as T;
    } catch {
      return null;
    }
  }

  async set<T>(key: string, value: T, options?: CacheOptions): Promise<void> {
    const fullKey = this.buildKey(key, options?.prefix);
    const ttl = options?.ttl ?? this.defaultTTL;

    await redis.setex(fullKey, ttl, JSON.stringify(value));
  }

  async getOrSet<T>(
    key: string,
    fetcher: () => Promise<T>,
    options?: CacheOptions
  ): Promise<T> {
    const cached = await this.get<T>(key, options);
    if (cached !== null) return cached;

    const data = await fetcher();
    await this.set(key, data, options);
    return data;
  }

  async invalidate(key: string, prefix?: string): Promise<void> {
    const fullKey = this.buildKey(key, prefix);
    await redis.del(fullKey);
  }

  async invalidatePattern(pattern: string): Promise<void> {
    const keys = await redis.keys(pattern);
    if (keys.length > 0) {
      await redis.del(...keys);
    }
  }

  private buildKey(key: string, prefix?: string): string {
    return prefix ? `${prefix}:${key}` : key;
  }
}

export const cache = new CacheService();

Implementação do Pattern Cache-Aside

// src/services/product-service.ts
import { cache } from '@/lib/cache';
import { prisma } from '@/lib/db';

export class ProductService {
  async getProduct(id: string) {
    return cache.getOrSet(
      `product:${id}`,
      () => prisma.product.findUnique({
        where: { id },
        include: { category: true, reviews: { take: 10 } },
      }),
      { ttl: 600, prefix: 'products' }
    );
  }

  async getPopularProducts(limit = 20) {
    return cache.getOrSet(
      `popular:${limit}`,
      () => prisma.product.findMany({
        orderBy: { salesCount: 'desc' },
        take: limit,
        include: { category: true },
      }),
      { ttl: 300, prefix: 'products' }
    );
  }

  async updateProduct(id: string, data: UpdateProductInput) {
    const product = await prisma.product.update({
      where: { id },
      data,
    });

    // Invalidar cache relacionado
    await cache.invalidate(`product:${id}`, 'products');
    await cache.invalidatePattern('products:popular:*');

    return product;
  }
}

Configuração de Headers de Cache HTTP

// src/middleware.ts
import { NextResponse, NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  const res = NextResponse.next();
  const path = req.nextUrl.pathname;

  // Assets estáticos: cache de longo prazo
  if (path.match(/\.(js|css|png|jpg|svg|woff2)$/)) {
    res.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
  }

  // API: sem cache
  if (path.startsWith('/api/')) {
    res.headers.set('Cache-Control', 'no-store');
  }

  // Páginas: cache de curto prazo + ISR
  if (!path.startsWith('/api/') && !path.match(/\.[a-z]+$/)) {
    res.headers.set('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
  }

  return res;
}

Cache em Memória (Interno da Aplicação)

Para pequenas quantidades de dados, cache in-memory é eficaz.

// src/lib/memory-cache.ts
interface CacheEntry<T> {
  value: T;
  expiresAt: number;
}

export class MemoryCache {
  private store = new Map<string, CacheEntry<unknown>>();
  private maxSize: number;

  constructor(maxSize = 1000) {
    this.maxSize = maxSize;
  }

  get<T>(key: string): T | null {
    const entry = this.store.get(key);
    if (!entry) return null;

    if (Date.now() > entry.expiresAt) {
      this.store.delete(key);
      return null;
    }

    return entry.value as T;
  }

  set<T>(key: string, value: T, ttlMs: number): void {
    // Verificação de limite de tamanho
    if (this.store.size >= this.maxSize) {
      const firstKey = this.store.keys().next().value;
      if (firstKey) this.store.delete(firstKey);
    }

    this.store.set(key, {
      value,
      expiresAt: Date.now() + ttlMs,
    });
  }

  clear(): void {
    this.store.clear();
  }
}

// Para dados acessados frequentemente como valores de configuração
export const configCache = new MemoryCache(100);

Guia de Seleção de Estratégia de Cache

Tipo de DadosCache RecomendadoTTL Sugerido
Dados de configuraçãoMemória + Redis1 hora
Perfis de usuárioRedis10 minutos
Listas de produtosRedis + CDN5 minutos
Informações de sessãoRedis24 horas
Assets estáticosCDN1 ano
Respostas de APIHTTP Cache1 minuto

Monitoramento de Cache

// Medição da taxa de acerto do cache
export class CacheMetrics {
  private hits = 0;
  private misses = 0;

  recordHit() { this.hits++; }
  recordMiss() { this.misses++; }

  getHitRate(): number {
    const total = this.hits + this.misses;
    return total === 0 ? 0 : this.hits / total;
  }

  getStats() {
    return {
      hits: this.hits,
      misses: this.misses,
      hitRate: `${(this.getHitRate() * 100).toFixed(1)}%`,
    };
  }
}

Resumo

Com o Claude Code, você pode projetar e implementar eficientemente estratégias de cache em múltiplas camadas como cache Redis, cache HTTP e cache em memória. Documentando as diretrizes de design de cache no CLAUDE.md, você obtém uma implementação consistente em todo o projeto. Para uma visão geral de melhorias de performance, consulte dicas para triplicar a produtividade.

Para mais informações sobre o Claude Code, consulte a documentação oficial da Anthropic. Para detalhes sobre o Redis, consulte a documentação oficial do Redis.

#Claude Code #caching #Redis #performance #design