Ir para o conteúdo

tempest_fastapi_sdk.queue

Fila de mensagens sobre o FastStream: publisher, consumer, topologia, retry, dedup e tracing.

« Tempo real e mensageria


queue

FastStream-backed message queue primitives.

Imports the optional faststream package lazily so the rest of the SDK remains importable when the [queue] extra is not installed.

MessageBroker is the recommended typed, transport-agnostic facade (constructors, @on / class-based consumers, channel-first publish). AsyncQueueManager is a minimal lifecycle wrapper around an injected broker (renamed from AsyncBrokerManager, kept as a deprecated alias).

PublishResult

PublishResult = object

Transport-specific confirmation returned by publish (or None).

Each FastStream transport returns its own confirmation type (AMQP ConfirmationFrameType | None, Kafka RecordMetadata or future, NATS PubAck | None, Redis int | bytes).

MessageBroker

MessageBroker(broker: BrokerUsecase[Any, Any], *, declare_topology: bool = True)

Typed, transport-agnostic publish/subscribe over FastStream.

A message broker is for event-driven fan-out between services or workers: a producer :meth:publish-es an event to a channel and every consumer subscribed to that channel (via :meth:on) receives it. Delivery is at-least-once, so handlers should be idempotent.

Pick the transport with a constructor rather than importing FastStream yourself::

from pydantic import BaseModel
from tempest_fastapi_sdk.queue import MessageBroker

mq = MessageBroker.rabbitmq("amqp://guest:guest@localhost:5672/")

class OrderPaid(BaseModel):
    order_id: str

@mq.on("orders.paid")
async def handle(event: OrderPaid) -> None:
    await mark_paid(event.order_id)

# FastAPI lifespan
await mq.connect()
await mq.publish("orders.paid", OrderPaid(order_id="abc"))
await mq.disconnect()

The handler's type hint (event: OrderPaid) drives decoding: FastStream validates the inbound payload into that Pydantic model before your function runs, so a malformed message never reaches your code. :meth:publish accepts a Pydantic model, a dict, str or bytes — models are serialized to JSON automatically.

Attributes:

Name Type Description
broker BrokerUsecase[Any, Any]

The underlying FastStream broker — the escape hatch for transport features the facade doesn't wrap.

Wrap an already-constructed FastStream broker.

Prefer the transport constructors (:meth:rabbitmq, :meth:redis, :meth:kafka, :meth:nats); use this directly only to inject a pre-configured or custom broker (e.g. a test broker).

Parameters:

Name Type Description Default
broker BrokerUsecase[Any, Any]

A FastStream broker.

required
declare_topology bool

Whether :meth:connect declares the dead-letter exchanges named by the registered :class:~tempest_fastapi_sdk.queue.QueueSpec. True makes a spec work with no infrastructure step, which is what a small team wants. Set it to False where the broker is managed and the application has no permission to declare — the exchanges then have to exist already, and a missing one fails at subscribe time.

True

transport property

transport: TransportEnum

Return which transport this facade is wrapping.

Read from the broker class at call time, so it is correct for an injected broker as well as for one built by a constructor.

Returns:

Name Type Description
TransportEnum TransportEnum

The detected transport.

specs property

specs: dict[str, QueueSpec]

Return the topology declared through this broker, by channel.

Returns:

Type Description
dict[str, QueueSpec]

dict[str, QueueSpec]: A copy, so callers cannot mutate the

dict[str, QueueSpec]

registry the declaration step reads.

is_connected property

is_connected: bool

Return True once :meth:connect has succeeded.

Returns:

Name Type Description
bool bool

True while the broker is started.

rabbitmq classmethod

rabbitmq(
    url: str,
    *,
    declare_topology: bool = True,
    prefetch: int | None = None,
    **options: Any,
) -> MessageBroker

Build a RabbitMQ-backed broker ([queue] extra).

Parameters:

Name Type Description Default
url str

AMQP URL, e.g. "amqp://guest:guest@localhost:5672/".

required
declare_topology bool

See :meth:__init__.

True
prefetch int | None

Caps how many unacknowledged messages the broker pushes to this connection. Without a cap the broker delivers as fast as the consumer acks: one slow handler accumulates messages in process memory, one replica can take the whole batch and leave its siblings idle, and an unacked backlog is held in RAM until the worker is OOM-killed and the whole lot is redelivered. Per-consumer overrides go on :meth:on.

None
**options Any

Extra keyword arguments forwarded to faststream.rabbit.RabbitBroker.

{}

Returns:

Name Type Description
MessageBroker MessageBroker

A facade around a RabbitBroker.

redis classmethod

redis(url: str, *, declare_topology: bool = True, **options: Any) -> MessageBroker

Build a Redis-backed broker ([queue-redis] extra).

Parameters:

Name Type Description Default
url str

Redis URL, e.g. "redis://localhost:6379/0".

required
declare_topology bool

See :meth:__init__.

True
**options Any

Extra keyword arguments forwarded to faststream.redis.RedisBroker.

{}

Returns:

Name Type Description
MessageBroker MessageBroker

A facade around a RedisBroker.

kafka classmethod

kafka(
    *bootstrap_servers: str, declare_topology: bool = True, **options: Any
) -> MessageBroker

Build a Kafka-backed broker ([queue-kafka] extra).

Kafka has no queues: a channel is a topic, and who gets a copy is decided by the consumer group. Consumers sharing a group_id (see :meth:on) split the topic's partitions between them; each distinct group reads every record. Without a group there is nowhere to commit an offset. A publish key (see :meth:publish) picks the partition, so the records of one key are read in the order they were written.

Parameters:

Name Type Description Default
*bootstrap_servers str

One or more host:port seeds.

()
declare_topology bool

See :meth:__init__.

True
**options Any

Extra keyword arguments forwarded to faststream.kafka.KafkaBroker.

{}

Returns:

Name Type Description
MessageBroker MessageBroker

A facade around a KafkaBroker.

Raises:

Type Description
ValueError

When no seed is given. FastStream accepts the empty list and the broker fails only on connect(), with KafkaConnectionError: Unable to bootstrap from []; the usual cause is MessageBroker.kafka(**settings.kafka_kwargs()), which carries every setting but the positional seeds.

kafka_from_settings classmethod

kafka_from_settings(
    settings: KafkaSettings, *, declare_topology: bool = True, **options: Any
) -> MessageBroker

Build the Kafka broker a :class:KafkaSettings describes.

The seeds are positional on :meth:kafka and the rest comes from :meth:~tempest_fastapi_sdk.settings.KafkaSettings.kafka_kwargs, so a plain MessageBroker.kafka(**settings.kafka_kwargs()) would connect to FastStream's localhost default; this is the one call that passes both halves.

Parameters:

Name Type Description Default
settings KafkaSettings

The mixin, or a service Settings composing it.

required
declare_topology bool

See :meth:__init__.

True
**options Any

Extra keyword arguments forwarded to faststream.kafka.KafkaBroker. A key that :meth:~tempest_fastapi_sdk.settings.KafkaSettings.kafka_kwargs also returns (security, client_id) wins over the settings.

{}

Returns:

Name Type Description
MessageBroker MessageBroker

A facade around a KafkaBroker.

nats classmethod

nats(
    servers: str | list[str], *, declare_topology: bool = True, **options: Any
) -> MessageBroker

Build a NATS-backed broker ([queue-nats] extra).

Parameters:

Name Type Description Default
servers str | list[str]

NATS server URL(s).

required
declare_topology bool

See :meth:__init__.

True
**options Any

Extra keyword arguments forwarded to faststream.nats.NatsBroker.

{}

Returns:

Name Type Description
MessageBroker MessageBroker

A facade around a NatsBroker.

on

on(
    channel: str | QueueSpec,
    /,
    *,
    prefetch: int | None = None,
    ack_policy: AckPolicy | None = None,
    group_id: str | None = None,
    auto_offset_reset: OffsetResetEnum | str | None = None,
    **options: Any,
) -> Callable[[Handler], Handler]

Register the decorated async function as a consumer of channel.

The handler's parameter type hint drives decoding — annotate it with a Pydantic model and FastStream validates every inbound message into that model before the handler runs::

@mq.on("orders.paid")
async def handle(event: OrderPaid) -> None:
    ...

Parameters:

Name Type Description Default
channel str | QueueSpec

The logical channel to subscribe to. Maps to a queue (RabbitMQ), topic (Kafka), subject (NATS) or channel (Redis) under the hood. A spec with a :class:~tempest_fastapi_sdk.queue.ExchangeBinding (see :meth:QueueSpec.consumer <tempest_fastapi_sdk.queue.QueueSpec.consumer>) declares its exchange and binds the queue to it.

required
prefetch int | None

Caps how many unacknowledged messages the broker pushes to this consumer, overriding the connection-wide cap set on :meth:rabbitmq. RabbitMQ only: raises on Kafka, NATS and Redis.

None
ack_policy AckPolicy | None

FastStream's ack policy for this consumer. None keeps FastStream's choice, except on a spec with a dead-letter exchange, where it is pinned to REJECT_ON_ERROR so a raising handler's message reaches the dead-letter queue — no faststream import needed. On Kafka the policy is the commit behavior: None is FastStream's ACK_FIRST, offsets auto-committed on a timer whatever the handler did; ACK commits after the handler, also when it raised; NACK_ON_ERROR seeks back to the failed record so it is read again. Any policy but ACK_FIRST needs group_id.

None
group_id str | None

Kafka consumer group. Consumers sharing it split the topic's partitions — each record goes to one of them; every distinct group gets its own copy. Kafka only.

None
auto_offset_reset OffsetResetEnum | str | None

