🪐 Ray Serve

데이터 엔지니어 · AI 엔지니어를 위한 핵심 요약
📅 2026.03 ⚡ distributed 📦 serving 📈 scaling 🔧 실무 스터디 가이드

📋 목차

  1. Ray Serve란?
  2. 왜 써야 하는가?
  3. 핵심 개념
  4. 퀵스타트
  5. 핵심 설정 레퍼런스
  6. 실무 팁 & 트러블슈팅
  7. 참고 자료

1. Ray Serve란?

Ray Serve는 Ray 생태계 위에서 동작하는 확장 가능한 모델 서빙 프레임워크입니다. 하나의 파이썬 함수/클래스를 분산 배포하여 트래픽에 따라 자동으로 스케일링하며, GPU/CPU 리소스를 효율적으로 사용합니다.

🔁 자동 스케일링

요청 수에 따라 replica 수를 동적으로 조절. zero-scaledown도 지원하여 비용 최적화.

🧩 멀티 모델 & 라우팅

하나의 엔드포인트에서 여러 모델을 조합하거나, 버전별 라우팅, A/B 테스트 가능.

⚙️ 배치 & 스트리밍

동적 배치 처리, WebSocket 스트리밍, FastAPI 통합으로 실시간 서비스 구축.

💡 핵심 요약: Ray Serve는 프로덕션 ML 서빙을 위해 설계된 분산, 탄력적, Python‑네이티브 서빙 레이어입니다.

2. 왜 써야 하는가?

기존 서빙 방식(TensorFlow Serving, TorchServe, Flask/Gunicorn)과 비교한 Ray Serve의 차별점:

비교 항목Ray ServeFlask + GunicornTF Serving / TorchServe
분산 스케일링✅ 기본 내장 (Ray 클러스터)❌ 수동 (워커 관리)⚠️ 제한적 (모델별)
멀티 모델 라우팅✅ 네이티브 (DAG, composition)❌ 직접 구현⚠️ 부분 지원
GPU 공유 / 동적 배치✅ 자동 배치, fraction GPU❌✅ (정적 배치)
스트리밍 / WebSocket✅ FastAPI + WebSocket⚠️ (확장 필요)❌
Python 생태계✅ 완전한 Python (any lib)✅⚠️ (제한적 커스텀)
⚠️ 주의: 단순 단일 모델 서빙만 필요하면 TorchServe나 FastAPI로 충분할 수 있습니다. Ray Serve는 복잡한 파이프라인, 높은 확장성, 멀티 모델이 필요한 경우에 빛을 발합니다.

3. 핵심 개념

Ray Serve의 주요 구성 요소와 아키텍처를 이해하는 것이 중요합니다.

┌─────────────────────────────────────────────────────┐ │ Ray Serve Architecture │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Ingress │────▶│ Router │────▶│ Replica │ │ │ │ (HTTP/gRPC)│ │ (Deployment) │ │ (Worker)│ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌─────────────────────────────────────────────┐ │ │ │ Ray Cluster (분산 스케줄러) │ │ │ │ object store · distributed futures · autoscaler │ │ └─────────────────────────────────────────────┘ │ │ │ │ • Deployment: 배포 단위 (모델, 함수, 클래스) │ │ • Replica: 실제 worker 프로세스 (CPU/GPU) │ │ • Router: 요청을 replica로 분산 (라운드로빈/캐싱) │ └─────────────────────────────────────────────────────┘

4. 퀵스타트

설치부터 첫 번째 모델 서빙까지 5분 가이드.

📦 설치

pip install "ray[serve]"

또는 conda:

conda install -c conda-forge ray-serve

⚙️ 기본 설정 & 첫 예제

model.py — 간단한 텍스트 분류기 서빙:

from ray import serve
from transformers import pipeline

@serve.deployment(
    num_replicas=2,
    ray_actor_options={"num_gpus": 0.2},
    autoscaling_config={
        "min_replicas": 1,
        "max_replicas": 5,
        "target_num_ongoing_requests_per_replica": 10,
    }
)
class TextClassifier:
    def __init__(self):
        self.model = pipeline("sentiment-analysis")

    async def __call__(self, request):
        text = (await request.json())["text"]
        result = self.model(text)
        return {"result": result}

serve.run(TextClassifier.bind())

CLI로 실행:

serve run model:TextClassifier

요청 테스트 (curl):

curl -X POST http://localhost:8000/ \
  -H "Content-Type: application/json" \
  -d '{"text": "Ray Serve is amazing!"}'
✅ 결과: {"result": [{"label": "POSITIVE", "score": 0.999}]}

5. 핵심 설정 레퍼런스

파라미터타입설명예시
num_replicasint고정 replica 수 (autoscaling 비활성)2
autoscaling_configdict자동 스케일링 정책{"min_replicas":1, "max_replicas":10}
ray_actor_optionsdictGPU/CPU 리소스 할당{"num_gpus": 0.5}
max_concurrent_queriesintreplica당 동시 요청 제한100
user_configany런타임 업데이트 가능한 설정{"batch_size": 32}
route_prefixstrHTTP 경로 (예: /classify)"/v1/predict"

자세한 옵션은 공식 Deployment API 참조.

6. 실무 팁 & 트러블슈팅

🔥 문제: GPU 메모리 부족

해결: ray_actor_options={"num_gpus": 0.3} 으로 GPU fraction 사용. 또는 max_concurrent_queries를 낮춰 메모리 경합 완화.

⏱️ 문제: 콜드 스타트 지연

해결: min_replicas=1 이상 유지. 모델 로딩 시간이 길면 health_check_period_s 조정.

📦 문제: 배치 처리 최적화

해결: @serve.batch(max_batch_size=32, batch_wait_timeout_s=0.1) 데코레이터로 동적 배칭.

🔧 트러블슈팅 요약:

7. 참고 자료

#distributed #serving #scaling #Ray #MLOps