Vercel 빌드 캐시 invalidated 방법
Vercel 빌드 캐시가 작동하는 원리와 캐시를 무효화하는 다양한 방법을 알아봅니다.
Vercel 빌드 캐시 invalidated 방법
Introduction
Vercel은 빌드 프로세스를 가속화하기 위해 캐시 메커니즘을 사용합니다. 하지만 캐시가 올바르게 무효화되지 않으면 예상치 못한 빌드 결과나 배포 문제가 발생할 수 있습니다. 이 글에서는 Vercel 빌드 캐시가 작동하는 원리와 캐시를 효과적으로 무효화하는 방법을 살펴보겠습니다.
Environment
- Vercel 프로젝트 (Next.js 14+)
- Turborepo (monorepo 환경)
- npm/yarn 패키지 매니저
- Git 기반 배포
Problem
빌드 캐시로 인해 문제가 발생하는 경우:
# 캐시된 빌드 결과가 다른 환경에서 실행됨
vercel build --prod
# 빌드 캐시 디렉토리 확인
ls -la .vercel/cache
# 캐시가 예상과 다르게 동작하는 경우
Error: Build cache contains stale dataAnalysis
Vercel 빌드 캐시는 다음 요소들을 기반으로 캐시 키를 생성합니다:
- package-lock.json 또는 yarn.lock: 의존성 해시
- 소스 코드 해시: 파일 변경 감지
- 환경 변수: 빌드 시 환경 변수
- Node.js 버전: 런타임 버전
캐시가 무효화되는 조건:
- lock 파일 변경
- 소스 코드 변경
- 환경 변수 변경
- 수동 캐시 삭제
Solution
1. Vercel CLI를 사용한 캐시 관리
# 빌드 캐시 삭제
rm -rf .vercel/cache
# 강제 재빌드
vercel build --force
# 특정 프로덕션 배포 캐시 삭제
vercel cache purge --token=YOUR_TOKEN
# 프로젝트 빌드 캐시 확인
vercel cache ls2. vercel.json에서 캐시 제어
{
"build": {
"cache": {
"exclude": [
"node_modules/**",
".env.local",
"*.test.js"
]
}
}
}3. Turborepo 캐시 설정
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**"],
"env": ["DATABASE_URL", "API_KEY"]
},
"lint": {
"outputs": []
},
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"]
}
}
}4. 환경 변수 기반 캐시 무효화
// scripts/invalidate-cache.js
const crypto = require('crypto');
const fs = require('fs');
function generateCacheKey() {
const envVars = [
process.env.DATABASE_URL,
process.env.API_KEY,
process.env.NODE_ENV
].join('-');
return crypto.createHash('md5').update(envVars).digest('hex');
}
// 빌드 시 캐시 키 확인
const currentKey = generateCacheKey();
const cacheFile = '.vercel/cache-key';
if (fs.existsSync(cacheFile)) {
const savedKey = fs.readFileSync(cacheFile, 'utf8');
if (savedKey !== currentKey) {
console.log('Cache invalidated due to environment change');
fs.rmSync('.vercel/cache', { recursive: true, force: true });
}
}
fs.writeFileSync(cacheFile, currentKey);5. GitHub Actions에서 캐시 관리
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Cache Vercel
uses: actions/cache@v4
with:
path: .vercel/cache
key: vercel-${{ hashFiles('**/lock files') }}
restore-keys: |
vercel-
- name: Deploy to Vercel
uses: amondnet/vercel-action@v25
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-args: '--prod'
- name: Clear cache if needed
if: contains(github.event.head_commit.message, '[clear-cache]')
run: |
rm -rf .vercel/cache
echo "Cache cleared"6. 캐시 무효화 스크립트
// scripts/clear-vercel-cache.js
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
function clearVercelCache() {
const cacheDir = path.join(__dirname, '../.vercel/cache');
if (fs.existsSync(cacheDir)) {
fs.rmSync(cacheDir, { recursive: true, force: true });
console.log('Vercel cache cleared successfully');
} else {
console.log('No cache directory found');
}
}
function forceRedeploy() {
try {
execSync('vercel --prod --force', { stdio: 'inherit' });
console.log('Force redeploy completed');
} catch (error) {
console.error('Redeploy failed:', error.message);
process.exit(1);
}
}
// 메인 실행
clearVercelCache();
forceRedeploy();7. 캐시 모니터링
// scripts/monitor-cache.js
const { execSync } = require('child_process');
function getCacheStats() {
try {
const output = execSync('vercel cache ls --json', { encoding: 'utf8' });
const stats = JSON.parse(output);
console.log('Cache Statistics:');
console.log(`Total size: ${stats.totalSize} bytes`);
console.log(`Entry count: ${stats.entries.length}`);
console.log(`Last updated: ${stats.lastUpdated}`);
} catch (error) {
console.error('Failed to get cache stats:', error.message);
}
}
getCacheStats();Lessons Learned
- 캐시 키 이해: 캐시가 어떤 요소들을 기반으로 생성되는지 이해하는 것이 중요합니다.
- 수동 무효화: 문제가 발생할 때 수동으로 캐시를 무효화하는 방법을 알아야 합니다.
- 환경 변수 관리: 환경 변수 변경 시 캐시가 자동으로 무효화되지 않을 수 있습니다.
- CI/CD 통합: GitHub Actions 등에서 캐시 관리를 자동화하는 것이 효과적입니다.
- 모니터링: 캐시 히트율을 모니터링하여 빌드 시간을 최적화해야 합니다.
This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.