Where the group starts when it has no committed offset. A member or its value ("earliest", what FastStream's own keyword takes); an unknown value raises ValueError. None keeps Kafka's LATEST. Kafka only.

None
**options Any

Extra transport-specific subscriber options forwarded to FastStream (e.g. exchange= on RabbitMQ).

{}

Returns:

Type Description
Callable[[Handler], Handler]

Callable[[Handler], Handler]: The subscriber decorator.

Raises:

Type Description
ValueError

When the spec has a dead-letter exchange and ack_policy is ACK, ACK_FIRST or NACK_ON_ERROR, none of which ever dead-letters; or, on Kafka, when the ack policy commits and no group_id is set.

UnsupportedTopologyError

When prefetch is set on a transport without it, or group_id / auto_offset_reset on one other than Kafka.

publish async

publish(
    channel: str | QueueSpec,
    message: object,
    *,
    exchange: ExchangeSpec | str | None = None,
    key: str | bytes | None = None,
    message_id: str | None = None,
    **options: Any,
) -> PublishResult

Publish message to channel.

Parameters:

Name Type Description Default
channel str | QueueSpec

The destination channel, or the :class:~tempest_fastapi_sdk.queue.QueueSpec declaring it. Publishing only needs the name, so a spec here is accepted for symmetry with :meth:on — the topology is applied where the queue is declared, not per message. With exchange, the channel is the routing key: a bare string as given, or the event key of a spec's :class:~tempest_fastapi_sdk.queue.ExchangeBinding (not the queue name, which no binding routes by).

required
message object

The payload. A Pydantic model or dict is serialized to JSON; str / bytes are sent as-is.

required
exchange ExchangeSpec | str | None

Publish to this exchange instead of straight to the queue named channel, so every queue bound under that key gets a copy. An :class:~tempest_fastapi_sdk.queue.ExchangeSpec is declared on the first publish to it and not again until :meth:disconnect; publishing to an exchange that does not exist is an AMQP channel error, so a relay that runs before any consumer would otherwise depend on someone else having declared it. A bare name is passed through undeclared — the exchange already exists (amq.topic, or one the infrastructure owns) and its type is not ours to assert. RabbitMQ only.

None
key str | bytes | None

Kafka record key. Records with the same key go to the same partition, so a consumer reads them in the order they were written; None lets the producer spread records over the partitions. A str is encoded as UTF-8 (aiokafka takes bytes only and raises TypeError on a str). Kafka only.

None
message_id str | None

The id :meth:deduplicate keys on. None fills a fresh UUID — without a stable id there is no key to work from, and a redelivery is indistinguishable from a new event. Pass your own to key deduplication on something the domain owns. On a transport whose publish has no message_id (Kafka, NATS, Redis) it travels in the :data:~tempest_fastapi_sdk.queue.dedup.MESSAGE_ID_HEADER header instead, overriding a header of that name in headers=.

None
**options Any

Extra transport-specific publish options forwarded to FastStream (e.g. headers=, correlation_id=).

{}

Returns:

Name Type Description
PublishResult PublishResult

Whatever the transport's publish returns (often

PublishResult

None; AMQP returns a confirmation when publisher confirms

PublishResult

are on).

Raises:

Type Description
RuntimeError

When :meth:connect has not been called yet.

UnsupportedTopologyError

When exchange is given on a transport without exchanges, or key on one other than Kafka.

ValueError

When exchange comes with a routing_key= option, which would contradict the channel.

declare_retry_topology async

declare_retry_topology(topology: RetryTopology) -> None

Declare and bind the three queues of a retry chain.

Declaring the queues is not enough. Each one has to be bound to its exchange, and a chain declared without the bindings routes a rejected message into an exchange with nothing behind it — where RabbitMQ drops it silently. Verified against a real broker: with the bindings the message comes back on schedule, without them it is delivered once and disappears.

Idempotent, like every AMQP declaration: re-declaring an exchange or queue with the same properties is a no-op, and re-binding an existing binding does nothing.

Call it after :meth:connect, since it needs a live channel.

Parameters:

Name Type Description Default
topology RetryTopology

The :class:~tempest_fastapi_sdk.queue.RetryTopology built by :func:~tempest_fastapi_sdk.queue.retry_queues.

required

Raises:

Type Description
NotImplementedError

On a transport without exchanges. The chain is AMQP-specific, and pretending otherwise would declare nothing and report success.

dead_letter

dead_letter(sink: DeadLetterSink, *, max_attempts: int = DEFAULT_MAX_ATTEMPTS) -> None

Route terminally-failed consumes to sink.

Without this, a handler that raises loses its message: the ack policy rejects it and, unless the queue declares a dead-letter exchange, the broker discards it with no error surface at all.

The sink is the same :class:~tempest_fastapi_sdk.tasks.DeadLetterSink protocol the task path uses, so DbDeadLetterSink and the admin panel work unchanged and a dead task and a dead event share one screen.

Call it before :meth:connect.

Parameters:

Name Type Description Default
sink DeadLetterSink

Where dead events go.

required
max_attempts int

Deliveries to allow before reporting. Must match the :class:~tempest_fastapi_sdk.queue.ConsumerRetryPolicy used to build the retry topology, if any.

DEFAULT_MAX_ATTEMPTS

deduplicate

deduplicate(store: DedupStore, *, ttl_seconds: int = DEFAULT_DEDUP_TTL_SECONDS) -> None

Run each message id at most once, across redeliveries.

The transport is at-least-once: a restart, a requeue or a lost ack all redeliver. This claims the id before the handler runs and marks it done after, so the second delivery is skipped.

Not exactly-once. The mark and the handler's effect are not atomic; a crash between them leaves a claim that expires and the message runs again. When the effect is a row keyed by something the domain owns, an INSERT ... ON CONFLICT DO NOTHING is idempotent with no extra moving part and is the better answer.

Call it before :meth:connect.

Parameters:

Name Type Description Default
store DedupStore

A :class:~tempest_fastapi_sdk.queue.DedupStore — MemoryDedupStore for a single replica, RedisDedupStore for more than one.

required
ttl_seconds int

How long an id is remembered. Must outlive the retry topology's total delay, or the last retry runs as if the message were new.

DEFAULT_DEDUP_TTL_SECONDS

enable_tracing

enable_tracing() -> None

Open a span per consumed message, linked to the publish.

:meth:publish already injects the trace context and the current request id into the message headers; this is the other half — each consume runs inside a span carrying the messaging semantic conventions, linked to the publishing trace rather than parented by it, and with the publisher's request id restored so the worker's log lines carry it.

A no-op without the [otel] extra, and non-recording when the extra is present but no provider was configured. Request-id propagation works either way.

Call it before :meth:connect.

enable_metrics

enable_metrics(metrics: QueueMetrics) -> None

Publish consume counts and durations for every channel.

Call it before :meth:connect.

Parameters:

Name Type Description Default
metrics QueueMetrics

A :class:~tempest_fastapi_sdk.queue.QueueMetrics.

required

register

register(consumer: Consumer) -> None

Wire a class-based :class:Consumer onto this broker.

Reads every binding the consumer declares (constructor form or grouped @subscribe methods — see :class:~tempest_fastapi_sdk.queue.Consumer) and subscribes each handler to its channel. When a binding carries an explicit schema (the constructor form), that model drives decoding; otherwise the handler's own type hint does.

A binding's prefetch goes through the same translation :meth:on applies — FastStream carries the cap on a Channel object and has no prefetch keyword, so forwarding it verbatim raises TypeError instead of capping anything.

A binding's ack_policy, group_id and auto_offset_reset are resolved — and refused — exactly as :meth:on does it.

Call it at import/startup time, before :meth:connect.

Parameters:

Name Type Description Default
consumer Consumer

The consumer instance to register.

required

Raises:

Type Description
ValueError

When a spec with a dead-letter exchange is bound under an ack policy that never dead-letters, or a Kafka binding commits without a group_id.

UnsupportedTopologyError

When a binding sets a knob its transport cannot express.

publisher

publisher(channel: str | QueueSpec, /, **options: Any) -> QueuePublisher

Return a reusable publisher bound to channel.

Useful to declare a typed outbound endpoint once and call it many times, and so the channel shows up in FastStream's AsyncAPI docs. The returned object is called as await pub.publish(msg).

Parameters:

Name Type Description Default
channel str | QueueSpec

The destination channel.

required
**options Any

Extra transport-specific publisher options.

{}

Returns:

Name Type Description
QueuePublisher QueuePublisher

A FastStream publisher object bound to

QueuePublisher

channel.

publisher_for

publisher_for(
    publisher: type[PublisherT],
    *,
    channel: str | QueueSpec | None = None,
    schema: type | None = None,
    **options: Any,
) -> PublisherT

Bind a class-based :class:Publisher to this broker.

The publish-side counterpart of :meth:register, and the reason it takes a class rather than an instance: a :class:~tempest_fastapi_sdk.queue.Publisher is useless until it has a broker, so constructing it separately would only create a window in which it exists and cannot publish.

The declared channel goes through the same binding :meth:on uses, so a :class:~tempest_fastapi_sdk.queue.QueueSpec is validated against the transport here, at startup, and registered for :meth:declare_topology. Without that, a service that only publishes would name a dead-letter exchange nobody declares — and every rejected message on the consuming side would be dropped at routing time, silently.

channel and schema are named rather than left to **options so the type checker sees them and a publish option that happens to share one of those names is not swallowed. They override whatever the class declares, which is what lets one Publisher subclass serve a channel only known at runtime — per tenant, per environment — without a subclass per value.

Parameters:

Name Type Description Default
publisher type[PublisherT]

The Publisher subclass.

required
channel str | QueueSpec | None

Overrides the class attribute. Required when the class declares none.

None
schema type | None

Overrides the class attribute.

None
**options Any

