본문 바로가기

장 실습: 캐시 hit와 miss를 지표로 만들기

캐시 조회 분기에서 hit·miss 카운터를 한 번씩 기록합니다. 가격 수정 뒤 캐시 삭제와 miss 증가가 함께 일어나는지 확인합니다.

캐시가 원본 호출을 줄였는지 로그를 세는 대신 hit와 miss를 함께 기록해 봅니다. 성능 모니터링의 MetricsService에 카운터를 더하고 상품 조회와 가격 변경을 이어 확인합니다.

이 글을 마치면 다음을 할 수 있습니다.

  • 캐시 조회 분기에서 hit·miss 카운터를 한 번씩 기록합니다.
  • 가격 수정 뒤 캐시 삭제와 miss 증가가 함께 일어나는지 확인합니다.

시작 상태

앞 글까지의 perf-app을 씁니다. 캐싱 전략의 ProductsService와 update()의 key 삭제, 앞 글의 MetricsService·MetricsModule·GET /metrics가 있어야 합니다. 완성 파일은 첫 글의 Redis 설정을 기준으로 합니다.

Redis와 nest-postgres를 켜고 프로젝트 폴더에서 npm run start:dev로 시작합니다. 추가 패키지는 없습니다. 전역 접두사 없이 3000번 포트를 쓰며, 지표를 세기 시작할 때는 서버를 다시 시작하고 60초 넘게 조회하지 않은 상품을 고릅니다.

완성 조건

첫 글에서는 캐시가 일했는지를 [origin] 로그로 확인했습니다. 이것을 지표로 바꿔 hit 비율을 숫자로 볼 수 있게 하세요.

  • /metrics에 cache_lookups_total 카운터가 있고, 라벨은 cache(어느 캐시인지)와 result(hit 또는 miss)입니다.
  • GET /products/:id가 캐시에서 값을 찾으면 result="hit"가, 찾지 못해 원본을 읽으면 result="miss"가 1 늘어납니다.
  • 가격을 PATCH로 고친 직후의 첫 조회는 miss로 기록됩니다.
  • 지표를 다루는 코드는 MetricsService에만 있고, ProductsService는 메서드 하나를 부르기만 합니다.

힌트: MetricsModule은 이미 MetricsService를 내보내고 있습니다. 상품 모듈이 이 모듈을 가져오면 ProductsService의 생성자에서 주입받을 수 있습니다.

1단계: 카운터를 서비스에 등록하기

MetricsService의 같은 Registry에 cache_lookups_total을 만들고 recordCacheLookup 메서드에서 기록합니다.

체크포인트: 라벨 이름은 cache, result 두 개이고 결과 값은 hit 또는 miss입니다.

2단계: 상품 조회의 두 분기에 기록하기

상품 모듈에 MetricsModule을 가져오고 서비스 생성자에서 주입받습니다. 캐시 값을 반환하기 직전에는 hit, 원본을 읽기 전에는 miss를 기록합니다.

체크포인트: 캐시가 빈 상품을 연속 세 번 조회하면 miss는 1, hit는 2입니다.

3단계: 가격 수정 뒤 다시 조회하기

첫 글의 PATCH 요청으로 가격을 고친 뒤 같은 상품을 한 번 더 조회합니다. 이어서 아래 장 전체 점검을 진행합니다.

체크포인트: miss가 2로 늘고 hit는 2입니다. 네 번의 조회 중 hit 비율은 2 ÷ 4입니다.

다를 때 먼저 볼 곳

증상먼저 볼 곳
MetricsService 주입 오류로 시작하지 않는다ProductsModule의 imports에 MetricsModule이 있는지
첫 요청도 hit로 나온다기존 Redis 값이 만료된 상품으로 시작했는지
가격 수정 뒤 miss가 늘지 않는다update에서 같은 product:v1 key를 지우는지

완성 파일과 확인

완성 파일과 확인 절차 보기

아래 완성 파일은 9장 첫 글 본문의 Redis 캐시와 key 삭제까지 적용한 상태입니다. 동시 요청을 합치는 선택 연습을 했다면 기존 inFlight 처리를 유지하고, hit 반환 직전과 miss 분기에 같은 기록 호출을 더합니다.

src/metrics/metrics.service.ts
import { Injectable } from '@nestjs/common';
import * as client from 'prom-client';

@Injectable()
export class MetricsService {
  private readonly register = new client.Registry();
  private readonly httpRequestDurationSeconds: client.Histogram<string>;
  private readonly totalRequests: client.Counter<string>;
  private readonly cacheLookups: client.Counter<string>;

