---
title: Run background workers with Rust and Vercel Daemons
description: Build a Rust Vercel Function that enqueues jobs to Vercel Queues and a containerized Rust daemon that polls, processes, and shuts down cleanly.
products: ["Vercel Daemons","Vercel Functions"]
url: "https://vercel.com/kb/guide/rust-background-workers-vercel-daemons"
published: 2026-12-04
last_updated: 2026-12-04
authors: Ben Sabic
related_resources:
  - title: "Build Vercel Functions with the Rust runtime"
    url: "/kb/guide/vercel-functions-on-rust"
    description: "Create Rust handlers in api/ with vercel_runtime 2.x, parse JSON requests, run background tasks, configure Fluid compute settings, and deploy to Vercel."
  - title: "Deploy Rust on Vercel with Docker"
    url: "/kb/guide/deploy-rust-on-vercel-with-docker"
    description: "Build a Rust application with Axum and Docker, then deploy it to Vercel Functions. Learn how to configure environment variables, managed storage, and preview deployments for your project."
  - title: "The Complete Guide to Vercel Daemons"
    url: "/kb/guide/vercel-daemons"
    description: "Run background workers with Vercel Daemons. Learn how to deploy container images, configure resources, handle shutdowns, and manage instances."
  - title: "Process background jobs in Python with Vercel Queues"
    url: "/kb/guide/python-and-vercel-queues"
    description: "Move slow and failure-prone work out of your Python request handlers, with typed topics, consumer groups, and built-in retries."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect rust-background-workers-vercel-daemons"
---