Default publish options for every message it sends.

{}

Returns:

Name Type Description
PublisherT PublisherT

The bound instance.

Raises:

Type Description
UnsupportedTopologyError

When the declared spec sets a field the transport cannot honor.

connect async

connect() -> None

Start the broker so consumers and publishers go live.

Idempotent — safe to call from the FastAPI lifespan and again elsewhere; extra calls are no-ops while the broker is alive.

On RabbitMQ the connection is opened and :meth:declare_topology runs before the subscribers start. The other order left a window in which a consumer was already receiving and its dead-letter exchange did not exist yet: a message rejected in it was routed nowhere and dropped. A declaration the broker refuses (PRECONDITION_FAILED on a queue that exists with other arguments) therefore surfaces before any consumer runs, and the connection opened for it is closed before the error propagates.

declare_topology async

declare_topology() -> list[str]

Declare the dead-letter exchanges and queues the specs name.

A queue carrying x-dead-letter-exchange is declared happily by RabbitMQ even when that exchange does not exist — and then every rejected message is dropped at routing time, silently. The same happens when the exchange exists and no queue is bound to it: routing finds no destination and the message is gone. So the exchange is declared, and a spec whose :class:~tempest_fastapi_sdk.queue.DeadLetterSpec names a queue gets that queue declared and bound under its routing key. :meth:connect calls this before the subscribers start, unless the broker was built with declare_topology=False.

Idempotent: declaring an exchange that already exists with the same properties is a no-op in AMQP. Only durable topic exchanges are declared, which is what a dead-letter exchange should be — a non-durable one would vanish on restart and take the routing with it.

Returns:

Type Description
list[str]

list[str]: The exchange names declared, in sorted order.

list[str]

Empty on a transport with no such concept, or when no spec

list[str]

asked for dead-lettering.

replay_dead_letters async

replay_dead_letters(
    source: QueueSpec | RetryTopology | str,
    *,
    into: str | None = None,
    limit: int = DEFAULT_REPLAY_LIMIT,
) -> int

Move dead-lettered messages back to the queue they failed on.

For after the fix: each message is read from the dead-letter queue, republished straight to the origin queue through the default exchange — never to the shared exchange, which would hand a second copy to every other consumer of the event — and only then acknowledged. A publish that fails puts the message back on the dead-letter queue and stops the run, so a message is never acknowledged without having been delivered somewhere. The origin queue is checked first: through the default exchange, a publish to a queue that does not exist raises nothing — the broker hands the message back as unroutable — and acking after it would lose it.

What travels: the body as bytes, message_id (the deduplication key, so a consumer with :meth:deduplicate still recognises it), content_type, content_encoding, correlation_id, priority, timestamp, type, reply_to and the headers, persisted. expiration, app_id and user_id do not: a replay is a new delivery, not a resurrection of the old one's lifetime; FastStream's publish takes no app_id; and the broker checks user_id against the replaying connection's login, so the original's would be refused. The broker's x-death bookkeeping is dropped: the retry middleware counts attempts from it, and a replayed message that kept it would be given up on at its first failure instead of getting a fresh budget.

At least once, not exactly once: when the publish succeeds and the ack that follows fails (the connection drops between them), the message is both back on the origin queue and still on the dead-letter queue, and the next replay delivers it again. A consumer with :meth:deduplicate skips the second copy by its message_id.

Parameters:

Name Type Description Default
source QueueSpec | RetryTopology | str

Where the dead messages are. A spec built with a dead-letter queue (as :meth:QueueSpec.consumer <tempest_fastapi_sdk.queue.QueueSpec.consumer> builds it) replays that queue into the spec's own; a :class:~tempest_fastapi_sdk.queue.RetryTopology replays its .dead queue into its main one; a bare name is the dead-letter queue itself and needs into.

required
into str | None

The queue to return messages to. Only for a bare name; the other forms already say.

None
limit int

Most messages to move in this call. A message that fails again lands back on the dead-letter queue behind the others, so without a cap a still-broken consumer turns the replay into a loop.

DEFAULT_REPLAY_LIMIT

Returns:

Name Type Description
int int

How many messages went back.

Raises:

Type Description
ValueError

When limit is not positive, when a bare name comes without into (or a spec/topology with it), or when the spec names no dead-letter queue.

NotImplementedError

On a transport without queues to read from.

RuntimeError

When :meth:connect has not been called yet.

ChannelNotFoundEntity

When the dead-letter queue or the origin queue does not exist. Nothing is read.

disconnect async

disconnect() -> None

Stop the broker and release its connections.

Forgets which exchanges :meth:publish declared, so the next :meth:connect declares them again rather than trusting a connection that is gone.

lifespan async

lifespan() -> AsyncGenerator[MessageBroker, None]

Connect on entry, disconnect on exit — for scripts and tests.

Long-lived apps should call :meth:connect / :meth:disconnect from their own FastAPI lifespan instead.

Yields:

Name Type Description
MessageBroker AsyncGenerator[MessageBroker, None]

This connected facade.

broker_dependency async

broker_dependency() -> AsyncIterator[MessageBroker]

FastAPI Depends provider yielding this connected facade.

Yields:

Name Type Description
MessageBroker AsyncIterator[MessageBroker]

This facade.

Raises:

Type Description
RuntimeError

When :meth:connect has not been called yet.

health_check async

health_check(timeout: float = 2.0) -> bool

Report whether the broker connection is alive right now.

Delegates to the FastStream broker's own ping(timeout), which every transport implements: RabbitMQ and NATS read the live connection state, Redis sends a PING and Kafka asks the cluster for its metadata. A connection that dropped after :meth:connect therefore reports False. Before :meth:connect (or after :meth:disconnect) it returns False without touching the network. Wire it into a readiness probe with make_health_router(checks={"queue": mq.health_check}); the default timeout stays below the router's per-check bound.

Parameters:

Name Type Description Default
timeout float

Seconds the ping may take before it gives up and reports False.

2.0

Returns:

Name Type Description
bool bool

True when the broker is started and its ping

bool

answered within timeout.

QueuePublisher

Bases: Protocol

Minimal surface of a publisher from :meth:MessageBroker.publisher.

publish

publish(message: object, /, **kwargs: Any) -> Awaitable[PublishResult]

Publish message through the bound channel.

Consumer

Consumer(
    *,
    channel: str | QueueSpec | None = None,
    schema: type | None = None,
    prefetch: int | None = None,
    ack_policy: AckPolicy | None = None,
    group_id: str | None = None,
    auto_offset_reset: OffsetResetEnum | str | None = None,
    **options: Any,
)

Bases: Generic[MessageT]

Base class for class-based message consumers.

Subclass it in one of the two styles shown in the module docstring. Both are explicit — nothing is inferred from the class name. Register an instance with :meth:~tempest_fastapi_sdk.queue.MessageBroker.register.

Attributes:

Name Type Description
channel str | QueueSpec | None

The channel for the constructor form, or the QueueSpec declaring it along with the topology it needs. Left None in the grouped form.

schema type | None

The payload model for the constructor form.

prefetch int | None

Unacknowledged-message cap for every binding this consumer declares. A :func:subscribe that names its own prefetch overrides it for that channel.

ack_policy AckPolicy | None

Ack policy for every binding, with the same override rule as :attr:prefetch. None lets :meth:~tempest_fastapi_sdk.queue.MessageBroker.register decide (REJECT_ON_ERROR on a spec with a dead-letter exchange).

group_id str | None

Kafka consumer group for every binding, with the same override rule as :attr:prefetch. Kafka only.

auto_offset_reset OffsetResetEnum | str | None

Where that group starts without a committed offset, same override rule. Kafka only.

options dict[str, Any]

Subscriber options for the constructor form. Never mutated, so the empty class-level default is safe to share.

Configure the constructor form.

Parameters:

Name Type Description Default
channel str | QueueSpec | None

The channel to consume, or the QueueSpec declaring it. Required for the constructor form; omit it in the grouped (@subscribe) form.

None
schema type | None

The Pydantic model the payload is validated into. Passing it here is the explicit, no-magic path — it drives decoding instead of relying on an annotation.

None
prefetch int | None

Caps how many unacknowledged messages the broker pushes to this consumer, the same knob :meth:~tempest_fastapi_sdk.queue.MessageBroker.on exposes. Applies to every binding the consumer declares, including the grouped form's, unless a :func:subscribe names its own. RabbitMQ only.

None
ack_policy AckPolicy | None

Ack policy for every binding, unless a :func:subscribe names its own.

None
group_id str | None

Kafka consumer group for every binding, unless a :func:subscribe names its own. Kafka only.

None
auto_offset_reset OffsetResetEnum | str | None

Where that group starts without a committed offset, unless a :func:subscribe names its own. Kafka only.

None
**options Any

Extra transport-specific subscriber options forwarded to FastStream (e.g. exchange= on RabbitMQ), for the constructor form. The grouped form takes its own on each :func:subscribe.

{}

handle async

handle(message: MessageT) -> None

Handle one message — override in the constructor form.

Parameters:

Name Type Description Default
message MessageT

The decoded payload (an instance of :attr:schema when one was given).

required

Raises:

Type Description
NotImplementedError

When neither handle is overridden nor any :func:subscribe method is defined.

subscriptions

subscriptions() -> list[Subscription]

Return every channel → handler binding this consumer declares.

Grouped @subscribe methods take precedence; if none are present, the constructor form (channel + handle) is used. A binding with no prefetch of its own inherits :attr:prefetch; the same goes for ack_policy, group_id and auto_offset_reset.

Returns:

Type Description
list[Subscription]

list[Subscription]: One entry per subscription.

Raises:

Type Description
ValueError

When the consumer declares neither a @subscribe method nor a channel.

