Streaming · By Divya Madhavan
GCP Pub/Sub to BigQuery: Schema Drift, Python Retries and Dead-Letter Topics
Choose an ingestion path, reject incompatible events deliberately and acknowledge Python subscriber messages only after a successful BigQuery write.
Choose managed delivery or a Python worker
Start with a managed BigQuery subscription when the source payload maps to the target table and you do not need a custom processing service. A Python pull subscriber is useful for explicit validation and application logic; Dataflow is another option when the transformation and operational requirements justify it. These are alternative ingestion paths, not stages that must all run together. Define the event contract and recovery policy before choosing one. This article’s callback is an instructional custom-worker example, not the implementation of a managed BigQuery subscription.
Define a schema drift policy before the first incident
Treat additive optional fields, missing required fields and incompatible type changes as different changes. A new nullable field can be introduced through a reviewed table migration; it does not justify automatically changing production schemas from a subscriber callback. Keep a versioned producer contract, test old and new producers against it, and decide whether unknown fields are rejected, retained in a raw envelope or intentionally discarded. Keep original input durably if later reconstruction is a requirement. The code below deliberately rejects every field outside contract v1; it detects drift but does not perform schema evolution.
Understand managed BigQuery subscription failures
When a managed subscription uses the table schema, unknown fields and its drop-unknown-fields setting affect whether a message can be written. Dropping fields may restore flow while discarding information, so make that an explicit contract decision. Inspect the subscription state as well as individual messages: a subscription-level schema or permission error can leave a backlog without forwarding records to a dead-letter topic. Correct the table or IAM problem first. A dead-letter topic is therefore not a substitute for monitoring subscription health.
Python subscriber: validate, write, then acknowledge
Provision a pull subscription, a target table and Application Default Credentials before wiring this callback. The runtime identity needs subscription-consumption and table-write permissions; enable the relevant APIs. The small example writes one row per callback for clarity, not maximum throughput. It checks row-level BigQuery errors as well as raised exceptions. Validation failures and write failures both nack so a configured retry/dead-letter policy can handle them. The sample validates two string fields only: add timestamp, size, privacy and business checks for your contract. Do not use it unchanged as a general-purpose streaming platform.
import json
import logging
def validate_event(raw):
event = json.loads(raw.decode("utf-8"))
if not isinstance(event, dict):
raise ValueError("Expected a JSON object")
required = {"event_id", "event_type"}
if set(event) != required:
raise ValueError("Unexpected or missing fields: contract v1")
if any(not isinstance(event[k], str) or not event[k].strip()
for k in required):
raise ValueError("event_id and event_type must be nonempty strings")
return event
def make_callback(bq, table):
# bq is an authenticated google.cloud.bigquery.Client.
# table: project.dataset.raw_events, with STRING columns:
# event_id, event_type, pubsub_message_id.
def callback(message):
try:
row = validate_event(message.data)
row["pubsub_message_id"] = message.message_id
errors = bq.insert_rows_json(
table, [row],
row_ids=[message.message_id],
ignore_unknown_values=False,
skip_invalid_rows=False,
timeout=30,
)
if errors:
raise RuntimeError("BigQuery rejected the row")
except Exception:
# Use structured counters/error categories in production.
# Do not log raw payloads containing sensitive information.
logging.exception("Ingestion failed; leaving message for retry")
message.nack()
return
message.ack()
return callback
# Wiring in a provisioned environment:
# pip install google-cloud-pubsub google-cloud-bigquery
# Configure Application Default Credentials and least-privilege IAM.
# from google.cloud import pubsub_v1, bigquery
# with pubsub_v1.SubscriberClient() as subscriber:
# future = subscriber.subscribe(
# "projects/PROJECT/subscriptions/SUBSCRIPTION",
# callback=make_callback(bigquery.Client(), "PROJECT.DATASET.TABLE"),
# flow_control=pubsub_v1.types.FlowControl(max_messages=10),
# await_callbacks_on_shutdown=True,
# )
# try:
# future.result()
# except KeyboardInterrupt:
# future.cancel()
# future.result()
Why this is at-least-once ingestion
The BigQuery write may succeed and the worker may crash before acknowledging the Pub/Sub message. A subsequent delivery can write the row again. Passing a stable message ID to insert_rows_json provides only best-effort insertAll deduplication; it is not a guarantee of unique rows. A producer retry can also create a second Pub/Sub message ID for the same business event. Retain the stable business event_id and build a separately validated deduplication or merge process for consumers. Use the Storage Write API with a deliberately managed stream/offset design if stronger write semantics are required; it still does not automatically make the whole source-to-consumer workflow exactly once.
Configure a dead-letter topic and a recovery subscription
Create a dead-letter topic and a subscription on that topic so forwarded messages can be inspected and retained. Configure the source subscription’s dead-letter policy and retry backoff, and grant the Pub/Sub service agent the documented forwarding/acknowledgment permissions. Delivery attempts are approximate, not a precise application retry counter. Set retention to cover your recovery objective. Avoid using the DLQ for routine permission outages: alert on a rising backlog and persistent errors so a bad deployment is fixed rather than merely retried.
Replay only after fixing the cause
Capture failure categories without exposing payloads in logs. Repair the contract, transformation or permissions, then replay a bounded set into an isolated validation destination. Preserve the business event ID and provenance; republishing creates a new transport message identity, so message-ID-only deduplication will not protect the business totals. Compare distinct events, duplicates, rejected records and consumer aggregates before reopening traffic. Do not wire the dead-letter topic straight back to the source topic as an unbounded retry loop.
A small failure-injection checklist
Try malformed JSON, an unexpected field, an empty event ID, an incompatible table schema and a temporary write exception. Verify that each failed write leaves the message unacknowledged. Then simulate a successful write followed by a worker crash and check that duplicate events are visible to reconciliation. Measure backlog age, DLQ volume, successful writes, rejection categories and event-to-query latency under representative load. The callback’s control flow was tested locally with fakes; cloud IAM, throughput, managed delivery and live BigQuery writes were not exercised.