Split View: CDN과 엣지 컴퓨팅 완전 해부 — Anycast, 캐시 무효화, DDoS 방어, Lambda@Edge vs Workers vs Compute
CDN과 엣지 컴퓨팅 완전 해부 — Anycast, 캐시 무효화, DDoS 방어, Lambda@Edge vs Workers vs Compute
들어가며 — 1.3초의 승부
2006년 Amazon 실험: 페이지 로딩이 100ms 느려지면 매출 1% 감소. 2017년 Google: 모바일에서 1초 → 3초면 바운스율 32% 증가.
1초를 벌기 위해 인터넷 회사들은 지구 전체에 서버를 깔고, BGP를 조작하고, 캐시 계층을 쌓고, 심지어 서버리스 함수를 사용자 반경 100km 안에 배치했다. 이 글에서는:
- CDN의 탄생 — Akamai가 1998년 풀려던 문제
- Anycast 라우팅의 내부 — "어떻게 같은 IP가 전 세계 어디서든 가까운 곳으로?"
- 캐시 계층 전략 — tiered, shielded, push
- 캐시 무효화의 난제와 실전 패턴
- DDoS 방어 — L3/L4/L7 3층 방패
- 엣지 컴퓨팅의 의미와 3대 제품(Lambda@Edge, Cloudflare Workers, Fastly Compute)
- 이미지/비디오 변환의 엣지 처리
- Zero Trust — Cloudflare Access로 VPN을 대체
- 실전 장애 사례 3개
이전 글 WebAssembly + WASI 완전 해부에서 Wasm이 엣지의 실행 엔진이라고 했다. 이 글에서는 그 엔진이 올라가는 전 세계 규모의 인프라를 본다.
1. CDN의 탄생 — 1998년 Akamai
문제: 1997년 슈퍼볼
CBS가 스포츠 이벤트를 웹으로 스트리밍 시도. 서버는 보스턴에, 사용자는 캘리포니아에. 1997년 기준 미 대륙 왕복 약 70ms, 대역폭 경쟁까지. 사이트가 다운.
MIT 연구팀이 이를 계기로 창업 — Akamai (하와이어로 "빠른").
해법: 컨텐츠를 사용자 가까이 복제
세계 각 ISP의 POP(Point of Presence)에 캐시 서버를 깔고, 같은 요청이 가까운 서버에서 응답되게 한다. 1999년 Akamai가 세계 최초로 사용자 DNS를 지리적으로 다른 IP로 응답하는 글로벌 시스템 상용화.
1999~2025 CDN 진화
- 1999: Akamai 상용화, 정적 자산 캐시
- 2004: CloudFront 전신인 LimeLight
- 2008: AWS CloudFront 시작
- 2009: Cloudflare 창업, 무료 플랜 도입
- 2011: Fastly — Varnish 기반 고성능
- 2017: Cloudflare Workers — 엣지 컴퓨팅 대중화
- 2019: Fastly Compute@Edge (Wasm 기반)
- 2022: CDN이 Zero Trust, DDoS, Bot 방어까지 흡수
- 2025: Cloudflare/Fastly가 AI 추론까지 엣지로
2. Anycast — 같은 IP, 다른 위치
전통 DNS 기반 지리 라우팅
1990년대 Akamai 방식: 사용자가 a.akamai.net을 조회 → DNS가 클라이언트 IP를 보고 가장 가까운 서버 IP 응답.
한계:
- 재귀 리졸버의 IP로만 위치 추정 → 부정확 (EDNS Client Subnet로 개선)
- TTL 만료 전까진 경로 변경 X
- 여러 IP 유지 필요
Anycast — BGP 레벨의 마법
Cloudflare가 1.1.1.1 하나의 IP를 세계 300+ 도시의 수천 개 서버에 동시 할당. 사용자가 1.1.1.1로 패킷 보내면 BGP 라우팅이 자동으로 가장 가까운 서버로 전달.
작동 원리:
- Cloudflare가 각 POP에서 같은 AS 번호로
1.1.1.0/24prefix를 BGP로 광고 - 주변 ISP들은 여러 경로 중 가장 짧은 AS-path를 선택
- 결과적으로 사용자는 지리적으로 가까운 POP으로 라우팅
Anycast의 이점
- DNS 레벨 튜닝 불필요
- 하나의 POP이 다운되면 BGP가 자동으로 다음 가까운 POP으로 재라우팅 (페일오버 초단위)
- 단일 IP로 전 세계 서비스
Anycast의 함정
세션 유지가 어렵다. 초기 TCP 3-way handshake 중 BGP 경로가 바뀌면? 새 POP이 SYN만 봤지 ACK를 못 봤으므로 연결 실패.
해결책:
- 대부분 CDN이 BGP 경로를 충분히 안정화
- QUIC/Connection ID 기반 마이그레이션 (이전 글)
- 세션 친화성: L7 세션은 Anycast 입구 후 내부 Unicast로 전환
3. 캐시 계층 — Edge에서 Origin까지
사용자 요청이 캐시를 만나는 순서
[사용자] → [엣지 POP(가까운 도시)] → [리저널 캐시] → [Origin Shield] → [Origin 서버]
각 계층의 역할:
엣지 POP: 사용자 반경 50~200km. 90% 이상의 히트 목표. 리저널 캐시: 대륙/지역 단위. 엣지에서 miss일 때. Origin Shield: Origin 직전. 캐시 공유로 origin 부하 최소화. Origin: 실제 컨텐츠 저장소 (S3, 웹서버).
Hit Ratio의 경제학
1TB 월 트래픽 서비스 가정:
- 엣지 hit 95% → origin으로 50GB만 감 → 대역폭 비용 절감
- Cloudflare의 대역폭은 고객에게 공짜(Free), AWS S3는 $50~100/TB. 엣지로 몇 배 비용 절감
Cache-Control 헤더의 해석
Cache-Control: public, max-age=31536000, s-maxage=86400, immutable
public— 중간 캐시 허용max-age=31536000— 브라우저 캐시 1년s-maxage=86400— CDN 캐시 1일immutable— 검증 요청조차 하지 말라 (reload 시에도)
모던 엣지는 stale-while-revalidate도 지원:
Cache-Control: max-age=3600, stale-while-revalidate=86400
"1시간 내 신선, 24시간까지는 stale 응답하되 백그라운드 갱신".
Key 설계 — 같은 URL을 다르게 보아야 할 때
기본 캐시 키는 URL이지만 같은 URL이라도:
- 모바일 vs 데스크톱 (이미지 해상도)
- 언어/지역
- 인증 상태
헤더 기반 cache key 확장이 필요:
cacheKey:
- url
- header: Accept-Encoding
- header: User-Agent(normalized) # 모바일/데스크톱만
너무 많은 차원 → 카디널리티 폭발, hit ratio 붕괴. 정책 설계가 중요.
4. 캐시 무효화 — 두 난제 중 하나
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
문제의 본질
URL로 컨텐츠가 바뀌었는데 CDN이 아직 예전 걸 서빙. 전 세계 수백 POP에 퍼진 캐시를 어떻게 "한 번에" 지우나?
무효화 4가지 전략
1. TTL 자연 만료
- 쉬움, 제어 없음
- 즉각 반영 필요한 뉴스/가격엔 부적합
2. Purge (즉시 삭제)
- CDN API 호출로 URL 삭제
- Cloudflare: 초당 100k+ 요청 처리
- 비용: 플랜에 따라 무료~유료
3. Surrogate Key / Tag 기반 무효화
- 응답에
Surrogate-Key: product-42 cat-electronics헤더 - "cat-electronics 태그 모두 지우기"로 수천 URL 일괄 무효화
- Fastly가 이 패턴 선도, Varnish 기원
4. Versioned URL (캐시 버스팅)
- 파일 이름에 해시:
main.abc123.js - 배포마다 새 URL → 무효화 불필요, 옛 파일은 만료로 자연 소멸
- React/Next.js/Vite 기본값
현실 — 조합
실제 운영은 네 가지를 조합:
- CSS/JS: versioned URL
- API 응답: 짧은 TTL + surrogate key
- 이미지: 긴 TTL + 필요시 purge
- HTML: stale-while-revalidate
5. DDoS 방어 — 3층 방패
공격 유형별 대응
L3/L4 (볼륨형) — UDP 플러드, SYN 플러드, amplification
- Anycast로 분산 흡수
- 네트워크 경계 장비가 비정상 패턴 차단
- 2024년 역사상 최대: Cloudflare 기준 3.8Tbps 방어
L7 (애플리케이션) — HTTP 플러드, Slowloris, 재귀 쿼리
- Rate Limiting (IP/경로/쿠키 단위)
- Challenge (CAPTCHA, Turnstile)
- Bot Management (행동 지문, JS challenge)
Target (자원 고갈) — DB 고비용 쿼리, 결제 전면 공격
- WAF (ModSecurity, Cloudflare WAF 룰)
- 캐싱으로 origin 보호
- Circuit Breaker
Scrubbing Center 아키텍처
전통 DDoS 보호:
- 고객의 정상 트래픽이 scrubbing center 통과
- 악성 패턴 차단, 정상만 origin으로 전달
문제: 고객 origin IP가 노출되면 우회 공격.
Modern CDN: 흡수 기반
Cloudflare/Fastly의 Anycast는 전 세계 수백 POP이 공격을 분산 흡수. 개별 POP이 overload되어도 BGP가 다른 POP으로 이동.
"Magic Transit" 같은 제품은 BGP로 고객의 /24 prefix 자체를 CDN이 대신 광고해서 원천부터 보호.
6. 엣지 컴퓨팅 3대 제품
AWS Lambda@Edge (2017)
- CloudFront 이벤트 기반 (Viewer Request/Response, Origin Request/Response)
- Node.js, Python 런타임
- 콜드 스타트: 수백 ms
- 리전이 제한됨 (모든 POP 아님)
- 최대 실행 시간: Viewer는 5초, Origin은 30초
- 메모리: 128~10,240MB
용도: 리다이렉트, A/B 테스트, 인증 검증
Cloudflare Workers (2017)
- V8 Isolate 기반 (Wasm 추가 가능)
- JavaScript/TypeScript/Rust(via Wasm)
- 콜드 스타트: ~5ms
- 300+ 도시 모든 POP에서 실행
- 제한: 10ms CPU (Free), 최대 30초 (유료)
- Durable Objects — 강한 일관성 상태
용도: 전체 애플리케이션 (Remix, Next.js on Workers), API gateway, 동적 이미지 변환
Fastly Compute@Edge (2019)
- Wasm/WASI 기반
- Rust, JavaScript, Go (TinyGo), AssemblyScript
- 콜드 스타트: ~35μs
- Fastly의 모든 POP
- 무제한 실행 시간 (현실적 한계 내)
용도: API 변환, A/B 테스트, 이미지 변환, 복잡한 edge logic
3가지 비교
| 항목 | Lambda@Edge | Workers | Compute@Edge |
|---|---|---|---|
| 엔진 | Lambda (컨테이너) | V8 Isolate | Wasm |
| 콜드 스타트 | ~수백 ms | ~5ms | ~35μs |
| POP 수 | 제한 (13 리전) | 300+ | 80+ |
| 실행 시간 | 5~30초 | 10ms~30초 | 제한 실질 없음 |
| 언어 | Node, Python | JS/TS, Wasm | Wasm 타겟 모두 |
| 가격 | 비쌈 | 저렴 | 중간 |
7. 이미지 최적화 — CDN의 킬러 기능
왜 중요한가
웹 트래픽의 50% 이상이 이미지. 적절한 포맷/크기 선택만으로 페이지 로드 절반 단축.
현대 이미지 형식
- JPEG — 여전히 기본, 압축률 OK
- WebP — Chrome 2010, 모든 모던 브라우저 지원
- AVIF — WebP보다 +30% 압축, Safari 16+ 지원
- JPEG XL — Safari 17+, 점진 채택
엣지 이미지 변환
Cloudflare Images, Fastly Image Optimizer, AWS CloudFront + Lambda@Edge:
https://cdn.example.com/photo.jpg?w=400&fm=webp&q=75
엣지가 요청 시 실제 변환, 결과 캐시. origin은 원본 하나만 보관.
Responsive Images with Accept
브라우저가 Accept: image/avif, image/webp, image/*를 보내면 엣지가 지원 포맷 중 최적을 응답. Vary: Accept로 캐시 키 분리.
8. 스트리밍 미디어 — HLS/DASH/LL-HLS
ABR (Adaptive Bitrate)
비디오를 여러 비트레이트로 미리 인코딩:
- 240p @ 400kbps
- 480p @ 1000kbps
- 720p @ 2500kbps
- 1080p @ 5000kbps
플레이어가 현재 대역폭에 따라 세그먼트별로 선택. 끊김 없이 품질 조정.
HLS (HTTP Live Streaming, Apple)
m3u8 마스터 플레이리스트 → 각 해상도 플레이리스트 → 6초 .ts 세그먼트. HTTP 기반이라 CDN과 완벽 궁합.
LL-HLS (Low Latency)
표준 HLS는 30초+ 지연. LL-HLS는 2초 이하 가능.
- 세그먼트 내 partial segment
- HTTP/2 push
- Preload hint
WebRTC — 초저지연
스트리밍이 아닌 실시간 대화용 (500ms 미만 지연). CDN이 아닌 SFU(Selective Forwarding Unit) 필요.
9. Zero Trust — VPN을 대체하는 방식
왜 VPN이 한계인가
- "내부망 접근 = 신뢰"라는 가정 낡음
- 내부 악성 계정이 모든 걸 털 수 있음
- 원격 근무 대규모화로 VPN이 병목
Zero Trust 모델
모든 요청을 항상 인증 + 컨텍스트 평가. 내부/외부 구분 없음.
구성:
- 사용자 ID (SSO)
- 디바이스 상태 (MDM 통해 검증)
- 네트워크 위치
- 요청 컨텍스트
엣지 기반 Zero Trust
Cloudflare Access, Google BeyondCorp, Zscaler 등:
- 내부 앱을 엣지 네트워크 통해 노출
- 모든 요청이 엣지에서 인증 체크
- 정상만 내부로 전달
이점:
- 내부 앱에 Public IP 불필요
- DDoS 방어 자동
- 사용자 로그가 중앙 집중
Cloudflare Access는 무료 플랜도 있어 개인/스타트업에 인기.
10. 실전 장애 사례
사례 1: 2021년 Fastly 전 세계 1시간 다운
고객의 VCL(Varnish Config Language) 설정이 엣지 글로벌 버그를 트리거. 전 세계 POP 동시 다운. Amazon, NYT, Reddit, UK 정부 사이트 영향. 교훈: CDN 설정 테스트 환경 필수, 벤더 다중화 고려.
사례 2: 2017년 Cloudbleed
Cloudflare HTTP 파서가 메모리 영역을 잘못 읽어 다른 고객의 HTTP 응답 일부를 응답에 섞음. Google 캐시에 민감 데이터 남음. 7일 만에 수습. 교훈: 메모리 안전 언어(Rust)로 파서 재작성, 이후 Cloudflare는 핵심 컴포넌트를 Rust로 이전.
사례 3: 2022년 Rogers Canada
ISP 장애가 DNS/긴급신고까지 마비. CDN 간접 영향. 교훈: 네트워크 의존성 매핑, 비상 경로 설계.
11. 벤더 선택 가이드
Cloudflare
강점: 가격(무료 플랜 넉넉), 개발자 경험, Workers 생태계, Zero Trust. 약점: 동영상 스트리밍은 특화 아님, 엔터프라이즈 커스텀 지원은 한계.
Akamai
강점: 대형 엔터프라이즈 레퍼런스, 복잡한 미디어 워크플로우, 보안 감사 성숙도. 약점: 비쌈, 개발자 UX는 최신 기준 아님.
Fastly
강점: 매우 빠른 purge (150ms 미만 전 세계), VCL 커스터마이즈, Wasm Compute. 약점: 가격이 Cloudflare보다 비싸고, 진입 학습 곡선.
AWS CloudFront
강점: AWS 생태계 통합, 낮은 출구 비용(AWS 내부 서비스로). 약점: 엣지 기능 제한, 개발자 UX 평범.
현실 — 다중 벤더
대규모 미디어는 Akamai + Fastly 다중, 스타트업은 Cloudflare 단일이 흔한 패턴.
12. 관측성과 디버깅
CDN 응답 헤더
디버깅의 친구들:
CF-Ray: 123abc-ICN # Cloudflare
Age: 3421 # 현재 캐시 경과
X-Cache: HIT from edge # Fastly 캐시 hit 여부
X-Served-By: cache-icn1 # 어느 POP에서 응답
로그 스트리밍
- Cloudflare Logpush → S3/GCS/Splunk
- Fastly Real-time Log → S3/Kinesis
- CloudFront → S3 + Athena
실시간 대시보드
Prometheus로 수집, Grafana로 시각화:
- Hit ratio per origin
- P99 edge latency per POP
- 4xx/5xx 비율
- Bandwidth to origin
13. 비용 최적화 — 대역폭이 현금
원칙 1: Hit Ratio를 올려라
90% → 95%로 올리면 origin 트래픽 절반. 튜닝:
- Cache-Control 명시
- 쿠키/쿼리 파라미터 정규화
- Origin Shield 활성화
원칙 2: 이미지 포맷 최적화
JPG → WebP 전환만으로 트래픽 30% 감소.
원칙 3: Brotli 압축
gzip보다 15~25% 추가 압축. 대부분 CDN이 기본 지원.
원칙 4: Origin 위치 전략
Cloudflare/Fastly는 대부분 origin egress 무료 (같은 CDN 간). AWS CloudFront → AWS 리전은 저렴. 교차 클라우드는 비쌈.
원칙 5: Commit 계약
트래픽 예측 가능하면 연간 commit으로 40%+ 할인 가능.
14. 함정과 안티패턴
함정 1: Origin에 캐시 헤더 없음
Origin이 Cache-Control 없이 응답 → CDN이 보수적으로 캐시 안 함. 항상 명시하자.
함정 2: 쿠키/쿼리스트링으로 캐시 깨기
?timestamp=123이나 광고 트래킹 쿠키가 매 요청 다름 → 캐시 miss. 정규화 규칙 필수.
함정 3: purge를 습관처럼
매 배포마다 "전체 purge"는 origin 재폭발. 버전드 URL이나 surrogate key 쓰기.
함정 4: Anycast + UDP 상태 저장
UDP 세션을 Anycast로 하면 BGP 변경 시 깨짐. QUIC의 Connection ID 또는 L4 stickiness 필요.
함정 5: Origin Shield 없이 Hot Event
바이럴 트래픽이 POP 전체에 확산 → 각 POP에서 origin으로 miss → origin 다운. Shield로 공용 캐시 계층.
함정 6: 미리보기/staging URL을 CDN 안 통과
CDN 없이 origin 직접 노출되면 DDoS 위험. staging도 access control 붙여 CDN 뒤로.
15. 실전 체크리스트 12가지
- Cache-Control을 명시적으로 — 기본값 의존 X
- Brotli 압축 켜기
- AVIF/WebP 자동 변환 — 50% 이미지 크기 절감
- Origin Shield 활성화 — 대형 이벤트 대비
- Purge 전략 문서화 — surrogate key vs versioned URL
- Rate Limiting 기본값 설정 — 인증 엔드포인트 특히
- WAF OWASP Top 10 룰 적용
- HTTP/3 ON — 모바일 UX 향상
- 관측성 통합 — CDN 로그 → SIEM
- 비용 알림 — 예상 대비 이탈 감지
- 벤더 다중화 PoC — 주요 서비스는 2개 CDN
- 엣지 컴퓨팅 사용처 검토 — 리다이렉트, 인증, A/B는 엣지로
다음 글 예고 — Chaos Engineering
"인터넷이 느려지면 어떻게 할까?" "AZ 하나가 다운되면?" 답은 실제로 부숴보는 것. 다음 글에서는:
- Netflix의 Chaos Monkey 탄생 (2010)
- 4 Pillars of Chaos Engineering
- Game Day — 실전 시뮬레이션 훈련
- Netflix의 Simian Army — Chaos Monkey/Gorilla/Kong
- LitmusChaos / Chaos Mesh — Kubernetes 카오스
- AWS Fault Injection Simulator
- Observability + Chaos 조합
- 조직 문화로의 확장 — 비난 없는 포스트모템
- 카오스 실험 설계 방법
운영 회의에서 "카오스 엔지니어링 도입 검토 중"이라고 한 번쯤 들었을 것이다. 다음 글에서 그 의미를 해체해본다.
"장애를 피할 수는 없다. 장애에 대비할 수는 있다. 카오스 엔지니어링은 그 대비를 코드화한다."
CDN and Edge Computing Deep Dive — Anycast, Cache Invalidation, DDoS Defense, Lambda@Edge vs Workers vs Compute
Introduction — The 1.3-Second Battle
2006 Amazon experiment: every 100ms of added page latency costs 1% in sales. 2017 Google: on mobile, going from 1s to 3s increases bounce rate by 32%.
To win back a second, internet companies have spread servers across the globe, manipulated BGP, stacked cache tiers, and even placed serverless functions within 100km of every user. In this post:
- The birth of CDN — the problem Akamai solved in 1998
- The internals of Anycast routing — "how does the same IP route to the nearest location everywhere?"
- Cache tier strategies — tiered, shielded, push
- The hard problem of cache invalidation and real-world patterns
- DDoS defense — the L3/L4/L7 three-layer shield
- The meaning of edge computing and the three major products (Lambda@Edge, Cloudflare Workers, Fastly Compute)
- Image/video transformation at the edge
- Zero Trust — replacing VPN with Cloudflare Access
- Three real-world incident case studies
In the previous post WebAssembly + WASI Deep Dive, we showed Wasm as the execution engine of the edge. In this post, we look at the globe-scale infrastructure that engine runs on.
1. The Birth of CDN — Akamai, 1998
The Problem: 1997 Super Bowl
CBS tried streaming a sports event over the web. The server was in Boston, users in California. In 1997, a round trip across the US took about 70ms, plus bandwidth contention. The site went down.
An MIT research team turned this into a company — Akamai (Hawaiian for "smart/quick").
The Solution: Replicate Content Close to Users
Place cache servers in POPs (Points of Presence) at ISPs around the world, and serve identical requests from the nearest server. In 1999, Akamai commercialized the world's first global system that responded to a user's DNS query with a geographically distinct IP.
1999-2025 CDN Evolution
- 1999: Akamai commercialized, static asset caching
- 2004: LimeLight, the predecessor of CloudFront
- 2008: AWS CloudFront launches
- 2009: Cloudflare founded, introduces free plan
- 2011: Fastly — high performance based on Varnish
- 2017: Cloudflare Workers — edge computing goes mainstream
- 2019: Fastly Compute@Edge (Wasm-based)
- 2022: CDNs absorb Zero Trust, DDoS, and Bot defense
- 2025: Cloudflare/Fastly extend AI inference to the edge
2. Anycast — Same IP, Different Locations
Traditional DNS-Based Geo Routing
1990s Akamai approach: user queries a.akamai.net → DNS inspects the client IP and returns the closest server's IP.
Limitations:
- Location inferred only from the recursive resolver's IP, often inaccurate (improved via EDNS Client Subnet)
- No path change until TTL expires
- Requires maintaining many IPs
Anycast — Magic at the BGP Level
Cloudflare assigns the same IP 1.1.1.1 to thousands of servers across 300+ cities simultaneously. When a user sends a packet to 1.1.1.1, BGP routing automatically delivers it to the closest server.
How it works:
- Cloudflare advertises the
1.1.1.0/24prefix from every POP with the same AS number via BGP - Neighboring ISPs pick the shortest AS-path among multiple routes
- The user is routed to the geographically closest POP
Benefits of Anycast
- No need for DNS-level tuning
- If one POP goes down, BGP automatically re-routes to the next closest POP (failover in seconds)
- Single IP serves the entire globe
Anycast's Pitfalls
Session persistence is hard. What if the BGP path changes during the initial TCP 3-way handshake? The new POP only saw the SYN, not the ACK, so the connection fails.
Workarounds:
- Most CDNs keep BGP paths stable enough
- QUIC/Connection ID-based migration (previous post)
- Session affinity: switch from Anycast at the entry point to internal Unicast for L7 sessions
3. Cache Tiers — From Edge to Origin
The Order a Request Encounters Caches
[User] -> [Edge POP (nearest city)] -> [Regional cache] -> [Origin Shield] -> [Origin server]
The role of each tier:
Edge POP: within 50-200km of the user. Target: 90%+ hit ratio. Regional cache: continent/region level. Used on edge miss. Origin Shield: right before origin. Shared cache to minimize origin load. Origin: the actual content store (S3, web server).
The Economics of Hit Ratio
Assume 1TB/month of traffic:
- Edge hit ratio 95% -> only 50GB reaches origin -> massive bandwidth savings
- Cloudflare's bandwidth is free to customers; AWS S3 charges $50-100/TB. Edge caching cuts cost by multiples.
Interpreting Cache-Control Headers
Cache-Control: public, max-age=31536000, s-maxage=86400, immutable
public— intermediate caches allowedmax-age=31536000— browser cache 1 years-maxage=86400— CDN cache 1 dayimmutable— do not even send revalidation requests (even on reload)
Modern edges also support stale-while-revalidate:
Cache-Control: max-age=3600, stale-while-revalidate=86400
"Fresh within 1 hour, serve stale for up to 24 hours while refreshing in the background."
Key Design — When the Same URL Should Be Treated Differently
The default cache key is the URL, but the same URL may differ by:
- Mobile vs desktop (image resolution)
- Language/region
- Auth state
Header-based cache key extensions are needed:
cacheKey:
- url
- header: Accept-Encoding
- header: User-Agent(normalized) # mobile/desktop only
Too many dimensions -> cardinality explosion, hit ratio collapses. Policy design matters.
4. Cache Invalidation — One of Two Hard Things
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
The Heart of the Problem
Content at a URL changes, but the CDN still serves the old version. How do you "instantly" wipe a cache scattered across hundreds of POPs worldwide?
Four Invalidation Strategies
1. Natural TTL expiry
- Easy, no control
- Unsuitable for news/prices that need immediate reflection
2. Purge (immediate delete)
- Invoke the CDN API to purge a URL
- Cloudflare: handles 100k+ purges per second
- Cost: free-to-paid depending on plan
3. Surrogate Key / Tag-based invalidation
- Response has header
Surrogate-Key: product-42 cat-electronics - "Purge everything tagged cat-electronics" invalidates thousands of URLs at once
- Fastly pioneered this pattern, originating in Varnish
4. Versioned URLs (cache busting)
- Hash in the filename:
main.abc123.js - Each deploy yields new URLs -> no invalidation needed, old files age out naturally
- Default in React/Next.js/Vite
Reality — Combinations
Production operations combine all four:
- CSS/JS: versioned URLs
- API responses: short TTL + surrogate key
- Images: long TTL + purge when needed
- HTML: stale-while-revalidate
5. DDoS Defense — Three-Layer Shield
Responses by Attack Type
L3/L4 (volumetric) — UDP flood, SYN flood, amplification
- Distributed absorption via Anycast
- Network edge devices drop abnormal patterns
- 2024 largest on record: Cloudflare absorbed 3.8Tbps
L7 (application) — HTTP flood, Slowloris, recursive queries
- Rate limiting (per IP/path/cookie)
- Challenges (CAPTCHA, Turnstile)
- Bot management (behavioral fingerprints, JS challenges)
Target (resource exhaustion) — expensive DB queries, payment endpoint attacks
- WAF (ModSecurity, Cloudflare WAF rules)
- Protecting origin via caching
- Circuit breakers
Scrubbing Center Architecture
Traditional DDoS protection:
- Customer's legitimate traffic passes through a scrubbing center
- Malicious patterns are filtered; only legitimate traffic reaches origin
Problem: if the customer's origin IP is exposed, attackers can bypass.
Modern CDN: Absorption-Based
Cloudflare/Fastly Anycast distributes and absorbs attacks across hundreds of POPs worldwide. Even if an individual POP is overloaded, BGP shifts traffic to another POP.
Products like "Magic Transit" let the CDN advertise the customer's own /24 prefix via BGP for upstream protection.
6. The Three Edge Computing Products
AWS Lambda@Edge (2017)
- Event-driven via CloudFront (Viewer Request/Response, Origin Request/Response)
- Node.js, Python runtimes
- Cold start: hundreds of ms
- Limited to a subset of regions (not every POP)
- Max execution time: 5s for Viewer, 30s for Origin
- Memory: 128-10,240MB
Use cases: redirects, A/B testing, auth validation
Cloudflare Workers (2017)
- Based on V8 Isolate (with optional Wasm)
- JavaScript/TypeScript/Rust (via Wasm)
- Cold start: ~5ms
- Runs on all POPs in 300+ cities
- Limits: 10ms CPU (Free), up to 30s (paid)
- Durable Objects — strongly consistent state
Use cases: full applications (Remix, Next.js on Workers), API gateways, dynamic image transformation
Fastly Compute@Edge (2019)
- Wasm/WASI-based
- Rust, JavaScript, Go (TinyGo), AssemblyScript
- Cold start: ~35 microseconds
- All of Fastly's POPs
- Unbounded execution time (within practical limits)
Use cases: API transformation, A/B testing, image transformation, complex edge logic
Comparison of the Three
| Metric | Lambda@Edge | Workers | Compute@Edge |
|---|---|---|---|
| Engine | Lambda (container) | V8 Isolate | Wasm |
| Cold start | ~hundreds of ms | ~5ms | ~35 microseconds |
| POP count | limited (13 regions) | 300+ | 80+ |
| Execution time | 5-30s | 10ms-30s | effectively unlimited |
| Languages | Node, Python | JS/TS, Wasm | anything targeting Wasm |
| Price | expensive | cheap | medium |
7. Image Optimization — The CDN Killer Feature
Why It Matters
Over 50% of web traffic is images. Choosing the right format/size alone can cut page load time in half.
Modern Image Formats
- JPEG — still the baseline, decent compression
- WebP — Chrome 2010, supported by all modern browsers
- AVIF — +30% compression over WebP, supported by Safari 16+
- JPEG XL — Safari 17+, gradual adoption
Edge Image Transformation
Cloudflare Images, Fastly Image Optimizer, AWS CloudFront + Lambda@Edge:
https://cdn.example.com/photo.jpg?w=400&fm=webp&q=75
The edge transforms on demand and caches the result. Origin keeps just the single original.
Responsive Images with Accept
When the browser sends Accept: image/avif, image/webp, image/*, the edge picks the best supported format. Separate cache keys via Vary: Accept.
8. Streaming Media — HLS/DASH/LL-HLS
ABR (Adaptive Bitrate)
Encode the video at multiple bitrates up front:
- 240p at 400kbps
- 480p at 1000kbps
- 720p at 2500kbps
- 1080p at 5000kbps
The player picks per segment based on current bandwidth. Quality adjusts seamlessly.
HLS (HTTP Live Streaming, Apple)
m3u8 master playlist -> per-resolution playlist -> 6-second .ts segments. HTTP-based, a perfect match for CDNs.
LL-HLS (Low Latency)
Standard HLS has 30s+ delay. LL-HLS can achieve under 2 seconds:
- Partial segments within a segment
- HTTP/2 push
- Preload hints
WebRTC — Ultra-Low Latency
Not for streaming but real-time conversation (sub-500ms latency). Needs an SFU (Selective Forwarding Unit), not a CDN.
9. Zero Trust — Replacing VPN
Why VPN Has Hit Its Limits
- The "internal network access = trust" assumption is outdated
- A compromised internal account can exfiltrate everything
- Remote work at scale has turned VPN into a bottleneck
The Zero Trust Model
Every request is always authenticated + context-evaluated. No inside/outside distinction.
Components:
- User ID (SSO)
- Device posture (validated via MDM)
- Network location
- Request context
Edge-Based Zero Trust
Cloudflare Access, Google BeyondCorp, Zscaler, etc:
- Expose internal apps through the edge network
- Every request is authenticated at the edge
- Only legitimate traffic is forwarded internally
Benefits:
- No public IP needed for internal apps
- DDoS defense automatically
- Centralized user logs
Cloudflare Access has a free plan, which made it popular with individuals and startups.
10. Real-World Incidents
Case 1: Fastly's 1-Hour Global Outage, 2021
A customer's VCL (Varnish Config Language) setting triggered a global edge bug. All POPs went down simultaneously. Amazon, NYT, Reddit, and UK government sites were affected. Lesson: CDN config test environments are essential; consider vendor diversity.
Case 2: Cloudbleed, 2017
Cloudflare's HTTP parser read an out-of-bounds memory region and mixed fragments of another customer's HTTP response into responses. Sensitive data ended up in Google's cache. It took 7 days to clean up. Lesson: rewrite parsers in memory-safe languages (Rust). Cloudflare subsequently migrated core components to Rust.
Case 3: Rogers Canada, 2022
An ISP outage paralyzed DNS and even emergency services. Indirect CDN impact. Lesson: map network dependencies, design emergency paths.
11. Vendor Selection Guide
Cloudflare
Strengths: price (generous free plan), developer experience, Workers ecosystem, Zero Trust. Weaknesses: video streaming isn't the specialty; enterprise custom support is limited.
Akamai
Strengths: large enterprise references, complex media workflows, mature security auditing. Weaknesses: expensive; developer UX is not up to modern standards.
Fastly
Strengths: extremely fast purge (under 150ms globally), VCL customization, Wasm Compute. Weaknesses: pricier than Cloudflare and a steep learning curve.
AWS CloudFront
Strengths: AWS ecosystem integration, low egress cost (to other AWS services). Weaknesses: limited edge features, average developer UX.
Reality — Multi-Vendor
Large-scale media often runs Akamai + Fastly in parallel; startups typically stick to Cloudflare alone.
12. Observability and Debugging
CDN Response Headers
Debugger's best friends:
CF-Ray: 123abc-ICN # Cloudflare
Age: 3421 # seconds since cache entry
X-Cache: HIT from edge # Fastly cache hit
X-Served-By: cache-icn1 # which POP served the response
Log Streaming
- Cloudflare Logpush -> S3/GCS/Splunk
- Fastly Real-time Log -> S3/Kinesis
- CloudFront -> S3 + Athena
Real-Time Dashboards
Collect with Prometheus, visualize with Grafana:
- Hit ratio per origin
- P99 edge latency per POP
- 4xx/5xx ratio
- Bandwidth to origin
13. Cost Optimization — Bandwidth Is Cash
Principle 1: Raise the Hit Ratio
Going from 90% to 95% halves origin traffic. Tuning:
- Explicit Cache-Control
- Normalize cookies/query parameters
- Enable Origin Shield
Principle 2: Optimize Image Formats
Just converting JPG to WebP can cut traffic by 30%.
Principle 3: Brotli Compression
Brotli adds 15-25% more compression over gzip. Most CDNs enable it by default.
Principle 4: Origin Location Strategy
Cloudflare/Fastly generally waive egress between themselves and origin (within the same CDN). AWS CloudFront to AWS regions is cheap. Cross-cloud is expensive.
Principle 5: Commit Contracts
If your traffic is predictable, an annual commit can get you 40%+ discount.
14. Pitfalls and Anti-Patterns
Pitfall 1: No Cache Headers at Origin
If origin responds without Cache-Control, the CDN is conservative and doesn't cache. Always be explicit.
Pitfall 2: Breaking Cache with Cookies/Query Strings
?timestamp=123 or ad-tracking cookies that differ per request -> cache miss. Normalization rules are mandatory.
Pitfall 3: Habitual Purging
A full purge on every deploy causes origin re-explosion. Use versioned URLs or surrogate keys.
Pitfall 4: Anycast + Stateful UDP
Running UDP sessions over Anycast breaks on BGP changes. You need QUIC's Connection ID or L4 stickiness.
Pitfall 5: Hot Event Without Origin Shield
Viral traffic hits all POPs -> each POP misses and goes to origin -> origin goes down. Use Shield as a shared cache layer.
Pitfall 6: Preview/Staging URLs Bypassing the CDN
If staging is exposed directly without CDN, DDoS risk follows. Put staging behind access control and the CDN.
15. Real-World Checklist of 12
- Explicit Cache-Control — don't rely on defaults
- Turn on Brotli compression
- Auto-convert to AVIF/WebP — cut image size 50%
- Enable Origin Shield — prepare for large events
- Document your purge strategy — surrogate key vs versioned URL
- Set default rate limiting — especially on auth endpoints
- Apply WAF OWASP Top 10 rules
- Turn on HTTP/3 — improves mobile UX
- Integrate observability — CDN logs -> SIEM
- Cost alerts — detect deviations from forecasts
- Multi-vendor PoC — use two CDNs for critical services
- Review edge-compute use cases — redirects, auth, A/B belong at the edge
Coming Next — Chaos Engineering
"What happens when the internet slows down?" "What if one AZ goes down?" The answer is to actually break things on purpose. In the next post:
- The birth of Netflix's Chaos Monkey (2010)
- The 4 Pillars of Chaos Engineering
- Game Day — real-world simulation drills
- Netflix's Simian Army — Chaos Monkey/Gorilla/Kong
- LitmusChaos / Chaos Mesh — chaos for Kubernetes
- AWS Fault Injection Simulator
- Combining Observability + Chaos
- Extension to organizational culture — blameless postmortems
- How to design chaos experiments
You've probably heard "we're considering chaos engineering" in an ops meeting at least once. The next post unpacks what it actually means.
"You cannot avoid failure. You can prepare for failure. Chaos engineering codifies that preparation."