Subscription dataclass

Subscription(
    channel: str | QueueSpec,
    handler: Callable[..., Awaitable[Any]],
    schema: type | None,
    options: dict[str, Any],
    prefetch: int | None = None,
    ack_policy: AckPolicy | None = None,
    group_id: str | None = None,
    auto_offset_reset: OffsetResetEnum | str | None = None,
)

One channel → handler binding produced by a :class:Consumer.

Attributes:

Name Type Description
channel str | QueueSpec

The channel to subscribe on, or the spec declaring it.

handler Callable[..., Awaitable[Any]]

The async callable that receives each decoded message.

schema type | None

Explicit payload model. When set, it drives decoding regardless of the handler's annotation; when None the handler's own type hint is used.

options dict[str, Any]

Extra transport-specific subscriber options.

prefetch int | None

Per-consumer unacknowledged-message cap, kept apart from :attr:options because it is translated into a FastStream Channel rather than forwarded as a keyword.

ack_policy AckPolicy | None

The ack policy asked for, resolved by :meth:~tempest_fastapi_sdk.queue.MessageBroker.register.

group_id str | None

The Kafka consumer group asked for.

auto_offset_reset OffsetResetEnum | str | None

Where that group starts without a committed offset.

ConcurrentDeliveryError

Bases: RuntimeError

The same message id is already being processed elsewhere.

Raised so the broker rejects the duplicate rather than acknowledging it. Acknowledging would be the dangerous choice: the in-flight worker may still fail, and the copy that could have retried would be gone.

DedupStateEnum

Bases: BaseStrEnum

What the store knew about a message id when it was claimed.

Attributes:

Name Type Description
NEW

Never seen. The handler runs.

IN_FLIGHT

Another delivery of the same id is being processed. The handler does not run and the message is rejected, so the retry topology offers it again later — by which time the other worker has either finished (DONE, skip) or died (key expired, re-run).

DONE

Already processed successfully. The handler does not run and the message is acknowledged.

DedupStore

Bases: Protocol

Where processed message ids are remembered.

Three operations, because two-phase marking needs them. :meth:claim must be atomic — two workers claiming the same id concurrently must not both receive :attr:DedupStateEnum.NEW, which is why it is one call rather than a get followed by a set.

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Mark key in-flight if it is unseen, and report what it was.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

What the store held before this call.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key as successfully processed.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Forget key so a later delivery processes it again.

Parameters:

Name Type Description Default
key str

The message id.

required

MemoryDedupStore dataclass

MemoryDedupStore(entries: MutableMapping[str, tuple[str, float]] = dict())

In-process :class:DedupStore, for one replica and for tests.

Correct only while a single process consumes the channel — two replicas each keep their own table and neither sees the other's claims, so a redelivery routed to the sibling runs the handler again. Use :class:RedisDedupStore for anything with more than one worker.

Attributes:

Name Type Description
entries MutableMapping[str, tuple[str, float]]

Key to (marker, expires_at).

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Claim key, reporting what the store already held.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

The prior state.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key done.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Drop key.

Parameters:

Name Type Description Default
key str

The message id.

required

RedisDedupStore

RedisDedupStore(client: Any, *, prefix: str = 'tempest:dedup:')

:class:DedupStore backed by an async redis client.

:meth:claim is a single SET key in_flight NX EX ttl, so the atomicity two-phase marking depends on comes from Redis rather than from a lock of our own — two workers racing on the same id cannot both be told NEW.

Wrap a Redis client.

Parameters:

Name Type Description Default
client Any

An async redis.asyncio.Redis-compatible client exposing set, get and delete.

required
prefix str

Key namespace, so dedup keys never collide with the application's own.

'tempest:dedup:'

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Claim key atomically via SET NX.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

The prior state. A lost race reads the current

DedupStateEnum

value to tell IN_FLIGHT from DONE; a key that expires

DedupStateEnum

between the two calls reads as DONE, which skips one

DedupStateEnum

message rather than running it twice — the safer way to be

DedupStateEnum

wrong for a handler that is not free to repeat.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key done.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Drop key.

Parameters:

Name Type Description Default
key str

The message id.

required

AsyncQueueManager

AsyncQueueManager(broker: BrokerUsecase[Any, Any])

Manage the lifecycle of an injected FastStream broker.

A minimal wrapper: it wraps any FastStream broker (RabbitBroker, KafkaBroker, NatsBroker, RedisBroker, etc.) with a uniform connect / disconnect / health-check surface matching the SDK's other backends, and forwards publish. Reach for it when you already build your own broker and only want lifecycle management.

For the batteries-included experience — transport constructors, a typed @on(channel) consumer decorator, class-based consumers and channel-first publish — use :class:~tempest_fastapi_sdk.queue.MessageBroker instead.

The broker is injected so consumers stay free to choose the transport without forcing FastStream to import every backend.

Typical usage::

from faststream.rabbit import RabbitBroker
from tempest_fastapi_sdk import AsyncQueueManager

broker = RabbitBroker("amqp://guest:guest@localhost:5672/")
queue = AsyncQueueManager(broker)

@queue.broker.subscriber("orders")
async def handle(msg: OrderMessage) -> None:
    ...

# FastAPI lifespan
await queue.connect()
...
await queue.disconnect()

Attributes:

Name Type Description
broker BrokerUsecase[Any, Any]

The wrapped broker instance.

Initialize the manager.

Parameters:

Name Type Description Default
broker BrokerUsecase[Any, Any]

A FastStream broker instance. Construct it with whatever transport-specific configuration the application needs.

required

is_connected property

is_connected: bool

Return True once :meth:connect succeeded.

Returns:

Name Type Description
bool bool

True while the broker is started.

connect async

connect() -> None

Start the broker so subscribers and publishers are live.

Safe to call multiple times — subsequent calls are no-ops while the same broker is alive.

disconnect async

disconnect() -> None

Stop the broker and release its connections.

publish async

publish(message: object, *args: Any, **kwargs: Any) -> PublishResult

Publish message through the underlying broker.

Parameters:

Name Type Description Default
message object

The payload to publish. Forwarded as-is.

required
*args Any

Positional broker-specific arguments (queue, exchange, topic, etc.).

()
**kwargs Any

Keyword broker-specific arguments.

{}

Returns:

Name Type Description
PublishResult PublishResult

Whatever the broker's publish returns

PublishResult

(often None; AMQP returns a confirmation when enabled).

Raises:

Type Description
RuntimeError

When :meth:connect was not called yet.

lifespan async

lifespan() -> AsyncGenerator[BrokerUsecase[Any, Any], None]

Yield the broker inside an async with block.

Connects on entry, disconnects on exit. Convenient for short scripts and tests; long-lived applications should call :meth:connect / :meth:disconnect from their own lifespan.

Yields:

Type Description
AsyncGenerator[BrokerUsecase[Any, Any], None]

BrokerUsecase[Any, Any]: The connected broker.

broker_dependency async

broker_dependency() -> AsyncIterator[BrokerUsecase[Any, Any]]

Async generator dependency suitable for FastAPI Depends.

Yields:

Type Description
AsyncIterator[BrokerUsecase[Any, Any]]

BrokerUsecase[Any, Any]: The connected broker.

Raises:

Type Description
RuntimeError

When :meth:connect was not called yet.

health_check async

health_check(timeout: float = 2.0) -> bool

Report whether the broker connection is alive right now.

Delegates to the FastStream broker's own ping(timeout), so a connection that dropped after :meth:connect reports False. Before :meth:connect (or after :meth:disconnect) it returns False without touching the network.

Parameters:

Name Type Description Default
timeout float

Seconds the ping may take before it gives up and reports False.

2.0

Returns:

Name Type Description
bool bool

True when the broker is started and its ping

bool

answered within timeout.

Publisher

Publisher(
    broker: MessageBroker,
    *,
    channel: str | QueueSpec | None = None,
    schema: type | None = None,
    **options: Any,
)

Bases: Generic[MessageT]

Base class for class-based publishers, bound to one channel.

Subclass it with the channel and the payload model, then obtain an instance from :meth:~tempest_fastapi_sdk.queue.MessageBroker.publisher_for. The constructor form works too, for a channel only known at runtime::

orders = Publisher[OrderPaid](
    mq, channel="orders.paid", schema=OrderPaid,
)

Nothing is inferred from the class name — same rule as :class:~tempest_fastapi_sdk.queue.Consumer.

Attributes:

Name Type Description
channel str | QueueSpec | None

The destination. A :class:~tempest_fastapi_sdk.queue.QueueSpec also declares the topology; a plain string just names it.

schema type | None

The payload model. When set, :meth:publish refuses anything that is not an instance of it. None disables the check and accepts whatever the transport does.

Bind this publisher to a broker.

Parameters:

Name Type Description Default
broker MessageBroker

The facade to publish through.

required
channel str | QueueSpec | None

Overrides the class attribute. Required when the class does not declare one.

None
schema type | None

Overrides the class attribute.

None
**options Any

Default publish options merged into every :meth:publish call (e.g. headers=). A keyword passed to :meth:publish wins over one given here, so the per-message call can always override the default.

{}

Raises:

Type Description
ValueError

When neither the class nor the constructor names a channel, since there would be nowhere to publish to.

publish async

publish(
    message: MessageT, *, key: str | bytes | None = None, **options: Any
) -> PublishResult

Publish message to this publisher's channel.

Parameters:

Name Type Description Default
message MessageT

The payload. Validated against :attr:schema when one is declared.

required
key str | bytes | None

Kafka record key, exactly as :meth:~tempest_fastapi_sdk.queue.MessageBroker.publish takes it: same key, same partition, read in order. Kafka only.

None
**options Any

Extra publish options for this message, overriding the defaults given to the constructor.

