faststream-gcp-pubsub
A Google Cloud Pub/Sub broker for FastStream, maintained by the community.
from faststream import FastStream
from pydantic import BaseModel
from faststream_gcp_pubsub import PubSub, PubSubBroker
class Order(BaseModel):
id: int
amount: float
broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)
shipments = broker.publisher("shipments")
@broker.subscriber(PubSub("orders-billing"), topic="orders")
@shipments
async def bill(order: Order) -> dict[str, int]:
# the return value is published to the `shipments` topic
return {"order_id": order.id}
@app.after_startup
async def place_order() -> None:
await broker.publish(Order(id=1, amount=9.5), "orders")
faststream run service:app
The handler reads the orders-billing subscription of the orders topic, decodes the JSON body
into Order, acknowledges the message once the handler returns, and publishes its result to
shipments.
Install
pip install faststream-gcp-pubsub
The package needs Python 3.10 or newer and FastStream 0.7. Extras: otel (OpenTelemetry),
prometheus, cli (the faststream command).
Features
Topics and subscriptions
Pub/Sub keeps topics and subscriptions as separate resources: a publisher names a topic, a
subscriber names a subscription attached to a topic. Short ids are expanded with the broker's
project; a full name (projects/other/subscriptions/x) is used as it is.
@broker.subscriber("orders-billing", topic="orders")
async def bill(order: dict[str, int]) -> None: ...
A subscription named without a topic is taken as attached to the topic of the same name.
Declaring resources
The broker creates nothing by default. A declaration with declare=True creates the topic and
the subscription at startup when they do not exist, with the settings you give:
from datetime import timedelta
from faststream import FastStream
from faststream_gcp_pubsub import (
DeadLetterPolicy,
PubSub,
PubSubBroker,
PubSubTopic,
RetryPolicy,
)
broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)
orders = PubSubTopic(
"orders",
declare=True,
labels={"team": "billing"},
message_retention_duration=timedelta(days=1),
)
billing = PubSub(
"orders-billing",
declare=True,
ack_deadline_seconds=30,
enable_message_ordering=True,
enable_exactly_once_delivery=True,
filter='attributes.region = "eu"',
dead_letter_policy=DeadLetterPolicy("orders-dead", max_delivery_attempts=5),
retry_policy=RetryPolicy(
minimum_backoff=timedelta(seconds=10),
maximum_backoff=timedelta(seconds=300),
),
message_retention_duration=timedelta(days=2),
labels={"team": "billing"},
)
@broker.subscriber(billing, topic=orders)
async def bill(order: dict[str, int]) -> None: ...
The dead-letter topic is created too. An existing subscription keeps its own settings.
broker.declare_topic(...) and broker.declare_subscription(...) create resources by hand.
Publishing
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")
Headers travel as message attributes. FastStream adds correlation_id, content-type and,
when set, reply_to. publish returns the message id the service assigned; publish_batch
sends all messages in one request (at most 1000 messages and 10 MB).
A publisher object keeps defaults for every call:
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")
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 (await each call): concurrent
calls reach the service in any order.
Acknowledgement
The subscriber acknowledges a message when its handler returns and nacks it when the handler
raises (AckPolicy.NACK_ON_ERROR). A failed message is redelivered under the subscription's
retry policy and moves to its dead-letter topic after the last attempt. With
ack_policy=AckPolicy.MANUAL, msg.ack(), msg.nack() and msg.reject() settle by hand;
reject acknowledges, as Pub/Sub has no reject.
Acks and nacks of one subscription are sent together, one request per 50 ms or per 1000 ids.
On a subscription with exactly-once delivery, ack() waits for the service's confirmation and
raises on a failure. msg.delivery_attempt counts deliveries on a subscription with a
dead-letter policy.
Leases and flow control
The subscriber reads through a streaming pull and keeps each message leased: it extends the ack
deadline of every message in work until the handler settles it, up to max_lease. Flow control
bounds what is held at once:
from faststream import FastStream
from faststream_gcp_pubsub import FlowControl, PubSubBroker
broker = PubSubBroker(project_id="my-project", graceful_timeout=30.0)
app = FastStream(broker)
@broker.subscriber(
"orders-billing",
topic="orders",
flow_control=FlowControl(
max_messages=100,
max_bytes=10 * 1024 * 1024,
ack_deadline=60,
max_lease=1800.0,
ack_batch_wait=0.05,
),
max_workers=10,
)
async def bill(order: dict[str, int]) -> None: ...
max_workers handles that many messages at once. On shutdown the subscriber stops reading,
waits for handlers in work up to the broker's graceful_timeout, sends the pending acks and
returns the messages it still holds to the service.
Replies
A message published with reply_to="<topic>" gets the handler's return value published to that
topic. PubSubResponse sets the reply's ordering key and headers (attributes):
@broker.subscriber("jobs-worker", topic="jobs")
async def run(job: dict[str, str]) -> PubSubResponse:
return PubSubResponse(
{"done": True},
headers={"worker": "w1"},
ordering_key=job["owner"],
)
broker.request() raises FeatureNotSupportedException: Pub/Sub has no reply channel of its
own, so a reply is a message on a topic the caller subscribes to.
Testing
TestPubSubBroker runs the broker in process, with no service behind it:
@pytest.mark.asyncio()
async def test_service() -> None:
async with TestPubSubBroker(broker) as br:
await br.publish(Order(id=1, amount=9.5), "orders")
bill.mock.assert_called_once_with({"id": 1, "amount": 9.5})
shipments.mock.assert_called_once_with({"order_id": 1})
It routes like the service: a topic delivers to every subscription attached to it, consumers of
one subscription share its messages, and a subscription read by get_one() keeps messages until
they are read. A publish the service would reject (attribute names and sizes, ordering key size,
message and request size, resource id format) raises the service's InvalidArgument.
Emulator
The broker connects to the Pub/Sub emulator
when PUBSUB_EMULATOR_HOST is set or emulator_host="localhost:8085" is passed, with no
credentials.
Credentials
The broker authenticates with Application Default Credentials. GCPSecurity passes other
credentials:
def from_key_file() -> PubSubBroker:
return PubSubBroker(
project_id="my-project",
security=GCPSecurity.from_service_account_file("key.json"),
)
api_endpoint="europe-west1-pubsub.googleapis.com:443" selects a regional endpoint.
FastAPI
from fastapi import FastAPI
from faststream_gcp_pubsub.fastapi import PubSubRouter
router = PubSubRouter(project_id="my-project")
@router.subscriber("orders-billing", topic="orders")
async def bill(order: dict[str, int]) -> None: ...
@router.post("/orders")
async def place_order(order: dict[str, int]) -> str:
return await router.broker.publish(order, "orders")
app = FastAPI()
app.include_router(router)
Observability and AsyncAPI
faststream_gcp_pubsub.opentelemetry.PubSubTelemetryMiddleware and
faststream_gcp_pubsub.prometheus.PubSubPrometheusMiddleware follow FastStream's middlewares.
faststream docs serve service:app serves the AsyncAPI document: subscribers appear with their
subscription and topic, publishers with their topic.
Development
See CONTRIBUTING.md. The source lives at https://github.com/powersemmi/faststream-gcp-pubsub.
License
Apache License 2.0. The shared broker testcases under tests/ are adapted from FastStream, under
the same license (see tests/NOTICE).
Metadata
Release files for faststream-gcp-pubsub 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| faststream_gcp_pubsub-0.2.0.tar.gz | 42.8 kB | With provenance | Details for faststream_gcp_pubsub-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| faststream_gcp_pubsub-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for faststream_gcp_pubsub-0.2.0-py3-none-any.whl |
Total release size: 97.3 kB
Release files / faststream_gcp_pubsub-0.2.0.tar.gz
| Download URL | faststream_gcp_pubsub-0.2.0.tar.gz |
|---|---|
| Size | 42.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c0d701e5342d1af422f738944d885cd9d3b38bd907fb5a2a1113b974d1fec947
|
|
BLAKE2b-256 checksum How to use checksums |
77cdb22b59d36ed8f688cbb406a9ad7a1f118bf9b514457056341b35866d8caf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.
Transparency logRelease files / faststream_gcp_pubsub-0.2.0-py3-none-any.whl
| Download URL | faststream_gcp_pubsub-0.2.0-py3-none-any.whl |
|---|---|
| Size | 54.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5d6f7fe241111801353989ccdfaf30ea9bc430964452be04cd0dc620dc97b47c
|
|
BLAKE2b-256 checksum How to use checksums |
ce654edcd6f99a8ff032dbfa1b605eecaf61433d36edc3f4ffe11bf9e800b8c2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.
Transparency logSecurity for faststream-gcp-pubsub 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for faststream_gcp_pubsub-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.