Rendering 3D frames

Run Blender in a container, with the system packages it needs and a request timeout only a container app can set.

Introduction

Blender rendering one frame of a turntable on a GPU, with no model and no weights in the app at all.

It is the case the container path is for: the app needs an environment more than it needs code. Blender links against system libraries, ships as a tarball with its own Python, and has a command line rather than an API.

Building the image

Dockerfile
FROM python:3.12-slim

ARG BLENDER=4.5.9
ARG SERIES=4.5

# Blender ships as a tarball with its own Python, so there is nothing to pip
# install. What apt is for here is the libraries it links against even when it
# never opens a window: X, GL, Wayland, fontconfig and freetype are all needed
# by a build that only ever renders to a file.
RUN apt-get update && apt-get install -y --no-install-recommends \
      curl xz-utils \
      libx11-6 libxi6 libxxf86vm1 libxfixes3 libxrender1 libxkbcommon0 \
      libxrandr2 libxinerama1 libxcursor1 \
      libwayland-client0 libwayland-cursor0 libwayland-egl1 libdecor-0-0 \
      libgl1 libegl1 libglu1-mesa libsm6 libice6 libglib2.0-0 \
      libfreetype6 libfontconfig1 libtbb12 \
    && rm -rf /var/lib/apt/lists/*

RUN curl -fsSL "https://download.blender.org/release/Blender${SERIES}/blender-${BLENDER}-linux-x64.tar.xz" \
      -o /tmp/blender.tar.xz \
    && mkdir -p /opt/blender \
    && tar -xJf /tmp/blender.tar.xz -C /opt/blender --strip-components=1 \
    && rm /tmp/blender.tar.xz \
    && ln -s /opt/blender/blender /usr/local/bin/blender

# Fail the build, not the first request. A missing shared library is invisible
# until Blender is executed, and a build that succeeds and then answers 500 is
# the worst version of this.
RUN blender --version

WORKDIR /app
COPY scene.py server.py /app/

ENV PORT=8080
EXPOSE 8080
CMD ["python", "/app/server.py"]

Nothing here is pip installed. Blender brings its own Python, so apt is only there for the X and GL libraries it links against even when it never opens a window.

Declaring the contract

container.yaml
configVersion: 2
port: 8080
probes:
  readiness: /ready
  liveness: /health
timeouts:
  requestSeconds: 600
  startupSeconds: 600
endpoints:
  - path: render
    default: true
    input:
      type: object
      additionalProperties: false
      required: [frame]
      properties:
        frame:
          type: integer
          minimum: 1
          maximum: 240
          description: Which frame of the turntable to render.
        samples:
          type: integer
          minimum: 1
          maximum: 512
          description: Cycles samples per pixel. More is cleaner and slower.
        width:
          type: integer
          minimum: 64
          maximum: 2048
        height:
          type: integer
          minimum: 64
          maximum: 2048
    output:
      type: object
      properties:
        image:
          type: string
          description: The rendered frame as a base64 PNG.
        frame:
          type: integer
        device:
          type: string
          description: Which Cycles device rendered it, GPU or CPU.
        seconds:
          type: number

A code app has its endpoints read out of your source. A builder cannot look inside an image and find the routes, so a container app declares them.

The endpoint path here is a single segment, render, and the server responds to POST /render, so there is nothing for target to do.

Do not bind 8000, 8888, 8889 or 9090. The platform binds all four inside a worker pod, and every container in a pod shares one network namespace. Taking one does not warn you: your server either loses the bind or becomes reachable through a Service that was never meant to carry your traffic. This one uses 8080.

Request timeouts

timeouts.requestSeconds defaults to 60, and a render takes longer than that. This container.yaml asks for 600, and the platform waits that plus 30 seconds.

requestTimeoutSecs is container-only. A code app stores it and does not apply it, which is one reason to choose this path for long work you want bounded.

Writing the server

server.py
"""The server the platform talks to. Stdlib only, so the image stays small.

Runware hands this server the request's ``payload`` member alone, not the
envelope around it, so a local curl and a real invocation send the same body.
"""

import base64
import json
import os
import subprocess
import tempfile
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

PORT = int(os.environ.get("PORT", "8080"))
BLENDER = "/usr/local/bin/blender"
SCENE = "/app/scene.py"

DEFAULTS = {"samples": 48, "width": 960, "height": 540}


def render(frame, samples, width, height):
    with tempfile.TemporaryDirectory() as work:
        target = str(Path(work) / "frame")
        started = time.time()
        result = subprocess.run(
            [BLENDER, "--background", "--factory-startup", "--python", SCENE,
             "--", str(frame), str(samples), str(width), str(height), target],
            capture_output=True, text=True, timeout=570,
        )
        seconds = time.time() - started

        if result.returncode != 0:
            raise RuntimeError(result.stderr[-2000:] or result.stdout[-2000:])

        device = "CPU"
        for line in result.stdout.splitlines():
            if line.startswith("RUNWARE_DEVICE="):
                device = line.split("=", 1)[1].strip()

        # Blender appends the frame number to a path with no extension.
        written = sorted(Path(work).glob("frame*.png")) or sorted(Path(work).glob("*.png"))
        if not written:
            raise RuntimeError(f"blender wrote no image: {result.stdout[-1000:]}")

        return {
            "image": base64.b64encode(written[0].read_bytes()).decode("ascii"),
            "frame": frame,
            "device": device,
            "seconds": round(seconds, 2),
        }


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def _send(self, status, body):
        raw = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)

    def do_GET(self):
        # Readiness is immediate: Blender is in the image, so there are no
        # weights to fetch and nothing to load before the first frame.
        if self.path in ("/ready", "/health"):
            return self._send(200, {"status": "ok"})

        return self._send(404, {"error": "not found"})

    def do_POST(self):
        if self.path.rstrip("/") not in ("/render", ""):
            return self._send(404, {"error": f"no endpoint at {self.path}"})

        try:
            length = int(self.headers.get("Content-Length", "0"))
            payload = json.loads(self.rfile.read(length) or b"{}")
        except (ValueError, json.JSONDecodeError) as problem:
            return self._send(400, {"error": f"bad body: {problem}"})

        values = {**DEFAULTS}
        for key in DEFAULTS:
            if payload.get(key) is not None:
                values[key] = int(payload[key])

        try:
            return self._send(200, render(int(payload["frame"]), **values))
        except KeyError:
            return self._send(400, {"error": "frame is required"})
        except subprocess.TimeoutExpired:
            return self._send(504, {"error": "render did not finish in time"})
        except Exception as problem:  # noqa: BLE001
            return self._send(500, {"error": str(problem)})

    def log_message(self, fmt, *args):
        print(f"{self.address_string()} {fmt % args}", flush=True)


ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()

Stdlib only, so the image stays small and there is no framework to pin. Readiness is about your weights, and this app has none: Blender is in the image, so /ready returns 200 straight away.

Runware passes your server the payload member alone, not the envelope around it, so the local call below sends the same body a real invocation does.

Deploying the app

render-farmrtx-pro-6000source
From a URL
runware serverless deploy --from https://runware.ai/docs/serverless/examples/render-farm.zip
From a clone
runware serverless deploy --container . \
  --id render-farm \
  --gpu-type rtx-pro-6000 \
  --max-workers 4

--container points at the directory, not at a file, and that directory holds the Dockerfile and the container.yaml beside whatever the Dockerfile copies.

--max-workers defaults to 1, and for this app that defeats the point. Four workers render four frames at once.

Testing before you deploy

The code path cannot be tested this way. It is your image, so run the whole thing first:

docker build -t render-farm .
docker run --rm -p 8080:8080 render-farm

curl http://localhost:8080/ready
curl -X POST http://localhost:8080/render \
  -H 'Content-Type: application/json' \
  -d '{"frame": 1, "samples": 16}'

Fanning out frames

There is no map primitive. You call the endpoint once per frame, and --max-workers decides how many of those run at a time. One app, one queue, and the loop is yours.

Calling the app

import { createClient } from '@runware/sdk'

const client = await createClient({ apiKey: process.env.RUNWARE_API_KEY })

const task = await client.invoke({
  appId: 'render-farm',
  endpointPath: 'render',
  payload: {
    frame: 12,
    samples: 64
  }
}, {
  deliveryMethod: 'sync'
})
import asyncio
import os

from runware import InvokeOptions, Runware


async def main():
    client = Runware(api_key=os.environ["RUNWARE_API_KEY"])
    try:
        task = await client.invoke(
            "render-farm",
            "render",
            {
                "frame": 12,
                "samples": 64
            },
            options=InvokeOptions(delivery_method="sync"),
        )
    finally:
        await client.close()


asyncio.run(main())
curl https://api.serverless.runware.ai/v1/apps/render-farm/invoke-sync/render \
  -H "Authorization: Bearer $RUNWARE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "taskId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
    "payload": {
      "frame": 12,
      "samples": 64
    }
  }'
echo '{"frame":12,"samples":64}' | runware serverless apps invoke render-farm render --sync -f -
{
  "taskId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "payload": {
    "frame": 12,
    "samples": 64
  }
}

A container app takes the payload your server expects, with no parameter name wrapping it, because there is no handler signature to bind to.

The frame comes back as a base64 PNG at output.image. A container app has no predictions wrapper: output is your server's response body as it was, unlike a code app, whose handler result arrives at output.predictions[0]. device says whether Cycles found a GPU or fell back to the CPU, which is the first thing to read if a render was slower than you expected.

Measured on an RTX PRO 6000, at the default 960x540:

CallTaskThe render alone
Build1m7s
First call, cold container29s1.8s
A warm worker, 32 samples2.1s1.2s
A warm worker, 128 samples2.1s1.4s
A warm worker, 1280x720 at 96 samples2.3s1.9s

device came back GPU on every one, so Cycles found the card without being told which backend to use. The sample count barely moves the number: at this resolution the render is dominated by scene setup rather than by sampling.