{}

Returns:

Name Type Description
PublishResult PublishResult

Whatever the transport's publish returns.

Raises:

Type Description
TypeError

When :attr:schema is declared and message is not an instance of it. Caught here rather than at the consumer, which is a process away and can only reject what already left.

RuntimeError

When the broker is not connected.

UnsupportedTopologyError

When key is set on a transport other than Kafka.

ConsumerRetryPolicy dataclass

ConsumerRetryPolicy(
    max_attempts: int = DEFAULT_MAX_ATTEMPTS, delay_ms: int = DEFAULT_RETRY_DELAY_MS
)

How many times to retry a failing consumer, and how long to wait.

Attributes:

Name Type Description
max_attempts int

Total deliveries, including the first. 1 disables retrying and sends the first failure straight to the dead queue.

delay_ms int

Milliseconds a message waits before being offered again.

QueueMetrics

QueueMetrics(registry: CollectorRegistry | None = None)

Prometheus counters and durations for consumed messages.

Mirrors :class:~tempest_fastapi_sdk.tasks.TaskMetrics so the event path and the task path graph the same way, on the same registry and the same /metrics endpoint:

  • queue_messages_total{channel,status} — status is ok, error, or duplicate for a delivery :meth:~tempest_fastapi_sdk.queue.MessageBroker.deduplicate rejected because a sibling worker held the claim. Its own label keeps a normal dedup outcome out of the error rate an alert reads.
  • queue_message_duration_seconds{channel} — handler wall time.

Without this, the consumer failure rate is invisible: the message is rejected, the broker discards or dead-letters it, and nothing counts.

Register the two collectors.

Parameters:

Name Type Description Default
registry CollectorRegistry | None

Registry to register on. None uses the SDK's shared one, so the series appear on the same /metrics as everything else.

None

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

middleware

middleware() -> type[BaseMiddleware]

Build the FastStream middleware that feeds these collectors.

Returns:

Type Description
type[BaseMiddleware]

type[BaseMiddleware]: A faststream.BaseMiddleware subclass.

Raises:

Type Description
ImportError

When the [queue] extra is not installed.

RetryTopology dataclass

RetryTopology(
    main: QueueSpec,
    retry: QueueSpec,
    dead: QueueSpec,
    channel: str,
    main_exchange: str,
    retry_exchange: str,
    dead_exchange: str,
)

The three queues a retried channel needs.

Carries the exchange names as well as the queues, because the queues alone are not a working topology: each has to be bound to its exchange, and a chain declared without the bindings routes a rejected message into an exchange with nothing behind it — where RabbitMQ silently drops it. See :meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_retry_topology.

Attributes:

Name Type Description
main QueueSpec

What the consumer subscribes to. Dead-letters to the retry exchange when the handler rejects.

retry QueueSpec

The waiting room. Holds nothing but a TTL; when a message expires it is dead-lettered back to the main exchange, which is what makes the delay work without a plugin.

dead QueueSpec

Terminal. Nothing routes out of it — it is read by a human, or by the admin panel.

channel str

The routing key every binding uses.

main_exchange str

Exchange the main queue is bound to.

retry_exchange str

Exchange the retry queue is bound to.

dead_exchange str

Exchange the dead queue is bound to.

DeadLetterSpec dataclass

DeadLetterSpec(exchange: str, routing_key: str | None = None, queue: str | None = None)

Where a rejected message goes.

On RabbitMQ, dead-lettering is a property of the queue, not of the consumer: the broker routes a message to exchange when it is rejected without requeue, expires, or overflows the queue length. Without it, a rejected message is discarded — which is the default and is silent.

Naming a :attr:queue makes the topology complete: the exchange and that queue are declared and bound before any subscriber starts, so a message rejected on the first delivery already has somewhere to go. Leave it None when something else consumes the exchange — the delayed-retry chain of :func:~tempest_fastapi_sdk.queue.retry_queues is the case: its retry queue is bound there, and a second queue under the same key would receive a duplicate of every failure.

Attributes:

Name Type Description
exchange str

The exchange rejected messages are published to. Declared by :meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_topology.

routing_key str | None

Routing key to use when dead-lettering. None keeps the message's original key. With fan-out that key is the event's, shared by every consumer of it, so a dead-letter queue bound by it would collect the failures of all of them; :meth:QueueSpec.consumer sets it to the queue name instead.

queue str | None

The dead-letter queue to declare and bind to :attr:exchange under :attr:routing_key, or None to declare only the exchange. Requires :attr:routing_key: an unset key binds nothing predictable.

ExchangeBinding dataclass

ExchangeBinding(exchange: ExchangeSpec, routing_key: str)

Bind a queue to an exchange under a routing key.

This is what turns one published event into one copy per consumer: each consumer's queue is bound to the same exchange with the same key, and the broker delivers to every bound queue. Without a binding, two consumers subscribing to the same queue name share one queue and split the messages between them instead.

Attributes:

Name Type Description
exchange ExchangeSpec

The exchange to bind to. Declared when the subscriber starts.

routing_key str

The key (a pattern, on a topic exchange) the queue receives.

ExchangeKindEnum

Bases: BaseStrEnum

AMQP exchange type.

Mirrors faststream.rabbit.ExchangeType value for value, so the topology module imports nothing from FastStream and stays importable without the [queue] extra.

Attributes:

Name Type Description
TOPIC

Routes by pattern (task.*). The default, because it subsumes a direct exchange — an exact key is a pattern with no wildcards — and lets a consumer subscribe to a family of events later without re-declaring anything.

DIRECT

Routes by exact key.

FANOUT

Ignores the key; every bound queue gets a copy.

HEADERS

Routes by message headers.

ExchangeSpec dataclass

ExchangeSpec(name: str, kind: ExchangeKindEnum = TOPIC, durable: bool = True)

An exchange to publish to or bind a queue to.

Attributes:

Name Type Description
name str

The exchange name.

kind ExchangeKindEnum

The exchange type.

durable bool

Whether it survives a broker restart. True, because a non-durable exchange vanishes on restart and takes every binding to it along, so the queues behind it stop receiving with nothing reporting it.

OffsetResetEnum

Bases: BaseStrEnum

Where a Kafka consumer group starts when it has no committed offset.

Only read when the group has never committed on a partition (a new group, or offsets expired by the broker's retention). A group that committed resumes from its commit whatever this says.

Attributes:

Name Type Description
LATEST

Start at the end — only records written after the consumer joined are read. Kafka's and FastStream's default, and the reason a brand-new consumer misses everything that was published before its first deploy.

EARLIEST

Start at the oldest record the topic still retains.

NONE

Refuse to start without a committed offset.

QueueSpec dataclass

QueueSpec(
    name: str,
    durable: bool = True,
    dead_letter: DeadLetterSpec | None = None,
    message_ttl_ms: int | None = None,
    max_priority: int | None = None,
    max_length: int | None = None,
    queue_type: QueueTypeEnum = CLASSIC,
    binding: ExchangeBinding | None = None,
)

A channel plus the topology it needs.

Accepted anywhere a channel string is, so adopting it is per-channel rather than all-or-nothing.

Attributes:

Name Type Description
name str

The channel name. The only required field, and the only one every transport understands.

durable bool

Whether the queue survives a broker restart. True matches the transport defaults; setting it to False on a transport that cannot express it raises.

dead_letter DeadLetterSpec | None

Where rejected messages go.

message_ttl_ms int | None

Discard (or dead-letter) a message after this many milliseconds.

max_priority int | None

Enable a priority queue with this many levels. Incompatible with :attr:QueueTypeEnum.QUORUM.

max_length int | None

Cap the queue at this many messages; overflow is dead-lettered when :attr:dead_letter is set.

queue_type QueueTypeEnum

Classic or quorum.

binding ExchangeBinding | None

Bind the queue to an exchange under a routing key, so it receives its own copy of what is published there. None leaves the queue on the default exchange, reachable by its name only.

consumer classmethod

consumer(
    consumer: str,
    channel: str,
    *,
    exchange: ExchangeSpec | str,
    dead_letter_exchange: str | None = None,
    queue_type: QueueTypeEnum = CLASSIC,
) -> QueueSpec

Build one consumer's queue for an event published to exchange.

The fan-out shape: every module that reacts to channel gets its own durable queue, <consumer>.<channel>, bound to the shared exchange under channel — so each receives a copy instead of competing for one.

With dead_letter_exchange, a rejected message is routed there under the queue name (not the event key, which every consumer shares) into <consumer>.<channel>.dlq, and both are declared before the subscribers start. Replay it with :meth:~tempest_fastapi_sdk.queue.MessageBroker.replay_dead_letters, which returns it to this queue only.

Parameters:

Name Type Description Default
consumer str

The consuming module, e.g. "gamification".

required
channel str

The event's routing key, e.g. "task.completed".

required
exchange ExchangeSpec | str

The exchange the event is published to. A bare name is a durable topic exchange.

required
dead_letter_exchange str | None

Exchange rejected messages go to, or None to discard them.

None
queue_type QueueTypeEnum

Classic or quorum.

CLASSIC

Returns:

Name Type Description
QueueSpec QueueSpec

The spec to pass to

QueueSpec

meth:~tempest_fastapi_sdk.queue.MessageBroker.on.

QueueTypeEnum

Bases: BaseStrEnum

RabbitMQ queue implementation.

Attributes:

Name Type Description
CLASSIC

The default. One queue master, mirrored only if a policy says so.

QUORUM

Raft-replicated across nodes. Survives the loss of a node without the message loss classic mirroring can suffer, at the cost of memory and of not supporting x-max-priority — which is why combining it with :attr:QueueSpec.max_priority raises. Message TTL is supported, so the delayed-retry chain built by :func:~tempest_fastapi_sdk.queue.retry_queues works on quorum queues. Reach for it once losing a message matters more than the extra resources.

TransportEnum

Bases: BaseStrEnum

Which broker a :class:QueueSpec is being translated for.

Detected from the FastStream broker class rather than recorded at construction, so a :class:~tempest_fastapi_sdk.queue.MessageBroker built by injecting a broker directly is classified the same way as one built through a transport constructor.

UnsupportedTopologyError

Bases: RuntimeError

A :class:QueueSpec asks for something the transport cannot do.

Raised where the queue is bound — :meth:~MessageBroker.on, :meth:~MessageBroker.publisher, :meth:~MessageBroker.register — which is startup, not per message, so the mismatch surfaces on the first run rather than as a queue that quietly lacks the property you declared. :meth:~MessageBroker.publish only reads the name, since the topology belongs to the declaration and not to the message.

consume_span

consume_span(channel: str, headers: dict[str, Any] | None = None)

Span around one consumed message, linked to the publishing trace.

Follows the OpenTelemetry messaging semantic conventions: messaging.system, messaging.destination.name and messaging.operation, with the span named "<channel> process".

The publishing trace is attached as a link, not as a parent. The convention recommends it for asynchronous consumption, and the reason is practical: a consumer can run minutes after the publish, and a child span of that duration would stretch the request's trace and make its latency unreadable. A link keeps both traces truthful and still lets you jump between them.

Restores the publisher's request id for the duration of the block, so the worker's log lines carry the id of the request that caused them — which is worth more than the span to anyone debugging with grep.

Prepare a span for a message on channel.

Parameters:

Name Type Description Default
channel str

The queue/topic the message arrived on.

required
headers dict[str, Any] | None

The message headers, read for the trace context and the request id.

None

subscribe

subscribe(
    channel: str | QueueSpec,
    *,
    prefetch: int | None = None,
    ack_policy: AckPolicy | None = None,
    group_id: str | None = None,
    auto_offset_reset: OffsetResetEnum | str | None = None,
    **options: Any,
) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]

