Skip to main content

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.

✓ Automatic replica autoscaling ✓ Multi-model pipeline DAG ✓ Fractional GPU allocation ✓ LLM streaming support
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

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 clusterNative (Ray)K8s-basedK8s-basedK8s-based
Pipeline DAGDeployment graphRunner compositionEnsemble modelsNo
AutoscalingRequest-queue basedKEDA-basedManual replicasManual replicas
LLM streamingGenerator streamingSSE streaminggRPC streamingLimited
GPU fractional allocYes (0.25, 0.5)NoNoNo
Raw GPU throughputGoodGoodBestGood
Best forDistributed, Ray usersPackaging & deployMax throughputPyTorch 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.