Split View: Chaos Engineering 완전 가이드 2025: 복원력 테스트, Chaos Monkey, Litmus, 게임 데이
Chaos Engineering 완전 가이드 2025: 복원력 테스트, Chaos Monkey, Litmus, 게임 데이
도입: 왜 Chaos Engineering인가
현대의 분산 시스템은 수십에서 수백 개의 마이크로서비스, 메시지 큐, 데이터베이스, 캐시, 로드 밸런서로 구성됩니다. 이 복잡한 시스템에서 장애는 "발생할지 여부"가 아니라 "언제 발생하는가"의 문제입니다.
2012년 Netflix는 AWS US-East-1 리전 장애로 전체 서비스가 중단되는 사태를 겪었습니다. 이 사건 이후 Netflix는 "장애를 피하는 대신, 장애에 강한 시스템을 만들자"라는 철학으로 Chaos Engineering을 탄생시켰습니다.
Chaos Engineering은 단순히 "무작위로 서버를 죽이는 것"이 아닙니다. 과학적 실험 방법론에 기반하여, 시스템의 취약점을 사전에 발견하고, 장애 발생 시에도 서비스가 정상 동작하도록 복원력(resilience)을 강화하는 규율입니다.
이 글에서 다루는 내용
- Chaos Engineering의 핵심 원칙과 실험 설계
- Netflix Chaos Monkey 탄생 스토리와 Simian Army
- 주요 도구 비교: Litmus Chaos, Chaos Mesh, Gremlin, AWS FIS
- 장애 유형별 실험: 네트워크, CPU, 메모리, Pod, 노드, AZ
- Kubernetes 환경의 카오스 실험 YAML 예제
- Game Day 운영 가이드
- 점진적 도입 전략 (개발 → 스테이징 → 프로덕션)
- Netflix와 Amazon 사례 연구
- CI/CD 통합과 관찰 가능성
1. Chaos Engineering 핵심 원칙
Chaos Engineering의 원칙은 principlesofchaos.org에 명시되어 있습니다.
1.1 정상 상태 가설 (Steady State Hypothesis)
모든 카오스 실험은 "정상 상태"를 정의하는 것에서 시작합니다.
정상 상태 예시:
- API 응답 시간 p99 < 200ms
- 에러율 < 0.1%
- 주문 처리 성공률 > 99.9%
- 데이터베이스 복제 지연 < 1초
정상 상태 가설이란: "특정 장애를 주입하더라도, 시스템은 정상 상태를 유지할 것이다"라는 예측입니다.
1.2 실제 세계 이벤트를 변형하라 (Vary Real-World Events)
실제로 발생할 수 있는 장애를 시뮬레이션해야 합니다.
| 장애 유형 | 실제 사례 | 실험 방법 |
|---|---|---|
| 서버 다운 | 하드웨어 장애, OOM Kill | Pod/인스턴스 강제 종료 |
| 네트워크 지연 | 리전 간 통신 지연 | tc 명령으로 레이턴시 주입 |
| 네트워크 파티션 | 스위치 장애 | iptables 규칙으로 트래픽 차단 |
| CPU 과부하 | 갑작스런 트래픽 급증 | stress-ng로 CPU 부하 생성 |
| 디스크 가득 참 | 로그 폭증 | dd 명령으로 디스크 채우기 |
| DNS 장애 | DNS 서버 다운 | DNS 응답 조작 |
| AZ 장애 | 데이터센터 장애 | 전체 AZ 트래픽 차단 |
1.3 프로덕션에서 실험하라 (Run Experiments in Production)
진정한 신뢰도는 프로덕션 환경에서만 검증할 수 있습니다. 스테이징 환경은 트래픽 패턴, 데이터 볼륨, 인프라 구성이 프로덕션과 다르기 때문입니다.
물론, 처음부터 프로덕션에서 시작하라는 의미는 아닙니다. 점진적으로 도입하되, 궁극적 목표는 프로덕션 실험이어야 합니다.
1.4 폭발 반경을 최소화하라 (Minimize Blast Radius)
폭발 반경 제어 전략:
1. 소규모 시작: 단일 인스턴스 → 인스턴스 그룹 → AZ → 리전
2. 시간 제한: 실험 지속 시간 설정 (예: 5분)
3. 자동 중단: 핵심 메트릭 임계값 초과 시 실험 즉시 중단
4. 트래픽 제한: 전체 트래픽의 1%에만 실험 적용
5. 롤백 계획: 실험 전 롤백 절차 확인
1.5 자동화하라 (Automate Experiments)
수동 실험은 확장할 수 없습니다. 자동화는 다음을 포함합니다.
- 실험 스케줄링 (매주 특정 시간에 실행)
- CI/CD 파이프라인 통합
- 자동 결과 수집 및 보고서 생성
- 중단 조건 자동 모니터링
2. Chaos Monkey: Netflix의 시작
2.1 탄생 배경
2010년, Netflix는 자체 데이터센터에서 AWS로 전면 이전하면서 근본적인 질문에 직면했습니다.
"클라우드 인프라에서 서버는 언제든 사라질 수 있다. 우리 시스템은 이를 견딜 수 있는가?"
이 질문에 답하기 위해 탄생한 것이 Chaos Monkey입니다. Chaos Monkey는 프로덕션 환경에서 무작위로 인스턴스를 종료하여, 모든 서비스가 단일 인스턴스 장애에 내성을 갖도록 강제했습니다.
2.2 Simian Army
Chaos Monkey의 성공 이후, Netflix는 더 다양한 장애 시나리오를 실험하기 위해 Simian Army를 만들었습니다.
Simian Army 구성원:
┌─────────────────────┬──────────────────────────────────────┐
│ 이름 │ 역할 │
├─────────────────────┼──────────────────────────────────────┤
│ Chaos Monkey │ 무작위 인스턴스 종료 │
│ Latency Monkey │ 네트워크 지연 주입 │
│ Conformity Monkey │ 모범 사례 미준수 인스턴스 탐지 │
│ Doctor Monkey │ 비정상 인스턴스 건강 검사 │
│ Janitor Monkey │ 미사용 리소스 정리 │
│ Security Monkey │ 보안 취약점 탐지 │
│ Chaos Gorilla │ 전체 AZ 장애 시뮬레이션 │
│ Chaos Kong │ 전체 리전 장애 시뮬레이션 │
└─────────────────────┴──────────────────────────────────────┘
2.3 Chaos Monkey 설정 예시
# Chaos Monkey 설정 (Spinnaker 통합)
chaos_monkey:
enabled: true
leashed: false
schedule:
frequency: "weekday"
start_hour: 10
end_hour: 16
timezone: "Asia/Seoul"
grouping: "cluster"
probability: 1.0
exceptions:
- account: "prod-critical"
region: "ap-northeast-2"
stack: "payment"
3. 카오스 도구 비교
3.1 주요 도구 개요
| 도구 | 개발사 | 환경 | 라이선스 | 특징 |
|---|---|---|---|---|
| Litmus Chaos | CNCF | Kubernetes | Apache 2.0 | ChaosHub, GitOps 네이티브 |
| Chaos Mesh | CNCF | Kubernetes | Apache 2.0 | 강력한 대시보드, TimeChaos |
| Gremlin | Gremlin Inc. | 모든 환경 | 상용 | SaaS 기반, 엔터프라이즈 기능 |
| AWS FIS | AWS | AWS | 종량제 | AWS 서비스 네이티브 통합 |
| Azure Chaos Studio | Microsoft | Azure | 종량제 | Azure 서비스 네이티브 통합 |
| Steady State | Steadybit | 모든 환경 | 상용 | 안전 가드레일 강조 |
3.2 Litmus Chaos 상세
Litmus는 CNCF Incubating 프로젝트로, Kubernetes 네이티브 카오스 엔지니어링 프레임워크입니다.
# Litmus Chaos 설치
apiVersion: v1
kind: Namespace
metadata:
name: litmus
---
# LitmusChaos Operator 배포
apiVersion: apps/v1
kind: Deployment
metadata:
name: chaos-operator-ce
namespace: litmus
spec:
replicas: 1
selector:
matchLabels:
name: chaos-operator
template:
metadata:
labels:
name: chaos-operator
spec:
serviceAccountName: litmus
containers:
- name: chaos-operator
image: litmuschaos/chaos-operator:3.0.0
env:
- name: CHAOS_RUNNER_IMAGE
value: "litmuschaos/chaos-runner:3.0.0"
- name: WATCH_NAMESPACE
value: ""
Litmus의 핵심 개념은 ChaosExperiment, ChaosEngine, ChaosResult입니다.
# Pod Delete 실험 정의
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosExperiment
metadata:
name: pod-delete
namespace: litmus
spec:
definition:
scope: Namespaced
permissions:
- apiGroups: [""]
resources: ["pods"]
verbs: ["delete", "list", "get"]
image: "litmuschaos/go-runner:3.0.0"
args:
- -c
- ./experiments -name pod-delete
command:
- /bin/bash
env:
- name: TOTAL_CHAOS_DURATION
value: "30"
- name: CHAOS_INTERVAL
value: "10"
- name: FORCE
value: "false"
3.3 Chaos Mesh 상세
Chaos Mesh는 다양한 장애 유형을 지원하는 Kubernetes 카오스 플랫폼입니다.
# Chaos Mesh 설치 (Helm)
# helm repo add chaos-mesh https://charts.chaos-mesh.org
# helm install chaos-mesh chaos-mesh/chaos-mesh -n chaos-mesh --create-namespace
# 네트워크 지연 실험
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-delay-example
namespace: default
spec:
action: delay
mode: all
selector:
namespaces:
- default
labelSelectors:
app: my-service
delay:
latency: "200ms"
jitter: "50ms"
correlation: "50"
duration: "5m"
scheduler:
cron: "@every 1h"
3.4 AWS Fault Injection Service (FIS)
AWS FIS는 AWS 서비스에 네이티브로 통합된 카오스 엔지니어링 서비스입니다.
{
"description": "EC2 인스턴스 종료 실험",
"targets": {
"myInstances": {
"resourceType": "aws:ec2:instance",
"resourceTags": {
"Environment": "staging",
"ChaosReady": "true"
},
"selectionMode": "COUNT(1)"
}
},
"actions": {
"stopInstances": {
"actionId": "aws:ec2:stop-instances",
"parameters": {},
"targets": {
"Instances": "myInstances"
}
}
},
"stopConditions": [
{
"source": "aws:cloudwatch:alarm",
"value": "arn:aws:cloudwatch:ap-northeast-2:123456789:alarm:HighErrorRate"
}
],
"roleArn": "arn:aws:iam::123456789:role/FISRole"
}
3.5 Gremlin
Gremlin은 상용 SaaS 기반 카오스 엔지니어링 플랫폼입니다.
# Gremlin 에이전트 설치 (Kubernetes)
helm repo add gremlin https://helm.gremlin.com
helm install gremlin gremlin/gremlin \
--set gremlin.secret.managed=true \
--set gremlin.secret.type=secret \
--set gremlin.secret.teamID=YOUR_TEAM_ID \
--set gremlin.secret.clusterID=my-cluster \
--set gremlin.secret.teamSecret=YOUR_SECRET
Gremlin의 장점은 직관적인 UI, 세밀한 제어, 안전 기능(Safety Net)입니다. 무료 티어에서도 기본적인 카오스 실험이 가능합니다.
4. 장애 유형별 실험
4.1 네트워크 장애
네트워크 장애는 분산 시스템에서 가장 흔하고 치명적인 문제입니다.
# Chaos Mesh: 네트워크 파티션
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-partition
namespace: default
spec:
action: partition
mode: all
selector:
namespaces:
- default
labelSelectors:
app: order-service
direction: both
target:
selector:
namespaces:
- default
labelSelectors:
app: payment-service
mode: all
duration: "2m"
# Chaos Mesh: 패킷 손실
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: packet-loss
namespace: default
spec:
action: loss
mode: all
selector:
labelSelectors:
app: api-gateway
loss:
loss: "25"
correlation: "50"
duration: "3m"
# Chaos Mesh: 대역폭 제한
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: bandwidth-limit
namespace: default
spec:
action: bandwidth
mode: all
selector:
labelSelectors:
app: file-service
bandwidth:
rate: "1mbps"
limit: 20971520
buffer: 10000
duration: "5m"
4.2 CPU 스트레스
# Chaos Mesh: CPU 스트레스
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: cpu-stress
namespace: default
spec:
mode: one
selector:
labelSelectors:
app: compute-service
stressors:
cpu:
workers: 4
load: 80
duration: "5m"
4.3 메모리 압박
# Chaos Mesh: 메모리 스트레스
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: memory-stress
namespace: default
spec:
mode: one
selector:
labelSelectors:
app: cache-service
stressors:
memory:
workers: 2
size: "512MB"
duration: "3m"
4.4 Pod 강제 종료
# Chaos Mesh: Pod Kill
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: pod-kill-example
namespace: default
spec:
action: pod-kill
mode: fixed
value: "2"
selector:
namespaces:
- default
labelSelectors:
app: web-frontend
gracePeriod: 0
duration: "1m"
# Chaos Mesh: 컨테이너 Kill
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: container-kill
namespace: default
spec:
action: container-kill
mode: one
selector:
labelSelectors:
app: multi-container-app
containerNames:
- sidecar-proxy
duration: "30s"
4.5 노드 드레인
# Litmus: 노드 드레인 실험
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: node-drain-engine
namespace: litmus
spec:
engineState: active
chaosServiceAccount: litmus-admin
experiments:
- name: node-drain
spec:
components:
env:
- name: TOTAL_CHAOS_DURATION
value: "60"
- name: TARGET_NODE
value: "worker-node-02"
- name: APP_NAMESPACE
value: "default"
- name: APP_LABEL
value: "app=critical-service"
4.6 AZ 장애 시뮬레이션
AZ(Availability Zone) 장애는 가장 큰 폭발 반경을 가진 실험입니다.
# AWS FIS: AZ 장애 시뮬레이션
# 특정 AZ의 모든 서브넷에 대해 네트워크 차단
experiment_template:
description: "AZ-a failure simulation"
targets:
azSubnets:
resourceType: "aws:ec2:subnet"
resourceTags:
AvailabilityZone: "ap-northeast-2a"
selectionMode: "ALL"
actions:
disruptConnectivity:
actionId: "aws:network:disrupt-connectivity"
parameters:
scope: "all"
targets:
Subnets: "azSubnets"
duration: "PT10M"
stopConditions:
- source: "aws:cloudwatch:alarm"
value: "arn:aws:cloudwatch:region:account:alarm:CriticalErrorRate"
4.7 DNS 장애
# Chaos Mesh: DNS 장애
apiVersion: chaos-mesh.org/v1alpha1
kind: DNSChaos
metadata:
name: dns-failure
namespace: default
spec:
action: error
mode: all
selector:
labelSelectors:
app: external-api-client
patterns:
- "external-api.example.com"
duration: "2m"
5. 실험 설계 방법론
5.1 체계적 실험 설계
카오스 실험은 과학적 실험과 동일한 구조를 따릅니다.
카오스 실험 설계 프레임워크:
1. 가설 수립 (Hypothesis)
"결제 서비스 Pod 1개가 종료되더라도,
주문 성공률은 99.9% 이상을 유지할 것이다"
2. 정상 상태 정의 (Steady State)
- 주문 성공률: 99.95%
- API 응답 시간 p99: 180ms
- 에러율: 0.05%
3. 실험 변수 (Variables)
- 독립 변수: Pod 1개 강제 종료
- 종속 변수: 주문 성공률, 응답 시간, 에러율
4. 폭발 반경 (Blast Radius)
- 대상: payment-service의 3개 Pod 중 1개
- 영향 범위: 결제 관련 요청의 약 33%
5. 중단 조건 (Abort Conditions)
- 주문 성공률 < 99.0%
- API 응답 시간 p99 > 1000ms
- 동시 에러 수 > 100/min
6. 실행 및 관찰 (Execute and Observe)
- 실험 시작 전 5분간 기준선 수집
- 실험 실행 (2분)
- 실험 종료 후 5분간 복구 관찰
7. 분석 및 개선 (Analyze and Improve)
- 가설 검증/반증
- 발견된 취약점 문서화
- 개선 작업 티켓 생성
5.2 실험 체크리스트
실험 전 체크리스트:
[ ] 가설이 명확하게 정의되어 있는가?
[ ] 정상 상태 메트릭이 수집되고 있는가?
[ ] 폭발 반경이 적절하게 제한되어 있는가?
[ ] 중단 조건이 설정되어 있는가?
[ ] 롤백 절차가 문서화되어 있는가?
[ ] 관련 팀에 사전 통보했는가?
[ ] 모니터링 대시보드가 준비되어 있는가?
[ ] On-Call 엔지니어가 대기 중인가?
실험 중 체크리스트:
[ ] 메트릭을 실시간으로 모니터링하고 있는가?
[ ] 중단 조건을 지속적으로 확인하고 있는가?
[ ] 예상치 못한 부작용이 없는가?
실험 후 체크리스트:
[ ] 시스템이 정상 상태로 복구되었는가?
[ ] 실험 결과가 기록되었는가?
[ ] 발견된 문제에 대한 액션 아이템이 생성되었는가?
[ ] 결과를 팀에 공유했는가?
5.3 실험 결과 기록 템플릿
실험 ID: CE-2025-042
날짜: 2025-04-14
실험자: SRE 팀 (홍길동)
가설: payment-service의 Pod 1개가 종료되어도
주문 성공률 99.9% 이상 유지
정상 상태 기준선:
- 주문 성공률: 99.97%
- p99 응답 시간: 165ms
- 에러율: 0.03%
실험 결과:
- 주문 성공률: 99.12% (가설 반증!)
- p99 응답 시간: 892ms
- 에러율: 0.88%
- 복구 시간: 45초
발견 사항:
1. Kubernetes readiness probe 간격이 30초로 설정되어 있어
트래픽이 종료 중인 Pod로 계속 전달됨
2. Circuit breaker 타임아웃이 너무 길게 설정 (10초)
3. 재시도 로직이 같은 Pod로 재시도함
개선 액션:
- [HIGH] readiness probe 간격을 5초로 단축
- [HIGH] Circuit breaker 타임아웃을 2초로 조정
- [MED] 재시도 시 다른 인스턴스로 라우팅하도록 수정
6. Game Day 운영 가이드
6.1 Game Day란?
Game Day는 팀이 함께 모여 계획된 장애 시나리오를 실행하고, 실시간으로 대응하며, 학습하는 훈련 세션입니다. 군사 훈련의 "War Game"에서 영감을 받았으며, 실제 장애 상황에서의 대응 능력을 향상시킵니다.
6.2 Game Day 계획
Game Day 계획 템플릿:
1. 목적
- 결제 시스템의 AZ 장애 복원력 검증
- 인시던트 대응 프로세스 훈련
- 새로운 팀원 온보딩
2. 일정
- 날짜: 2025년 4월 14일 (월)
- 시간: 14:00 ~ 17:00 KST
- 장소: 대회의실 + Zoom
3. 참가자
- 게임 마스터: SRE 리드 (시나리오 주입 담당)
- 인시던트 커맨더: 백엔드 리드
- 대응팀: 백엔드 3명, 프론트엔드 1명, DBA 1명
- 관찰자: CTO, PM
4. 시나리오 (참가자에게는 비공개)
시나리오 1: payment-service Pod 50% 종료
시나리오 2: 데이터베이스 읽기 복제본 연결 끊김
시나리오 3: 외부 PG사 API 응답 5초 지연
5. 성공 기준
- 탐지 시간 < 5분
- 완화 시간 < 15분
- 고객 영향 없음
6. 안전 장치
- 킬 스위치: 게임 마스터가 즉시 모든 실험 중단 가능
- 프로덕션 아닌 스테이징 환경에서 실행
- 실제 고객 트래픽에 영향 없음
6.3 Game Day 역할
역할 정의:
게임 마스터 (Game Master)
- 시나리오 설계 및 장애 주입
- 실험 중단 결정권
- 힌트 제공 (필요시)
- 시간 관리
인시던트 커맨더 (Incident Commander)
- 대응팀 조율
- 의사결정
- 커뮤니케이션 관리
- 에스컬레이션 판단
대응팀 (Responders)
- 문제 진단 및 해결
- 런북 참조 및 실행
- 실시간 상태 보고
관찰자 (Observers)
- 대응 과정 기록
- 프로세스 개선점 메모
- 개입하지 않음 (중요!)
서기 (Scribe)
- 타임라인 기록
- 주요 의사결정 기록
- 발견 사항 정리
6.4 Game Day 실행 타임라인
14:00 - 14:15 킥오프 브리핑
- 규칙 설명
- 안전 장치 확인
- 도구 접근 확인
14:15 - 14:20 시나리오 1 주입 (게임 마스터)
14:20 - 14:50 대응팀 탐지 및 대응
14:50 - 15:00 시나리오 1 리뷰
15:00 - 15:10 휴식
15:10 - 15:15 시나리오 2 주입
15:15 - 15:45 대응팀 탐지 및 대응
15:45 - 15:55 시나리오 2 리뷰
15:55 - 16:00 시나리오 3 주입
16:00 - 16:30 대응팀 탐지 및 대응
16:30 - 16:40 시나리오 3 리뷰
16:40 - 17:00 종합 회고 (Retrospective)
- 잘한 점
- 개선할 점
- 액션 아이템 도출
6.5 Game Day 회고
회고 질문 목록:
탐지 (Detection)
- 어떤 알림이 가장 먼저 발생했는가?
- 해당 알림을 보고 문제를 정확히 파악할 수 있었는가?
- 놓친 알림이 있었는가?
- 탐지 시간을 줄일 수 있는 방법은?
대응 (Response)
- 런북이 도움이 되었는가?
- 커뮤니케이션 채널은 효과적이었는가?
- 역할 분담은 명확했는가?
- 에스컬레이션이 필요했는가?
복구 (Recovery)
- 복구에 걸린 시간은 적절했는가?
- 자동 복구 메커니즘이 작동했는가?
- 수동 개입이 필요한 부분은?
시스템 (System)
- 예상대로 동작하지 않은 부분은?
- 개선이 필요한 모니터링은?
- 자동화가 필요한 작업은?
7. 점진적 도입 전략
7.1 Phase 1: 개발 환경 (1~2주)
목표: 팀의 카오스 엔지니어링 역량 구축
활동:
1. 카오스 도구 설치 (Chaos Mesh 또는 Litmus)
2. 간단한 실험 실행
- 개발 환경에서 Pod Kill
- 네트워크 지연 주입
3. 실험 설계 방법 교육
4. 첫 번째 실험 보고서 작성
성공 지표:
- 팀원 전원이 실험 1회 이상 실행
- 실험 설계 프로세스 문서화 완료
7.2 Phase 2: 스테이징 환경 (2~4주)
목표: 실전에 가까운 환경에서 체계적 실험
활동:
1. 스테이징에 카오스 도구 배포
2. 핵심 서비스 대상 체계적 실험
- 서비스 간 통신 장애
- 데이터베이스 연결 풀 고갈
- 캐시 전면 장애
3. 첫 번째 Game Day 실행
4. CI/CD 파이프라인에 기본 실험 통합
성공 지표:
- 주 1회 이상 정기 실험 실행
- Game Day 1회 완료
- 발견된 취약점 3건 이상 개선
7.3 Phase 3: 프로덕션 카나리 (4~8주)
목표: 프로덕션에서 안전하게 실험 시작
활동:
1. 프로덕션 카오스 실험 안전 장치 구축
- 자동 중단 조건 설정
- 킬 스위치 구현
- 실험 영향 범위 제한
2. 소규모 프로덕션 실험
- 전체 트래픽의 1%에 대해 단일 Pod Kill
- 비핵심 서비스에 네트워크 지연
3. 관찰 가능성 대시보드 강화
성공 지표:
- 프로덕션 실험 5회 이상 안전하게 완료
- 고객 영향 제로
- 자동 중단 메커니즘 1회 이상 검증
7.4 Phase 4: 프로덕션 정규화 (8주 이후)
목표: 카오스 엔지니어링을 일상적 실천으로 정착
활동:
1. 자동화된 주기적 실험 실행
2. 새로운 서비스 배포 시 필수 카오스 테스트
3. 분기별 대규모 Game Day
4. AZ/리전 수준 장애 시뮬레이션
5. 카오스 문화 확산 (전사 교육)
성공 지표:
- 월 10회 이상 자동 실험 실행
- 분기별 Game Day 정례화
- MTTR(평균 복구 시간) 50% 감소
- 장애 관련 인시던트 30% 감소
8. Netflix 사례 연구
8.1 Chaos Kong: 리전 대피 훈련
Netflix는 Chaos Kong이라는 실험으로 전체 AWS 리전 장애를 시뮬레이션합니다.
Chaos Kong 프로세스:
1. 준비 단계
- 트래픽 라우팅 확인
- 대체 리전 용량 확인
- 모니터링 강화
- 관련 팀 사전 통보
2. 실행 단계
- US-East-1 리전의 모든 트래픽을 US-West-2로 전환
- DNS 기반 글로벌 로드 밸런싱 활용
- 전환 과정에서 메트릭 실시간 모니터링
3. 관찰 항목
- 트래픽 전환 완료 시간
- 대체 리전의 오토스케일링 응답 시간
- 사용자 경험 영향 (재생 품질, 시작 시간)
- 데이터 일관성
4. 복구 단계
- 트래픽을 원래 리전으로 복원
- 데이터 동기화 확인
- 전체 결과 분석
8.2 Netflix의 카오스 성숙도 모델
Level 0: 카오스 없음
- 장애 시 수동 대응
- "우리 시스템은 잘 작동한다"는 희망
Level 1: 기본 카오스
- Chaos Monkey로 인스턴스 종료
- 개별 서비스 복원력 확인
Level 2: 체계적 카오스
- 다양한 장애 유형 실험
- Game Day 정기 실행
- 결과 기반 개선
Level 3: 고급 카오스
- AZ 장애 시뮬레이션
- CI/CD 통합
- 자동화된 실험
Level 4: 카오스 문화
- 리전 대피 훈련 (Chaos Kong)
- 모든 팀이 카오스 실험 수행
- 복원력이 아키텍처 의사결정의 핵심 기준
9. Amazon 사례 연구
9.1 Amazon GameDay
Amazon은 2004년부터 GameDay라는 장애 훈련을 실행해왔습니다.
Amazon GameDay 원칙:
1. "Everything fails, all the time" - Werner Vogels
- 장애를 정상적인 운영의 일부로 간주
2. 점진적 복잡도 증가
- 단일 서비스 → 서비스 체인 → 전체 시스템
3. 비난 없는 문화
- 장애 대응 실패를 학습 기회로 전환
4. 문서화
- 모든 GameDay 결과를 상세히 기록
5. 반복
- 같은 시나리오를 반복하여 개선 검증
9.2 AWS FIS 통합 사례
{
"description": "Multi-AZ resilience test",
"targets": {
"ec2Instances": {
"resourceType": "aws:ec2:instance",
"resourceTags": {
"chaos-ready": "true"
},
"filters": [
{
"path": "Placement.AvailabilityZone",
"values": ["ap-northeast-2a"]
}
],
"selectionMode": "ALL"
},
"rdsInstances": {
"resourceType": "aws:rds:db",
"resourceTags": {
"chaos-ready": "true"
},
"selectionMode": "ALL"
}
},
"actions": {
"stopEC2": {
"actionId": "aws:ec2:stop-instances",
"targets": {
"Instances": "ec2Instances"
},
"startAfter": []
},
"failoverRDS": {
"actionId": "aws:rds:failover-db-cluster",
"targets": {
"Clusters": "rdsInstances"
},
"startAfter": ["stopEC2"]
}
},
"stopConditions": [
{
"source": "aws:cloudwatch:alarm",
"value": "arn:aws:cloudwatch:region:account:alarm:HighErrorRate"
}
]
}
10. CI/CD 통합
10.1 파이프라인 통합 전략
# GitHub Actions: 카오스 테스트 통합
name: Chaos Testing Pipeline
on:
push:
branches: [main]
schedule:
- cron: '0 2 * * 1-5' # 평일 새벽 2시
jobs:
deploy-staging:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Staging
run: kubectl apply -f k8s/staging/
chaos-test:
needs: deploy-staging
runs-on: ubuntu-latest
steps:
- name: Install Litmus
run: |
kubectl apply -f https://litmuschaos.github.io/litmus/3.0.0/litmus-3.0.0.yaml
- name: Run Pod Delete Experiment
run: |
kubectl apply -f chaos/experiments/pod-delete.yaml
sleep 120
kubectl get chaosresult pod-delete-result -o jsonpath='{.status.experimentStatus.verdict}'
- name: Run Network Delay Experiment
run: |
kubectl apply -f chaos/experiments/network-delay.yaml
sleep 180
kubectl get chaosresult network-delay-result -o jsonpath='{.status.experimentStatus.verdict}'
- name: Verify System Recovery
run: |
./scripts/verify-steady-state.sh
- name: Collect Results
if: always()
run: |
kubectl get chaosresults -o yaml > chaos-results.yaml
- name: Upload Results
if: always()
uses: actions/upload-artifact@v4
with:
name: chaos-results
path: chaos-results.yaml
10.2 카나리 배포와 카오스 통합
# Argo Rollouts + Chaos 통합
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: my-service
spec:
replicas: 10
strategy:
canary:
steps:
- setWeight: 10
- pause:
duration: 5m
# 카나리에 카오스 실험 실행
- analysis:
templates:
- templateName: chaos-analysis
args:
- name: service-name
value: my-service
- setWeight: 50
- pause:
duration: 10m
- setWeight: 100
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: chaos-analysis
spec:
metrics:
- name: success-rate-during-chaos
interval: 30s
successCondition: result[0] >= 99.5
provider:
prometheus:
address: http://prometheus:9090
query: |
sum(rate(http_requests_total{status="200",service="my-service"}[5m]))
/
sum(rate(http_requests_total{service="my-service"}[5m]))
* 100
11. 관찰 가능성과 카오스
11.1 모니터링 대시보드
카오스 실험 중 반드시 모니터링해야 할 메트릭입니다.
핵심 메트릭 (Golden Signals):
1. 레이턴시 (Latency)
- p50, p90, p99 응답 시간
- 서비스 간 호출 레이턴시
2. 트래픽 (Traffic)
- 초당 요청 수 (RPS)
- 트래픽 분포
3. 에러 (Errors)
- HTTP 5xx 비율
- 어플리케이션 에러율
- 타임아웃 비율
4. 포화도 (Saturation)
- CPU 사용률
- 메모리 사용률
- 네트워크 대역폭
- 디스크 I/O
11.2 Grafana 대시보드 예시
{
"dashboard": {
"title": "Chaos Engineering Dashboard",
"panels": [
{
"title": "Request Success Rate",
"type": "gauge",
"targets": [
{
"expr": "sum(rate(http_requests_total{status=~\"2..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"
}
],
"thresholds": {
"steps": [
{ "color": "red", "value": 0 },
{ "color": "yellow", "value": 99 },
{ "color": "green", "value": 99.9 }
]
}
},
{
"title": "P99 Latency",
"type": "timeseries",
"targets": [
{
"expr": "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))"
}
]
},
{
"title": "Error Rate",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"
}
]
},
{
"title": "Active Chaos Experiments",
"type": "stat",
"targets": [
{
"expr": "count(chaos_experiment_status{phase=\"Running\"})"
}
]
}
]
}
}
11.3 알림 설정
# Prometheus AlertManager 규칙
groups:
- name: chaos-safety-alerts
rules:
- alert: ChaosExperimentHighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[2m]))
/
sum(rate(http_requests_total[2m]))
> 0.05
for: 1m
labels:
severity: critical
team: sre
annotations:
summary: "카오스 실험 중 에러율 5% 초과"
description: "즉시 실험을 중단하고 상태를 확인하세요"
- alert: ChaosExperimentHighLatency
expr: |
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[2m]))
> 2.0
for: 1m
labels:
severity: warning
team: sre
annotations:
summary: "카오스 실험 중 P99 레이턴시 2초 초과"
12. SRE와의 관계
Chaos Engineering은 SRE(Site Reliability Engineering)의 핵심 실천 중 하나입니다.
SRE와 Chaos Engineering의 관계:
SRE 목표: 안정적이고 확장 가능한 시스템 운영
│
├── SLO/SLI/SLA 정의 → 카오스 실험의 성공 기준
│
├── Error Budget → 카오스 실험 실행 여부 결정
│ (예산이 충분할 때만 공격적 실험 가능)
│
├── 인시던트 관리 → Game Day 시나리오 소스
│ (과거 장애를 재현하여 개선 검증)
│
├── 포스트모템 → 새로운 카오스 실험 아이디어
│ (장애 분석에서 발견된 취약점 실험)
│
└── Toil 제거 → 카오스 실험 자동화
(반복적인 수동 실험을 자동화)
13. 퀴즈
아래 퀴즈를 통해 학습한 내용을 점검해 보세요.
Q1: Chaos Engineering의 첫 번째 단계는 무엇인가요?
정답: 정상 상태 가설 (Steady State Hypothesis) 수립
모든 카오스 실험은 시스템의 정상 상태를 정의하고, "이 장애를 주입하더라도 정상 상태를 유지할 것이다"라는 가설을 세우는 것에서 시작합니다. 가설 없이 장애를 주입하는 것은 카오스 엔지니어링이 아니라 단순한 파괴입니다.
Q2: Netflix의 Chaos Kong은 어떤 수준의 장애를 시뮬레이션하나요?
정답: 전체 AWS 리전 장애
Chaos Kong은 Netflix의 가장 극단적인 카오스 실험으로, 전체 AWS 리전의 트래픽을 다른 리전으로 전환하는 리전 대피(Region Evacuation)를 시뮬레이션합니다. 이를 통해 Netflix는 리전 수준의 장애에도 서비스가 유지되는지 검증합니다.
Q3: 폭발 반경(Blast Radius)을 최소화하기 위한 전략 3가지를 설명하세요.
정답:
- 소규모 시작: 단일 인스턴스에서 시작하여 점진적으로 그룹, AZ, 리전 수준으로 확대합니다.
- 시간 제한: 실험 지속 시간을 명시적으로 설정하여 장기간 영향을 방지합니다.
- 자동 중단 조건: 핵심 메트릭이 임계값을 초과하면 실험을 자동으로 중단합니다. 예를 들어 에러율이 5%를 넘으면 즉시 중단합니다.
추가로 트래픽 제한(일부 트래픽에만 적용)과 롤백 계획도 중요한 전략입니다.
Q4: Game Day에서 게임 마스터(Game Master)의 역할은 무엇인가요?
정답:
게임 마스터는 Game Day의 운영자로서 다음 역할을 수행합니다:
- 시나리오 설계: 실험할 장애 시나리오를 사전에 설계합니다 (참가자에게는 비공개).
- 장애 주입: 카오스 도구를 사용하여 계획된 시점에 장애를 주입합니다.
- 실험 중단 결정권: 상황이 통제 불능이 되면 킬 스위치로 즉시 중단합니다.
- 힌트 제공: 대응팀이 막힌 경우 힌트를 제공합니다.
- 시간 관리: 전체 타임라인을 관리합니다.
Q5: Chaos Engineering의 점진적 도입 4단계를 순서대로 나열하세요.
정답:
- Phase 1: 개발 환경 (1~2주) - 도구 설치, 기초 실험, 팀 교육
- Phase 2: 스테이징 환경 (2~4주) - 체계적 실험, 첫 Game Day, CI/CD 통합
- Phase 3: 프로덕션 카나리 (4~8주) - 소규모 프로덕션 실험, 안전 장치 구축
- Phase 4: 프로덕션 정규화 (8주 이후) - 자동화된 정기 실험, AZ/리전 장애 시뮬레이션
핵심은 "천천히, 안전하게, 점진적으로" 확대하는 것입니다.
참고 자료
- Principles of Chaos Engineering - principlesofchaos.org
- Chaos Engineering: System Resiliency in Practice - Casey Rosenthal, Nora Jones (O'Reilly)
- Netflix Tech Blog: Chaos Engineering - netflixtechblog.com
- Litmus Chaos Documentation - litmuschaos.io/docs
- Chaos Mesh Documentation - chaos-mesh.org/docs
- AWS Fault Injection Service - AWS 공식 문서
- Azure Chaos Studio - Microsoft 공식 문서
- Gremlin Documentation - gremlin.com/docs
- Google SRE Book - Chapter 17: Testing for Reliability - sre.google/sre-book
- The Practice of Cloud System Administration - Thomas Limoncelli 외
- Awesome Chaos Engineering - GitHub 리포지터리
- CNCF Chaos Engineering Whitepaper - cncf.io
- Learning Chaos Engineering - Russ Miles (O'Reilly)
- Chaos Engineering Adoption Guide - Gremlin Blog
Chaos Engineering Complete Guide 2025: Resilience Testing, Chaos Monkey, Litmus, Game Day
Introduction: Why Chaos Engineering
Modern distributed systems consist of dozens to hundreds of microservices, message queues, databases, caches, and load balancers. In these complex systems, failure is not a question of "if" but "when."
In 2012, Netflix experienced a complete service outage due to an AWS US-East-1 region failure. After this incident, Netflix adopted the philosophy of "instead of avoiding failure, build systems resilient to failure" and gave birth to Chaos Engineering.
Chaos Engineering is not simply "randomly killing servers." It is a discipline grounded in scientific experimentation methodology that proactively discovers system vulnerabilities and strengthens resilience so services continue operating normally even during failures.
What This Post Covers
- Core principles and experiment design of Chaos Engineering
- Netflix Chaos Monkey origin story and the Simian Army
- Tool comparison: Litmus Chaos, Chaos Mesh, Gremlin, AWS FIS
- Fault type experiments: network, CPU, memory, Pod, node, AZ
- Kubernetes chaos experiment YAML examples
- Game Day operations guide
- Progressive adoption strategy (dev to staging to production)
- Netflix and Amazon case studies
- CI/CD integration and observability
1. Core Principles of Chaos Engineering
The principles of Chaos Engineering are defined at principlesofchaos.org.
1.1 Steady State Hypothesis
Every chaos experiment begins with defining "steady state."
Steady State Examples:
- API response time p99 < 200ms
- Error rate < 0.1%
- Order processing success rate > 99.9%
- Database replication lag < 1 second
The steady state hypothesis is: "Even after injecting a specific failure, the system will maintain its steady state."
1.2 Vary Real-World Events
You must simulate failures that could actually occur in production.
| Failure Type | Real-World Case | Experiment Method |
|---|---|---|
| Server Down | Hardware failure, OOM Kill | Force-terminate Pod/instance |
| Network Latency | Cross-region communication delay | Inject latency via tc command |
| Network Partition | Switch failure | Block traffic via iptables rules |
| CPU Overload | Sudden traffic spike | Generate CPU load with stress-ng |
| Disk Full | Log explosion | Fill disk with dd command |
| DNS Failure | DNS server down | Manipulate DNS responses |
| AZ Failure | Data center outage | Block all AZ traffic |
1.3 Run Experiments in Production
True confidence can only be validated in production environments. Staging environments differ from production in traffic patterns, data volumes, and infrastructure configuration.
Of course, this does not mean starting in production right away. Adopt progressively, but the ultimate goal should be production experimentation.
1.4 Minimize Blast Radius
Blast Radius Control Strategies:
1. Start small: Single instance -> instance group -> AZ -> region
2. Time limit: Set experiment duration (e.g., 5 minutes)
3. Auto-abort: Stop experiment immediately when key metrics exceed thresholds
4. Traffic limit: Apply experiment to only 1% of total traffic
5. Rollback plan: Verify rollback procedure before experiment
1.5 Automate Experiments
Manual experiments cannot scale. Automation includes:
- Experiment scheduling (running at specific times each week)
- CI/CD pipeline integration
- Automated result collection and report generation
- Automatic abort condition monitoring
2. Chaos Monkey: Netflix's Beginning
2.1 Origin Story
In 2010, as Netflix migrated entirely from its own data centers to AWS, the team faced a fundamental question:
"In cloud infrastructure, servers can disappear at any time. Can our system handle this?"
Chaos Monkey was born to answer this question. It randomly terminates instances in production, forcing every service to be resilient against single-instance failures.
2.2 The Simian Army
After the success of Chaos Monkey, Netflix created the Simian Army to experiment with a wider variety of failure scenarios.
Simian Army Members:
+----------------------+--------------------------------------+
| Name | Role |
+----------------------+--------------------------------------+
| Chaos Monkey | Random instance termination |
| Latency Monkey | Network latency injection |
| Conformity Monkey | Detect non-compliant instances |
| Doctor Monkey | Unhealthy instance health checks |
| Janitor Monkey | Clean up unused resources |
| Security Monkey | Detect security vulnerabilities |
| Chaos Gorilla | Full AZ failure simulation |
| Chaos Kong | Full region failure simulation |
+----------------------+--------------------------------------+
2.3 Chaos Monkey Configuration Example
# Chaos Monkey Configuration (Spinnaker Integration)
chaos_monkey:
enabled: true
leashed: false
schedule:
frequency: "weekday"
start_hour: 10
end_hour: 16
timezone: "America/New_York"
grouping: "cluster"
probability: 1.0
exceptions:
- account: "prod-critical"
region: "us-east-1"
stack: "payment"
3. Chaos Tool Comparison
3.1 Tool Overview
| Tool | Developer | Environment | License | Features |
|---|---|---|---|---|
| Litmus Chaos | CNCF | Kubernetes | Apache 2.0 | ChaosHub, GitOps native |
| Chaos Mesh | CNCF | Kubernetes | Apache 2.0 | Powerful dashboard, TimeChaos |
| Gremlin | Gremlin Inc. | All | Commercial | SaaS-based, enterprise features |
| AWS FIS | AWS | AWS | Pay-per-use | Native AWS service integration |
| Azure Chaos Studio | Microsoft | Azure | Pay-per-use | Native Azure service integration |
| Steadybit | Steadybit | All | Commercial | Safety guardrails emphasis |
3.2 Litmus Chaos in Detail
Litmus is a CNCF Incubating project and a Kubernetes-native chaos engineering framework.
# Litmus Chaos Installation
apiVersion: v1
kind: Namespace
metadata:
name: litmus
---
# LitmusChaos Operator Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: chaos-operator-ce
namespace: litmus
spec:
replicas: 1
selector:
matchLabels:
name: chaos-operator
template:
metadata:
labels:
name: chaos-operator
spec:
serviceAccountName: litmus
containers:
- name: chaos-operator
image: litmuschaos/chaos-operator:3.0.0
env:
- name: CHAOS_RUNNER_IMAGE
value: "litmuschaos/chaos-runner:3.0.0"
- name: WATCH_NAMESPACE
value: ""
The core concepts of Litmus are ChaosExperiment, ChaosEngine, and ChaosResult.
# Pod Delete Experiment Definition
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosExperiment
metadata:
name: pod-delete
namespace: litmus
spec:
definition:
scope: Namespaced
permissions:
- apiGroups: [""]
resources: ["pods"]
verbs: ["delete", "list", "get"]
image: "litmuschaos/go-runner:3.0.0"
args:
- -c
- ./experiments -name pod-delete
command:
- /bin/bash
env:
- name: TOTAL_CHAOS_DURATION
value: "30"
- name: CHAOS_INTERVAL
value: "10"
- name: FORCE
value: "false"
3.3 Chaos Mesh in Detail
Chaos Mesh is a Kubernetes chaos platform supporting diverse fault types.
# Chaos Mesh Installation (Helm)
# helm repo add chaos-mesh https://charts.chaos-mesh.org
# helm install chaos-mesh chaos-mesh/chaos-mesh -n chaos-mesh --create-namespace
# Network Delay Experiment
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-delay-example
namespace: default
spec:
action: delay
mode: all
selector:
namespaces:
- default
labelSelectors:
app: my-service
delay:
latency: "200ms"
jitter: "50ms"
correlation: "50"
duration: "5m"
scheduler:
cron: "@every 1h"
3.4 AWS Fault Injection Service (FIS)
AWS FIS is a chaos engineering service natively integrated with AWS services.
{
"description": "EC2 instance termination experiment",
"targets": {
"myInstances": {
"resourceType": "aws:ec2:instance",
"resourceTags": {
"Environment": "staging",
"ChaosReady": "true"
},
"selectionMode": "COUNT(1)"
}
},
"actions": {
"stopInstances": {
"actionId": "aws:ec2:stop-instances",
"parameters": {},
"targets": {
"Instances": "myInstances"
}
}
},
"stopConditions": [
{
"source": "aws:cloudwatch:alarm",
"value": "arn:aws:cloudwatch:us-east-1:123456789:alarm:HighErrorRate"
}
],
"roleArn": "arn:aws:iam::123456789:role/FISRole"
}
3.5 Gremlin
Gremlin is a commercial SaaS-based chaos engineering platform.
# Gremlin Agent Installation (Kubernetes)
helm repo add gremlin https://helm.gremlin.com
helm install gremlin gremlin/gremlin \
--set gremlin.secret.managed=true \
--set gremlin.secret.type=secret \
--set gremlin.secret.teamID=YOUR_TEAM_ID \
--set gremlin.secret.clusterID=my-cluster \
--set gremlin.secret.teamSecret=YOUR_SECRET
Gremlin's advantages include an intuitive UI, fine-grained control, and safety features (Safety Net). Basic chaos experiments are available even on the free tier.
4. Fault Type Experiments
4.1 Network Failures
Network failures are the most common and critical issues in distributed systems.
# Chaos Mesh: Network Partition
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-partition
namespace: default
spec:
action: partition
mode: all
selector:
namespaces:
- default
labelSelectors:
app: order-service
direction: both
target:
selector:
namespaces:
- default
labelSelectors:
app: payment-service
mode: all
duration: "2m"
# Chaos Mesh: Packet Loss
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: packet-loss
namespace: default
spec:
action: loss
mode: all
selector:
labelSelectors:
app: api-gateway
loss:
loss: "25"
correlation: "50"
duration: "3m"
# Chaos Mesh: Bandwidth Limitation
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: bandwidth-limit
namespace: default
spec:
action: bandwidth
mode: all
selector:
labelSelectors:
app: file-service
bandwidth:
rate: "1mbps"
limit: 20971520
buffer: 10000
duration: "5m"
4.2 CPU Stress
# Chaos Mesh: CPU Stress
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: cpu-stress
namespace: default
spec:
mode: one
selector:
labelSelectors:
app: compute-service
stressors:
cpu:
workers: 4
load: 80
duration: "5m"
4.3 Memory Pressure
# Chaos Mesh: Memory Stress
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: memory-stress
namespace: default
spec:
mode: one
selector:
labelSelectors:
app: cache-service
stressors:
memory:
workers: 2
size: "512MB"
duration: "3m"
4.4 Pod Kill
# Chaos Mesh: Pod Kill
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: pod-kill-example
namespace: default
spec:
action: pod-kill
mode: fixed
value: "2"
selector:
namespaces:
- default
labelSelectors:
app: web-frontend
gracePeriod: 0
duration: "1m"
# Chaos Mesh: Container Kill
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
name: container-kill
namespace: default
spec:
action: container-kill
mode: one
selector:
labelSelectors:
app: multi-container-app
containerNames:
- sidecar-proxy
duration: "30s"
4.5 Node Drain
# Litmus: Node Drain Experiment
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: node-drain-engine
namespace: litmus
spec:
engineState: active
chaosServiceAccount: litmus-admin
experiments:
- name: node-drain
spec:
components:
env:
- name: TOTAL_CHAOS_DURATION
value: "60"
- name: TARGET_NODE
value: "worker-node-02"
- name: APP_NAMESPACE
value: "default"
- name: APP_LABEL
value: "app=critical-service"
4.6 AZ Failure Simulation
AZ (Availability Zone) failure is the experiment with the largest blast radius.
# AWS FIS: AZ Failure Simulation
experiment_template:
description: "AZ-a failure simulation"
targets:
azSubnets:
resourceType: "aws:ec2:subnet"
resourceTags:
AvailabilityZone: "us-east-1a"
selectionMode: "ALL"
actions:
disruptConnectivity:
actionId: "aws:network:disrupt-connectivity"
parameters:
scope: "all"
targets:
Subnets: "azSubnets"
duration: "PT10M"
stopConditions:
- source: "aws:cloudwatch:alarm"
value: "arn:aws:cloudwatch:region:account:alarm:CriticalErrorRate"
4.7 DNS Failure
# Chaos Mesh: DNS Failure
apiVersion: chaos-mesh.org/v1alpha1
kind: DNSChaos
metadata:
name: dns-failure
namespace: default
spec:
action: error
mode: all
selector:
labelSelectors:
app: external-api-client
patterns:
- "external-api.example.com"
duration: "2m"
5. Experiment Design Methodology
5.1 Systematic Experiment Design
Chaos experiments follow the same structure as scientific experiments.
Chaos Experiment Design Framework:
1. Hypothesis
"Even if 1 payment-service Pod is terminated,
order success rate will remain above 99.9%"
2. Steady State Definition
- Order success rate: 99.95%
- API response time p99: 180ms
- Error rate: 0.05%
3. Variables
- Independent variable: Force-terminate 1 Pod
- Dependent variables: Order success rate, response time, error rate
4. Blast Radius
- Target: 1 of 3 payment-service Pods
- Impact scope: Approximately 33% of payment requests
5. Abort Conditions
- Order success rate < 99.0%
- API response time p99 > 1000ms
- Concurrent errors > 100/min
6. Execute and Observe
- Collect baseline for 5 minutes before experiment
- Execute experiment (2 minutes)
- Observe recovery for 5 minutes after experiment
7. Analyze and Improve
- Verify/falsify hypothesis
- Document discovered vulnerabilities
- Create improvement work tickets
5.2 Experiment Checklist
Pre-Experiment Checklist:
[ ] Is the hypothesis clearly defined?
[ ] Are steady state metrics being collected?
[ ] Is the blast radius appropriately limited?
[ ] Are abort conditions configured?
[ ] Is the rollback procedure documented?
[ ] Have relevant teams been notified?
[ ] Is the monitoring dashboard ready?
[ ] Is an on-call engineer standing by?
During-Experiment Checklist:
[ ] Are metrics being monitored in real-time?
[ ] Are abort conditions being continuously checked?
[ ] Are there any unexpected side effects?
Post-Experiment Checklist:
[ ] Has the system returned to steady state?
[ ] Have experiment results been recorded?
[ ] Have action items been created for discovered issues?
[ ] Have results been shared with the team?
5.3 Experiment Result Template
Experiment ID: CE-2025-042
Date: 2025-04-14
Experimenter: SRE Team (Jane Doe)
Hypothesis: Even when 1 payment-service Pod is terminated,
order success rate remains above 99.9%
Steady State Baseline:
- Order success rate: 99.97%
- p99 response time: 165ms
- Error rate: 0.03%
Experiment Results:
- Order success rate: 99.12% (Hypothesis FALSIFIED!)
- p99 response time: 892ms
- Error rate: 0.88%
- Recovery time: 45 seconds
Findings:
1. Kubernetes readiness probe interval set to 30s,
causing traffic to continue routing to terminating Pod
2. Circuit breaker timeout set too high (10 seconds)
3. Retry logic retrying to the same Pod
Improvement Actions:
- [HIGH] Reduce readiness probe interval to 5 seconds
- [HIGH] Adjust circuit breaker timeout to 2 seconds
- [MED] Modify retry logic to route to different instances
6. Game Day Operations Guide
6.1 What is Game Day?
Game Day is a training session where the team gathers to execute planned failure scenarios, respond in real-time, and learn. Inspired by military "War Games," it improves response capabilities during actual incidents.
6.2 Game Day Planning
Game Day Planning Template:
1. Purpose
- Verify payment system AZ failure resilience
- Train incident response process
- Onboard new team members
2. Schedule
- Date: Monday, April 14, 2025
- Time: 14:00 - 17:00 EST
- Location: Conference Room + Zoom
3. Participants
- Game Master: SRE Lead (injects scenarios)
- Incident Commander: Backend Lead
- Response Team: 3 Backend, 1 Frontend, 1 DBA
- Observers: CTO, PM
4. Scenarios (hidden from participants)
Scenario 1: Kill 50% of payment-service Pods
Scenario 2: Database read replica connection lost
Scenario 3: External payment gateway 5-second delay
5. Success Criteria
- Detection time < 5 minutes
- Mitigation time < 15 minutes
- Zero customer impact
6. Safety Measures
- Kill switch: Game master can stop all experiments immediately
- Run in staging, not production
- No impact on actual customer traffic
6.3 Game Day Roles
Role Definitions:
Game Master
- Design scenarios and inject failures
- Authority to abort experiments
- Provide hints (when needed)
- Time management
Incident Commander
- Coordinate response team
- Decision making
- Communication management
- Escalation judgment
Response Team (Responders)
- Diagnose and resolve issues
- Reference and execute runbooks
- Report status in real-time
Observers
- Record response process
- Note process improvements
- Do NOT intervene (important!)
Scribe
- Record timeline
- Document key decisions
- Organize findings
6.4 Game Day Execution Timeline
14:00 - 14:15 Kickoff Briefing
- Explain rules
- Confirm safety measures
- Verify tool access
14:15 - 14:20 Scenario 1 Injection (Game Master)
14:20 - 14:50 Response Team Detection and Response
14:50 - 15:00 Scenario 1 Review
15:00 - 15:10 Break
15:10 - 15:15 Scenario 2 Injection
15:15 - 15:45 Response Team Detection and Response
15:45 - 15:55 Scenario 2 Review
15:55 - 16:00 Scenario 3 Injection
16:00 - 16:30 Response Team Detection and Response
16:30 - 16:40 Scenario 3 Review
16:40 - 17:00 Comprehensive Retrospective
- What went well
- What to improve
- Derive action items
6.5 Game Day Retrospective
Retrospective Questions:
Detection
- Which alert fired first?
- Could you accurately identify the problem from the alert?
- Were there any missed alerts?
- How can we reduce detection time?
Response
- Was the runbook helpful?
- Were communication channels effective?
- Was role assignment clear?
- Was escalation needed?
Recovery
- Was recovery time acceptable?
- Did auto-recovery mechanisms work?
- Which parts required manual intervention?
System
- Which parts did not behave as expected?
- What monitoring needs improvement?
- What tasks need automation?
7. Progressive Adoption Strategy
7.1 Phase 1: Development Environment (1-2 weeks)
Goal: Build team chaos engineering capabilities
Activities:
1. Install chaos tools (Chaos Mesh or Litmus)
2. Run simple experiments
- Pod Kill in development environment
- Network latency injection
3. Experiment design methodology training
4. Write first experiment report
Success Metrics:
- Every team member has run at least 1 experiment
- Experiment design process documented
7.2 Phase 2: Staging Environment (2-4 weeks)
Goal: Systematic experiments in production-like environment
Activities:
1. Deploy chaos tools to staging
2. Systematic experiments on core services
- Inter-service communication failures
- Database connection pool exhaustion
- Full cache failure
3. Execute first Game Day
4. Integrate basic experiments into CI/CD pipeline
Success Metrics:
- At least 1 regular experiment per week
- 1 Game Day completed
- 3+ discovered vulnerabilities improved
7.3 Phase 3: Production Canary (4-8 weeks)
Goal: Begin safe production experiments
Activities:
1. Build production chaos experiment safety measures
- Configure auto-abort conditions
- Implement kill switch
- Limit experiment impact scope
2. Small-scale production experiments
- Single Pod Kill on 1% of total traffic
- Network latency on non-critical services
3. Enhance observability dashboards
Success Metrics:
- 5+ production experiments completed safely
- Zero customer impact
- Auto-abort mechanism verified at least once
7.4 Phase 4: Production Normalization (8+ weeks)
Goal: Establish chaos engineering as routine practice
Activities:
1. Automated periodic experiment execution
2. Mandatory chaos tests for new service deployments
3. Quarterly large-scale Game Days
4. AZ/region-level failure simulation
5. Chaos culture evangelization (company-wide training)
Success Metrics:
- 10+ automated experiments per month
- Quarterly Game Days established
- MTTR reduced by 50%
- Failure-related incidents reduced by 30%
8. Netflix Case Study
8.1 Chaos Kong: Region Evacuation Drill
Netflix uses an experiment called Chaos Kong to simulate full AWS region failure.
Chaos Kong Process:
1. Preparation Phase
- Verify traffic routing
- Confirm alternative region capacity
- Enhance monitoring
- Notify relevant teams in advance
2. Execution Phase
- Route all US-East-1 traffic to US-West-2
- Leverage DNS-based global load balancing
- Real-time metric monitoring during transition
3. Observation Points
- Traffic transition completion time
- Alternative region auto-scaling response time
- User experience impact (playback quality, start time)
- Data consistency
4. Recovery Phase
- Restore traffic to original region
- Verify data synchronization
- Full results analysis
8.2 Netflix Chaos Maturity Model
Level 0: No Chaos
- Manual response to failures
- Hope that "our system works fine"
Level 1: Basic Chaos
- Instance termination with Chaos Monkey
- Individual service resilience verification
Level 2: Systematic Chaos
- Diverse fault type experiments
- Regular Game Day execution
- Results-based improvements
Level 3: Advanced Chaos
- AZ failure simulation
- CI/CD integration
- Automated experiments
Level 4: Chaos Culture
- Region evacuation drill (Chaos Kong)
- All teams performing chaos experiments
- Resilience as core architecture decision criterion
9. Amazon Case Study
9.1 Amazon GameDay
Amazon has been running failure drills called GameDay since 2004.
Amazon GameDay Principles:
1. "Everything fails, all the time" - Werner Vogels
- Treat failure as a normal part of operations
2. Progressive complexity increase
- Single service -> service chain -> full system
3. Blameless culture
- Turn failure response failures into learning opportunities
4. Documentation
- Record all GameDay results in detail
5. Repetition
- Repeat same scenarios to verify improvements
9.2 AWS FIS Integration Example
{
"description": "Multi-AZ resilience test",
"targets": {
"ec2Instances": {
"resourceType": "aws:ec2:instance",
"resourceTags": {
"chaos-ready": "true"
},
"filters": [
{
"path": "Placement.AvailabilityZone",
"values": ["us-east-1a"]
}
],
"selectionMode": "ALL"
},
"rdsInstances": {
"resourceType": "aws:rds:db",
"resourceTags": {
"chaos-ready": "true"
},
"selectionMode": "ALL"
}
},
"actions": {
"stopEC2": {
"actionId": "aws:ec2:stop-instances",
"targets": {
"Instances": "ec2Instances"
},
"startAfter": []
},
"failoverRDS": {
"actionId": "aws:rds:failover-db-cluster",
"targets": {
"Clusters": "rdsInstances"
},
"startAfter": ["stopEC2"]
}
},
"stopConditions": [
{
"source": "aws:cloudwatch:alarm",
"value": "arn:aws:cloudwatch:region:account:alarm:HighErrorRate"
}
]
}
10. CI/CD Integration
10.1 Pipeline Integration Strategy
# GitHub Actions: Chaos Test Integration
name: Chaos Testing Pipeline
on:
push:
branches: [main]
schedule:
- cron: '0 2 * * 1-5' # Weekdays at 2 AM
jobs:
deploy-staging:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Staging
run: kubectl apply -f k8s/staging/
chaos-test:
needs: deploy-staging
runs-on: ubuntu-latest
steps:
- name: Install Litmus
run: |
kubectl apply -f https://litmuschaos.github.io/litmus/3.0.0/litmus-3.0.0.yaml
- name: Run Pod Delete Experiment
run: |
kubectl apply -f chaos/experiments/pod-delete.yaml
sleep 120
kubectl get chaosresult pod-delete-result -o jsonpath='{.status.experimentStatus.verdict}'
- name: Run Network Delay Experiment
run: |
kubectl apply -f chaos/experiments/network-delay.yaml
sleep 180
kubectl get chaosresult network-delay-result -o jsonpath='{.status.experimentStatus.verdict}'
- name: Verify System Recovery
run: |
./scripts/verify-steady-state.sh
- name: Collect Results
if: always()
run: |
kubectl get chaosresults -o yaml > chaos-results.yaml
- name: Upload Results
if: always()
uses: actions/upload-artifact@v4
with:
name: chaos-results
path: chaos-results.yaml
10.2 Canary Deployment with Chaos Integration
# Argo Rollouts + Chaos Integration
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: my-service
spec:
replicas: 10
strategy:
canary:
steps:
- setWeight: 10
- pause:
duration: 5m
# Run chaos experiment on canary
- analysis:
templates:
- templateName: chaos-analysis
args:
- name: service-name
value: my-service
- setWeight: 50
- pause:
duration: 10m
- setWeight: 100
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: chaos-analysis
spec:
metrics:
- name: success-rate-during-chaos
interval: 30s
successCondition: result[0] >= 99.5
provider:
prometheus:
address: http://prometheus:9090
query: |
sum(rate(http_requests_total{status="200",service="my-service"}[5m]))
/
sum(rate(http_requests_total{service="my-service"}[5m]))
* 100
11. Observability and Chaos
11.1 Monitoring Dashboard
Metrics that must be monitored during chaos experiments.
Key Metrics (Golden Signals):
1. Latency
- p50, p90, p99 response times
- Inter-service call latency
2. Traffic
- Requests per second (RPS)
- Traffic distribution
3. Errors
- HTTP 5xx rate
- Application error rate
- Timeout rate
4. Saturation
- CPU utilization
- Memory utilization
- Network bandwidth
- Disk I/O
11.2 Grafana Dashboard Example
{
"dashboard": {
"title": "Chaos Engineering Dashboard",
"panels": [
{
"title": "Request Success Rate",
"type": "gauge",
"targets": [
{
"expr": "sum(rate(http_requests_total{status=~\"2..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"
}
],
"thresholds": {
"steps": [
{ "color": "red", "value": 0 },
{ "color": "yellow", "value": 99 },
{ "color": "green", "value": 99.9 }
]
}
},
{
"title": "P99 Latency",
"type": "timeseries",
"targets": [
{
"expr": "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))"
}
]
},
{
"title": "Error Rate",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"
}
]
},
{
"title": "Active Chaos Experiments",
"type": "stat",
"targets": [
{
"expr": "count(chaos_experiment_status{phase=\"Running\"})"
}
]
}
]
}
}
11.3 Alert Configuration
# Prometheus AlertManager Rules
groups:
- name: chaos-safety-alerts
rules:
- alert: ChaosExperimentHighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[2m]))
/
sum(rate(http_requests_total[2m]))
> 0.05
for: 1m
labels:
severity: critical
team: sre
annotations:
summary: "Error rate exceeds 5% during chaos experiment"
description: "Immediately abort experiment and check status"
- alert: ChaosExperimentHighLatency
expr: |
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[2m]))
> 2.0
for: 1m
labels:
severity: warning
team: sre
annotations:
summary: "P99 latency exceeds 2 seconds during chaos experiment"
12. Relationship with SRE
Chaos Engineering is one of the core practices of SRE (Site Reliability Engineering).
Relationship between SRE and Chaos Engineering:
SRE Goal: Operate reliable and scalable systems
|
+-- SLO/SLI/SLA Definition -> Success criteria for chaos experiments
|
+-- Error Budget -> Determines whether to run chaos experiments
| (Aggressive experiments only when budget is sufficient)
|
+-- Incident Management -> Source of Game Day scenarios
| (Reproduce past failures to verify improvements)
|
+-- Postmortems -> New chaos experiment ideas
| (Experiment on vulnerabilities found in failure analysis)
|
+-- Toil Elimination -> Chaos experiment automation
(Automate repetitive manual experiments)
13. Quiz
Test your understanding with these questions.
Q1: What is the first step in Chaos Engineering?
Answer: Establishing a Steady State Hypothesis
Every chaos experiment begins with defining the system's steady state and forming the hypothesis: "Even after injecting this failure, the system will maintain steady state." Injecting failures without a hypothesis is not chaos engineering -- it is just destruction.
Q2: What level of failure does Netflix's Chaos Kong simulate?
Answer: Full AWS region failure
Chaos Kong is Netflix's most extreme chaos experiment, simulating a Region Evacuation where all traffic from an entire AWS region is redirected to another region. This verifies that Netflix's service remains operational even during region-level failures.
Q3: Describe 3 strategies for minimizing blast radius.
Answer:
- Start small: Begin with a single instance and progressively expand to instance groups, AZs, and regions.
- Time limits: Explicitly set experiment duration to prevent prolonged impact.
- Auto-abort conditions: Automatically stop the experiment when key metrics exceed thresholds. For example, immediately abort if error rate exceeds 5%.
Additional important strategies include traffic limiting (applying experiments to only a portion of traffic) and having a rollback plan.
Q4: What is the role of the Game Master during a Game Day?
Answer:
The Game Master is the operator of the Game Day and performs the following roles:
- Scenario design: Design failure scenarios in advance (kept secret from participants).
- Failure injection: Use chaos tools to inject failures at planned moments.
- Experiment abort authority: Use the kill switch to immediately stop if situation becomes uncontrollable.
- Hint provision: Provide hints if the response team gets stuck.
- Time management: Manage the overall timeline.
Q5: List the 4 phases of progressive Chaos Engineering adoption in order.
Answer:
- Phase 1: Development Environment (1-2 weeks) - Tool installation, basic experiments, team training
- Phase 2: Staging Environment (2-4 weeks) - Systematic experiments, first Game Day, CI/CD integration
- Phase 3: Production Canary (4-8 weeks) - Small-scale production experiments, safety measures
- Phase 4: Production Normalization (8+ weeks) - Automated regular experiments, AZ/region failure simulation
The key principle is "slowly, safely, progressively" expanding scope.
References
- Principles of Chaos Engineering - principlesofchaos.org
- Chaos Engineering: System Resiliency in Practice - Casey Rosenthal, Nora Jones (O'Reilly)
- Netflix Tech Blog: Chaos Engineering - netflixtechblog.com
- Litmus Chaos Documentation - litmuschaos.io/docs
- Chaos Mesh Documentation - chaos-mesh.org/docs
- AWS Fault Injection Service - AWS Official Documentation
- Azure Chaos Studio - Microsoft Official Documentation
- Gremlin Documentation - gremlin.com/docs
- Google SRE Book - Chapter 17: Testing for Reliability - sre.google/sre-book
- The Practice of Cloud System Administration - Thomas Limoncelli et al.
- Awesome Chaos Engineering - GitHub Repository
- CNCF Chaos Engineering Whitepaper - cncf.io
- Learning Chaos Engineering - Russ Miles (O'Reilly)
- Chaos Engineering Adoption Guide - Gremlin Blog