🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Pub/Sub Deep Dive: Schemas, Filtering & BigQuery Subscriptions

GCP Data EngineeringPub/Sub AdvancedđŸŸĸ Free Lesson

Pub/Sub Advanced Patterns

Master advanced Pub/Sub patterns including schemas, filtering, BigQuery subscriptions, and dead-letter topics.

18 min readAdvanced

What You'll Learn

  • 1Attach a Protobuf or JSON schema to a topic and choose the right validation mode
  • 2Write attribute filters that Pub/Sub can actually evaluate, and know what filters cannot see
  • 3Design dead-letter topologies that isolate poison messages without stalling healthy consumers
  • 4Decide between a BigQuery subscription, a Dataflow consumer, and a pull subscription for a given latency budget

Pub/Sub is the ingress fabric for nearly every real-time pipeline on GCP, and most incidents blamed on Dataflow actually start in topic or subscription configuration. This lesson covers the four areas interviewers probe hardest: schema validation, subscription filtering, BigQuery subscriptions, and exactly-once delivery semantics, with the quota numbers that show up in capacity discussions.

Delivery Semantics and Core Quotas

Pub/Sub guarantees at-least-once delivery by default. Every acknowledged message can be redelivered if the ack deadline expires, so consumers must be idempotent. Exactly-once delivery is an opt-in subscription setting that suppresses duplicates across redeliveries and across regions for acknowledged ackIds, at the cost of a higher minimum lease.

The numbers worth memorising: a single message may carry up to 10 MB including attributes. The default ack deadline is 10 seconds, adjustable between 10 seconds and 10 minutes. With exponential backoff configured, a single ack deadline extension can stretch a message lease to about ten times the minimum backoff window, which bounds how long a slow consumer can hold work before redelivery. Topic and subscription message retention each max out at 7 days, which defines how long a stopped consumer can stay down before data is lost. Ordering keys cap publish throughput at 1 MB per second per key, so partition-by-key designs must spread hot keys.

SettingDefaultRange or ceilingConsequence of the limit
Max message size10 MBhard ceilingLarge payloads need Cloud Storage references
Ack deadline10 s10 s to 600 sToo short causes redelivery storms
Topic retention7 days10 min to 7 daysOffline consumers must restart within window
Exactly-once min ack deadline60 s60 s floorSlower failure detection
Ordering key throughput1 MB/s per keyper keyHot keys throttle publishers

Schema Validation at Publish Time

Attaching a schema makes the topic validate every publish instead of trusting producers. Pub/Sub supports Protocol Buffers and JSON schemas, stored as schema resources with revision history so consumers can pin to a known version. Validation mode decides the failure policy: ALLOW lets non-conforming messages through with no rejection, while REJECT drops publishes that fail validation and returns an error to the publisher.

# Register a Protobuf schema, then attach it to a topic in REJECT mode.
gcloud pubsub schemas create event-schema \
  --project=my-project \
  --type=avro \
  --definition=event-schema.avsc

gcloud pubsub topics create events-validated \
  --project=my-project \
  --schema=event-schema@1 \
  --message-encoding=JSON

gcloud pubsub topics update events-validated \
  --project=my-project \
  --schema-validation-policy=REJECT

A topic supports at most two schemas during migration: the active schema and one pending revision, which lets you evolve a message shape without a flag day. Keep field numbers stable in Protobuf definitions; reusing a number for a different type breaks binary decoding on consumers that have not upgraded, and Pub/Sub will happily validate the publisher while the subscriber fails at runtime.

Filtering at the Subscription Layer

Subscription filters drop unmatched messages before they reach a consumer, which cuts egress and keeps pull queues small. Filter expressions compare message attributes with equality and inequality operators, combined with AND and OR; parentheses group terms, and AND binds tighter than OR. The critical limitation is that filters only see attributes, never the message payload, and they support string equality rather than numeric comparison, so a predicate on an amount field must be pushed into an attribute by the producer or evaluated in the consumer.

python
from google.cloud import pubsub_v1
import json

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path("my-project", "events")

subscription = pubsub_v1.SubscriberClient()
sub_path = subscription.subscription_path("my-project", "purchases-only")

subscription.create_subscription(
    request={
        "name": sub_path,
        "topic": topic_path,
        "filter": 'event_type = "purchase" AND region = "us-central1"',
    }
)

event = {"event_id": "e-1", "amount": 150.0}
publisher.publish(
    topic_path,
    data=json.dumps(event).encode("utf-8"),
    event_type="purchase",
    region="us-central1",
).result()

Filtered-out messages are acknowledged automatically and never appear in the subscription, so they do not count against ack deadlines but they do count against publish volume. Size filters with many distinct attribute values carefully; each subscription evaluates its own filter on every message, and a topic with dozens of filtered subscriptions spends publish fan-out on messages most subscribers will never see.

BigQuery Subscriptions

A BigQuery subscription streams matching messages straight into a BigQuery table without a Dataflow job in the middle. It supports schema validation from the topic schema, optional metadata columns that carry the Pub/Sub topic, subscription, message id, publish time, and attributes, and exactly-once delivery to prevent duplicate rows. It is the cheapest possible path from events to analytics storage, and the worst place to put logic that needs joins, windowing, or enrichment.

