Consuming#
A handler is a function decorated with @broker.subscriber. It receives the decoded body and
any FastStream dependencies.
import logging
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker, SqsMessage
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)
@broker.subscriber("orders")
async def bill(order: dict[str, int], msg: SqsMessage) -> None:
# how many times SQS handed this message out, this delivery included
if msg.receive_count > 1:
logger.info(
"order %s: delivery %d from %s, sent at %s",
order["id"],
msg.receive_count,
msg.queue,
msg.sent_timestamp,
)
msg is the SqsMessage of the delivery. It carries receive_count, message_group_id,
sent_timestamp and queue. The attributes of the message are its headers.
Polling#
A subscriber long-polls its queue: each receive waits up to wait_time seconds (20 by default)
for a message. FlowControl(polls=...) runs several poll loops at once. A poll asks only for the
free slots of the in-flight cap, so a slow
handler stops the polling and messages never age unseen.
When a poll fails with a retryable error (throttling, a timeout, a connection failure), the subscriber logs a warning and retries with a growing delay, from 0.1 to 10 seconds with jitter. The delay resets on the first poll that succeeds. A queue that does not exist, or access that the service denies, stops the subscriber with an error log.
Acknowledgement#
The default policy is AckPolicy.NACK_ON_ERROR: the message is deleted when the handler returns
and made visible again when it raises. SQS maps the settlements this way:
| Settlement | What SQS does |
|---|---|
| ack | The message is deleted. |
| nack | The visibility timeout is set to zero and the message is available at once. Its receive count grows. |
| reject | The message is deleted. SQS has no reject. |
A failed message returns to the queue until its receive count passes the redrive policy and the queue moves it to the dead-letter queue. That is how a poison message leaves a queue.
The policy is set per subscriber with ack_policy= or for the broker with
CapoSqsBroker(ack_policy=...). Each message settles once; a later call does nothing.
Settlements are batched: deletes and visibility changes go out when 10 are waiting or 50 ms after
the first, whichever comes first. ack() returns once the entry is queued and does not wait for
the service.
Manual settlement#
With AckPolicy.MANUAL the handler settles the message.
from faststream import AckPolicy, FastStream
from faststream_sqs_sns import CapoSqsBroker, SqsMessage
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
@broker.subscriber("orders", ack_policy=AckPolicy.MANUAL)
async def bill(order: dict[str, int], msg: SqsMessage) -> None:
if order["amount"] < 0:
# deleted without redelivery
await msg.reject()
elif order["amount"] == 0:
# visible again at once; its receive count grows
await msg.nack()
else:
await msg.ack()
Receive count#
msg.receive_count counts how many times SQS handed the message out, the current delivery
included. A handler may use it to stop retrying a message that keeps failing.
SQS can also hand a message out without a handler ever seeing it. A receive that the service
answered but the client never read leaves up to 10 messages invisible until their visibility
timeout runs out, and they return with receive_count + 1. This happens when a poll is cancelled
in flight, and when the SDK retries a ReceiveMessage after a 5xx response. Any SQS client
behaves this way. The redrive count includes these receives, so set max_receive_count with some
room.
Batch subscribers#
With batch=True the messages of one receive reach the handler as one list, at most
max_messages of them. The handler's msg is an SqsBatchMessage; receive_counts and
message_group_ids hold the per-message fields, and ack(), nack() and reject() settle every
message of the batch.
import logging
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker, SqsQueue
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)
# the messages of one receive (up to `max_messages`) arrive as one list
@broker.subscriber(SqsQueue("orders", max_messages=10), batch=True)
async def bill(orders: list[dict[str, int]]) -> None:
logger.info("%d orders", len(orders))
Concurrency#
By default a subscriber handles one message at a time. max_workers handles that many at once.
On a FIFO queue the messages of one group still run in
order.
A batch subscriber (batch=True) handles one batch at a time, as upstream FastStream's batch
subscribers do: it ignores max_workers and warns with a RuntimeWarning. More batches run in
parallel with more poll loops, FlowControl(polls=...): each loop hands its own receive to the
handler.
Reading messages without a handler#
A subscriber without a handler is read by hand. get_one receives one message and returns
None when none arrives within the timeout. The message is held and its visibility extended like
any other.
from typing import Any
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
# a subscriber without a handler is read by hand
orders = broker.subscriber("orders")
async def read_one() -> Any | None:
message = await orders.get_one(timeout=5.0)
if message is None:
return None
order = await message.decode()
await message.ack()
return order
Iterating the subscriber reads a stream of messages:
from typing import Any
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
orders = broker.subscriber("orders")
async def read_all() -> list[Any]:
received: list[Any] = []
async for message in orders:
received.append(await message.decode())
await message.ack()
if len(received) == 3:
break
return received
The messages are settled by hand, as no handler stands behind them.
The SNS JSON envelope#
A queue subscribed to a topic with raw delivery receives the message as it was published. The
broker subscribes a declared queue that way. A queue that someone else subscribed without raw
delivery receives an SNS envelope: a JSON document whose Message field holds the body and whose
MessageAttributes field holds the attributes.
The broker leaves the envelope as it is. A custom parser unwraps it. The parser calls the
original parser first and then replaces the body and the headers:
import json
import logging
from collections.abc import Awaitable, Callable
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker, SqsMessage, SqsQueue
from faststream_sqs_sns.message import SqsRawMessage
async def unwrap_sns(
raw: SqsRawMessage,
original_parser: Callable[[SqsRawMessage], Awaitable[SqsMessage]],
) -> SqsMessage:
"""Read the SNS JSON envelope of a queue subscribed without raw delivery."""
message = await original_parser(raw)
envelope = json.loads(message.body) # ruff: ignore[banned-api]
if isinstance(envelope, dict) and envelope.get("Type") == "Notification":
message.body = str(envelope["Message"]).encode()
for name, attribute in envelope.get("MessageAttributes", {}).items():
message.headers[name] = attribute["Value"]
return message
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)
# the queue is subscribed to the topic elsewhere, with raw delivery off
@broker.subscriber(SqsQueue("audit"), parser=unwrap_sns)
async def audit(event: dict[str, str], msg: SqsMessage) -> None:
logger.info("%s %s", event, msg.headers.get("origin"))
The handler receives the inner message and the attributes of the envelope as headers:
notification = {
"Type": "Notification",
"Message": json.dumps({"kind": "created"}),
"MessageAttributes": {"origin": {"Type": "String", "Value": "shop"}},
}
async with TestSqsBroker(envelope.broker) as br:
await br.publish(notification, "audit")
envelope.audit.mock.assert_called_once_with({"kind": "created"})
parser= on the broker applies the parser to every subscriber.
Shutdown#
Cancelling a long poll does not cancel it on the server: a message the server hands to the dead
request stays invisible until its visibility timeout. So stop() works in this order:
- No subscriber issues a new
ReceiveMessage. Every subscriber stops at the same time. - Messages received before the stop and still waiting for a worker go back to the queue at once, with visibility 0.
- Polls in flight and running handlers are awaited together, under one deadline: the broker's
graceful_timeout. A message that a poll returns after the stop goes back at once, with visibility 0, and never reaches a handler. - When the deadline passes, the polls and handlers still running are cancelled.
- The pending deletes and visibility changes are sent, and any message still held goes back, before the clients close.
So stop() takes at most graceful_timeout plus the last settlement calls: one batch call per 10
pending entries, sent concurrently. graceful_timeout is 25 seconds by default, so one 20-second
long poll finishes within it, and the default fits the 30-second grace period of Kubernetes. A
poll cancelled at the deadline leaves its messages invisible until their visibility timeout. The
stop log names how many polls were cancelled.