Ray Serve: Scalable ML Model Serving & Online Inference
Ray Serve is a scalable model serving library built on Ray. Deploy ML models as HTTP endpoints with automatic autoscaling, GPU-aware scheduling, and composable multi-model pipelines — on a single machine or a distributed cluster.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →Basic Deployment with @serve.deployment
Install with pip install "ray[serve]". A Deployment is a class bound to an HTTP route:
import ray
from ray import serve
from starlette.requests import Request
import torch
ray.init()
serve.start()
@serve.deployment(
num_replicas=2,
ray_actor_options={"num_cpus": 1, "num_gpus": 0.5},
autoscaling_config={
"min_replicas": 1,
"max_replicas": 8,
"target_num_ongoing_requests_per_replica": 5,
},
)
@serve.ingress(app) # FastAPI app as HTTP ingress
class SentimentClassifier:
def __init__(self):
from transformers import pipeline
self.pipe = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
device=0, # GPU 0
)
async def classify(self, request: Request) -> dict:
body = await request.json()
result = self.pipe(body["text"])[0]
return {"label": result["label"], "score": result["score"]}
# Deploy and get a handle
handle = serve.run(SentimentClassifier.bind())
result = ray.get(handle.classify.remote("Ray Serve is amazing!"))
print(result) # {"label": "POSITIVE", "score": 0.9998} Model Composition: Pipeline DAG
Chain deployments into a pipeline where each stage processes the output of the previous:
from ray import serve
import numpy as np
@serve.deployment(ray_actor_options={"num_cpus": 1})
class TextPreprocessor:
def preprocess(self, text: str) -> list:
# Tokenize, clean, normalize
return text.lower().split()
@serve.deployment(ray_actor_options={"num_gpus": 1})
class EmbeddingModel:
def __init__(self):
from sentence_transformers import SentenceTransformer
self.model = SentenceTransformer("all-MiniLM-L6-v2")
def embed(self, tokens: list) -> list:
return self.model.encode([" ".join(tokens)]).tolist()
@serve.deployment
class PipelineOrchestrator:
def __init__(self, preprocessor, embedder):
self.preprocessor = preprocessor
self.embedder = embedder
async def predict(self, text: str) -> dict:
# Chained async calls across deployments
tokens = await self.preprocessor.preprocess.remote(text)
embedding = await self.embedder.embed.remote(tokens)
return {"embedding": embedding, "dims": len(embedding)}
# Bind deployments into a graph
preprocessor = TextPreprocessor.bind()
embedder = EmbeddingModel.bind()
pipeline = PipelineOrchestrator.bind(preprocessor, embedder)
serve.run(pipeline) Production Autoscaling Configuration
Configure autoscaling via YAML for production deployments:
# serve_config.yaml
applications:
- name: llm-inference
route_prefix: /v1
import_path: app:LLMService
deployments:
- name: LLMService
num_replicas: "auto" # enable autoscaling
max_ongoing_requests: 10
ray_actor_options:
num_cpus: 2
num_gpus: 1
memory: 8000000000 # 8 GB RAM reservation
autoscaling_config:
min_replicas: 1
max_replicas: 4
target_num_ongoing_requests_per_replica: 3
upscale_delay_s: 5 # fast scale-up
downscale_delay_s: 60 # slow scale-down
# Deploy with:
# serve deploy serve_config.yaml
# Monitor with:
# serve status Ray Serve vs BentoML vs Triton vs TorchServe
| Feature | Ray Serve | BentoML | Triton | TorchServe |
|---|---|---|---|---|
| Distributed cluster | Native (Ray) | K8s-based | K8s-based | K8s-based |
| Pipeline DAG | Deployment graph | Runner composition | Ensemble models | No |
| Autoscaling | Request-queue based | KEDA-based | Manual replicas | Manual replicas |
| LLM streaming | Generator streaming | SSE streaming | gRPC streaming | Limited |
| GPU fractional alloc | Yes (0.25, 0.5) | No | No | No |
| Raw GPU throughput | Good | Good | Best | Good |
| Best for | Distributed, Ray users | Packaging & deploy | Max throughput | PyTorch simple serving |
Frequently Asked Questions
What is Ray Serve and how does it relate to Ray?▼
Ray Serve is the model serving layer built on top of Ray, the distributed computing framework. Ray handles cluster management, distributed scheduling, and actor-based concurrency. Ray Serve adds HTTP routing, request batching, health checks, and model pipeline composition on top of Ray's execution engine. You can run Ray Serve on a single machine or scale to a 100-node cluster with the same API.
How does Ray Serve compare to Kubernetes-native serving?▼
Ray Serve handles both the compute cluster management (via Ray) and the serving framework in one system. With Kubernetes-native approaches, you manage pods separately from the serving logic. Ray Serve is better when you already use Ray for training/data processing and want a unified cluster. Kubernetes is better when you need infrastructure-level isolation, compliance controls, or have a heterogeneous workload beyond ML serving.
What is a Ray Serve deployment and how does it scale?▼
A Deployment is a Ray Serve unit of compute — a Python class or function bound to HTTP routes. You control replicas (number of concurrent instances), ray_actor_options (CPU/GPU allocation per replica), and autoscaling policies. Ray Serve's autoscaler monitors replica queue length and target_num_ongoing_requests_per_replica, then adds or removes replicas automatically.
How do I build a multi-model pipeline in Ray Serve?▼
Ray Serve uses a Deployment Graph where deployments can call each other as handles. A preprocessing deployment calls an embedding deployment which calls a reranking deployment — all chained with async calls. The HTTP ingress deployment is the entry point, and Ray manages the routing and data transfer between deployments automatically.
How does GPU allocation work in Ray Serve?▼
Set num_gpus in ray_actor_options to allocate GPUs per replica. With fractional GPU allocation (num_gpus=0.5), multiple replicas can share a single physical GPU, increasing utilization for small models. Ray Serve respects CUDA_VISIBLE_DEVICES and supports multi-GPU models via num_gpus=2 or more. Use placement groups for fine-grained co-location control.
Can Ray Serve handle streaming responses?▼
Yes. Ray Serve supports streaming via generator-based handlers. Your handle method can yield chunks, and Ray Serve streams the response to the client with Server-Sent Events (SSE) or chunked transfer encoding. This is essential for LLM token streaming — each token generated by the model is yielded and immediately sent to the client, enabling low time-to-first-token.