python
subscriber = pubsub_v1.SubscriberClient()

subscriber.create_subscription(
    request={
        "name": subscriber.subscription_path("my-project", "events-to-bq"),
        "topic": topic_path,
        "bigquery_config": {
            "table": "projects/my-project/datasets/analytics/tables/events",
            "write_metadata": True,
            "use_topic_schema": True,
        },
        "enable_exactly_once_delivery": True,
    }
)

Choose a BigQuery subscription when every message lands unchanged in a table and the consumer is a SQL query. Reach for Dataflow whenever the pipeline needs state: session windows, joins against reference data, aggregations before storage, or late-data handling. Mixing both on one topic is fine, since subscriptions are independent views of the same stream.

Ordering, Deduplication, and Idempotent Consumers

Ordering keys force messages sharing a key to publish and deliver in order, at the cost of the 1 MB per second per key ceiling and strict redelivery blocking: while a message for a key is unacknowledged, later messages for that key queue behind it. Turn ordering on only when the business truly requires sequence, such as device state transitions; analytics events usually tolerate out-of-order arrival better than a throttled publisher.

Exactly-once delivery removes duplicates for acknowledged messages but does not make the end-to-end pipeline idempotent, because a crash between a BigQuery write and the ack can still replay a row. The durable pattern is to carry a stable event id, use BigQuery table decorators or MERGE statements keyed on that id, or rely on the streaming buffer's built-in de-duplication window, which only covers roughly the first few minutes after insert.

Dead-Letter Topologies

Poison messages that throw on every attempt would otherwise block a consumer forever. A dead-letter policy on the subscription moves a message to a dead-letter topic after max_delivery_attempts failed acks, with a backoff policy that grows the retry interval from a 100 millisecond floor toward a 600 second ceiling. Consumers then read the dead-letter topic with a separate, more tolerant pipeline that logs, quarantines, or feeds a manual review queue.

ComponentHealthy pathFailure path
Main topicAll events published onceProducer retries on publish error
Work subscriptionProcessed within ack deadlineRedelivery until attempts exhausted
Dead-letter topicUnusedHolds messages after max attempts
Replay toolingUnusedRepublishes fixed messages to main topic

Set max_delivery_attempts between 5 and 100; the floor of 5 exists because transient failures rarely need more, and the ceiling bounds how long a stuck message can occupy lease extensions before freeing the subscription. Always publish the dead-letter topic into the same project or a project the same service account can write to, or silently dropped messages will pile up behind permission errors that Cloud Monitoring will not surface as failures.

Cost and Capacity Planning

Ingested volume, egress to consumers, and retention storage are the three billing axes. A pipeline that publishes 5,000 events per second at 2 KB each moves about 86 GB per day before fan-out, and every additional subscription multiplies egress. The practical lever is filtering and BigQuery subscriptions to cut the consumer leg, plus retention tuning so idle subscriptions stop paying for seven days of backlog storage they will never read.

Common Mistakes

Writing filter predicates that compare numeric attributes

Fix: Filters support string equality and inequality only; cast numbers to zero-padded strings in the producer or filter in the consumer.

Enabling ordering keys on every topic

Fix: Ordering caps throughput at 1 MB per second per key; reserve it for stateful event sequences and let analytics topics stay unordered.

Assuming exactly-once delivery makes the pipeline idempotent

Fix: A crash between the sink write and the ack still replays; key your sink on a stable event id and merge on that key.

Best Practices

  • Attach schemas in REJECT mode so malformed events fail at the producer, not in the consumer
  • Keep ack deadlines aligned with realistic processing time and enable exponential backoff on pull clients
  • Route failed messages through a dead-letter topic with replay tooling rather than infinite retries

Key Takeaways

  • At-least-once is the default; exactly-once is a subscription setting that still requires idempotent sinks
  • Filters see attributes only and evaluate string equality, never payload fields or numeric ranges
  • BigQuery subscriptions bypass Dataflow entirely, which is ideal for pass-through ingestion and wrong for any logic that needs state
  • Dead-letter policies bound poison-message damage with max_delivery_attempts between 5 and 100 and capped backoff

Interview Questions

Interview Questions

Q1: What do message schemas buy you in Pub/Sub?

Schemas validate structure at publish time, support revision pinning during migrations, and generate type-safe consumers; with REJECT mode a bad producer fails immediately instead of poisoning downstream jobs.

Q2: How does subscription filtering actually work?

Each subscription evaluates an attribute expression with equality, inequality, AND, OR, and parentheses on every message; non-matching messages are acknowledged and dropped before delivery, so consumers only pay for what they asked for.

Q3: When is a BigQuery subscription the wrong tool?

When the pipeline needs joins, windowed aggregation, enrichment, or late-data handling; those require Dataflow, and the BigQuery subscription should be reserved for pass-through storage of validated events.

Q4: How do you handle message ordering without tanking throughput?

Scope ordering keys narrowly so hot keys are rare, spread distinct keys across partitions, and keep payloads small; the 1 MB per second per key ceiling means a single overloaded key throttles its whole partition.

Q5: Design a replay strategy after a bad deploy corrupts consumers.

Messages sit in the dead-letter topic; fix the consumer, then republish dead-lettered messages to the main topic with original attributes, using the stored message id for deduplication at the sink.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement