Skip to content

Route requests to containers and scale instances

Choose which container instance handles each request. Every instance belongs to a Durable Object with its own ID. containers-py has helpers to pick an ID and get a stub so your Worker can call that Durable Object.

For how the platform places and scales instances, see Scaling and Routing and Limits and Instance Types.

Getting a stub

One container per entity

get_container(binding, name) returns the stub for the instance called name, and creates the instance on first use. The same name always reaches the same instance, so use it for a container per user, session or document:

from containers import get_container

container = get_container(self.env.MY_CONTAINER, f"user-{user_id}")
return await container.fetch(request)

get_container is a plain function, so don't await it. Only the calls you make on the stub need await.

A single shared container

With no name, get_container returns one shared instance, named "cf-singleton-container":

container = get_container(self.env.MY_CONTAINER)

Stateless instances

For interchangeable instances, get_random(binding, instances=3) picks one of instances named instances at random:

from containers import get_random

container = await get_random(self.env.MY_CONTAINER, 5)
return await container.fetch(request)

Unlike get_container, get_random is a coroutine. It picks an instance at random and doesn't check health or latency. Keep instances at or below max_instances in your Wrangler config. See Stateless instances for the platform side of this pattern.

Sending requests

Use fetch for the default port

await stub.fetch(request) calls the Durable Object's fetch() handler. That handler starts the container if needed and forwards the request to default_port. HTTP and WebSocket requests both work.

return await container.fetch(request)

Warning

fetch() picks the port from the request's cf-container-target-port header, and this call forwards the client's headers. In a public Worker, a client that sends that header can reach any port in the container, such as an admin or metrics server. A non-numeric value raises ValueError. Don't rely on the platform to remove the header. Pin the port with switch_port, which replaces it: container.fetch(switch_port(request, 8080)).

Use switch_port for another port

To reach a port other than default_port, rewrite the request with switch_port. It sets the cf-container-target-port header, which the Container class reads:

from containers import switch_port

return await container.fetch(switch_port(request, 9090))

Use container_fetch to build requests in Python

container_fetch sends a request straight to the container, starting it first if needed. It accepts either a Request or a URL. With a URL, keyword arguments are the same as for workers.Request, such as method, headers and body, and the URL can be relative:

import json
from http import HTTPMethod

response = await container.container_fetch(
    "/api/jobs",
    port=9090,
    method=HTTPMethod.POST,
    headers={"content-type": "application/json"},
    body=json.dumps({"input": "s3://bucket/video.mp4"}),
)

Passing request options together with a Request raises TypeError.

Warning

Called from your Worker, container_fetch is an RPC call, and WebSocket upgrades can't cross RPC yet. See workerd#2319. For WebSockets, use stub.fetch(...), combined with switch_port when you need another port.

Calling container methods from a Worker

You can call any public async def method on your Container subclass, including the SDK's own, through the stub over RPC:

container = get_container(self.env.MY_CONTAINER, "session-1")

state = await container.get_state()
await container.start_and_wait_for_ports(env_vars={"MODE": "batch"})
await container.stop("SIGINT")
await container.destroy()

JavaScript RPC has no keyword arguments, which affects what you can pass:

  • start, start_and_wait_for_ports, wait_for_port and container_fetch accept keyword arguments over RPC. The SDK unpacks them on the other side.
  • Call every other method, including any you define yourself, with positional arguments only.
  • Arguments and return values must be serialisable. An asyncio.Event can't cross RPC, so the abort= and signal= cancellation arguments only work when called from inside the Durable Object.

Adding your own methods

Define methods on your subclass, so the Worker calls container.transcode(...) instead of building HTTP requests:

import json
from http import HTTPMethod
from typing import TypedDict

from containers import Container, get_container
from workers import Request, Response, WorkerEntrypoint


class TranscodeResult(TypedDict):
    output_url: str
    duration_s: float


class Transcoder(Container):
    default_port = 8080

    async def transcode(self, source_url: str, preset: str) -> TranscodeResult:
        response = await self.container_fetch(
            "/transcode",
            method=HTTPMethod.POST,
            body=json.dumps({"source": source_url, "preset": preset}),
        )
        return await response.json()


class Default(WorkerEntrypoint):
    async def fetch(self, request: Request) -> Response:
        container = get_container(self.env.TRANSCODER, "video-123")
        result: TranscodeResult = await container.transcode(
            "https://example.com/in.mp4", "720p"
        )
        return Response.json(result)

Check requests before they reach the container

Override fetch on your subclass to add routing or authentication in front of the container. Forward with self.container_fetch, not self.fetch, or the call recurses:

from urllib.parse import urlparse

from containers import Container
from workers import Request, Response


class MyContainer(Container):
    default_port = 8080

    async def fetch(self, request: Request) -> Response:
        if urlparse(request.url).path == "/health":
            return Response("ok")

        if request.headers.get("authorization") != f"Bearer {self.env.API_TOKEN}":
            return Response("unauthorized", status=401)

        return await self.container_fetch(request)

Type hints

get_container and get_random take a DurableObjectNamespace and return a DurableObjectStub. Both are typing-only Protocols exported from containers, because the Workers runtime doesn't ship Python types for bindings:

from typing import Any

from containers import DurableObjectStub, get_container


def container_for(env: Any, user_id: str) -> DurableObjectStub:
    return get_container(env.MY_CONTAINER, f"user-{user_id}")

self.env is untyped, so annotate bindings yourself where it helps.

Typing calls on a stub

DurableObjectStub types fetch(), but every other attribute is Any, so a type checker won't catch a typo such as stub.get_stat() or a wrong argument. To have the type checker check your container's method signatures, annotate the result in the Worker, as result: TranscodeResult does above, or cast the stub to your subclass:

from typing import cast

container = cast(Transcoder, get_container(self.env.TRANSCODER, "video-123"))
result = await container.transcode("https://example.com/in.mp4", "720p")  # checked

The cast only changes what the type checker sees. At runtime the object is still an RPC stub. Only async def methods are safe to call through it, with the argument rules above. Through a stub, attributes such as default_port and plain methods such as renew_activity_timeout() don't behave as their annotations say.