The Vercel build introspects the entrypoint module's registered
subscriptions and compiles it into a queue-triggered function. No
vercel.json trigger configuration is needed.
send returns a message ID, or None when the server accepted the message for delivery,
but could not process it fully yet. Deferred messages are still delivered.
Receiving and Handling Messages
Decorated subscribers are the recommended way to handle messages. Register
subscribers with the @subscribe decorator:
# handle_orders.py
from vercel.queue import subscribe
@subscribe(topic="orders")
async def fulfill_order(order):
await process_order(order)
# Raising an error will automatically retry the message.
Decorating a function with @subscribe only declares it as a handler for a
particular topic. You also need a way to accept and route messages to handlers.
There are two primary ways: deploying handlers as Vercel Functions in push mode
and running polling loops on other infrastructure.
Auto-scaled push-mode on Vercel
The recommended way of deploying queue subscribers is to declare them in
pyproject.toml with [[tool.vercel.subscribers]]. Each entry points at a
module that registers subscriptions with @subscribe:
At build time, Vercel imports the entrypoint module, introspects every
subscription it registers, and compiles the subscriber into its own
queue-triggered function. Delivery tuning lives on the @subscribe
decorator (retry_after, initial_delay, max_concurrency,
max_attempts, consumer_group), so no vercel.json configuration is
needed.
A subscriber consumes every subscription registered by its entrypoint
module. Add an optional topics filter to split subscriptions across
several subscriber functions:
Queue message handlers can also be invoked by polling a topic manually. vercel.queue provides a
convenience API that starts an infinite polling loop for messages matching a given subscriber:
# subscriber_poll.py
import asyncio
from vercel.queue import poll_and_handle, subscribe
@subscribe(topic="orders")
async def fulfill_order(order):
print("Processing Order:", order)
async def main():
poller = asyncio.create_task(poll_and_handle(fulfill_order, interval=1))
# do work and cancel poller on a condition, such as a signal
asyncio.run(main())
Synchronous polling loops use threads instead of async tasks.
Manual Polling
It is also possible to poll a topic and receive messages directly:
# poll_loop.py
from vercel.queue import poll
async def main():
async for delivery in poll(
topic="orders",
consumer_group="fulfillment",
limit=10,
):
async with delivery as message:
await process_order(message.payload)
poll() polls the topic once for up to limit message deliverires which are then yielded by the
iterator. Use the yielded delivery as a context manager to obtain the message envelope which
contains the payload and metadata properties. Note that limit means up-to and it is
possible for poll() to return an empty iterator. In other words, poll() does not block until
new messages are available and it is usually necessary to build a polling loop around it.
Region Considerations when Polling
Messages can only be received from the region they were sent to. When polling, use a fixed region
for both sending and receiving, such as "iad1". Avoid using a changing runtime region for manual
polling, because it can distribute messages across regions unpredictably.
Retry and Backoff
When a topic handler raises, the message is not acknowledged and becomes available for redelivery
after the retry_after interval configured on the subscriber. Retries continue until the
handler succeeds or the message expires.
For finer control over retry timing, raise RetryAfter from a subscriber:
from vercel.queue import RetryAfter, subscribe
@subscribe(topic="orders")
async def fulfill_order(order: dict[str, str]) -> None:
try:
await process_order(order)
except RateLimitError as exc:
raise RetryAfter(60) from exc
Use message.metadata.delivery_count for exponential backoff:
For most use cases, the top-level send, poll_and_handle, and poll are all you need. For
advanced configuration such as explicit authentication, custom headers, deployment pinning, or
custom queue service URLs, create a QueueClient explicitly:
# explicit_client.py
import httpx2
from vercel.queue import ALL_DEPLOYMENTS, QueueClient
queue = QueueClient(
region="iad1", # Required unless VERCEL_REGION is set
token="my-token", # Auth token; detected from the environment by default
headers={"X-Custom": "header"},
deployment=ALL_DEPLOYMENTS, # Receive messages from all deployments when polling
timeout=10, # default timeout for API operations
http_client_factory=httpx2.AsyncClient, # any httpx-compatible HTTP client
)
await queue.send("my-topic", {"message": "Hello world"})
HTTPX2 is the default and the only HTTPX family installed by the SDK. For
migration, an application that explicitly installs legacy httpx may return a
complete httpx.Client or httpx.AsyncClient from http_client_factory.
Legacy transport objects must remain inside a legacy client; they cannot be
mounted in an httpx2.Client.
By default queue clients send requests to https://<region>.vercel-queue.com/. A custom endpoint
can be configured by passing a base_url keyword argument to the client constructor. The value
can be a fixed string, a format() template containing a {region} placeholder, or a callable
taking region name as a string and returning a formatted URL:
from vercel.queue import QueueClient
# Custom domain with a base path.
queue = QueueClient(base_url="https://proxy.example/queues/{region}")
# Callable resolver.
queue = QueueClient(base_url=lambda region: f"https://{region}.queue.internal")
Type-safe Message Passing and Streaming
By default, messages passed to send() and received by @subscribe handlers and poll() are
transmitted as JSON, so values must be JSON-serializable by Python. This is usually fine for
unstructured data, such as dictionaries and lists containing simple data. For more complex types,
such as dataclasses or Pydantic models, simply annotate the first argument of the handler
function:
from dataclasses import dataclass
from vercel.queue import send, subscribe
@dataclass
class Email:
to: str
subject: str
body: str
@subscribe(topic="emails")
async def receive_email(email: Email) -> None:
print(f"Received email to {email.to}: {email.subject}")
Note that type-safe message handling requires pydantic>=2.0 to be available. The simplest way
to ensure the correct version of Pydantic is to install the vercel-queue package with the
[typed] feature: uv add vercel-queue[typed].
To send types that require non-trivial serialization, pass the topic name not as a plain string,
but as a type-specialized Topic instance:
# custom_transport.py
from vercel.queue import Topic, send
@dataclass
class Email:
to: str
subject: str
body: str
emails_topic = Topic[Email]("emails")
async def send_email(to, subject, body):
await send(emails_topic, Email(to, subject, body))
# Type-specialized topics can also be used with @subscribe, in which case the
# type annotation on the handler argument must match the type of the topic
@subscribe(topic=emails_topic)
async def receive_email(email: Email) -> None:
print(f"Received email to {email.to}: {email.subject}")
Explicit type annotations can also be used to enable payload streaming for large messages:
# streaming.py
from collections.abc import AsyncIterable, AsyncIterator
from vercel.queue import ByteStreamTransport, QueueClient, Topic, subscribe
large_file = Topic[AsyncIterable[bytes]]("large-file")
async def file_chunks():
with open("large.bin", "rb") as file:
while chunk := file.read(1024 * 1024):
yield chunk
async def send_file():
await queue.send(large_file, file_chunks())
@subscribe(topic=large_file, consumer_group="archive")
async def archive_file(chunks: AsyncIterable[bytes]) -> None:
async for chunk in chunks:
await write_chunk(chunk)
Message transport is automatically determined from the handler argument type annotation
or Topic type specialization according to the following table:
Topic payload type
Default transport
Message format
JSON-compatible values, dict[...], list[...]
RawJsonTransport[Any]
JSON
Pydantic models and other structured annotations
TypedJsonTransport[T]
JSON with receive validation
bytes
ByteBufferTransport
Buffered binary
str
TextBufferTransport
Buffered UTF-8 text
Iterable[bytes] or AsyncIterable[bytes]
ByteStreamTransport
Streaming binary
Iterable[str] or AsyncIterable[str]
TextStreamTransport
Streaming UTF-8 text
Transport can also be set explicitly on the topic when the topic is unstructured or
when custom serialization is needed:
Use sanitize_name to convert arbitrary non-empty names to SanitizedName
markers. Plain strings are reversibly escaped, including underscores. Use
SanitizedName only when passing a queue-safe name that has already been
sanitized and must not be escaped again.
Wildcard Topics
It is possible to subscribe to multiple topics by using a wildcard (*) at the
end of the topic name. Bare wildcards are also allowed and act as catch-all
handlers.
Wildcard topics are not supported by poll() and if a wildcard handler is passed to
poll_and_handle(), a non-wildcard list of topics must also be specified to disambiguate
polling.
Local Development
For local tests and integration development, use the embedded queue service or
pytest plugin. It exercises the same client send, subscriber callback, lease renewal,
and acknowledgement paths without requiring a deployed Vercel Function.
import anyio
from vercel.queue import subscribe
from vercel.queue.embedded import embedded_queue_service
async def wait_until(predicate) -> None:
while not predicate():
await anyio.sleep(0.01)
async def test_queue() -> None:
seen: list[str] = []
@subscribe(topic="my-topic")
async def handler(message: dict[str, str]) -> None:
seen.append(message["message"])
async with embedded_queue_service() as service:
client = service.get_async_client()
message_id = await client.send("my-topic", {"message": "Hello world"})
assert message_id is not None
service.dispatcher.wake()
await wait_until(lambda: service.server.state.by_id[message_id].acknowledged)
assert seen == ["Hello world"]
Standalone HTTP dev server support is available through the devserver extra:
python -m vercel.queue.devserver --host 127.0.0.1
Install it with vercel-queue[devserver]. The command prints a JSON baseUrl
for the local queue API, including the random available port selected when
--port is omitted. Pass --port 8000 to bind a fixed port. This is useful for
cross-process or cross-runtime local integration.
License
MIT
Alternatives
Use instead of vercel-queue: tools that do the same job, closest first.