💻 Dev

🛠️ 처음부터 만드는 LRU Cache — Map + TTL + TypeScript

왜 직접 만드나?


npm 캐시 라이브러리 대신 Map 하나로 LRU + TTL 구현. 의존성 0, 번들 0.

전체 구현


```typescript
class LRUCache {
private map = new Map();
constructor(private max: number, private ttl: number) {}
get(key: string): V | undefined {
const e = this.map.get(key);
if (!e) return undefined;
if (Date.now() > e.exp) { this.map.delete(key); return undefined; }
this.map.delete(key);
this.map.set(key, e); // 맨 뒤(최신)로 이동
return e.value;
}
set(key: string, value: V): void {
this.map.delete(key);
if (this.map.size >= this.max) {
this.map.delete(this.map.keys().next().value!);
}
this.map.set(key, { value, exp: Date.now() + this.ttl });
}
}
```

핵심 트릭


ES6 `Map`은 삽입 순서를 보장한다. `delete` → `set`으로 항목을 맨 뒤로 보내면 LRU가 된다. `keys().next()`로 가장 오래된 항목을 O(1)에 제거.

실전 적용


```typescript
const cache = new LRUCache(1000, 5 * 60_000);
async function getUser(id: string) {
const hit = cache.get(id);
if (hit) return hit;
const user = await db.users.findById(id);
cache.set(id, user);
return user;
}
```

확장 포인트


  • 통계: hit/miss 카운터로 캐시 적중률 모니터링

  • GC: `setInterval`로 만료 항목 주기적 정리

  • L2: in-memory → Redis 2단 캐시 구조로 확장
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!