Skip to content

Publishing#

publish sends one message and returns the message id the service assigned. publish_batch sends several messages in one request and returns their ids.

service.py
from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)


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


async def place_orders() -> None:
    message_id = await broker.publish(
        {"id": 1},
        "orders",
        headers={"region": "eu"},
        ordering_key="customer-42",
        correlation_id="req-1",
    )
    ids = await broker.publish_batch({"id": 2}, {"id": 3}, topic="orders")
    assert isinstance(message_id, str)
    assert len(ids) == 2

A batch takes at most 1000 messages and 10 MB.

Attributes#

Headers travel as message attributes. Values are strings on the wire, so another value type is sent as its str(). FastStream adds correlation_id, content-type and, when set, reply_to.

Ordering keys#

Messages with one ordering key reach a subscription with enable_message_ordering=True in the order the service received them. Publish them one after another, awaiting each call: concurrent calls reach the service in any order.

Message ids#

publish returns the id of the message and publish_batch returns a list of ids in the order of the messages. The consumer reads the id from msg.raw_message.message_id.

Publisher objects#

A publisher object keeps the topic and the defaults for every call.

service.py
from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)


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


orders = broker.publisher(
    "orders",
    ordering_key="customer-42",
    headers={"source": "api"},
)


# a publisher object keeps its defaults for every call
async def place_order() -> None:
    await orders.publish({"id": 1})
    await orders.publish({"id": 2}, ordering_key="customer-43")

A call can replace the ordering key. Attributes given to a call are added to the publisher's.

Decorate a handler with a publisher to publish its return value, as the home page does with @shipments.

Limits of the service#

The service rejects a message with too many or too long attributes, an ordering key above 1024 bytes, or a body above 10 MB. The error is the service's InvalidArgument. The test broker raises the same error.