Mark a :class:Consumer method as the handler for channel.

The decorated method keeps its normal signature — its message parameter's type hint is what validates the payload. Only used in the grouped form; the constructor form overrides :meth:Consumer.handle instead.

Parameters:

Name Type Description Default
channel str | QueueSpec

The channel this method consumes, or the QueueSpec declaring it along with its topology.

required
prefetch int | None

Caps how many unacknowledged messages the broker pushes to this handler, exactly as :meth:~tempest_fastapi_sdk.queue.MessageBroker.on does. Named rather than left to **options because FastStream has no prefetch keyword — it carries the cap on a Channel object, so forwarding it verbatim raises TypeError. Overrides :attr:Consumer.prefetch. RabbitMQ only.

None
ack_policy AckPolicy | None

FastStream's ack policy for this handler, resolved as :meth:~tempest_fastapi_sdk.queue.MessageBroker.on resolves it: pinned to REJECT_ON_ERROR on a spec with a dead-letter exchange. Overrides :attr:Consumer.ack_policy.

None
group_id str | None

Kafka consumer group for this handler, as :meth:~tempest_fastapi_sdk.queue.MessageBroker.on takes it. Overrides :attr:Consumer.group_id. Kafka only.

None
auto_offset_reset OffsetResetEnum | str | None

Where the group starts without a committed offset. Overrides :attr:Consumer.auto_offset_reset. Kafka only.

None
**options Any

Extra transport-specific subscriber options forwarded to FastStream (e.g. exchange= on RabbitMQ).

{}

Returns:

Name Type Description
Callable Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]

The same method, tagged so register can find it.

delivery_attempt

delivery_attempt(message: object) -> int

Return which delivery this is, counting from 1.

RabbitMQ records every dead-lettering in the message's x-death header, so the number of times a message has already been rejected is readable without any state of our own — which matters, because a consumer restart must not reset the budget.

Entries whose reason is "expired" are skipped, and that is load-bearing rather than a detail. RabbitMQ keeps one entry per (queue, reason) pair, and the delayed-retry chain dead-letters a message twice per round: once out of the main queue (rejected) and once out of the retry queue when its TTL fires (expired). Summing every entry therefore advanced the counter by two per retry, so a max_attempts=3 policy gave up after two deliveries. An expiry is the waiting room emptying itself, not a delivery that failed.

Parameters:

Name Type Description Default
message object

The FastStream message being consumed.

required

Returns:

Name Type Description
int int

1 on first delivery, 2 on the first retry, and so

int

on. Falls back to 1 when the header is absent or malformed,

int

so an unreadable header costs an extra attempt rather than

int

dropping the message early.

retry_queues

retry_queues(
    channel: str,
    policy: ConsumerRetryPolicy | None = None,
    *,
    retry_exchange: str,
    main_exchange: str,
    dead_exchange: str,
    queue_type: QueueTypeEnum = CLASSIC,
) -> RetryTopology

Build the delayed-retry topology for channel.

RabbitMQ has no per-message delay of its own. The portable way to get one is a pair of queues: the main queue dead-letters a rejected message into a retry queue whose only job is to hold it, and that queue's TTL dead-letters it back to the main exchange when it expires. The message therefore reappears at the consumer delay_ms later, with the broker doing the waiting — so a worker restart in the meantime changes nothing.

The alternative is the rabbitmq_delayed_message_exchange plugin, which is simpler to declare and requires the plugin installed — not available on several managed offerings, including the free CloudAMQP tier. This builds on stock AMQP instead.

Parameters:

Name Type Description Default
channel str

The channel the consumer subscribes to.

required
policy ConsumerRetryPolicy | None

Attempts and delay. Defaults to :class:ConsumerRetryPolicy.

None
retry_exchange str

Exchange the main queue dead-letters to.

required
main_exchange str

Exchange the retry queue returns messages to. Must route back to channel.

required
dead_exchange str

Exchange the terminal queue is fed from.

required
queue_type QueueTypeEnum

Queue implementation for all three.

CLASSIC

Returns:

Name Type Description
RetryTopology RetryTopology

The three specs, ready to declare and subscribe.

Notes

max_attempts is not enforced by this topology — AMQP counts redeliveries in the x-death header but will not stop on its own. The count is enforced by the consumer middleware (:func:make_dead_letter_middleware), which reads that header and routes to the dead queue once the budget is spent. Declaring the topology without installing the middleware yields infinite retries, which is why they are documented together.

extract_context

extract_context(headers: dict[str, Any]) -> Any | None

Recover the publishing trace context from headers.

Parameters:

Name Type Description Default
headers dict[str, Any]

The consumed message's headers.

required

Returns:

Type Description
Any | None

Any | None: An OpenTelemetry Context, or None when the

Any | None

extra is missing or the message carries no traceparent.

inject_context

inject_context(headers: dict[str, Any]) -> dict[str, Any]

Add the current trace context and request id to headers.

Parameters:

Name Type Description Default
headers dict[str, Any]

Headers being assembled for a publish. Mutated in place and returned, for the caller's convenience.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The same mapping. Unchanged when no trace is

dict[str, Any]

active and no request id is set, so a publish outside a request

dict[str, Any]

carries no empty headers.

PublishResult

PublishResult = object

Transport-specific confirmation returned by publish (or None).

Each FastStream transport returns its own confirmation type (AMQP ConfirmationFrameType | None, Kafka RecordMetadata or future, NATS PubAck | None, Redis int | bytes).

QueuePublisher

Bases: Protocol

Minimal surface of a publisher from :meth:MessageBroker.publisher.

publish

publish(message: object, /, **kwargs: Any) -> Awaitable[PublishResult]

Publish message through the bound channel.

Publisher

Publisher(
    broker: MessageBroker,
    *,
    channel: str | QueueSpec | None = None,
    schema: type | None = None,
    **options: Any,
)

Bases: Generic[MessageT]

Base class for class-based publishers, bound to one channel.

Subclass it with the channel and the payload model, then obtain an instance from :meth:~tempest_fastapi_sdk.queue.MessageBroker.publisher_for. The constructor form works too, for a channel only known at runtime::

orders = Publisher[OrderPaid](
    mq, channel="orders.paid", schema=OrderPaid,
)

Nothing is inferred from the class name — same rule as :class:~tempest_fastapi_sdk.queue.Consumer.

Attributes:

Name Type Description
channel str | QueueSpec | None

The destination. A :class:~tempest_fastapi_sdk.queue.QueueSpec also declares the topology; a plain string just names it.

schema type | None

The payload model. When set, :meth:publish refuses anything that is not an instance of it. None disables the check and accepts whatever the transport does.

Bind this publisher to a broker.

Parameters:

Name Type Description Default
broker MessageBroker

The facade to publish through.

required
channel str | QueueSpec | None

Overrides the class attribute. Required when the class does not declare one.

None
schema type | None

Overrides the class attribute.

None
**options Any

Default publish options merged into every :meth:publish call (e.g. headers=). A keyword passed to :meth:publish wins over one given here, so the per-message call can always override the default.

{}

Raises:

Type Description
ValueError

When neither the class nor the constructor names a channel, since there would be nowhere to publish to.

publish async

publish(
    message: MessageT, *, key: str | bytes | None = None, **options: Any
) -> PublishResult

Publish message to this publisher's channel.

Parameters:

Name Type Description Default
message MessageT

The payload. Validated against :attr:schema when one is declared.

required
key str | bytes | None

Kafka record key, exactly as :meth:~tempest_fastapi_sdk.queue.MessageBroker.publish takes it: same key, same partition, read in order. Kafka only.

None
**options Any

Extra publish options for this message, overriding the defaults given to the constructor.

{}

Returns:

Name Type Description
PublishResult PublishResult