  constructor() {
    client.collectDefaultMetrics({ register: this.register });

    this.httpRequestDurationSeconds = new client.Histogram({
      name: 'http_request_duration_seconds',
      help: 'Duration of HTTP requests in seconds',
      labelNames: ['method', 'route', 'code'] as const,
      buckets: [0.1, 0.5, 1, 2, 5],
      registers: [this.register],
    });

    this.totalRequests = new client.Counter({
      name: 'http_requests_total',
      help: 'Total number of HTTP requests',
      labelNames: ['method', 'route', 'code'] as const,
      registers: [this.register],
    });

    this.cacheLookups = new client.Counter({
      name: 'cache_lookups_total',
      help: 'Total number of cache lookups',
      labelNames: ['cache', 'result'] as const,
      registers: [this.register],
    });
  }

  recordCacheLookup(cache: string, result: 'hit' | 'miss') {
    this.cacheLookups.labels(cache, result).inc();
  }

  recordHttpRequest(
    method: string,
    route: string,
    code: number,
    durationMs: number,
  ) {
    this.httpRequestDurationSeconds
      .labels(method, route, code.toString())
      .observe(durationMs / 1000);
    this.totalRequests.labels(method, route, code.toString()).inc();
  }

  getContentType(): string {
    return this.register.contentType;
  }

  async getMetrics(): Promise<string> {
    return this.register.metrics();
  }
}
src/products/products.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager';
import { Product, ProductRepository } from './product.repository';
import { UpdateProductDto } from './update-product.dto';
import { MetricsService } from '../metrics/metrics.service';

@Injectable()
export class ProductsService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
    private readonly products: ProductRepository,
    private readonly metrics: MetricsService,
  ) {}

  findAll(): Promise<Product[]> {
    return this.products.findAll();
  }

  async findOne(id: string): Promise<Product> {
    const key = `product:v1:${id}`;
    const cached = await this.cache.get<Product>(key);

    if (cached !== undefined) {
      this.metrics.recordCacheLookup('product', 'hit');
      return cached;
    }

    this.metrics.recordCacheLookup('product', 'miss');
    const product = await this.products.findOne(id);
    await this.cache.set(key, product, 60_000);
    return product;
  }

  async update(id: string, input: UpdateProductDto): Promise<Product> {
    const product = await this.products.update(id, input);
    await this.cache.del(`product:v1:${id}`);
    return product;
  }
}
src/products/products.module.ts
import { Module } from '@nestjs/common';
import { MetricsModule } from '../metrics/metrics.module';
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';
import { ProductRepository } from './product.repository';
import { ProductsController } from './products.controller';
import { ProductsService } from './products.service';

@Module({
  imports: [
    MetricsModule,
    CacheModule.registerAsync({
      useFactory: () => {
        const redisStore = createKeyv(
          process.env.REDIS_URL ?? 'redis://localhost:6379',
        );
        redisStore.on('error', (error: unknown) => {
          console.error('Redis cache error:', error);
        });

        return { stores: [redisStore] };
      },
    }),
  ],
  controllers: [ProductsController],
  providers: [ProductsService, ProductRepository],
})
export class ProductsModule {}

이렇게 확인합니다. 서버가 다시 시작한 뒤(Redis를 쓴다면 60초 넘게 요청하지 않은 상품 번호로) curl http://localhost:3000/products/1을 세 번 보내고 지표를 걸러 봅니다.

curl -s http://localhost:3000/metrics | grep cache_lookups_total

PowerShell에서는 curl.exe -s http://localhost:3000/metrics | Select-String cache_lookups_total입니다. result="miss"가 1, result="hit"가 2면 맞습니다. 이어서 첫 글의 PATCH 명령으로 가격을 고치고 한 번 더 조회하면 miss가 2로 늘어납니다. hit 비율은 hit ÷ (hit + miss)로, 지금은 2 ÷ 4입니다.

여기까지 하면 perf-app은 이 장의 네 주제를 모두 갖춥니다. 마지막으로 다음을 차례로 확인합니다.

  • GET /products/1을 반복하면 [origin] 로그가 처음 한 번만 찍히고, cache_lookups_total의 hit가 늘어납니다.
  • GET /users가 사용자 20명과 각자의 주문을 돌려주고, 터미널의 query: 줄은 두 개입니다(둘째 글의 연습 문제 2).
  • docker stop nest-postgres 뒤 GET /health/live는 200이고 GET /health/ready는 실패합니다. 다시 켜면 회복됩니다.
  • GET /metrics에 경로별 요청 수와 응답 시간 버킷이 나옵니다.

더 해 보기

  • GET /products 목록의 자동 캐시를 걷어 내고, 서비스에서 products:v1:list 같은 key로 직접 캐시한 뒤 update()에서 함께 지웁니다. 목록이 예전 가격을 보여 주던 문제가 사라지는지 확인합니다.
  • 데이터베이스 조회 시간을 재는 히스토그램을 더해 GET /users의 N+1 경로와 묶음 조회 경로를 숫자로 비교합니다.
  • ready가 Redis 연결도 확인하게 하고, Redis를 껐을 때의 응답을 정합니다.

이것으로 9장을 마칩니다. 다음 장의 CORS, CSRF, XSS 대응부터는 애플리케이션의 보안을 다룹니다.