Cloud Pub/Sub for Messaging and Event Streaming
What You'll Learn
- 1Describe the publish, persist, and acknowledge path and where each guarantee applies
- 2Choose pull or push delivery from throughput, retry, and infrastructure constraints
- 3Design ordering keys and dead-letter policies that survive poison messages
- 4Read lag metrics and turn them into alerts before a backlog becomes an outage
Pub/Sub Architecture
Pub/Sub decouples a producer from every consumer by giving both a named rendezvous point that neither has to be online for at the same instant. A publisher writes a message to a topic, the service durably persists replicas of it across zones, and each subscription independently accumulates its own cursor over that stream. Nothing about publishing requires knowing how many subscribers exist or how fast they drain, which is what makes fan-out to a dozen downstream services cost nothing in publisher latency.
The accounting that makes this work is the acknowledgement deadline. When a subscriber pulls a batch it receives an ack deadline, a countdown that starts between ten seconds and ten minutes; ack before it expires and the message is gone from that subscription, let it lapse and the message becomes eligible for redelivery. Nack shortens the deadline to ten seconds immediately, which is how a poison message is handed back quickly instead of stalling a whole batch.
Core Components
Topics:
- Named channels for message distribution
- Support for message filtering
- At-least-once delivery guarantee
- Global endpoint access
Subscriptions:
- Represent message delivery to subscribers
- Support for pull and push delivery
- Message acknowledgment mechanism
- Configurable retention periods
Messages:
- Immutable data payloads
- Custom attributes for metadata
- Message ordering keys
- Exactly-once delivery options
A subscription is a first-class durable object, not a connection. Deleting one discards its cursor and its retained backlog, while disconnecting a client merely stops pulling, so a new subscriber created after a topic has been running for months starts empty. Replaying history means pointing a fresh subscription at a retained window rather than asking the old one to rewind.
Topic and Subscription Management
Topic creation is cheap and safe to do ahead of need, because a topic with no subscriptions accumulates nothing beyond metadata. Message retention on the topic controls how far back a newly created subscription can go, and it is set per topic in seconds, so a late-arriving consumer can re-read a day of events without any producer cooperation. Subscription retention works the other way: it keeps unacked messages alive after they have been pulled but not yet acknowledged.
Creating Topics
# Create a topic
gcloud pubsub topics create my-topic
# Create a topic with labels
gcloud pubsub topics create my-topic \
--labels=env=production,team=data-engineering
# Create a topic with message retention
gcloud pubsub topics create my-topic \
--message-retention-duration=86400s # 1 day
Creating Subscriptions
# Create a pull subscription
gcloud pubsub subscriptions create my-subscription \
--topic=my-topic \
--ack-deadline=60
# Create a push subscription
gcloud pubsub subscriptions create my-push-subscription \
--topic=my-topic \
--push-endpoint=https://my-endpoint.example.com \
--ack-deadline=30
# Create a subscription with message retention
gcloud pubsub subscriptions create my-subscription \
--topic=my-topic \
--message-retention-duration=604800s # 7 days
Python Client Library
from google.cloud import pubsub_v1
import json
# Initialize publisher
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path('my-project', 'my-topic')
# Publish a message
data = json.dumps({
'event': 'user_signup',
'user_id': 'user_123',
'timestamp': '2024-01-15T10:30:00Z'
})
future = publisher.publish(
topic_path,
data.encode('utf-8'),
event_type='user_event',
source='web_app'
)
print(f'Published message ID: {future.result()}')
# Initialize subscriber
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path('my-project', 'my-subscription')
# Pull messages
response = subscriber.pull(
request={'subscription': subscription_path, 'max_messages': 10}
)
for message in response.received_messages:
print(f'Received message: {message.message.data}')
print(f'Attributes: {message.message.attributes}')
# Acknowledge the message
subscriber.acknowledge(
request={'subscription': subscription_path, 'ack_ids': [message.ack_id]}
)
Pull vs Push Subscriptions
Pull delivery puts the subscriber in control of flow: it opens a stream, asks for up to a thousand messages at a time, and acknowledges each one as its own work completes. Backpressure is then natural, because a slow worker simply stops asking for more, and batching is trivial, because hundreds of records arrive in one call ready to be written to BigQuery in a single insert. Every Dataflow, Dataproc, and Cloud Run worker is doing this under the hood.
Push inverts the direction. The service holds an HTTP endpoint and posts each message to it as a JSON envelope, which suits Cloud Run services, webhooks, and anything that already speaks HTTP. The endpoint must return a two hundred status to acknowledge; anything else, including a timeout, is a failure and is retried with exponential backoff. Push scales only as fast as your endpoint does, so it fits moderate volumes where running a listener costs more than it saves.
Pull Subscription
# Pull subscription example
from google.cloud import pubsub_v1
import concurrent.futures
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path('my-project', 'my-subscription')
def callback(message):
"""Process received message."""
print(f'Received message: {message.data}')
print(f'Message ID: {message.message_id}')
print(f'Attributes: {message.attributes}')
# Process the message
try:
process_message(message)
message.ack() # Acknowledge successful processing
except Exception as e:
message.nack() # Negative acknowledge for retry
# Subscribe to messages
future = subscriber.subscribe(subscription_path, callback=callback)
try:
future.result(timeout=300) # Listen for 5 minutes
except KeyboardInterrupt:
future.cancel()
print('Subscriber stopped.')
Push Subscription
# Push subscription endpoint
from flask import Flask, request
import json
app = Flask(__name__)
@app.route('/pubsub/push', methods=['POST'])
def pubsub_push():
"""Handle Pub/Sub push messages."""
envelope = request.get_json(silent=True)
if 'message' not in envelope:
return 'Bad request', 400
message = envelope['message']
data = json.loads(message['data'])
attributes = message.get('attributes', {})
# Process the message
process_message(data, attributes)
return 'OK', 200
def process_message(data, attributes):
"""Process the received message."""
print(f'Processing: {data}')
print(f'Attributes: {attributes}')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Comparison
| Feature | Pull Subscription | Push Subscription |
|---|---|---|
| Control | Subscriber controls when to fetch | Server sends messages automatically |
| Scalability | Better for high-throughput | Limited by endpoint capacity |
| Reliability | More control over retries | Depends on endpoint availability |
| Complexity | More complex to implement | Simpler implementation |
| Cost | Pay for pull operations | Pay for push operations |
Message Ordering
Ordering in Pub/Sub is opt-in and scoped to a key, never global. When a topic has message ordering enabled, every message sharing an ordering key is routed through one serial queue and delivered in publication order, while messages under different keys run in parallel. The cost of the guarantee is throughput: a key can only drain as fast as one subscriber processes it, so a hot key becomes a bottleneck the moment a subscriber falls behind.
Ordering and error handling also pull in opposite directions. A nack or a missed deadline while an ordered message is outstanding stops delivery for that key until redelivery settles, protecting sequence at the price of a stall, which is why ordered subscriptions pair with a dead-letter topic so a poison message is moved out instead of blocking everything behind it.
Message ordering ensures messages with the same ordering key are delivered in the order they were published.
Enabling Message Ordering
# Publish with ordering key
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path('my-project', 'my-ordered-topic')
# Messages with same ordering key are delivered in order
for i in range(10):
data = f'Message {i}'
future = publisher.publish(
topic_path,
data.encode('utf-8'),
ordering_key='user_123', # Same ordering key
sequence_number=str(i)
)
print(f'Published message {i}: {future.result()}')
# Create subscription with ordering
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path('my-project', 'my-ordered-subscription')
# Enable message ordering
subscription = subscriber.create_subscription(
request={
'name': subscription_path,
'topic': topic_path,
'enable_message_ordering': True,
'ack_deadline_seconds': 60
}
)
Ordering Key Best Practices
# Good: Use meaningful ordering keys
ordering_key = f'user_{user_id}' # Per-user ordering
ordering_key = f'session_{session_id}' # Per-session ordering
ordering_key = f'account_{account_id}' # Per-account ordering
# Bad: Too many ordering keys (reduces throughput)
# Each ordering key creates a separate ordering queue
# Use fewer ordering keys for better throughput
# Monitor ordering latency
from google.cloud import monitoring_v3
import time
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/my-project"
# Query ordering latency
interval = monitoring_v3.TimeInterval()
interval.end_time = time.time()
interval.start_time = time.time() - 3600 # Last hour
results = client.list_time_series(
request={
'name': project_name,
'filter': 'metric.type="pubsub.googleapis.com/subscription/num_undelivered_messages"',
'interval': interval,
'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
}
)
Dead-Letter Topics
Dead-letter topics capture messages that cannot be processed after a specified number of delivery attempts.
Without a dead-letter policy a malformed record is redelivered forever, and because every redelivery costs another ack deadline of wall-clock time, a handful of bad payloads can pin an entire subscription's throughput down. The policy gives the service a budget: after the configured attempts, Pub/Sub marks the message undeliverable and republishes it to the dead-letter topic, carrying the original attributes plus the topic it came from. The subscription itself keeps running, which is the whole point.
Delivery attempts are counted per subscription, so a second subscription on the same topic starts its own count, and the dead-letter topic needs its own subscription or the rescued messages simply accumulate unread.
Configuring Dead-Letter Topics
# Create dead-letter topic
gcloud pubsub topics create dead-letter-topic
# Create subscription with dead-letter policy
gcloud pubsub subscriptions create my-subscription \
--topic=my-topic \
--dead-letter-topic=dead-letter-topic \
--max-delivery-attempts=5
# Update existing subscription with dead-letter policy
gcloud pubsub subscriptions update my-subscription \
--dead-letter-topic=dead-letter-topic \
--max-delivery-attempts=5
Python Implementation
from google.cloud import pubsub_v1
import json
# Dead-letter subscription handler
def process_dead_letter(message):
"""Process messages from dead-letter topic."""
print(f'Dead letter message: {message.data}')
print(f'Original topic: {message.attributes.get("googclient_original_topic")}')
print(f'Delivery attempt: {message.delivery_attempt}')
# Log for investigation
log_dead_letter(message)
# Alert if needed
if message.delivery_attempt >= 3:
send_alert(f'Message failed {message.delivery_attempt} times')
message.ack()
# Subscribe to dead-letter topic
subscriber = pubsub_v1.SubscriberClient()
dlq_subscription_path = subscriber.subscription_path(
'my-project', 'dead-letter-subscription'
)
future = subscriber.subscribe(dlq_subscription_path, process_dead_letter)
Dead-Letter Policy Configuration
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path('my-project', 'my-topic')
subscription_path = subscriber.subscription_path('my-project', 'my-subscription')
# Create subscription with dead-letter policy
subscription = subscriber.create_subscription(
request={
'name': subscription_path,
'topic': topic_path,
'dead_letter_policy': {
'dead_letter_topic': 'projects/my-project/topics/dead-letter-topic',
'max_delivery_attempts': 5
},
'ack_deadline_seconds': 60,
'message_retention_duration': {'seconds': 86400} # 1 day
}
)
print(f'Subscription created: {subscription.name}')
Exactly-Once Delivery
Pub/Sub provides exactly-once delivery semantics through message deduplication.
The guarantee is narrower than the phrase suggests. Enabling exactly-once on a subscription makes the service deduplicate messages arriving within a seven-day window, so a subscriber that acknowledges a message and crashes before finishing never sees it again from that subscription. What it does not cover is work that happened outside Pub/Sub: if the subscriber processed the record but failed to write the result somewhere durable, no redelivery is coming and the side effect is lost.
That is why exactly-once is paired with an idempotent sink rather than trusted alone. If the subscriber writes to BigQuery using a deterministic message id as a column and merges on it, a duplicate write is a no-op even in the rare window the guarantee does not reach. Treat the Pub/Sub setting as removing the common duplicate case and let sink-side idempotency cover the remainder.
Enabling Exactly-Once Delivery
from google.cloud import pubsub_v1
# Create topic with exactly-once delivery
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path('my-project', 'my-exactly-once-topic')
topic = publisher.create_topic(
request={
'name': topic_path,
'message_retention_duration': {'seconds': 86400}
}
)
# Create subscription with exactly-once delivery
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
'my-project', 'my-exactly-once-subscription'
)
subscription = subscriber.create_subscription(
request={
'name': subscription_path,
'topic': topic_path,
'enable_exactly_once_delivery': True,
'ack_deadline_seconds': 60
}
)
Message Deduplication
# Publish with deduplication ID
from google.cloud import pubsub_v1
import hashlib
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path('my-project', 'my-exactly-once-topic')
# Generate deduplication ID
def generate_dedup_id(data):
"""Generate unique deduplication ID."""
return hashlib.sha256(data.encode()).hexdigest()
# Publish message with deduplication
data = json.dumps({'order_id': 'order_123', 'amount': 99.99})
dedup_id = generate_dedup_id(data)
future = publisher.publish(
topic_path,
data.encode('utf-8'),
deduplication_id=dedup_id,
event_type='order_created'
)
print(f'Published with dedup ID: {dedup_id}')
Message Filtering
Message filtering allows subscribers to receive only messages matching specific criteria.
Filters evaluate message attributes on the server side before a message is written into a subscription's backlog, so a filtered-out message costs that subscription nothing: no storage, no undelivered count, no ack deadline. One broad topic can therefore serve many narrow consumers, each declaring only the slice it wants, instead of the publisher fanning out to a topic per consumer type. The grammar is deliberately small, covering equality, inequality, and the boolean operators and, or, and parentheses.
The constraint is that filters read attributes only and never inspect the payload. Routing decisions must be lifted into attributes at publish time, so if a producer writes the event type inside the JSON body and nowhere else, no filter can select on it. The attribute schema of a topic is a contract worth reviewing as carefully as a table schema.
Filter Syntax
# Create subscription with filter
gcloud pubsub subscriptions create filtered-subscription \
--topic=my-topic \
--filter='attributes.event_type = "purchase"'
# Complex filter
gcloud pubsub subscriptions create complex-filtered-subscription \
--topic=my-topic \
--filter='attributes.region = "us-east1" AND attributes.event_type = "signup"'
Python Implementation
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path('my-project', 'my-topic')
subscription_path = subscriber.subscription_path(
'my-project', 'filtered-subscription'
)
# Create subscription with filter
subscription = subscriber.create_subscription(
request={
'name': subscription_path,
'topic': topic_path,
'filter': 'attributes.event_type = "purchase"',
'ack_deadline_seconds': 60
}
)
# Publish messages with attributes
publisher = pubsub_v1.PublisherClient()
# This message will be delivered
publisher.publish(
topic_path,
b'Purchase event',
event_type='purchase',
region='us-east1'
)
# This message will NOT be delivered (filtered out)
publisher.publish(
topic_path,
b'Login event',
event_type='login',
region='us-east1'
)
Performance Optimization
Throughput in Pub/Sub is rarely limited by the service and almost always limited by how the client drives it. Publishing one message per round trip leaves latency on the table, because each call pays a network hop; the client library already batches into a single request once the batch element count or the flush delay is reached, so raising the outstanding message limit and letting the publisher accumulate briefly is the cheapest win available. The same logic applies in reverse on the subscriber side, where a flow controller capping in-flight messages and bytes keeps a fast consumer from overwhelming a slow downstream writer.
Throughput Optimization
# Optimize publisher throughput
from google.cloud import pubsub_v1
from concurrent.futures import ThreadPoolExecutor
publisher = pubsub_v1.PublisherClient(
publisher_options=pubsub_v1.types.PublisherOptions(
enable_message_ordering=False,
flow_control=pubsub_v1.types.PublishFlowControl(
message_limit=1000,
byte_limit=10 * 1024 * 1024, # 10MB
limit_exceeded_behavior=pubsub_v1.types.LimitExceededBehavior.BLOCK
)
)
)
# Batch publishing
def publish_messages_batch(messages, topic_path):
"""Publish messages in batches."""
futures = []
for message in messages:
future = publisher.publish(
topic_path,
message['data'].encode('utf-8'),
**message['attributes']
)
futures.append(future)
# Wait for all messages to be published
for future in futures:
print(f'Published: {future.result()}')
# Use thread pool for parallel publishing
with ThreadPoolExecutor(max_workers=10) as executor:
executor.submit(publish_messages_batch, messages, topic_path)
Subscriber Optimization
# Optimize subscriber throughput
from google.cloud import pubsub_v1
import concurrent.futures
subscriber = pubsub_v1.SubscriberClient(
subscriber_options=pubsub_v1.types.SubscriberOptions(
enable_exactly_once_delivery=True,
flow_control=pubsub_v1.types.FlowControl(
limit_messages=1000,
limit_bytes=100 * 1024 * 1024, # 100MB
limit_exceeded_behavior=pubsub_v1.types.LimitExceededBehavior.BLOCK
)
)
)
# Process messages in parallel
def process_message_batch(messages):
"""Process a batch of messages."""
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(process_single_message, msg) for msg in messages]
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as e:
print(f'Error processing message: {e}')
Monitoring and Alerting
A subscription backlog is a leading indicator rather than a symptom. The metric that matters is the age of the oldest unacknowledged message, because it reports how far behind the consumer is in wall-clock terms while the undelivered count only reports how many messages exist. A flat count with a rising age means the consumer is alive but slow and probably blocked on a dependency; a rising count with a flat age means the consumer stopped entirely. Alert on both, with different severities, and give each subscription its own threshold.
Key Metrics
# Monitor Pub/Sub metrics
from google.cloud import monitoring_v3
import time
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/my-project"
# Key metrics to monitor:
# - pubsub.googleapis.com/subscription/num_undelivered_messages
# - pubsub.googleapis.com/subscription/oldest_unacked_message_age
# - pubsub.googleapis.com/subscription/ack_deadline_seconds
# - pubsub.googleapis.com/topic/message_count
def get_subscription_metrics(subscription_name, hours=1):
"""Get subscription metrics."""
interval = monitoring_v3.TimeInterval()
end_time = time.time()
interval.end_time = end_time
interval.start_time = end_time - (hours * 3600)
results = client.list_time_series(
request={
'name': project_name,
'filter': f'metric.type="pubsub.googleapis.com/subscription/num_undelivered_messages" AND resource.label.subscription="{subscription_name}"',
'interval': interval,
'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
}
)
for result in results:
print(f'Metric: {result.metric.type}')
for point in result.points:
print(f' Value: {point.value.int64_value}')
print(f' Time: {point.interval.end_time}')
Alerting Policies
# Create alerting policy
from google.cloud import monitoring_v3
client = monitoring_v3.AlertPolicyServiceClient()
project_name = f"projects/my-project"
alert_policy = monitoring_v3.AlertPolicy(
display_name="Pub/Sub High Lag Alert",
conditions=[
monitoring_v3.AlertPolicy.Condition(
display_name="High message lag",
condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
filter='metric.type="pubsub.googleapis.com/subscription/oldest_unacked_message_age"',
comparison=monitoring_v3.ComparisonType.COMPARISON_GT,
threshold_value=300, # 5 minutes
duration={"seconds": 300},
aggregations=[
monitoring_v3.Aggregation(
alignment_period={"seconds": 60},
per_series_aligner=monitoring_v3.Aggregation.Aligner.ALIGN_MEAN
)
]
)
)
],
notification_channels=[],
alert_strategy=monitoring_v3.AlertPolicy.AlertStrategy(
auto_close={"seconds": 1800} # Auto-close after 30 minutes
)
)
response = client.create_alert_policy(
request={"name": project_name, "alert_policy": alert_policy}
)
print(f'Created alert policy: {response.name}')
Production Rules Worth Encoding
Each rule below exists because ignoring it shows up as an outage or an invoice later, and the delivery semantics are easier to choose with the trade-offs side by side:
| Feature | Default at-least-once | Ordering enabled | Exactly-once enabled |
|---|---|---|---|
| Redelivery | Possible after nack or deadline | Possible, stalls the key | Deduplicated for seven days |
| Throughput per key | Parallel | Serial | Serial per key |
| Typical use | Logs, events, fan-out | State changes, ledgers | Payments, idempotent writes |
| Extra caution | Make the sink idempotent | Avoid hot keys | Still make the sink idempotent |
- Use message ordering - When message sequence matters
- Implement dead-letter topics - Capture failed messages
- Enable exactly-once delivery - For critical transactions
- Use message filtering - Reduce unnecessary message processing
- Monitor lag metrics - Track subscription backlog
- Optimize batch sizes - Balance throughput and latency
- Implement proper error handling - Use ack/nack appropriately
Common Mistakes
Setting a long ack deadline to give slow workers room
Fix: Ack per unit of work instead; a long deadline delays redelivery after a crash and inflates lag metrics.
Creating a dead-letter topic with no subscription on it
Fix: Rescued messages accumulate unread, so create the subscription and alert on its backlog as well.
Putting the event type in the payload instead of an attribute
Fix: Filters read attributes only, so publish routing metadata as attributes if any subscriber will filter on it.
Best Practices
- Ack inside the callback after the work is durably recorded, never before
- Batch on the publisher and cap in-flight messages on the subscriber with flow control
- Keep payloads well under the ten kilobyte ceiling and route on attributes
- Alert on oldest unacknowledged age per subscription, not just on undelivered count
Key Takeaways
- Each subscription owns an independent cursor, so replay means a new subscription over a retained window
- Pull gives backpressure for free; push is bounded by how fast your HTTP endpoint answers
- Ordering serialises per key and pairs with a dead-letter topic so one poison message cannot block forever
- Exactly-once removes duplicates within the delivery window, but the sink must still be idempotent
Interview Questions
Q1: Explain at-least-once versus exactly-once delivery in Pub/Sub.
By default a message can be redelivered after a nack or a missed ack deadline, so consumers must tolerate duplicates. Enabling exactly-once deduplicates messages for seven days per subscription, which removes duplicates but still requires an idempotent sink for anything the guarantee cannot observe.
Q2: How do you decide between a pull and a push subscription?
Use pull for high throughput, batching into BigQuery, and natural backpressure, since the worker controls how much it fetches. Use push when you already have an HTTP endpoint and modest volume; it retries with backoff on any non-two-hundred response but scales only as fast as the endpoint.
Q3: A subscription backlog keeps growing. How do you diagnose it?
Compare oldest unacknowledged age with undelivered count. Rising age with a flat count means consumers are slow and blocked on a dependency; a rising count with a flat age means consumers stopped. Then check ack deadline, filter configuration, and whether an ordering key is stalled.
Q4: What is the role of an ordering key and what does it cost?
Messages sharing an ordering key are delivered in publication order through a serial queue, which protects sequence but caps throughput at what one consumer can drain. Use keys such as account or device, avoid a single global key, and always attach a dead-letter policy so a failed message cannot block the queue.