Docs / Serverless

Write a handler

A handler is a Python function that receives a job and returns its output. The apipods SDK takes care of polling the queue, heartbeats, timeouts and reporting results.

A minimal handler

handler.py
import apipods

def handler(job):
    prompt = job["input"]["prompt"]
    return {"text": prompt.upper()}

apipods.serverless.start({"handler": handler})

Install the SDK with pip install apipods (version 1.9.1 or later). apipods.serverless.start() blocks forever: it connects to the endpoint's queue, calls handler for each job and posts the return value back. When you run the file outside Apipods it switches to local test mode.

The job object

Your handler receives a dict with two keys:

job
{
  "id": "job_3x9wq2mt",
  "input": {
    "prompt": "a lighthouse on a cliff at dusk, 35mm photo",
    "steps": 4
  }
}
  • id is the job ID the caller got back from /run. Use it to name output files or correlate logs.
  • input is exactly the input object from the request body. Validate it yourself; Apipods only checks that it is valid JSON within the payload limit.

Outputs and errors

Return any JSON-serializable value. It becomes the job's output and the job moves to COMPLETED. To fail a job, either raise an exception or return a dict with an error key:

handler.py
import os
import torch
import apipods
from diffusers import AutoPipelineForText2Image

# Module-level code runs once per worker, before the first job.
# Warmstart snapshots the worker after this point.
pipe = AutoPipelineForText2Image.from_pretrained(
    os.environ.get("MODEL_ID", "stabilityai/sdxl-turbo"),
    torch_dtype=torch.float16,
    variant="fp16",
).to("cuda")


def handler(job):
    params = job["input"]
    prompt = params.get("prompt")
    if not prompt:
        return {"error": "input.prompt is required"}

    steps = int(params.get("steps", 4))
    if not 1 <= steps <= 50:
        raise ValueError("steps must be between 1 and 50")

    seed = int(params.get("seed", torch.seed() % 2**31))
    generator = torch.Generator("cuda").manual_seed(seed)
    image = pipe(prompt, num_inference_steps=steps, guidance_scale=0.0, generator=generator).images[0]

    path = f"/volume/outputs/{job['id']}.png"
    os.makedirs(os.path.dirname(path), exist_ok=True)
    image.save(path)
    return {"path": path, "seed": seed}


apipods.serverless.start({"handler": handler})

A failed job looks like this on /status:

FAILED job
{
  "id": "job_7k2m4p8d",
  "status": "FAILED",
  "delayTime": 640,
  "executionTime": 211,
  "workerId": "wrk_8q3m2x9k",
  "error": {
    "type": "ValueError",
    "message": "steps must be between 1 and 50",
    "traceback": "Traceback (most recent call last): ..."
  },
  "createdAt": "2026-11-18T10:05:40Z",
  "completedAt": "2026-11-18T10:05:41Z"
}
Warning: Outputs are limited to 10 MB. For images, audio or video, write files to a network volume mounted at /volume or upload them to your own bucket, and return a path or URL.

Load models once

Code at module level runs once per worker, before the first job. Put model loading, tokenizer setup and warm-up passes there. It is also what Warmstart snapshots, so the cost is paid once per deploy rather than once per worker. Keep per-job work, such as decoding inputs and running inference, inside the handler.

Progress updates

Long jobs can report progress. The latest update appears as progress on /status while the job is IN_PROGRESS.

handler.py
import apipods

def handler(job):
    frames = job["input"]["frames"]
    for i in range(frames):
        render_frame(i)
        if i % 10 == 0:
            apipods.serverless.progress_update(job, {"percent": round(100 * i / frames)})
    return {"frames": frames}

apipods.serverless.start({"handler": handler})

Streaming and async handlers

Make the handler a generator to stream partial outputs. Make it async def to process several jobs at once on one worker with concurrency.

handler.py
import apipods

async def handler(job):
    async for token in model.generate(job["input"]["prompt"]):
        yield {"token": token}

apipods.serverless.start({
    "handler": handler,
    "concurrency_modifier": lambda current: 8,
    "return_aggregate_stream": True,
})

Environment variables

Your endpoint's env is set in every worker, including secret references like {{ secrets.HF_TOKEN }}. Apipods also sets:

VariableExampleDescription
APIPODS_ENDPOINT_IDep_4n8wq2ztThe endpoint the worker belongs to.
APIPODS_WORKER_IDwrk_8q3m2x9kUnique per worker. Appears in logs and on jobs as workerId.
APIPODS_GPU_POOL_IDL40SThe pool the worker was scheduled on.
APIPODS_REGION_IDeu-nl-1The region the worker runs in.