Use [Vercel Daemons](https://vercel.com/docs/daemons) to run Rust workers that poll a queue and process background jobs. For an order-processing app, the API publishes each order to [Vercel Queues](https://vercel.com/docs/queues) and responds without waiting for the worker to finish. Vercel runs the worker's container on [Fluid compute](https://vercel.com/docs/fluid-compute), maintains the configured instance count, and restarts processes that exit or crash.

Keep the HTTP handler and worker in one project with separate Rust crates:

- The [Vercel Function](https://vercel.com/docs/functions) in `api/enqueue.rs` validates each order and publishes it through the [Queues REST API](https://vercel.com/docs/queues/api) using `reqwest`.
  
- The daemon in `worker/` [polls for orders](https://vercel.com/docs/queues/poll-mode) and acknowledges each one after processing succeeds. It also exposes a local health endpoint and finishes its current delivery when it receives a shutdown signal.
  
- The project's `vercel.json` places both components in Washington, D.C. with the region code `iad1`, and configures the worker's resources and lifecycle.
  

For HTTP backends, use [native Rust functions](https://vercel.com/kb/guide/vercel-functions-on-rust) or [deploy Rust with Docker](https://vercel.com/kb/guide/deploy-rust-on-vercel-with-docker).

## Prerequisites

Before you start, make sure you have a [Vercel account](https://vercel.com/signup). For local development, install the latest [Vercel CLI](https://vercel.com/docs/cli), the current stable Rust toolchain with [rustup](https://rustup.rs), and Docker Desktop or a running Docker daemon.

## Build with your agent

Use this prompt in your repository to have a coding agent add a Rust producer function and a Vercel Queues polling daemon that fit your project:

### Agent prompt

```txt
Help me add a Rust background worker with Vercel Daemons and Vercel Queues to this repository using https://vercel.com/kb/guide/rust-background-workers-vercel-daemons. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect rust-background-workers-vercel-daemons`.

Inspect the repository's existing Rust crates, routes, Dockerfile setup, and deployment configuration first. If the job payload, topic name, or processing logic isn't clear, ask what messages the producer should enqueue and what idempotent work the daemon should run.

1. Keep the producer in the root crate (`api/enqueue.rs` with a unique `[[bin]]` entry using `vercel_runtime` 2.x) and keep the daemon as a separate crate in `worker/` with its own `Cargo.toml` and `Cargo.lock`. Exclude `worker` in the root `Cargo.toml` `[workspace]` table so the function builder does not compile daemon dependencies and `worker/` stays self-contained as a Docker build context.

2. In `api/enqueue.rs`, validate HTTP method, JSON syntax, and business rules before publishing to `https://{region}.vercel-queue.com/api/v3/topic/{topic}` with `reqwest`. Authenticate per request using the `x-vercel-oidc-token` header with a `VERCEL_OIDC_TOKEN` fallback for local dev, omit `Vqs-Deployment-Id` for deploymentless mode, forward an optional `Idempotency-Key` header as `Vqs-Idempotency-Key`, and return `202` with `messageId` (and `deferred` when `SendMessage` returns `202`).

3. In `worker/`, build a multi-stage Cargo Chef Dockerfile with a Bookworm builder and the existing Debian 12 distroless non-root runtime. Keep exec-form ENTRYPOINT, and test the final image for Linux amd64. Add `worker/.dockerignore` to exclude target/, .env*, and .git/ without excluding Cargo.lock. Give worker queue requests a 20-second total timeout and a 10-second connection timeout. Read `VERCEL_OIDC_TOKEN_FILE` on every queue request (failing when it is set to a non-empty path that is unreadable or contains an empty file; never cache) with a `VERCEL_OIDC_TOKEN` fallback only when `VERCEL_OIDC_TOKEN_FILE` is unset or empty. Poll `ReceiveMessages` with `Accept: application/x-ndjson` and `Vqs-Max-Messages: 1`, back off on `204` and errors, base64-decode payloads, process idempotently, acknowledge with `DELETE` on the URL-encoded `receiptHandle` only after success, serve `GET /health` with Axum for `livenessProbe`, and stop starting receive requests on `SIGTERM`, then finish any in-flight receive and its delivery before exiting.

4. Configure `vercel.json` with matching queue regions for the function and daemon, the worker resources, liveness probe, and shutdown grace period. Use `orders-preview` for Development and Preview and the default `orders` in Production. Queue requests are scoped by the OIDC token's team, project, and environment; omit `Vqs-Deployment-Id` on both producer and worker to retain access across rollouts within that scope.

5. Test the function with `vercel dev`. Build and run the worker for Linux amd64, using `vercel env run --environment development --` before `docker run` and passing `VERCEL_OIDC_TOKEN` and `QUEUE_TOPIC` with `-e`. Docker must receive parsed values, not the quoted `.env.local` file. Verify the health response, validation errors, acknowledgment, and SIGTERM draining; separate local mock results from hosted results. Before a public deployment, add authentication and rate limiting or keep Deployment Protection enabled. Deploy with `vercel deploy --prod` and verify `vercel daemons inspect` and `vercel logs --query 'source:daemon'`.

Return the changed files, required environment variables, and local and hosted test results.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "<topic>"`
```

## Understand what runs locally and on Vercel

Running a native Rust function alongside a containerized daemon involves three environments. Knowing what runs in each keeps local checks from masking container or production issues.

| Environment            | What to verify                                                                                                                                                                     |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local function         | Run `vercel dev` to compile the handler, check validation, and publish to the Development queue. It skips daemons.                                                                 |
| Local Docker container | Build and run the final image to check its Linux runtime, HTTPS access, message processing, health endpoint, and shutdown behavior.                                                |
| Vercel production      | Verify the deployed function and daemon together in `iad1`, including rotating token files, liveness probes, and runtime logs. Preview deployments do not run daemons during beta. |

Local checks exercise the function and worker against the Development queue. After deployment, test the same flow in Production and verify token rotation and liveness checks on Vercel.

## 1\. Set up the project layout

Create the project directory, with separate folders for the function and worker:

```bash
mkdir vercel-rust-daemons
cd vercel-rust-daemons
mkdir -p api worker/src
```

Create `.gitignore` at the project root so compiled artifacts, `.vercel`, and local OIDC tokens stay out of Git:

```text
# Rust build artifacts
target/
worker/target/

# Local Vercel state and secrets
.vercel
.env.local
```

Create `Cargo.toml` at the project root in TOML format to configure the producer function and exclude `worker/` from the root workspace:

```text
[package]
name = "vercel-rust-daemons"
version = "0.1.0"
edition = "2024"

[workspace]
exclude = ["worker"]

[dependencies]
http-body-util = "0.1"
reqwest = { version = "0.13", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
vercel_runtime = { version = "2" }

# Each handler has to be specified as [[bin]]
# Note that you need to provide unique names for each binary
[[bin]]
name = "enqueue"
path = "api/enqueue.rs"

[profile.release]
codegen-units = 1
lto = "fat"
opt-level = 3
```

`[[bin]]` entries tell Cargo which source files to build, while Vercel discovers the handlers in `api/`. Each entry needs a unique binary name and matching path. Vercel builds in release mode using the `[profile.release]` settings.

Exclude `worker` from the root workspace to keep it as a standalone crate with its own manifest and lockfile inside the Docker build context. The Rust Function builder then avoids compiling worker dependencies. The producer uses reqwest's default rustls support for TLS and its json feature for request and response bodies.

## 2\. Write the Rust enqueue function

Create `api/enqueue.rs` to validate incoming orders and publish them to Queues. Each publish request authenticates with the invocation's OIDC token:

```rust
use std::env;
use std::sync::OnceLock;
use std::time::Duration;

use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use serde_json::json;
use vercel_runtime::{Error, Request, Response, ResponseBody, run, service_fn};

const DEFAULT_REGION: &str = "iad1";
const DEFAULT_TOPIC: &str = "orders";
const MAX_IDEMPOTENCY_KEY_LEN: usize = 256;

static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

#[derive(Deserialize, Serialize)]
struct ItemInput {
    name: String,
    quantity: u32,
}

#[derive(Deserialize)]
struct SendMessageResponse {
    #[serde(rename = "messageId")]
    message_id: Option<String>,
    #[serde(default)]
    deferred: bool,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(req: Request) -> Result<Response<ResponseBody>, Error> {
    if req.method().as_str() != "POST" {
        return json_error(405, "Method not allowed", true);
    }

    let oidc_header = header(&req, "x-vercel-oidc-token");
    let idempotency_key = header(&req, "idempotency-key");

    if let Some(ref key) = idempotency_key {
        if key.chars().count() > MAX_IDEMPOTENCY_KEY_LEN {
            return json_error(
                400,
                "Idempotency-Key must be at most 256 characters",
                false,
            );
        }
    }

    let bytes = req.into_body().collect().await?.to_bytes();
    let payload: ItemInput = match serde_json::from_slice(&bytes) {
        Ok(item) => item,
        Err(_) => return json_error(400, "Invalid JSON body", false),
    };

    if payload.name.trim().is_empty()
        || !(1..=100).contains(&payload.quantity)
    {
        return json_error(
            422,
            "Name must not be blank and quantity must be between 1 and 100",
            false,
        );
    }

    let token = match resolve_oidc_token(oidc_header) {
        Some(value) => value,
        None => {
            eprintln!("Missing Vercel OIDC token");
            return json_error(500, "Server configuration error", false);
        }
    };

    let client = match http_client() {
        Ok(client) => client,
        Err(err) => {
            eprintln!("Failed to initialize HTTP client: {err}");
            return json_error(500, "Server configuration error", false);
        }
    };

    let region = env_non_empty("QUEUE_REGION")
        .unwrap_or_else(|| DEFAULT_REGION.to_string());
    let topic = env_non_empty("QUEUE_TOPIC")
        .unwrap_or_else(|| DEFAULT_TOPIC.to_string());
    let url = format!("https://{region}.vercel-queue.com/api/v3/topic/{topic}");

    let mut upstream_req = client
        .post(&url)
        .bearer_auth(&token)
        .json(&payload);

    if let Some(key) = idempotency_key {
        upstream_req = upstream_req.header("Vqs-Idempotency-Key", key);
    }

    let upstream = match upstream_req.send().await {
        Ok(resp) => resp,
        Err(err) => {
            eprintln!("Vercel Queues request failed: {err}");
            return json_error(502, "Queue service unavailable", false);
        }
    };

    if !upstream.status().is_success() {
        let status = upstream.status().as_u16();
        let body = upstream.text().await.unwrap_or_default();
        let snippet: String = body.chars().take(500).collect();
        eprintln!("Vercel Queues returned HTTP {status}: {snippet}");

        if status == 429 {
            return json_error(
                429,
                "Rate limit exceeded. Try again shortly.",
                false,
            );
        }
        return json_error(502, "Failed to enqueue message", false);
    }

    let queued: SendMessageResponse = match upstream.json().await {
        Ok(parsed) => parsed,
        Err(err) => {
            eprintln!("Failed to parse Queues response: {err}");
            return json_error(502, "Invalid response from queue service", false);
        }
    };

    let body = json!({
        "status": "queued",
        "topic": topic,
        "messageId": queued.message_id,
        "deferred": queued.deferred,
    });

    Ok(Response::builder()
        .status(202)
        .header("content-type", "application/json")
        .body(ResponseBody::from(body.to_string()))?)
}

fn header(req: &Request, name: &str) -> Option<String> {
    req.headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
}

fn http_client() -> Result<&'static reqwest::Client, reqwest::Error> {
    if let Some(client) = HTTP_CLIENT.get() {
        return Ok(client);
    }
    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .read_timeout(Duration::from_secs(30))
        .build()?;
    Ok(HTTP_CLIENT.get_or_init(|| client))
}

fn env_non_empty(name: &str) -> Option<String> {
    env::var(name)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

fn resolve_oidc_token(oidc_header: Option<String>) -> Option<String> {
    if let Some(token) = oidc_header {
        return Some(token);
    }
    env_non_empty("VERCEL_OIDC_TOKEN")
}

fn json_error(
    status: u16,
    message: &str,
    allow_post: bool,
) -> Result<Response<ResponseBody>, Error> {
    let mut builder = Response::builder()
        .status(status)
        .header("content-type", "application/json");
    if allow_post {
        builder = builder.header("allow", "POST");
    }
    let body = json!({ "error": message }).to_string();
    Ok(builder.body(ResponseBody::from(body))?)
}
```

### Validate input before publishing

[`BodyExt::collect`](https://docs.rs/http-body-util/latest/http_body_util/trait.BodyExt.html) reads the full request body into memory before [`serde_json::from_slice`](https://docs.rs/serde_json/latest/serde_json/fn.from_slice.html) parses it into `ItemInput`. Rust functions accept [request bodies up to 4.5 MB](https://vercel.com/docs/functions/limitations). Returning an explicit `400` for a bad payload keeps raw parsing errors out of a `500` response.

Non-`POST` requests receive `405` with `allow: POST`. Missing fields, invalid JSON, and values that cannot deserialize into `ItemInput` (such as a negative quantity for `u32`) receive `400`. Payloads that deserialize cleanly but have a blank `name` or a `quantity` outside `1..=100` (such as `0` or `101`) receive `422`. Validated orders are published with [`SendMessage`](https://vercel.com/docs/queues/api#sendmessage), which stores the raw JSON body and preserves `Content-Type: application/json` for the consumer.

### Authenticate requests and scope queue messages

The function reads the invocation's OIDC token for each request, with `VERCEL_OIDC_TOKEN` as the local fallback. Resolving it inside the handler prevents a warm instance from retaining an expired token.

The producer and worker omit `Vqs-Deployment-Id` so retained messages remain available across production rollouts. Requests still use the team, project, and environment from the [OIDC token](https://vercel.com/docs/queues/api#authentication). Even with a shared `orders-preview` topic name, a Development worker cannot consume Preview messages.

Keep message schemas compatible while old and new workers overlap during deployment. Topic and consumer names allow letters, digits, underscores, and hyphens; topic names have a 256-character limit.

### Handle idempotency, failover, and timeouts

If a client sends an `Idempotency-Key` header (up to 256 characters), `api/enqueue.rs` forwards it as `Vqs-Idempotency-Key`. Vercel Queues deduplicates matching keys out-of-band for the message's retention period (24 hours by default, up to 7 days); sends with an idempotency key are billed at 2x units for that Send operation.

`SendMessage` returns `201 Created` with `{"messageId": "..."}` during normal operation, or `202 Accepted` with `{"deferred": true}` during [regional failover](https://vercel.com/docs/queues/concepts#failover). The handler parses both responses, returns `202` to the caller, and maps upstream `429` or `5xx` errors to `429` or `502` without exposing raw upstream bodies. The shared `reqwest::Client` allows 10 seconds to connect and 30 seconds per read. Because the per-read timeout resets after each read, the function's `maxDuration` (30 seconds in `vercel.json`) bounds the whole invocation.

## 3\. Build the Rust worker daemon

Define the worker's dependencies in `worker/Cargo.toml`:

```text
[package]
name = "order-worker"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
base64 = "0.22"
percent-encoding = "2"
reqwest = { version = "0.13", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

[profile.release]
strip = true
lto = "thin"
```

The release profile uses thin LTO and strips debug symbols to reduce binary size.

Create `worker/src/main.rs` to run the Axum `/health` server alongside the Vercel Queues polling loop, reading the rotating OIDC token file on every request and draining cleanly on `SIGTERM`:

```rust
use std::env;
use std::net::SocketAddr;
use std::time::Duration;

use axum::{Json, Router, routing::get};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use serde::{Deserialize, Serialize};
use tokio::sync::watch;

const DEFAULT_REGION: &str = "iad1";
const DEFAULT_TOPIC: &str = "orders";
const DEFAULT_CONSUMER: &str = "order-processor";
const DEFAULT_HEALTH_PORT: u16 = 8080;
const VISIBILITY_TIMEOUT_SECONDS: u32 = 60;
const EMPTY_BACKOFF: Duration = Duration::from_secs(1);
const ERROR_BACKOFF: Duration = Duration::from_secs(2);

#[derive(Serialize)]
struct Health {
    status: &'static str,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct QueueEnvelope {
    message_id: String,
    receipt_handle: String,
    delivery_count: u32,
    body: String,
}

#[derive(Deserialize)]
struct OrderPayload {
    name: String,
    quantity: u32,
}

struct WorkerConfig {
    region: String,
    topic: String,
    consumer: String,
    health_port: u16,
}

async fn health() -> Json<Health> {
    Json(Health { status: "ok" })
}

#[tokio::main]
async fn main() {
    let config = WorkerConfig {
        region: env_non_empty("QUEUE_REGION")
            .or_else(|| env_non_empty("VERCEL_REGION"))
            .unwrap_or_else(|| DEFAULT_REGION.to_string()),
        topic: env_non_empty("QUEUE_TOPIC")
            .unwrap_or_else(|| DEFAULT_TOPIC.to_string()),
        consumer: env_non_empty("QUEUE_CONSUMER")
            .unwrap_or_else(|| DEFAULT_CONSUMER.to_string()),
        health_port: env::var("HEALTH_PORT")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(DEFAULT_HEALTH_PORT),
    };

    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(20))
        .build()
        .expect("build HTTP client");

    let (shutdown_tx, shutdown_rx) = watch::channel(false);
    tokio::spawn(async move {
        shutdown_signal().await;
        eprintln!("Received SIGTERM; finishing current message");
        let _ = shutdown_tx.send(true);
    });

    let address = SocketAddr::from(([0, 0, 0, 0], config.health_port));
    let app = Router::new().route("/health", get(health));
    let listener = tokio::net::TcpListener::bind(address)
        .await
        .expect("bind health listener");

    println!(
        "Worker started in region={} topic={} consumer={} health=0.0.0.0:{}",
        config.region, config.topic, config.consumer, config.health_port
    );

    let mut health_shutdown = shutdown_rx.clone();
    let health_server =
        axum::serve(listener, app).with_graceful_shutdown(async move {
            let _ = health_shutdown.wait_for(|&stopping| stopping).await;
        });

    let (health_result, ()) =
        tokio::join!(health_server, poll_loop(&client, &config, shutdown_rx));

    if let Err(err) = health_result {
        eprintln!("Health server exited with error: {err}");
        std::process::exit(1);
    }

    println!("Worker shut down cleanly");
}

async fn poll_loop(
    client: &reqwest::Client,
    config: &WorkerConfig,
    mut shutdown_rx: watch::Receiver<bool>,
) {
    let receive_url = format!(
        "https://{}.vercel-queue.com/api/v3/topic/{}/consumer/{}",
        config.region, config.topic, config.consumer
    );

    while !*shutdown_rx.borrow() {
        let token = match read_oidc_token().await {
            Ok(token) => token,
            Err(err) => {
                eprintln!("OIDC token error: {err}");
                wait_or_shutdown(&mut shutdown_rx, ERROR_BACKOFF).await;
                continue;
            }
        };

        let response = match client
            .post(&receive_url)
            .bearer_auth(&token)
            .header("Accept", "application/x-ndjson")
            .header("Vqs-Max-Messages", "1")
            .header(
                "Vqs-Visibility-Timeout-Seconds",
                VISIBILITY_TIMEOUT_SECONDS.to_string(),
            )
            .send()
            .await
        {
            Ok(resp) => resp,
            Err(err) => {
                eprintln!("ReceiveMessages request failed: {err}");
                wait_or_shutdown(&mut shutdown_rx, ERROR_BACKOFF).await;
                continue;
            }
        };

        if response.status().as_u16() == 204 {
            wait_or_shutdown(&mut shutdown_rx, EMPTY_BACKOFF).await;
            continue;
        }

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body = response.text().await.unwrap_or_default();
            let snippet: String = body.chars().take(500).collect();
            eprintln!("ReceiveMessages returned HTTP {status}: {snippet}");
            wait_or_shutdown(&mut shutdown_rx, ERROR_BACKOFF).await;
            continue;
        }

        let body = match response.text().await {
            Ok(text) => text,
            Err(err) => {
                eprintln!("Failed to read ReceiveMessages body: {err}");
                wait_or_shutdown(&mut shutdown_rx, ERROR_BACKOFF).await;
                continue;
            }
        };

        let mut handled_any = false;
        for line in body.lines().filter(|line| !line.trim().is_empty()) {
            handled_any = true;
            let envelope: QueueEnvelope = match serde_json::from_str(line) {
                Ok(parsed) => parsed,
                Err(err) => {
                    eprintln!("Failed to parse queue envelope: {err}");
                    continue;
                }
            };

            match handle_message(&envelope).await {
                Ok(()) => {
                    if let Err(err) = acknowledge_message(
                        client,
                        config,
                        &envelope.receipt_handle,
                    )
                    .await
                    {
                        eprintln!(
                            "Failed to acknowledge message {}: {err}",
                            envelope.message_id
                        );
                    }
                }
                Err(err) => {
                    eprintln!(
                        concat!(
                            "Processing failed for message {} (attempt {}); ",
                            "left unacknowledged: {}"
                        ),
                        envelope.message_id, envelope.delivery_count, err
                    );
                }
            }
        }

        if !handled_any {
            wait_or_shutdown(&mut shutdown_rx, EMPTY_BACKOFF).await;
        }
    }
}

async fn handle_message(envelope: &QueueEnvelope) -> Result<(), String> {
    let raw = STANDARD
        .decode(&envelope.body)
        .map_err(|err| format!("base64 decode error: {err}"))?;
    let order: OrderPayload = serde_json::from_slice(&raw)
        .map_err(|err| format!("invalid order JSON: {err}"))?;

    // Replace this simulated work with your idempotent job logic,
    // keyed by envelope.message_id or an application order ID.
    tokio::time::sleep(Duration::from_millis(200)).await;

    println!(
        "Processed message={} attempt={} name={} quantity={}",
        envelope.message_id, envelope.delivery_count, order.name, order.quantity
    );
    Ok(())
}

async fn acknowledge_message(
    client: &reqwest::Client,
    config: &WorkerConfig,
    receipt_handle: &str,
) -> Result<(), String> {
    let token = read_oidc_token().await?;
    let encoded_handle =
        utf8_percent_encode(receipt_handle, NON_ALPHANUMERIC).to_string();
    let ack_url = format!(
        "https://{}.vercel-queue.com/api/v3/topic/{}/consumer/{}/lease/{}",
        config.region, config.topic, config.consumer, encoded_handle
    );

    let response = client
        .delete(&ack_url)
        .bearer_auth(&token)
        .send()
        .await
        .map_err(|err| format!("request failed: {err}"))?;

    let status = response.status().as_u16();
    if status == 204 {
        return Ok(());
    }
    if status == 409 {
        return Err(
            "lease expired or receipt handle mismatch (HTTP 409)".to_string(),
        );
    }

    let body = response.text().await.unwrap_or_default();
    let snippet: String = body.chars().take(500).collect();
    Err(format!("unexpected HTTP {status}: {snippet}"))
}

async fn wait_or_shutdown(
    shutdown_rx: &mut watch::Receiver<bool>,
    duration: Duration,
) {
    tokio::select! {
        _ = tokio::time::sleep(duration) => {}
        _ = shutdown_rx.wait_for(|&stopping| stopping) => {}
    }
}

async fn read_oidc_token() -> Result<String, String> {
    if let Some(path) = env_non_empty("VERCEL_OIDC_TOKEN_FILE") {
        let content = tokio::fs::read_to_string(&path).await.map_err(|err| {
            format!("could not read VERCEL_OIDC_TOKEN_FILE ({path}): {err}")
        })?;
        let token = content.trim().to_string();
        if token.is_empty() {
            return Err(format!("VERCEL_OIDC_TOKEN_FILE ({path}) is empty"));
        }
        return Ok(token);
    }

    env_non_empty("VERCEL_OIDC_TOKEN").ok_or_else(|| {
        "missing VERCEL_OIDC_TOKEN_FILE or VERCEL_OIDC_TOKEN".to_string()
    })
}

fn env_non_empty(name: &str) -> Option<String> {
    env::var(name)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

async fn shutdown_signal() {
    let mut terminate =
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("install SIGTERM handler");

    terminate.recv().await;
}
```

Now that `worker/src/main.rs` exists, generate `worker/Cargo.lock` so Cargo Chef has a pinned lockfile inside the Docker build context:

```bash
cd worker
cargo generate-lockfile
cd ..
```

### Read the rotating OIDC token on every request

Vercel sets `VERCEL_REGION` and `VERCEL_OIDC_TOKEN_FILE` for each daemon instance. [OIDC tokens](https://vercel.com/docs/oidc) last 30 minutes, and Vercel refreshes the file about every five minutes. Reading the file for each receive and acknowledgment request keeps the worker using the latest token.

If the configured token file is unreadable or empty, the worker returns an error instead of using a stale fallback. For local Docker runs, `vercel env run` loads the Development variables and Docker passes `VERCEL_OIDC_TOKEN` into the worker. The worker uses it only when the file path is unset or empty.

### Poll and acknowledge orders

`ReceiveMessages` returns immediately, including a `204` response when no messages are available. The loop waits one second after an empty response and two seconds after a transient error. Both waits end early on `SIGTERM` to let idle workers exit.

The request accepts NDJSON with base64-encoded bodies and leases one message at a time for 60 seconds. The visibility timeout can range from 0 to 3,600 seconds. For large binary payloads, use the [multipart response format](https://vercel.com/docs/queues/api#receivemessages) to stream raw bytes without base64 overhead.

After processing succeeds, `acknowledge_message` encodes the receipt handle for the acknowledgment URL. Repeating an acknowledgment with the same handle returns `204`; an expired lease or mismatched handle returns `409`. [At-least-once delivery](https://vercel.com/docs/queues/concepts#at-least-once-delivery) means database writes and external API calls still need an idempotency key, such as the message ID or your order ID.

### Handle failed jobs and longer processing

The worker leaves failed jobs unacknowledged so they can be delivered again after the lease expires, with an increased delivery count. Queues has no built-in dead-letter queue. After your chosen retry threshold, save the payload and error to a database and acknowledge the message only after that write succeeds.

For work that may exceed the 60-second lease, add periodic [lease extension](https://vercel.com/docs/queues/api#extendlease) before it expires. The API accepts a new visibility timeout in seconds, up to the message's expiration. The worker shown here does not extend leases or store failed jobs, so add those behaviors before replacing its simulated task with longer jobs.

### Check process health

The Axum server listens on port 8080 for Vercel's internal [liveness probe](https://vercel.com/docs/daemons/config-reference#livenessprobe). Daemons do not accept inbound HTTP or TCP traffic, so this endpoint is not a public API and has no `PORT` routing requirement. Responses from 200 to 399 count as healthy.

The example's health endpoint confirms that the HTTP server responds. For production jobs, also track whether the worker can make progress, without making probe responses depend directly on external APIs. Consecutive probe failures trigger an immediate `SIGKILL` restart, bypassing the normal shutdown grace period.

### Finish the current delivery before shutdown

During a rollout, old and new instances can briefly overlap. On `SIGTERM`, the worker stops starting receive requests but completes any request already in flight, then processes and acknowledges its returned message before exiting.

The worker gives each queue request a 20-second total timeout. That leaves room for an in-flight receive, the simulated 200 ms task, and acknowledgment within the 60-second grace period. Real jobs need their own processing deadline and lease extension if they can exceed the visibility timeout.

## 4\. Package the worker with Docker

Create `worker/Dockerfile` using a multi-stage Cargo Chef build and a non-root Debian distroless runtime image:

```docker
FROM lukemathwalker/cargo-chef:latest-rust-1-bookworm AS chef
WORKDIR /app

FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS build
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --release

FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /app/target/release/order-worker /usr/local/bin/order-worker
ENTRYPOINT ["/usr/local/bin/order-worker"]
```

Cargo Chef caches dependencies separately from application source so Docker can reuse them after code edits. Both stages use Debian Bookworm to keep their C libraries compatible, and the final image runs as a non-root user without Cargo or the compiler. Keep the binary name aligned with `Cargo.toml` and pin the toolchain tag or digest to a compatible Debian release.

The distroless runtime includes CA certificates for HTTPS requests to Queues. Exec-form `ENTRYPOINT` makes the worker PID 1 so it receives `SIGTERM` directly. Vercel builds for Linux amd64 using `worker/` as the context and supplies deployment environment variables as build arguments. The resulting image is stored as `daemon.worker` in [Vercel Container Registry](https://vercel.com/docs/container-registry).

### Exclude local build artifacts

Create `worker/.dockerignore` so local build artifacts stay out of the Docker context and cannot overwrite Cargo Chef's dependency cache. Keep `Cargo.lock` in the context so both build stages use the same dependency versions:

```text
target/
.env*
.git/
```

## 5\. Configure `vercel.json`

Create `vercel.json` at the project root to pin the Rust function and the daemon to `iad1`, limit function duration to 30 seconds, and set the daemon's resources, liveness probe, and shutdown grace period:

```json
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "regions": ["iad1"],
  "functions": {
    "api/enqueue.rs": {
      "maxDuration": 30
    }
  },
  "daemons": {
    "worker": {
      "root": "worker/",
      "entrypoint": "Dockerfile",
      "instances": { "iad1": 1 },
      "resources": { "requests": { "memory": "1Gi" } },
      "livenessProbe": {
        "httpGet": { "port": 8080, "path": "/health" },
        "initialDelaySeconds": 5,
        "periodSeconds": 10,
        "timeoutSeconds": 1,
        "failureThreshold": 3
      },
      "terminationGracePeriodSeconds": 60
    }
  }
}
```

Messages sent to one [Vercel region](https://vercel.com/docs/regions#region-list) cannot be consumed from another. Setting `"regions": ["iad1"]` on the function, `"instances": { "iad1": 1 }` on the daemon, and `DEFAULT_REGION = "iad1"` in both crates keeps publishing, queue storage, and polling in the same region.

Key daemon settings in this file:

- `daemons.worker` names the daemon. Daemon names can contain only lowercase letters separated by `_`, `__`, or `-` (no digits), up to 64 characters.
  
- `resources.requests.memory` selects `"1Gi"` (1 GiB memory and 1 vCPU), the smallest size and half the `"2Gi"` default. Pro and Enterprise plans also support `"4Gi"` (2 vCPUs) and `"8Gi"` (4 vCPUs).
  
- `livenessProbe` starts checking `http://localhost:8080/health` 5 seconds after container startup, repeats every 10 seconds with a 1-second timeout, and restarts the container after 3 consecutive failures.
  
- `terminationGracePeriodSeconds` extends the shutdown window from the 30-second default to 60 seconds (configurable from `0` to `3600`), giving an in-flight job time to finish and acknowledge after `SIGTERM`.
  

## 6\. Test locally

Sign in to the Vercel CLI and link the project. Set `QUEUE_TOPIC` to `orders-preview` in the Development and Preview environments, then pull the Development [environment variables](https://vercel.com/docs/environment-variables) for local testing:

```bash
vercel login
vercel link
vercel env add QUEUE_TOPIC
vercel env pull
```

When `vercel env add` prompts you, enter `orders-preview` and select **Development** and **Preview**, leaving **Production** unselected. Pulling the environment writes the topic and a Development OIDC token to `.env.local`. That token expires after 12 hours, so pull the environment again and restart the local processes if queue requests return `401`.

Start [`vercel dev`](https://vercel.com/docs/cli/dev) from the project root to compile and serve `api/enqueue.rs`:

```bash
vercel dev
```

`vercel dev` starts the function and warns that it skips daemons. In another terminal at the project root, build the worker image and use the CLI to load the Development environment before starting Docker:

```bash
docker build --platform linux/amd64 -t worker worker/
vercel env run --environment development -- \
  docker run --rm --name worker --platform linux/amd64 \
  -p 8080:8080 -e VERCEL_OIDC_TOKEN -e QUEUE_TOPIC worker
```

Check the startup log for region `iad1`, topic `orders-preview`, and consumer `order-processor`. In a third terminal, test the health endpoint and submit valid and invalid orders. If `vercel dev` selects another port, update the requests to match:

```bash
# Check the worker's liveness endpoint
curl -sS http://localhost:8080/health

# Enqueue a valid order (expect 202 with messageId)
curl -sS -i -X POST http://localhost:3000/api/enqueue \
  -H "content-type: application/json" \
  -H "idempotency-key: order-local-1" \
  -d '{"name":"widget","quantity":3}'

# Quantity out of range (expect 422)
curl -sS -i -X POST http://localhost:3000/api/enqueue \
  -H "content-type: application/json" \
  -d '{"name":"widget","quantity":0}'

# Missing quantity (expect 400)
curl -sS -i -X POST http://localhost:3000/api/enqueue \
  -H "content-type: application/json" \
  -d '{"name":"widget"}'

# Unsupported GET request (expect 405 with allow: POST)
curl -sS -i http://localhost:3000/api/enqueue
```

The health endpoint returns `{"status":"ok"}`. During normal operation, a valid order returns HTTP 202 with a message ID and the `orders-preview` topic, followed by a worker log containing the order and delivery attempt. During regional failover, an accepted publish can instead report `deferred: true` without a message ID.

Invalid requests remain outside the queue. Quantities of 0 or 101 return 422; missing fields or a negative quantity return 400; other HTTP methods return 405.

Stop the container with the same 60-second grace period used in production:

```bash
docker stop -t 60 worker
```

Confirm the worker logs `Received SIGTERM; finishing current message` followed by `Worker shut down cleanly` and exits with status `0`.

## 7\. Deploy and verify in production

Each accepted enqueue request creates billable queue work. Before exposing the endpoint, add caller authentication and per-user rate limits, or restrict deployment access with [Deployment Protection](https://vercel.com/docs/deployment-protection).

Daemons run only in production deployments during beta. Deploy from the project root with [`vercel deploy`](https://vercel.com/docs/cli/deploy):

```bash
vercel deploy --prod
```

After the production deployment starts, Vercel runs one worker instance in `iad1`. Leave `QUEUE_TOPIC` unset in the Production environment so the function and daemon both use `orders`, then check their status with the [Vercel CLI](https://vercel.com/docs/cli/daemons):

```bash
vercel daemons ls
vercel daemons inspect worker
vercel daemons instances ls worker
```

`vercel daemons inspect worker` reports the `daemon.worker` image, memory allocation, regional instance counts, and whether any scaling overrides are active.

Send a test order to the production deployment. Use [`vercel curl`](https://vercel.com/docs/cli/curl), which attaches a Deployment Protection bypass header for your authenticated session, and pass `--data` (or place `-d` after `--`) because Vercel CLI reads `-d` as `--debug`:

```bash
vercel curl https://your-deployment-url.vercel.app/api/enqueue \
  -i -X POST \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-prod-1" \
  --data '{"name":"widget","quantity":3}'
```

Replace `your-deployment-url.vercel.app` with your production hostname. Confirm the response returns `202` with a `messageId`, then inspect daemon output in [Runtime Logs](https://vercel.com/docs/logs/runtime) with [`vercel logs`](https://vercel.com/docs/cli/logs):

```bash
vercel logs --query 'source:daemon'
```

Check the logs for the processed order and confirm its name, quantity, and delivery attempt. Monitor instance health, CPU, and memory in the daemon's metrics, and filter project logs with `daemon:worker` or `daemonInstanceId:<id>`.

Monitor the consumer group's **Max Message Age** and **Retry Depth** in [Queues Observability](https://vercel.com/docs/queues/observability). With Observability Plus, a **Queue Retry Depth** alert can notify you when retries exceed its threshold.

To deploy from Git, commit `Cargo.toml`, `Cargo.lock`, `api/`, `worker/Cargo.toml`, `worker/Cargo.lock`, `worker/src/`, `worker/Dockerfile`, `worker/.dockerignore`, and `vercel.json`, keeping `target/`, `worker/target/`, and `.env.local` in `.gitignore`.

## Scale and operate the daemon

### Override instance counts without redeploying

Daemon instance counts are fixed per region during beta. Increase the `iad1` worker count without redeploying by running:

> **Warning:**
>
> `vercel daemons scale` and `vercel daemons instances restart` apply immediately without a confirmation prompt. Scaling overrides persist across future deployments until you clear them.

```bash
vercel daemons scale worker iad1=3 fra1=0
```

CLI overrides change only the regions you specify; scaling through the dashboard saves overrides for every region. More instances in `iad1` share that region's queue work within the same consumer group. Workers in `fra1` consume messages published to the Frankfurt queue instead.

To clear CLI overrides and return to the counts declared in `vercel.json`, run:

```bash
vercel daemons scale worker --reset
```

To stop all workers without removing the definition, set every region to zero through a scaling override. Alternatively, clear existing overrides and deploy an empty `instances` map in `vercel.json`.

To replace one instance gracefully, get its ID from `vercel daemons instances ls worker` and pass it to the restart command. Vercel sends `SIGTERM` and schedules a replacement:

```bash
vercel daemons instances restart your-instance-id
```

### Export OpenTelemetry traces

Every daemon runs an OpenTelemetry OTLP trace collector over a Unix socket whose path Vercel sets in `VERCEL_OTEL_SOCKET_PATH`. Point any Rust OpenTelemetry OTLP/HTTP exporter that supports Unix sockets at that path using `POST /v1/traces` with protobuf or JSON payloads (optionally gzip-compressed); OTLP/gRPC is not supported. Review [Tracing in Daemons](https://vercel.com/docs/daemons/tracing) for beta export limits (192 KiB serialized span size, 32 KiB resource and scope attributes, 4 concurrent exports per instance, and a 10-second read timeout).

### Track quotas and costs

Daemons use [Fluid compute billing and quotas](https://vercel.com/docs/daemons/limits#default-quotas). Provisioned Memory accrues while an instance runs, including time spent waiting for I/O. Active CPU covers processing such as TLS operations during queue requests.

| Plan  | Allowances and capacity                                                                                                                                |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Hobby | 5 Active CPU-hours and 420 GB-hours of Provisioned Memory per team each month, shared across projects. Instances have 1 or 2 GiB of memory and 1 vCPU. |
| Pro   | Up to 16 vCPUs and 32 GiB of memory concurrently across instance sizes, with up to 8 GiB and 4 vCPUs per instance. CPU and memory usage are billed.    |

One continuously running 2 GiB instance consumes the Hobby memory allowance in roughly nine days; the 1 GiB configuration halves that usage rate. Reaching either Hobby quota stops the team's daemons until the next month begins in UTC or the team upgrades to Pro. Each project environment allows at most 50 instances across its daemons and regions.

[Queues billing](https://vercel.com/docs/queues/pricing) is separate. Every API call counts as at least one operation, with message sizes metered in 4 KiB chunks and idempotent sends charged at twice the units for that send. This includes empty polls: one request per second approaches 86,400 Receive operations a day per idle worker, before accounting for request latency. Increase idle backoff when jobs can wait longer.

## What can you build with Rust daemons?

Use Rust daemons for background jobs that need a persistent polling loop, a custom container binary, or controlled concurrency.

### Process high-throughput queue workloads

Decode binary payloads, generate thumbnails or PDFs, or run CPU-heavy transforms in Rust while your web frontend or Rust Functions acknowledge requests immediately. Independent consumer groups on the same topic each receive their own copy of every message, while multiple daemon instances in the same group share work. For large binary messages up to the 100 MB queue message limit, switch `ReceiveMessages` from `application/x-ndjson` to `Accept: multipart/mixed` to stream raw bytes without base64 encoding overhead.

### Control calls to rate-limited APIs

For order or invoice syncs, add a rate limiter before each provider request and respect its retry guidance. Fixed instance counts bound concurrency, but the polling loop shown here does not enforce a requests-per-second limit. If several workers share one provider allowance, coordinate that limit across them.

Choose the polling delay and batch size to suit the workload; Queues accepts batches of 1 to 10 messages. Extend leases while slow provider calls are in progress, and use provider-side idempotency keys to prevent duplicate writes.

### Hold open non-HTTP connections and poll external brokers

Run consumers for Amazon SQS, Kafka, or Redis, or maintain persistent outbound connections such as Postgres `LISTEN`/`NOTIFY`, MQTT, or IMAP where no inbound webhook triggers a function. Persist job state in [Vercel Blob](https://vercel.com/docs/vercel-blob) or a [Marketplace database](https://vercel.com/docs/marketplace-storage) so another instance can resume after a rollout or restart.

### Call private project services through bindings

In projects that use [Vercel Services](https://vercel.com/docs/services) (Beta), a daemon can declare [`bindings`](https://vercel.com/docs/daemons/config-reference#bindings) in `vercel.json` to call internal services over a private URL without exposing them publicly. Bindings point to the deployment that started the daemon instance. While a daemon can bind to a service, nothing can bind to a daemon, and native Rust functions cannot consume [service bindings](https://vercel.com/docs/services/bindings).

## Limitations

- Vercel Daemons is in Public Beta on all plans within their quotas. Vercel Queues and the [native Rust runtime](https://vercel.com/docs/functions/runtimes/rust) are in Beta.
  
- During beta, daemons run only in production deployments; Preview deployments omit them, and `vercel dev` skips them with a warning.
  
- Daemons do not autoscale and accept no inbound HTTP or TCP traffic. Scale counts manually with `vercel.json`, the dashboard, the CLI, or the REST API, and use [Vercel Functions](https://vercel.com/docs/functions) or Services for inbound requests.
  
- Local container filesystems are ephemeral. Store durable state in a queue, Vercel Blob, or an external database.
  
- Daemon names allow only lowercase letters separated by `_`, `__`, or `-` (no digits), up to 64 characters.
  
- Vercel Queues provides no built-in dead-letter queue, delivers messages in approximate write order with at-least-once semantics, and scopes messages to the region where they were published.
  
- Native Rust functions have a 4.5 MB request body limit and cannot consume service bindings or use the extended 1,800-second duration beta.
  

## Troubleshooting

### The worker never receives published messages

Compare the queue region and topic used by the function and worker. Their credentials must belong to the same team, project, and environment; matching topic names alone cannot connect a Development worker to Preview messages.

Keep both endpoints on the same queue region and omit `Vqs-Deployment-Id` on both sides for this deploymentless setup. Locally, both processes use the Development credentials and `orders-preview`. In Production, both use production credentials and the default `orders` topic.

### Queue requests return 401 locally or after running for a while

The local `VERCEL_OIDC_TOKEN` expires after 12 hours, so run `vercel env pull` again and restart `vercel dev` to refresh the function's credentials. Stop the worker, then [launch it again](#6.-test-locally) through `vercel env run` to reload its credentials.

In production, daemon tokens in `VERCEL_OIDC_TOKEN_FILE` expire after 30 minutes and refresh about every five minutes. Confirm `read_oidc_token` reads the file on every request instead of caching the token at startup.

### The daemon restarts repeatedly in production

Run `vercel daemons instances ls worker` and `vercel logs --query 'source:daemon'` to inspect exit logs and probe failures. Confirm the Axum server listens on `0.0.0.0:8080` (matching `livenessProbe.httpGet.port` and `path`), responds with `200` to `399` within `timeoutSeconds`, and does not wait on external APIs. After `failureThreshold` consecutive failures, Vercel sends `SIGKILL` immediately and applies exponential restart backoff from 1 second up to 5 minutes, replacing the instance after 10 minutes of short runs.

### The final image reports a missing loader or library

The binary was linked against libraries missing from the runtime image. Check that both stages use the same Debian release, as the Bookworm builder and Debian 12 runtime do here. Mixing Alpine with Debian, or building against a newer Debian release than the runtime, can produce incompatible binaries.

For a static MUSL build, use a compatible static runtime image. Test the final Linux amd64 image locally before deploying.

### Docker builds remain slow after small source changes

Copying the whole source tree before compiling dependencies invalidates the Cargo layer cache on every edit. Keep the Cargo Chef `planner` and `cargo chef cook` stages ahead of `COPY . .` and `cargo build --release`, and commit `worker/Cargo.lock` so dependency resolution is reproducible.

### Compilation fails on edition 2024 or let chains

Check `rustc --version` and update with `rustup update stable` if needed. The runtime requires features newer than the minimum compiler for the 2024 edition. Also update any older toolchain pinned in the project or its Dockerfile.

## Next steps

- Set resources, probes, and shutdown with [daemon configuration](https://vercel.com/docs/daemons/config-reference).
  
- Check [quotas and billing](https://vercel.com/docs/daemons/limits) before increasing worker counts.
  
- Use the [Queues API](https://vercel.com/docs/queues/api) for binary streaming, delayed delivery, and lease extension.
  
- Compare [background workers](https://vercel.com/docs/background-workers) using Queues, Cron Jobs, and Workflows.
  
- Add [native Rust HTTP endpoints](https://vercel.com/kb/guide/vercel-functions-on-rust) with Axum routing and request-scoped logs.
  
- Deploy a [containerized Rust server](https://vercel.com/kb/guide/deploy-rust-on-vercel-with-docker) to handle inbound HTTP requests.

## Related Resources

- [Build Vercel Functions with the Rust runtime](/kb/guide/vercel-functions-on-rust): Create Rust handlers in api/ with vercel\_runtime 2.x, parse JSON requests, run background tasks, configure Fluid compute settings, and deploy to Vercel.
- [Deploy Rust on Vercel with Docker](/kb/guide/deploy-rust-on-vercel-with-docker): Build a Rust application with Axum and Docker, then deploy it to Vercel Functions. Learn how to configure environment variables, managed storage, and preview deployments for your project.
- [The Complete Guide to Vercel Daemons](/kb/guide/vercel-daemons): Run background workers with Vercel Daemons. Learn how to deploy container images, configure resources, handle shutdowns, and manage instances.
- [Process background jobs in Python with Vercel Queues](/kb/guide/python-and-vercel-queues): Move slow and failure-prone work out of your Python request handlers, with typed topics, consumer groups, and built-in retries.

## More Vercel Daemons guides

- [Run your startup's background workers on Vercel Daemons](/kb/guide/startups-on-vercel-daemons): Run your startup's queue consumers and background workers on Vercel Daemons, with graceful shutdown, health checks, tracing, scaling, and cost controls.
- [Migrate Fly.io worker processes to Vercel Daemons](/kb/guide/migrate-fly-io-workers-to-vercel-daemons): Migrate Fly.io workers to Vercel Daemons with your existing Dockerfile. Map process settings, preserve queue state, and plan cutover and rollback.
- [Migrate Railway workers to Vercel Daemons](/kb/guide/migrate-railway-workers-to-vercel-daemons): Move Railway workers to Vercel Daemons with Docker configuration, broker migration, shutdown testing, a gradual queue handoff, and rollback.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
