556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / server-cache-lru.md
1.3 KB
1--- 2title: Cross-Request LRU Caching 3impact: HIGH 4impactDescription: caches across requests 5tags: server, cache, lru, cross-request 6--- 7 8## Cross-Request LRU Caching 9 10`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. 11 12**Implementation:** 13 14```typescript 15import { LRUCache } from 'lru-cache' 16 17const cache = new LRUCache<string, any>({ 18 max: 1000, 19 ttl: 5 * 60 * 1000 // 5 minutes 20}) 21 22export async function getUser(id: string) { 23 const cached = cache.get(id) 24 if (cached) return cached 25 26 const user = await db.user.findUnique({ where: { id } }) 27 cache.set(id, user) 28 return user 29} 30 31// Request 1: DB query, result cached 32// Request 2: cache hit, no DB query 33``` 34 35Use when sequential user actions hit multiple endpoints needing the same data within seconds. 36 37**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. 38 39**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. 40 41Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)