Skip to content

Publishing#

publish sends one message to a queue or publishes it to a topic and returns the message id the service assigned. publish_batch sends several messages and returns their ids.

service.py
from faststream import FastStream

from faststream_sqs_sns import CapoSqsBroker, SnsTopic

broker = CapoSqsBroker(region="eu-central-1", account_id="123456789012")
app = FastStream(broker)

orders = broker.publisher("orders", headers={"source": "api"})


@broker.subscriber("orders")
async def handle(order: dict[str, int]) -> None: ...


async def send() -> str:
    message_id = await broker.publish(
        {"id": 1},
        "orders",
        headers={"region": "eu"},
        correlation_id="req-1",
    )
    await broker.publish({"id": 2}, SnsTopic("events"))
    # a publisher object keeps its defaults for every call
    await orders.publish({"id": 3})
    return message_id

The destination is a queue (a name, a URL, an ARN or an SqsQueue) or a topic (an SnsTopic or a topic ARN). A publisher object, broker.publisher(...), keeps headers and message_group_id for every call and takes part in the AsyncAPI document.

A publish to a topic needs the topic's ARN. See Queues and topics for how a bare name is resolved.

Attributes#

Headers become SQS message attributes. A str is a String, bytes is a Binary, and int and float are a Number. bool and every other type raise TypeError at the call. A consumer reads String and Number attributes as str headers and Binary as bytes.

service.py
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 handle(order: dict[str, int], msg: SqsMessage) -> None:
    # str and number attributes arrive as str, binary attributes as bytes
    logger.info(
        "order %s: %s %s %s",
        order["id"],
        msg.headers.get("region"),
        msg.headers.get("priority"),
        msg.headers.get("trace"),
    )


async def send() -> None:
    await broker.publish(
        {"id": 1},
        "orders",
        headers={"region": "eu", "priority": 2, "trace": b"\x01\x02"},
    )

FastStream's own metadata travels as attributes too: correlation_id, content-type and, when set, reply_to. SQS allows 10 attributes per message, and the metadata and the encoding marker below count toward them. A message carries up to four of its own, so six headers always fit.

The test broker counts the attributes and raises like the service:

test_publishing.py
    async with TestSqsBroker(attributes.broker) as br:
        # eight headers, `correlation_id` and `content-type`: ten attributes
        await br.publish({"id": 1}, "orders", headers={f"h{i}": "v" for i in range(8)})

        with pytest.raises(SqsServiceError) as error:
            await br.publish(
                {"id": 1}, "orders", headers={f"h{i}": "v" for i in range(9)}
            )
        assert error.value.code == "InvalidParameterValue"

The real producer sends what you give it, and the service answers a message that breaks a limit.

Bodies#

SQS carries a body as text of a restricted character set. The broker sends a body as it is when it is valid UTF-8 within that set. Any other body (binary data, or text with a control character) goes as base64 with the attribute faststream-encoding=base64, and the consumer decodes it back to the bytes you published.

SQS refuses an empty body. An empty message goes out as a one-character stand-in with faststream-encoding=empty, and the handler receives b"". The marker takes one of the ten attributes. The consumer does not show it among the headers.

service.py
import logging

from faststream import FastStream

from faststream_sqs_sns import CapoSqsBroker

broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)


@broker.subscriber("blobs")
async def handle(body: bytes) -> None:
    logger.info("%d bytes", len(body))


async def send() -> None:
    # not valid UTF-8: sent as base64 with the `faststream-encoding` attribute
    await broker.publish(b"\x00\xff\x10", "blobs")
    # SQS refuses an empty body: a stand-in goes out and the handler still gets b""
    await broker.publish(b"", "blobs")

A message may be up to 1 MiB with its attributes on SQS and 256 KiB on SNS.

Batches#

publish_batch sends the messages in chunks of 10. To a standard queue or topic the chunks go out concurrently. To a FIFO queue or topic they go out one after another, so a message group keeps the order of the call. It returns the ids in the order of the messages.

When the service refuses some entries, publish_batch finishes every chunk and then raises BatchPublishError. Its message_ids list holds the id of each sent message and None for each failed one. Its failures list holds the index, the code and the text of each failure. Nothing is retried for you: a partial batch is a fact the caller decides on.

service.py
import logging

from faststream import FastStream

from faststream_sqs_sns import CapoSqsBroker
from faststream_sqs_sns.exceptions import BatchPublishError

broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)


@broker.subscriber("orders")
async def handle(order: dict[str, int]) -> None: ...


async def send_all(orders: list[dict[str, int]]) -> list[str | None]:
    try:
        return list(await broker.publish_batch(*orders, destination="orders"))
    except BatchPublishError as error:
        # the id of each sent message and None for each failed one, in the order of the call
        for failure in error.failures:
            logger.warning(
                "message %s failed: %s %s", failure.id, failure.code, failure.message
            )
        return error.message_ids

Delay#

delay hides a message from consumers for 0 to 900 seconds. It applies to standard queues. A FIFO queue takes a delay as a queue attribute, and a topic takes none, so delay on either raises.

service.py
from faststream import FastStream

from faststream_sqs_sns import CapoSqsBroker

broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)


@broker.subscriber("reminders")
async def remind(reminder: dict[str, str]) -> None: ...


async def schedule() -> None:
    # visible to consumers after 5 minutes; standard queues only, 0 to 900 seconds
    await broker.publish({"text": "pay the bill"}, "reminders", delay=300)

FIFO fields#

message_group_id and deduplication_id set the FIFO fields. See FIFO queues.

Errors#

Both backends raise the same exceptions, from faststream_sqs_sns.exceptions. The backend's own exception stays as __cause__.

Exception Meaning
SqsError The base of all the others. retryable tells whether repeating the call may succeed.
QueueNotFoundError The queue does not exist, or the caller may not see it.
TopicNotFoundError The topic does not exist, or the caller may not see it.
ThrottledError The service throttled the call. Retryable.
InvalidReceiptError A receipt handle is invalid or its message is no longer in flight.
ServiceUnavailableError A connection failure or a timeout. Retryable.
SqsServiceError Any other error of the service. code holds its error code.
BatchPublishError Some messages of a publish_batch were not sent.