Skip to content

Consuming#

A handler is a function decorated with @broker.subscriber. It receives the decoded body and any FastStream dependencies.

service.py
from faststream import FastStream, Header, Logger

from faststream_gcp_pubsub import PubSubBroker, PubSubMessage

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


@broker.subscriber("orders-billing", topic="orders")
async def bill(
    order: dict[str, int],
    msg: PubSubMessage,
    logger: Logger,
    region: str = Header(default="eu"),
) -> None:
    logger.info(
        "order %s from %s: message %s, key %r, published %s",
        order["id"],
        region,
        msg.raw_message.message_id,
        msg.ordering_key,
        msg.raw_message.publish_time,
    )

msg is the PubSubMessage of the delivery. Its ordering_key and delivery_attempt properties and the raw_message (message_id, publish_time, attributes, data) describe what the service sent. Attributes are also available as headers.

Acknowledgement#

The default policy is AckPolicy.NACK_ON_ERROR: the message is acknowledged when the handler returns and nacked when it raises. Pub/Sub maps the settlements this way:

Settlement What Pub/Sub does
ack The message is acknowledged and not delivered again.
nack The ack deadline is set to zero and the message is available for redelivery at once.
reject The message is acknowledged. Pub/Sub has no reject.

A failed message is redelivered under the subscription's retry policy and moves to its dead-letter topic after the last attempt. That is how a poison message leaves a subscription.

The policy is set per subscriber with ack_policy= or for the broker with PubSubBroker(ack_policy=...).

Manual settlement#

With AckPolicy.MANUAL the handler settles the message.

service.py
from faststream import AckPolicy, FastStream

from faststream_gcp_pubsub import PubSubBroker, PubSubMessage

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


@broker.subscriber("orders-billing", topic="orders", ack_policy=AckPolicy.MANUAL)
async def bill(order: dict[str, int], msg: PubSubMessage) -> None:
    if order["amount"] < 0:
        # Pub/Sub has no reject: the message is acknowledged and dropped
        await msg.reject()
    elif order["amount"] == 0:
        # available for redelivery at once
        await msg.nack()
    else:
        await msg.ack()

Delivery attempts#

msg.delivery_attempt counts the deliveries of a message. The service fills it when the subscription has a dead-letter policy and the value is 0 otherwise.

service.py
from faststream import FastStream, Logger

from faststream_gcp_pubsub import (
    DeadLetterPolicy,
    PubSub,
    PubSubBroker,
    PubSubMessage,
)

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

billing = PubSub(
    "orders-billing",
    declare=True,
    dead_letter_policy=DeadLetterPolicy("orders-dead", max_delivery_attempts=5),
)


@broker.subscriber(billing, topic="orders")
async def bill(order: dict[str, int], msg: PubSubMessage, logger: Logger) -> None:
    # counts deliveries; it is 0 on a subscription without a dead-letter policy
    logger.info("attempt %d of order %s", msg.delivery_attempt, order["id"])
    if msg.delivery_attempt < 3:
        error = "retry later"
        raise ValueError(error)

Reading messages without a handler#

A subscriber without a handler is read by hand. get_one pulls one message and returns None when none arrives within the timeout.

service.py
from typing import Any

from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

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

# a subscriber without a handler is read by hand
orders = broker.subscriber("orders-billing", topic="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:

service.py
from typing import Any

from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

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

orders = broker.subscriber("orders-billing", topic="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.

Concurrency#

By default a subscriber handles one message at a time. max_workers handles that many at once.

service.py
from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

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


# ten deliveries are handled at once
@broker.subscriber("orders-billing", topic="orders", max_workers=10)
async def bill(order: dict[str, int]) -> None: ...

max_workers works together with flow control: the subscriber reads at most max_messages messages that are not settled.