| 1 | --- |
| 2 | title: Cross-Request LRU Caching |
| 3 | impact: HIGH |
| 4 | impactDescription: caches across requests |
| 5 | tags: 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 |
| 15 | import { LRUCache } from 'lru-cache' |
| 16 | |
| 17 | const cache = new LRUCache<string, any>({ |
| 18 | max: 1000, |
| 19 | ttl: 5 * 60 * 1000 // 5 minutes |
| 20 | }) |
| 21 | |
| 22 | export 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 | |
| 35 | Use 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 | |
| 41 | Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache) |
| 42 |