Serve API Reference

Core APIs

ray.serve.start(detached: bool = False, http_options: Union[dict, ray.serve.config.HTTPOptions, None] = None, dedicated_cpu: bool = False, _checkpoint_path: str = 'ray://', **kwargs) → ray.serve.api.Client[source]

Initialize a serve instance.

By default, the instance will be scoped to the lifetime of the returned Client object (or when the script exits). If detached is set to True, the instance will instead persist until serve.shutdown() is called. This is only relevant if connecting to a long-running Ray cluster (e.g., with ray.init(address=”auto”) or ray.init(“ray://<remote_addr>”)).

Parameters
  • detached (bool) – Whether not the instance should be detached from this script. If set, the instance will live on the Ray cluster until it is explicitly stopped with serve.shutdown().

  • http_options (Optional[Dict, serve.HTTPOptions]) –

    Configuration options for HTTP proxy. You can pass in a dictionary or HTTPOptions object with fields:

    • host(str, None): Host for HTTP servers to listen on. Defaults to “127.0.0.1”. To expose Serve publicly, you probably want to set this to “0.0.0.0”.

    • port(int): Port for HTTP server. Defaults to 8000.

    • middlewares(list): A list of Starlette middlewares that will be applied to the HTTP servers in the cluster. Defaults to [].

    • location(str, serve.config.DeploymentMode): The deployment location of HTTP servers:

      • ”HeadOnly”: start one HTTP server on the head node. Serve assumes the head node is the node you executed serve.start on. This is the default.

      • ”EveryNode”: start one HTTP server per node.

      • ”NoServer” or None: disable HTTP server.

    • num_cpus (int): The number of CPU cores to reserve for each internal Serve HTTP proxy actor. Defaults to 0.

  • dedicated_cpu (bool) – Whether to reserve a CPU core for the internal Serve controller actor. Defaults to False.

PublicAPI (beta): This API is in beta and may change before becoming stable.

ray.serve.deployment(_func_or_class: Optional[Callable] = None, name: Optional[str] = None, version: Optional[str] = None, prev_version: Optional[str] = None, num_replicas: Optional[int] = None, init_args: Optional[Tuple[Any]] = None, init_kwargs: Optional[Dict[Any, Any]] = None, route_prefix: Optional[str] = None, ray_actor_options: Optional[Dict] = None, user_config: Optional[Any] = None, max_concurrent_queries: Optional[int] = None, _autoscaling_config: Union[Dict, ray.serve.config.AutoscalingConfig, None] = None, _graceful_shutdown_wait_loop_s: Optional[float] = None, _graceful_shutdown_timeout_s: Optional[float] = None) → Callable[[Callable], ray.serve.api.Deployment][source]

Define a Serve deployment.

Parameters
  • name (Optional[str]) – Globally-unique name identifying this deployment. If not provided, the name of the class or function will be used.

  • version (Optional[str]) – Version of the deployment. This is used to indicate a code change for the deployment; when it is re-deployed with a version change, a rolling update of the replicas will be performed. If not provided, every deployment will be treated as a new version.

  • prev_version (Optional[str]) – Version of the existing deployment which is used as a precondition for the next deployment. If prev_version does not match with the existing deployment’s version, the deployment will fail. If not provided, deployment procedure will not check the existing deployment’s version.

  • num_replicas (Optional[int]) – The number of processes to start up that will handle requests to this deployment. Defaults to 1.

  • init_args (Optional[Tuple]) – Positional args to be passed to the class constructor when starting up deployment replicas. These can also be passed when you call .deploy() on the returned Deployment.

  • init_kwargs (Optional[Dict]) – Keyword args to be passed to the class constructor when starting up deployment replicas. These can also be passed when you call .deploy() on the returned Deployment.

  • route_prefix (Optional[str]) – Requests to paths under this HTTP path prefix will be routed to this deployment. Defaults to ‘/{name}’. Routing is done based on longest-prefix match, so if you have deployment A with a prefix of ‘/a’ and deployment B with a prefix of ‘/a/b’, requests to ‘/a’, ‘/a/’, and ‘/a/c’ go to A and requests to ‘/a/b’, ‘/a/b/’, and ‘/a/b/c’ go to B. Routes must not end with a ‘/’ unless they’re the root (just ‘/’), which acts as a catch-all.

  • ray_actor_options (dict) – Options to be passed to the Ray actor constructor such as resource requirements.

  • user_config (Optional[Any]) – [experimental] Config to pass to the reconfigure method of the deployment. This can be updated dynamically without changing the version of the deployment and restarting its replicas. The user_config needs to be hashable to keep track of updates, so it must only contain hashable types, or hashable types nested in lists and dictionaries.

  • max_concurrent_queries (Optional[int]) – The maximum number of queries that will be sent to a replica of this deployment without receiving a response. Defaults to 100.

Example:

>>> @serve.deployment(name="deployment1", version="v1")
    class MyDeployment:
        pass
>>> MyDeployment.deploy(*init_args)
>>> MyDeployment.options(num_replicas=2, init_args=init_args).deploy()
Returns

Deployment

PublicAPI: This API is stable across Ray releases.

ray.serve.list_deployments() → Dict[str, ray.serve.api.Deployment][source]

Returns a dictionary of all active deployments.

Dictionary maps deployment name to Deployment objects.

PublicAPI: This API is stable across Ray releases.

ray.serve.get_deployment(name: str)ray.serve.api.Deployment[source]

Dynamically fetch a handle to a Deployment object.

This can be used to update and redeploy a deployment without access to the original definition.

Example:

>>> MyDeployment = serve.get_deployment("name")
>>> MyDeployment.options(num_replicas=10).deploy()
Parameters
  • name (str) – name of the deployment. This must have already been

  • deployed.

Returns

Deployment

PublicAPI: This API is stable across Ray releases.

ray.serve.shutdown() → None[source]

Completely shut down the connected Serve instance.

Shuts down all processes and deletes all state associated with the instance.

PublicAPI: This API is stable across Ray releases.

Deployment API

class ray.serve.api.Deployment(func_or_class: Callable, name: str, config: ray.serve.config.BackendConfig, version: Optional[str] = None, prev_version: Optional[str] = None, init_args: Optional[Tuple[Any]] = None, init_kwargs: Optional[Tuple[Any]] = None, route_prefix: Optional[str] = None, ray_actor_options: Optional[Dict] = None, _internal=False)[source]

PublicAPI: This API is stable across Ray releases.

deploy(*init_args, _blocking=True, **init_kwargs)[source]

Deploy or update this deployment.

Args:
init_args (optional): args to pass to the class __init__

method. Not valid if this deployment wraps a function.

init_kwargs (optional): kwargs to pass to the class __init__

method. Not valid if this deployment wraps a function.

PublicAPI: This API is stable across Ray releases.

delete()[source]

Delete this deployment. PublicAPI: This API is stable across Ray releases.

get_handle(sync: Optional[bool] = True) → Union[ray.serve.handle.RayServeHandle, ray.serve.handle.RayServeSyncHandle][source]

Get a ServeHandle to this deployment to invoke it from Python.

Args:
sync (bool): If true, then Serve will return a ServeHandle that

works everywhere. Otherwise, Serve will return an asyncio-optimized ServeHandle that’s only usable in an asyncio loop.

Returns:

ServeHandle

PublicAPI: This API is stable across Ray releases.

options(func_or_class: Optional[Callable] = None, name: Optional[str] = None, version: Optional[str] = None, prev_version: Optional[str] = None, init_args: Optional[Tuple[Any]] = None, init_kwargs: Optional[Dict[Any, Any]] = None, route_prefix: Optional[str] = None, num_replicas: Optional[int] = None, ray_actor_options: Optional[Dict] = None, user_config: Optional[Any] = None, max_concurrent_queries: Optional[int] = None, _autoscaling_config: Union[Dict, ray.serve.config.AutoscalingConfig, None] = None, _graceful_shutdown_wait_loop_s: Optional[float] = None, _graceful_shutdown_timeout_s: Optional[float] = None)ray.serve.api.Deployment[source]

Return a copy of this deployment with updated options.

Only those options passed in will be updated, all others will remain unchanged from the existing deployment.

PublicAPI: This API is stable across Ray releases.

ServeHandle API

class ray.serve.handle.RayServeHandle(controller_handle: ray.actor.ActorHandle, endpoint_name: str, handle_options: Optional[ray.serve.handle.HandleOptions] = None, *, _router: Optional[ray.serve.router.Router] = None, _internal_pickled_http_request: bool = False)[source]

A handle to a service endpoint.

Invoking this endpoint with .remote is equivalent to pinging an HTTP endpoint.

Example

>>> handle = serve_client.get_handle("my_endpoint")
>>> handle
RayServeSyncHandle(endpoint="my_endpoint")
>>> handle.remote(my_request_content)
ObjectRef(...)
>>> ray.get(handle.remote(...))
# result
>>> ray.get(handle.remote(let_it_crash_request))
# raises RayTaskError Exception
>>> async_handle = serve_client.get_handle("my_endpoint", sync=False)
>>> async_handle
RayServeHandle(endpoint="my_endpoint")
>>> await async_handle.remote(my_request_content)
ObjectRef(...)
>>> ray.get(await async_handle.remote(...))
# result
>>> ray.get(await async_handle.remote(let_it_crash_request))
# raises RayTaskError Exception
options(*, method_name: Union[str, ray.serve.handle.DEFAULT] = <DEFAULT.VALUE: 1>, shard_key: Union[str, ray.serve.handle.DEFAULT] = <DEFAULT.VALUE: 1>, http_method: Union[str, ray.serve.handle.DEFAULT] = <DEFAULT.VALUE: 1>, http_headers: Union[Dict[str, str], ray.serve.handle.DEFAULT] = <DEFAULT.VALUE: 1>)[source]

Set options for this handle.

Parameters
  • method_name (str) – The method to invoke on the backend.

  • http_method (str) – The HTTP method to use for the request.

  • shard_key (str) – A string to use to deterministically map this request to a backend if there are multiple for this endpoint.

async remote(*args, **kwargs)[source]

Issue an asynchronous request to the endpoint.

Returns a Ray ObjectRef whose results can be waited for or retrieved using ray.wait or ray.get (or await object_ref), respectively.

Returns

ray.ObjectRef

Parameters
  • request_data (dict, Any) – If it’s a dictionary, the data will be available in request.json() or request.form(). Otherwise, it will be available in request.body().

  • **kwargs – All keyword arguments will be available in request.query_params.

Batching Requests

ray.serve.batch(max_batch_size=10, batch_wait_timeout_s=0.0)[source]

Converts a function to asynchronously handle batches.

The function can be a standalone function or a class method. In both cases, the function must be async def and take a list of objects as its sole argument and return a list of the same length as a result.

When invoked, the caller passes a single object. These will be batched and executed asynchronously once there is a batch of max_batch_size or batch_wait_timeout_s has elapsed, whichever occurs first.

Example:

>>> @serve.batch(max_batch_size=50, batch_wait_timeout_s=0.5)
    async def handle_batch(batch: List[str]):
        return [s.lower() for s in batch]
>>> async def handle_single(s: str):
        return await handle_batch(s) # Returns s.lower().
Parameters
  • max_batch_size (int) – the maximum batch size that will be executed in one call to the underlying function.

  • batch_wait_timeout_s (float) – the maximum duration to wait for max_batch_size elements before running the underlying function.