HealthCheck 완벽 마스터
HealthCheck의 핵심 개념과 실전 활용법
학습 항목
이미지 로딩 중...
Load Balancing 실무 활용 완벽 가이드
실무에서 바로 활용 가능한 로드 밸런싱 기법과 패턴을 학습합니다. Nginx, Node.js, Python을 활용한 다양한 로드 밸런싱 전략과 헬스 체크, 세션 관리 방법을 다룹니다.
들어가며
이 글에서는 Load Balancing 실무 활용 완벽 가이드에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Round_Robin_로드_밸런서
- Weighted_Round_Robin
- Least_Connections_알고리즘
- Health_Check_구현
- Sticky_Session_구현
- IP_Hash_로드_밸런싱
- Nginx_기본_설정
- Nginx_가중치_및_헬스체크
- Circuit_Breaker_패턴
- Redis_기반_세션_공유
- Response_Time_기반_라우팅
- 종합_로드_밸런서_구현
1. Round_Robin_로드_밸런서
개요
가장 기본적인 로드 밸런싱 방식으로 요청을 순차적으로 서버에 분배합니다. 간단하고 효율적이며 서버 부하가 균등할 때 적합합니다.
코드 예제
class RoundRobinBalancer {
constructor(servers) {
this.servers = servers;
this.current = 0;
}
getNext() {
const server = this.servers[this.current];
this.current = (this.current + 1) % this.servers.length;
return server;
}
}
설명
인덱스를 순환하며 다음 서버를 선택하고, 배열 끝에 도달하면 다시 처음으로 돌아갑니다.
2. Weighted_Round_Robin
개요
서버의 성능에 따라 가중치를 부여하여 더 강력한 서버에 더 많은 요청을 분배합니다. 서버 스펙이 다를 때 유용합니다.
코드 예제
class WeightedBalancer {
constructor(servers) {
this.pool = servers.flatMap(s =>
Array(s.weight).fill(s.url)
);
this.index = 0;
}
getNext() {
const server = this.pool[this.index];
this.index = (this.index + 1) % this.pool.length;
return server;
}
}
설명
가중치만큼 서버를 풀에 복제하여 높은 가중치의 서버가 더 자주 선택되도록 합니다.
3. Least_Connections_알고리즘
개요
현재 활성 연결이 가장 적은 서버로 요청을 라우팅합니다. 요청 처리 시간이 불균등할 때 효과적입니다.
코드 예제
class LeastConnectionBalancer {
constructor(servers) {
this.servers = servers.map(url => ({url, connections: 0}));
}
getNext() {
return this.servers.reduce((min, server) =>
server.connections < min.connections ? server : min
);
}
release(server) {
server.connections--;
}
}
설명
각 서버의 활성 연결 수를 추적하고, 가장 적은 연결을 가진 서버를 선택합니다.
4. Health_Check_구현
개요
주기적으로 백엔드 서버의 상태를 확인하여 장애 서버를 자동으로 제외합니다. 고가용성 시스템의 필수 요소입니다.
코드 예제
class HealthChecker {
async checkServers(servers) {
return Promise.all(servers.map(async server => {
try {
const res = await fetch(`${server}/health`, {timeout: 3000});
return {url: server, healthy: res.ok};
} catch {
return {url: server, healthy: false};
}
}));
}
}
설명
각 서버의 헬스 체크 엔드포인트를 호출하고, 응답 상태에 따라 서버의 건강 상태를 판단합니다.
5. Sticky_Session_구현
개요
동일한 클라이언트의 요청을 항상 같은 서버로 라우팅합니다. 세션 데이터가 서버에 저장될 때 필요합니다.
코드 예제
class StickySessionBalancer {
constructor(servers) {
this.servers = servers;
this.sessions = new Map();
}
getServer(clientId) {
if (!this.sessions.has(clientId)) {
const index = Math.abs(this.hash(clientId)) % this.servers.length;
this.sessions.set(clientId, this.servers[index]);
}
return this.sessions.get(clientId);
}
}
설명
클라이언트 ID를 해싱하여 서버를 결정하고, Map에 저장하여 동일한 서버로 계속 연결합니다.
6. IP_Hash_로드_밸런싱
개요
클라이언트 IP를 해싱하여 특정 서버로 매핑합니다. 세션 유지가 필요하지만 별도 저장소 없이 구현할 때 사용합니다.
코드 예제
class IPHashBalancer {
constructor(servers) {
this.servers = servers;
}
getServer(clientIP) {
const hash = clientIP.split('.').reduce(
(acc, octet) => acc + parseInt(octet), 0
);
return this.servers[hash % this.servers.length];
}
}
설명
IP 주소의 각 옥텟을 합산하여 해시값을 만들고, 서버 개수로 나눈 나머지로 서버를 선택합니다.
7. Nginx_기본_설정
개요
Nginx를 사용한 HTTP 로드 밸런싱 기본 설정입니다. upstream 블록으로 백엔드 서버 그룹을 정의합니다.
코드 예제
upstream backend {
server backend1.example.com:3000;
server backend2.example.com:3000;
server backend3.example.com:3000;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
설명
upstream 블록에 백엔드 서버들을 나열하고, proxy_pass로 요청을 전달하면 자동으로 로드 밸런싱됩니다.
8. Nginx_가중치_및_헬스체크
개요
Nginx에서 서버 가중치와 헬스 체크를 설정하여 효율적이고 안정적인 로드 밸런싱을 구현합니다.
코드 예제
upstream backend {
server backend1.example.com:3000 weight=3 max_fails=3 fail_timeout=30s;
server backend2.example.com:3000 weight=2;
server backend3.example.com:3000 weight=1 backup;
}
server {
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header;
}
}
설명
weight로 트래픽 비율을 조정하고, max_fails와 fail_timeout으로 장애 감지를 설정합니다.
9. Circuit_Breaker_패턴
개요
연속된 실패 시 서버를 일시적으로 차단하여 시스템 전체의 안정성을 보호합니다. 장애 전파를 방지합니다.
코드 예제
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.failures = 0;
this.threshold = threshold;
this.state = 'CLOSED';
this.nextAttempt = Date.now();
}
async call(fn) {
if (this.state === 'OPEN' && Date.now() < this.nextAttempt) {
throw new Error('Circuit breaker is OPEN');
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failures = 0;
this.state = 'CLOSED';
}
onFailure() {
this.failures++;
if (this.failures >= this.threshold) {
this.state = 'OPEN';
this.nextAttempt = Date.now() + this.timeout;
}
}
}
설명
실패 횟수를 추적하여 임계값 초과 시 회로를 개방하고, 일정 시간 후 재시도를 허용합니다.
10. Redis_기반_세션_공유
개요
여러 서버 간 세션 데이터를 공유하기 위해 Redis를 활용합니다. Sticky Session 없이도 세션 일관성을 유지합니다.
코드 예제
const redis = require('redis');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const client = redis.createClient();
app.use(session({
store: new RedisStore({ client }),
secret: 'your-secret-key',
resave: false,
saveUninitialized: false
}));
설명
Redis를 세션 저장소로 사용하여 모든 서버가 동일한 세션 데이터에 접근할 수 있습니다.
11. Response_Time_기반_라우팅
개요
각 서버의 평균 응답 시간을 측정하여 가장 빠른 서버로 요청을 라우팅합니다. 성능 최적화에 효과적입니다.
코드 예제
class ResponseTimeBalancer {
constructor(servers) {
this.servers = servers.map(url => ({url, avgTime: 0, count: 0}));
}
getNext() {
return this.servers.reduce((fastest, server) =>
server.avgTime < fastest.avgTime ? server : fastest
);
}
recordTime(server, time) {
server.avgTime = (server.avgTime * server.count + time) / (server.count + 1);
server.count++;
}
}
설명
각 요청의 응답 시간을 기록하여 평균을 계산하고, 가장 낮은 평균 응답 시간을 가진 서버를 선택합니다.
12. 종합_로드_밸런서_구현
개요
여러 전략을 결합한 실무용 로드 밸런서입니다. 헬스 체크, 가중치, 실패 처리를 모두 포함합니다.
코드 예제
class ProductionBalancer {
constructor(servers) {
this.servers = servers.map(s => ({...s, healthy: true, failures: 0}));
this.index = 0;
setInterval(() => this.healthCheck(), 10000);
}
async getNext() {
const healthy = this.servers.filter(s => s.healthy);
if (healthy.length === 0) throw new Error('No healthy servers');
const server = healthy[this.index % healthy.length];
this.index++;
return server;
}
async healthCheck() {
for (const server of this.servers) {
try {
await fetch(`${server.url}/health`, {timeout: 5000});
server.healthy = true;
server.failures = 0;
} catch {
server.failures++;
if (server.failures >= 3) server.healthy = false;
}
}
}
}
설명
정기적인 헬스 체크로 서버 상태를 모니터링하고, 건강한 서버들 사이에서만 로드 밸런싱을 수행합니다.
마치며
이번 글에서는 Load Balancing 실무 활용 완벽 가이드에 대해 알아보았습니다. 총 12가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#JavaScript #LoadBalancing #Nginx #HealthCheck #SessionManagement