Whatever the transport's publish returns.

Raises:

Type Description
TypeError

When :attr:schema is declared and message is not an instance of it. Caught here rather than at the consumer, which is a process away and can only reject what already left.

RuntimeError

When the broker is not connected.

UnsupportedTopologyError

When key is set on a transport other than Kafka.

Subscription dataclass

Subscription(
    channel: str | QueueSpec,
    handler: Callable[..., Awaitable[Any]],
    schema: type | None,
    options: dict[str, Any],
    prefetch: int | None = None,
    ack_policy: AckPolicy | None = None,
    group_id: str | None = None,
    auto_offset_reset: OffsetResetEnum | str | None = None,
)

One channel → handler binding produced by a :class:Consumer.

Attributes:

Name Type Description
channel str | QueueSpec

The channel to subscribe on, or the spec declaring it.

handler Callable[..., Awaitable[Any]]

The async callable that receives each decoded message.

schema type | None

Explicit payload model. When set, it drives decoding regardless of the handler's annotation; when None the handler's own type hint is used.

options dict[str, Any]

Extra transport-specific subscriber options.

prefetch int | None

Per-consumer unacknowledged-message cap, kept apart from :attr:options because it is translated into a FastStream Channel rather than forwarded as a keyword.

ack_policy AckPolicy | None

The ack policy asked for, resolved by :meth:~tempest_fastapi_sdk.queue.MessageBroker.register.

group_id str | None

The Kafka consumer group asked for.

auto_offset_reset OffsetResetEnum | str | None

Where that group starts without a committed offset.

QueueSpec dataclass

QueueSpec(
    name: str,
    durable: bool = True,
    dead_letter: DeadLetterSpec | None = None,
    message_ttl_ms: int | None = None,
    max_priority: int | None = None,
    max_length: int | None = None,
    queue_type: QueueTypeEnum = CLASSIC,
    binding: ExchangeBinding | None = None,
)

A channel plus the topology it needs.

Accepted anywhere a channel string is, so adopting it is per-channel rather than all-or-nothing.

Attributes:

Name Type Description
name str

The channel name. The only required field, and the only one every transport understands.

durable bool

Whether the queue survives a broker restart. True matches the transport defaults; setting it to False on a transport that cannot express it raises.

dead_letter DeadLetterSpec | None

Where rejected messages go.

message_ttl_ms int | None

Discard (or dead-letter) a message after this many milliseconds.

max_priority int | None

Enable a priority queue with this many levels. Incompatible with :attr:QueueTypeEnum.QUORUM.

max_length int | None

Cap the queue at this many messages; overflow is dead-lettered when :attr:dead_letter is set.

queue_type QueueTypeEnum

Classic or quorum.

binding ExchangeBinding | None

Bind the queue to an exchange under a routing key, so it receives its own copy of what is published there. None leaves the queue on the default exchange, reachable by its name only.

consumer classmethod

consumer(
    consumer: str,
    channel: str,
    *,
    exchange: ExchangeSpec | str,
    dead_letter_exchange: str | None = None,
    queue_type: QueueTypeEnum = CLASSIC,
) -> QueueSpec

Build one consumer's queue for an event published to exchange.

The fan-out shape: every module that reacts to channel gets its own durable queue, <consumer>.<channel>, bound to the shared exchange under channel — so each receives a copy instead of competing for one.

With dead_letter_exchange, a rejected message is routed there under the queue name (not the event key, which every consumer shares) into <consumer>.<channel>.dlq, and both are declared before the subscribers start. Replay it with :meth:~tempest_fastapi_sdk.queue.MessageBroker.replay_dead_letters, which returns it to this queue only.

Parameters:

Name Type Description Default
consumer str

The consuming module, e.g. "gamification".

required
channel str

The event's routing key, e.g. "task.completed".

required
exchange ExchangeSpec | str

The exchange the event is published to. A bare name is a durable topic exchange.

required
dead_letter_exchange str | None

Exchange rejected messages go to, or None to discard them.

None
queue_type QueueTypeEnum

Classic or quorum.

CLASSIC

Returns:

Name Type Description
QueueSpec QueueSpec

The spec to pass to

QueueSpec

meth:~tempest_fastapi_sdk.queue.MessageBroker.on.

DeadLetterSpec dataclass

DeadLetterSpec(exchange: str, routing_key: str | None = None, queue: str | None = None)

Where a rejected message goes.

On RabbitMQ, dead-lettering is a property of the queue, not of the consumer: the broker routes a message to exchange when it is rejected without requeue, expires, or overflows the queue length. Without it, a rejected message is discarded — which is the default and is silent.

Naming a :attr:queue makes the topology complete: the exchange and that queue are declared and bound before any subscriber starts, so a message rejected on the first delivery already has somewhere to go. Leave it None when something else consumes the exchange — the delayed-retry chain of :func:~tempest_fastapi_sdk.queue.retry_queues is the case: its retry queue is bound there, and a second queue under the same key would receive a duplicate of every failure.

Attributes:

Name Type Description
exchange str

The exchange rejected messages are published to. Declared by :meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_topology.

routing_key str | None

Routing key to use when dead-lettering. None keeps the message's original key. With fan-out that key is the event's, shared by every consumer of it, so a dead-letter queue bound by it would collect the failures of all of them; :meth:QueueSpec.consumer sets it to the queue name instead.

queue str | None

The dead-letter queue to declare and bind to :attr:exchange under :attr:routing_key, or None to declare only the exchange. Requires :attr:routing_key: an unset key binds nothing predictable.

ExchangeSpec dataclass

ExchangeSpec(name: str, kind: ExchangeKindEnum = TOPIC, durable: bool = True)

An exchange to publish to or bind a queue to.

Attributes:

Name Type Description
name str

The exchange name.

kind ExchangeKindEnum

The exchange type.

durable bool

Whether it survives a broker restart. True, because a non-durable exchange vanishes on restart and takes every binding to it along, so the queues behind it stop receiving with nothing reporting it.

ExchangeBinding dataclass

ExchangeBinding(exchange: ExchangeSpec, routing_key: str)

Bind a queue to an exchange under a routing key.

This is what turns one published event into one copy per consumer: each consumer's queue is bound to the same exchange with the same key, and the broker delivers to every bound queue. Without a binding, two consumers subscribing to the same queue name share one queue and split the messages between them instead.

Attributes:

Name Type Description
exchange ExchangeSpec

The exchange to bind to. Declared when the subscriber starts.

routing_key str

The key (a pattern, on a topic exchange) the queue receives.

ExchangeKindEnum

Bases: BaseStrEnum

AMQP exchange type.

Mirrors faststream.rabbit.ExchangeType value for value, so the topology module imports nothing from FastStream and stays importable without the [queue] extra.

Attributes:

Name Type Description
TOPIC

Routes by pattern (task.*). The default, because it subsumes a direct exchange — an exact key is a pattern with no wildcards — and lets a consumer subscribe to a family of events later without re-declaring anything.

DIRECT

Routes by exact key.

FANOUT

Ignores the key; every bound queue gets a copy.

HEADERS

Routes by message headers.

OffsetResetEnum

Bases: BaseStrEnum

Where a Kafka consumer group starts when it has no committed offset.

