OpenAI API 응답 캐싱으로 비용 50% 절감하기

문제 상황

사용자 질의 응답 서비스를 운영하면서 GPT-4 API 비용이 월 $2,000을 넘어섰다. 로그를 분석해보니 유사한 질문이 반복적으로 들어오는데도 매번 API를 호출하고 있었다.

캐싱 전략

입력 텍스트를 해시키로 변환하고 Redis에 응답을 저장하는 방식을 선택했다. TTL은 24시간으로 설정했다.

import { createHash } from 'crypto';
import { redis } from './redis';
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

function getCacheKey(prompt: string, model: string): string {
  const hash = createHash('sha256')
    .update(`${model}:${prompt}`)
    .digest('hex');
  return `openai:${hash}`;
}

async function getChatCompletion(prompt: string, model = 'gpt-4') {
  const cacheKey = getCacheKey(prompt, model);
  
  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }
  
  const response = await openai.chat.completions.create({
    model,
    messages: [{ role: 'user', content: prompt }],
  });
  
  await redis.setex(cacheKey, 86400, JSON.stringify(response));
  return response;
}

결과

  • API 호출 47% 감소
  • 월 비용 $950으로 하락
  • 평균 응답 속도 2.3초 → 0.1초
  • 캐시 히트율 52%

주의사항

실시간성이 중요한 요청은 캐시 대상에서 제외했다. 날씨, 뉴스 등 시간에 민감한 질의는 별도 처리가 필요하다. 또한 사용자별 맥락이 필요한 대화는 세션 ID를 캐시키에 포함시켜야 한다.

Production 배포 후 일주일간 모니터링했고, 특별한 이슈 없이 안정적으로 운영 중이다.