NodeJS

주요 캐싱전략 정리

flutter developer 2024. 11. 28. 14:54

1. Write-Through

 

개념

  • 쓰기 작업 시 캐시와 데이터베이스를 동시에 업데이트하는 전략이다.
  • 읽기 작업은 캐시에서만 수행된다.

 

TypeScript 예제

class WriteThroughCache {
  private cache = new Map<string, any>();
  private database = new Map<string, any>();

  async write(key: string, value: any): Promise<void> {
    this.cache.set(key, value);
    this.database.set(key, value); // DB와 캐시에 동시 쓰기
  }

  async read(key: string): Promise<any> {
    return this.cache.get(key); // 캐시에서 읽기
  }
}

 

다이어그램

https://www.linkedin.com/pulse/write-through-caching-strategy-enjoyalgorithms/

 


 

2. Write-Behind (Write-Back)

 

개념

  • 쓰기 작업 시 캐시에만 저장하고, 데이터베이스 업데이트는 비동기로 처리한다.
  • 쓰기 성능을 최적화하지만, 장애 시 데이터 손실 위험이 있다.

TypeScript 예제

class WriteBehindCache {
  private cache = new Map<string, any>();
  private database = new Map<string, any>();

  async write(key: string, value: any): Promise<void> {
    this.cache.set(key, value);
    setTimeout(() => this.database.set(key, value), 1000); // 비동기로 DB 업데이트
  }

  async read(key: string): Promise<any> {
    const value = this.cache.get(key);
    if (value) return value;
    return this.database.get(key); // 캐시에 없으면 DB에서 읽기
  }
}

 

다이어그램

https://www.enjoyalgorithms.com/blog/write-behind-caching-pattern


 

3. Cache-Aside (Lazy Loading)

 

개념

  • 데이터가 캐시에 없을 경우, 데이터베이스에서 가져와 캐시에 저장한다.
  • 데이터 갱신은 별도로 처리.

TypeScript 예제

class CacheAside {
  private cache = new Map<string, any>();
  private database = new Map<string, any>();

  async read(key: string): Promise<any> {
    const value = this.cache.get(key);
    if (value) return value;

    // 캐시에 없으면 DB에서 조회하고 캐시에 저장
    const dbValue = this.database.get(key);
    if (dbValue) {
      this.cache.set(key, dbValue);
      return dbValue;
    }
    return null;
  }

  async write(key: string, value: any): Promise<void> {
    this.database.set(key, value); // DB에 쓰기
    this.cache.delete(key); // 캐시 무효화
  }
}

 

다이어그램

https://www.enjoyalgorithms.com/blog/cache-aside-caching-strategy


4. Read-Through

 

개념

  • 읽기 요청 시 캐시에서 데이터를 가져온다.
  • 캐시에 없으면 캐시가 데이터베이스에서 데이터를 가져와 저장 후 반환.

TypeScript 예제

class ReadThroughCache {
  private cache = new Map<string, any>();
  private database = new Map<string, any>();

  async read(key: string): Promise<any> {
    let value = this.cache.get(key);
    if (!value) {
      value = this.database.get(key); // DB에서 가져옴
      if (value) this.cache.set(key, value); // 캐시에 저장
    }
    return value;
  }

  async write(key: string, value: any): Promise<void> {
    this.cache.set(key, value);
    this.database.set(key, value); // 동시 업데이트
  }
}

 

다이어그램


5. Distributed Cache

 

개념

  • 여러 노드에 데이터를 샤딩하거나 복제하여 저장한다.
  • Redis Cluster나 Memcached를 주로 사용

TypeScript 예제 (Redis)

import * as Redis from 'ioredis';

const redis = new Redis.Cluster([
  { host: '127.0.0.1', port: 6379 },
  { host: '127.0.0.2', port: 6379 },
]);

async function write(key: string, value: any): Promise<void> {
  await redis.set(key, value);
}

async function read(key: string): Promise<any> {
  return redis.get(key);
}

 

다이어그램

https://blog.coderco.io/p/system-design-distributed-caching


6. Cache Eviction

 

개념

  • 캐시 공간이 부족할 때 특정 데이터를 제거하는 전략
  • LRU, LFU, FIFO 등이 주로 사용

TypeScript 예제 (LRU)

class LRUCache {
  private cache = new Map<string, any>();

  constructor(private capacity: number) {}

  get(key: string): any {
    if (!this.cache.has(key)) return null;

    const value = this.cache.get(key);
    this.cache.delete(key); // 기존 위치 제거
    this.cache.set(key, value); // 맨 끝에 다시 삽입
    return value;
  }

  put(key: string, value: any): void {
    if (this.cache.has(key)) this.cache.delete(key);

    if (this.cache.size >= this.capacity) {
      // 첫 번째 항목 제거
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }
}

 

다이어그램 (LRU)

https://x.com/ChrisStaud/status/1764670994768445751

 


7. Content Delivery Network (CDN) Caching (AWS CloudFront 활용)

 

개념

  • 정적 콘텐츠(예: 이미지, HTML)를 사용자와 가까운 서버에 캐싱하여 제공한다.
  • 글로벌 네트워크를 통해 빠른 응답 제공

다이어그램

https://nexnetsolutions.com/solutions/telecom-service-provider/content-delivery-network-cdn/

CDN 캐싱은 주로 AWS CloudFront, Akamai, Cloudflare 등에서 설정하며, 정적 콘텐츠에 적합함