Only read when the group has never committed on a partition (a new group, or offsets expired by the broker's retention). A group that committed resumes from its commit whatever this says.

Attributes:

Name Type Description
LATEST

Start at the end — only records written after the consumer joined are read. Kafka's and FastStream's default, and the reason a brand-new consumer misses everything that was published before its first deploy.

EARLIEST

Start at the oldest record the topic still retains.

NONE

Refuse to start without a committed offset.

QueueTypeEnum

Bases: BaseStrEnum

RabbitMQ queue implementation.

Attributes:

Name Type Description
CLASSIC

The default. One queue master, mirrored only if a policy says so.

QUORUM

Raft-replicated across nodes. Survives the loss of a node without the message loss classic mirroring can suffer, at the cost of memory and of not supporting x-max-priority — which is why combining it with :attr:QueueSpec.max_priority raises. Message TTL is supported, so the delayed-retry chain built by :func:~tempest_fastapi_sdk.queue.retry_queues works on quorum queues. Reach for it once losing a message matters more than the extra resources.

TransportEnum

Bases: BaseStrEnum

Which broker a :class:QueueSpec is being translated for.

Detected from the FastStream broker class rather than recorded at construction, so a :class:~tempest_fastapi_sdk.queue.MessageBroker built by injecting a broker directly is classified the same way as one built through a transport constructor.

UnsupportedTopologyError

Bases: RuntimeError

A :class:QueueSpec asks for something the transport cannot do.

Raised where the queue is bound — :meth:~MessageBroker.on, :meth:~MessageBroker.publisher, :meth:~MessageBroker.register — which is startup, not per message, so the mismatch surfaces on the first run rather than as a queue that quietly lacks the property you declared. :meth:~MessageBroker.publish only reads the name, since the topology belongs to the declaration and not to the message.

ConsumerRetryPolicy dataclass

ConsumerRetryPolicy(
    max_attempts: int = DEFAULT_MAX_ATTEMPTS, delay_ms: int = DEFAULT_RETRY_DELAY_MS
)

How many times to retry a failing consumer, and how long to wait.

Attributes:

Name Type Description
max_attempts int

Total deliveries, including the first. 1 disables retrying and sends the first failure straight to the dead queue.

delay_ms int

Milliseconds a message waits before being offered again.

RetryTopology dataclass

RetryTopology(
    main: QueueSpec,
    retry: QueueSpec,
    dead: QueueSpec,
    channel: str,
    main_exchange: str,
    retry_exchange: str,
    dead_exchange: str,
)

The three queues a retried channel needs.

Carries the exchange names as well as the queues, because the queues alone are not a working topology: each has to be bound to its exchange, and a chain declared without the bindings routes a rejected message into an exchange with nothing behind it — where RabbitMQ silently drops it. See :meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_retry_topology.

Attributes:

Name Type Description
main QueueSpec

What the consumer subscribes to. Dead-letters to the retry exchange when the handler rejects.

retry QueueSpec

The waiting room. Holds nothing but a TTL; when a message expires it is dead-lettered back to the main exchange, which is what makes the delay work without a plugin.

dead QueueSpec

Terminal. Nothing routes out of it — it is read by a human, or by the admin panel.

channel str

The routing key every binding uses.

main_exchange str

Exchange the main queue is bound to.

retry_exchange str

Exchange the retry queue is bound to.

dead_exchange str

Exchange the dead queue is bound to.

retry_queues

retry_queues(
    channel: str,
    policy: ConsumerRetryPolicy | None = None,
    *,
    retry_exchange: str,
    main_exchange: str,
    dead_exchange: str,
    queue_type: QueueTypeEnum = CLASSIC,
) -> RetryTopology

Build the delayed-retry topology for channel.

RabbitMQ has no per-message delay of its own. The portable way to get one is a pair of queues: the main queue dead-letters a rejected message into a retry queue whose only job is to hold it, and that queue's TTL dead-letters it back to the main exchange when it expires. The message therefore reappears at the consumer delay_ms later, with the broker doing the waiting — so a worker restart in the meantime changes nothing.

The alternative is the rabbitmq_delayed_message_exchange plugin, which is simpler to declare and requires the plugin installed — not available on several managed offerings, including the free CloudAMQP tier. This builds on stock AMQP instead.

Parameters:

Name Type Description Default
channel str

The channel the consumer subscribes to.

required
policy ConsumerRetryPolicy | None

Attempts and delay. Defaults to :class:ConsumerRetryPolicy.

None
retry_exchange str

Exchange the main queue dead-letters to.

required
main_exchange str

Exchange the retry queue returns messages to. Must route back to channel.

required
dead_exchange str

Exchange the terminal queue is fed from.

required
queue_type QueueTypeEnum

Queue implementation for all three.

CLASSIC

Returns:

Name Type Description
RetryTopology RetryTopology

The three specs, ready to declare and subscribe.

Notes

max_attempts is not enforced by this topology — AMQP counts redeliveries in the x-death header but will not stop on its own. The count is enforced by the consumer middleware (:func:make_dead_letter_middleware), which reads that header and routes to the dead queue once the budget is spent. Declaring the topology without installing the middleware yields infinite retries, which is why they are documented together.

delivery_attempt

delivery_attempt(message: object) -> int

Return which delivery this is, counting from 1.

RabbitMQ records every dead-lettering in the message's x-death header, so the number of times a message has already been rejected is readable without any state of our own — which matters, because a consumer restart must not reset the budget.

Entries whose reason is "expired" are skipped, and that is load-bearing rather than a detail. RabbitMQ keeps one entry per (queue, reason) pair, and the delayed-retry chain dead-letters a message twice per round: once out of the main queue (rejected) and once out of the retry queue when its TTL fires (expired). Summing every entry therefore advanced the counter by two per retry, so a max_attempts=3 policy gave up after two deliveries. An expiry is the waiting room emptying itself, not a delivery that failed.

Parameters:

Name Type Description Default
message object

The FastStream message being consumed.

required

Returns:

Name Type Description
int int

1 on first delivery, 2 on the first retry, and so

int

on. Falls back to 1 when the header is absent or malformed,

int

so an unreadable header costs an extra attempt rather than

int

dropping the message early.

QueueMetrics

QueueMetrics(registry: CollectorRegistry | None = None)

Prometheus counters and durations for consumed messages.

Mirrors :class:~tempest_fastapi_sdk.tasks.TaskMetrics so the event path and the task path graph the same way, on the same registry and the same /metrics endpoint:

  • queue_messages_total{channel,status} — status is ok, error, or duplicate for a delivery :meth:~tempest_fastapi_sdk.queue.MessageBroker.deduplicate rejected because a sibling worker held the claim. Its own label keeps a normal dedup outcome out of the error rate an alert reads.
  • queue_message_duration_seconds{channel} — handler wall time.

Without this, the consumer failure rate is invisible: the message is rejected, the broker discards or dead-letters it, and nothing counts.

Register the two collectors.

Parameters:

Name Type Description Default
registry CollectorRegistry | None

Registry to register on. None uses the SDK's shared one, so the series appear on the same /metrics as everything else.

None

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

middleware

middleware() -> type[BaseMiddleware]

Build the FastStream middleware that feeds these collectors.

Returns:

Type Description
type[BaseMiddleware]

type[BaseMiddleware]: A faststream.BaseMiddleware subclass.

Raises:

Type Description
ImportError

When the [queue] extra is not installed.

DedupStore

Bases: Protocol

Where processed message ids are remembered.

Three operations, because two-phase marking needs them. :meth:claim must be atomic — two workers claiming the same id concurrently must not both receive :attr:DedupStateEnum.NEW, which is why it is one call rather than a get followed by a set.

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Mark key in-flight if it is unseen, and report what it was.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

What the store held before this call.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key as successfully processed.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Forget key so a later delivery processes it again.

Parameters:

Name Type Description Default
key str

The message id.

required

DedupStateEnum

Bases: BaseStrEnum

What the store knew about a message id when it was claimed.

Attributes:

Name Type Description
NEW

Never seen. The handler runs.

IN_FLIGHT

Another delivery of the same id is being processed. The handler does not run and the message is rejected, so the retry topology offers it again later — by which time the other worker has either finished (DONE, skip) or died (key expired, re-run).

DONE

Already processed successfully. The handler does not run and the message is acknowledged.

MemoryDedupStore dataclass

MemoryDedupStore(entries: MutableMapping[str, tuple[str, float]] = dict())

In-process :class:DedupStore, for one replica and for tests.

Correct only while a single process consumes the channel — two replicas each keep their own table and neither sees the other's claims, so a redelivery routed to the sibling runs the handler again. Use :class:RedisDedupStore for anything with more than one worker.

Attributes:

Name Type Description
entries MutableMapping[str, tuple[str, float]]

Key to (marker, expires_at).

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Claim key, reporting what the store already held.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

The prior state.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key done.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Drop key.

Parameters:

Name Type Description Default
key str

The message id.

required

RedisDedupStore

RedisDedupStore(client: Any, *, prefix: str = 'tempest:dedup:')

:class:DedupStore backed by an async redis client.

:meth:claim is a single SET key in_flight NX EX ttl, so the atomicity two-phase marking depends on comes from Redis rather than from a lock of our own — two workers racing on the same id cannot both be told NEW.

Wrap a Redis client.

Parameters:

Name Type Description Default
client Any

An async redis.asyncio.Redis-compatible client exposing set, get and delete.

required
prefix str

Key namespace, so dedup keys never collide with the application's own.

'tempest:dedup:'

claim async

claim(key: str, *, ttl_seconds: int) -> DedupStateEnum

Claim key atomically via SET NX.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long the mark lives.

required

Returns:

Name Type Description
DedupStateEnum DedupStateEnum

The prior state. A lost race reads the current

DedupStateEnum

value to tell IN_FLIGHT from DONE; a key that expires

DedupStateEnum

between the two calls reads as DONE, which skips one

DedupStateEnum

message rather than running it twice — the safer way to be

DedupStateEnum

wrong for a handler that is not free to repeat.

complete async

complete(key: str, *, ttl_seconds: int) -> None

Mark key done.

Parameters:

Name Type Description Default
key str

The message id.

required
ttl_seconds int

How long to remember it.

required

release async

release(key: str) -> None

Drop key.

Parameters:

Name Type Description Default
key str

The message id.

required

ConcurrentDeliveryError

Bases: RuntimeError

The same message id is already being processed elsewhere.

Raised so the broker rejects the duplicate rather than acknowledging it. Acknowledging would be the dangerous choice: the in-flight worker may still fail, and the copy that could have retried would be gone.

consume_span

consume_span(channel: str, headers: dict[str, Any] | None = None)

Span around one consumed message, linked to the publishing trace.

Follows the OpenTelemetry messaging semantic conventions: messaging.system, messaging.destination.name and messaging.operation, with the span named "<channel> process".

The publishing trace is attached as a link, not as a parent. The convention recommends it for asynchronous consumption, and the reason is practical: a consumer can run minutes after the publish, and a child span of that duration would stretch the request's trace and make its latency unreadable. A link keeps both traces truthful and still lets you jump between them.

Restores the publisher's request id for the duration of the block, so the worker's log lines carry the id of the request that caused them — which is worth more than the span to anyone debugging with grep.

Prepare a span for a message on channel.

Parameters:

Name Type Description Default
channel str

The queue/topic the message arrived on.

required
headers dict[str, Any] | None

The message headers, read for the trace context and the request id.

None

inject_context

inject_context(headers: dict[str, Any]) -> dict[str, Any]

Add the current trace context and request id to headers.

Parameters:

Name Type Description Default
headers dict[str, Any]

Headers being assembled for a publish. Mutated in place and returned, for the caller's convenience.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The same mapping. Unchanged when no trace is

dict[str, Any]

active and no request id is set, so a publish outside a request

dict[str, Any]

carries no empty headers.

extract_context

extract_context(headers: dict[str, Any]) -> Any | None

Recover the publishing trace context from headers.

Parameters:

Name Type Description Default
headers dict[str, Any]

The consumed message's headers.

required

Returns:

Type Description
Any | None

Any | None: An OpenTelemetry Context, or None when the

Any | None

extra is missing or the message carries no traceparent.