🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Streaming Pipeline Architecture: Pub/Sub → Dataflow → BigQuery → Looker

GCP Data EngineeringStreaming Pipelines🟢 Free Lesson

Streaming Pipeline Architecture

Build production-ready real-time streaming pipelines using Pub/Sub, Dataflow, BigQuery, and Looker on GCP.

22 min readAdvanced

What You'll Learn

  • 1Decompose a real-time requirement into ingest, process, serve and visualise stages
  • 2Choose a delivery guarantee and pair it with an idempotent write strategy
  • 3Select window, trigger and accumulation mode from the latency target
  • 4Diagnose a streaming backlog from lag, watermark and worker metrics

Four Stages and One Latency Budget

A streaming pipeline is four decisions in a trench coat: where events land, how they are transformed, where results are stored, and how fast someone must be able to see them. On GCP the reference shape is Pub/Sub for ingestion, Dataflow for windowed processing, BigQuery for storage and aggregation, and Looker for the dashboard. Each hop adds latency, so the budget is allocated before any code is written. A pipeline promising a five minute dashboard can tolerate micro batching in BigQuery; one promising three seconds cannot, and must use the BigQuery Storage Write API, avoid session windows with long gaps, and put a materialized view in front of the explore.

The conceptual shift that catches people out is that a streaming job never sees "the data" as a finished set. It sees an unbounded stream that must be cut into finite groups by a window, and the engine estimates how complete each window is with a watermark: a timestamp below which no more late data is expected. Everything downstream, from triggers to side outputs for late data, is machinery for deciding what to do when reality disagrees with that estimate.

The pattern below writes one row per window per event type, keeps duplicates harmless, and leaves a dead letter path for malformed payloads, which is the minimum viable shape for a pipeline you will be paged about.

Ingestion: Delivery Guarantees Worth Paying For

Pub/Sub gives at least once delivery by default and exactly once on request, and the difference shows up in how you write the consumer, not in the marketing. An acknowledgement is idempotent for the duration of the ack deadline, so a redelivery after a crash is normal and expected.

python
from google.cloud import pubsub_v1
import json

publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
project_id = "my-project"

topic_path = publisher.topic_path(project_id, "real-time-events")
publisher.create_topic(request={"name": topic_path})

sub_path = subscriber.subscription_path(project_id, "events-to-dataflow")
subscriber.create_subscription(
    request={
        "name": sub_path,
        "topic": topic_path,
        "ack_deadline_seconds": 60,
        "enable_exactly_once_delivery": True,
        "dead_letter_policy": {
            "dead_letter_topic": f"projects/{project_id}/topics/events-deadletter",
            "max_delivery_attempts": 5
        },
        "message_retention_duration": {"seconds": 604800}
    }
)

def publish_event(event_data):
    data = json.dumps(event_data).encode("utf-8")
    future = publisher.publish(
        topic_path,
        data=data,
        event_type=event_data.get("event_type"),
        user_id=event_data.get("user_id")
    )
    return future.result()

Three settings carry real consequences. The ack deadline must exceed the slowest processing time or Dataflow will be fighting redeliveries that look like duplicates in every downstream count; sixty seconds is generous for a transform, and the minimum accepted value is ten. max_delivery_attempts = 5 moves poison messages to the dead letter topic instead of spinning forever, and the dead letter topic needs its own subscription or the messages quietly pile up. Ordering keys guarantee sequence within a key and deliberately sacrifice throughput and availability to do so, so they belong on per entity flows such as a single device, not on a global topic.

Windowing, Triggers and Accumulation

Beam gives every element three independent settings, and interviews hinge on naming them separately: the window decides which group an element belongs to, the trigger decides when results are emitted, and the accumulation mode decides what happens to state after an emission.

python
import apache_beam as beam
from apache_beam.transforms.window import FixedWindows, Sessions
from apache_beam.transforms.trigger import (
    AfterWatermark, AfterProcessingTime, AccumulationMode
)
from apache_beam.io.gcp.bigquery import WriteToBigQuery, BigQueryDisposition
import json

def run_streaming_pipeline():
    pipeline_options = PipelineOptions([
        '--project', 'my-project',
        '--runner', 'DataflowRunner',
        '--region', 'us-central1',
        '--temp_location', 'gs://my-data-lake/temp/',
        '--streaming',
        '--enable_streaming_engine',
        '--num_workers', '4',
        '--max_num_workers', '50',
        '--autoscaling_algorithm', 'THROUGHPUT_BASED'
    ])

    with beam.Pipeline(options=pipeline_options) as pipeline:
        messages = (
            pipeline
            | 'Read Pub/Sub' >> beam.io.ReadFromPubSub(
                topic='projects/my-project/topics/real-time-events'
            )
            | 'Decode JSON' >> beam.Map(lambda x: json.loads(x.decode('utf-8')))
        )

        windowed_counts = (
            messages
            | 'Window into 1 min' >> beam.WindowInto(
                FixedWindows(60),
                trigger=AfterWatermark(
                    early=AfterProcessingTime(10),
                    late=AfterProcessingTime(30)
                ),
                allowed_lateness=300,
                accumulation_mode=AccumulationMode.DISCARDING
            )
            | 'Extract event type' >> beam.Map(lambda x: (x['event_type'], 1))
            | 'Count per window' >> beam.CombinePerKey(sum)
        )

        (
            windowed_counts
            | 'Format for BQ' >> beam.Map(lambda x: {
                'event_type': x[0],
                'event_count': x[1],
                'window_end': x[0]
            })
            | 'Write to BQ' >> WriteToBigQuery(
                'my-project:analytics.real_time_counts',
                schema='event_type:STRING,event_count:INT64,window_end:TIMESTAMP',
                write_disposition=BigQueryDisposition.WRITE_APPEND,
                create_disposition=BigQueryDisposition.CREATE_IF_NEEDED
            )
        )

if __name__ == '__main__':
    run_streaming_pipeline()

AfterProcessingTime(10) emits a speculative result ten seconds after the first element of a window arrives, which is what makes a dashboard feel live before the watermark advances. Late elements past the watermark re-emit until allowed_lateness expires, at which point the window is dropped and the side output is where you send what falls out. AccumulationMode.DISCARDING means each emission contains only what arrived since the last one, while ACCUMULATING repeats the full window and forces the sink to be idempotent; pick one and write it in the runbook, because mixing them is how totals double.

Window and Trigger Cheat Sheet

ConstructWhat it producesLatencyTypical use
FixedWindows(60)Non-overlapping one minute bucketsUp to one minute plus watermarkCounts per minute, billing periods
SlidingWindows(60, 10)Buckets overlapping every ten secondsUp to ten secondsMoving averages, rolling rates
Sessions(gap)Buckets closed after an idle gapGap length plus watermarkPer user activity bursts
GlobalWindowsOne bucket for all timeNever closes without a triggerLookups and enrichment only
AfterWatermark(past)Fires when the watermark passes the endCorrect but slowAuthoritative totals
AfterCount(n)Fires after n elementsFast, size dependentMicro-batches into BigQuery

A dashboard that must refresh every ten seconds usually pairs sliding windows with an early trigger and a discarding mode, then accepts that the first number is provisional. An invoice can never work that way: it needs a closed watermark, an accumulating mode, and a separate path for late corrections.

Writing into BigQuery Without Regret

Streaming writes land in a mutable streaming buffer first, so rows are not queryable the moment they are acknowledged and recently streamed rows cannot be updated or deleted for roughly thirty minutes. Two rules prevent the expensive surprises. First, do not create a partition per event or per second: BigQuery caps a table at about a thousand streaming partitions per day, and a per second partition strategy either fails or fragments the table into tiny units that cost more to scan than the data is worth. Second, prefer the Storage Write API or Dataflow's WriteToBigQuery over hand-rolled REST inserts, because the Write API supports first write wins semantics within a stream, which turns duplicates into no-ops instead of corrections.

-- Partition by day, cluster by the columns Looker filters on
CREATE TABLE `project.analytics.real_time_counts`
(
  event_type STRING,
  window_end TIMESTAMP,
  event_count INT64
)
PARTITION BY DATE(window_end)
CLUSTER BY event_type
OPTIONS(require_partition_filter = true);

-- Rolling average the dashboard reads
CREATE MATERIALIZED VIEW `project.analytics.real_time_dashboard_mv`
PARTITION BY DATE(window_end)
CLUSTER BY event_type
AS
SELECT
  event_type,
  window_end,
  event_count,
  AVG(event_count) OVER (
    PARTITION BY event_type
    ORDER BY window_end
    ROWS BETWEEN 5 PRECEDING AND CURRENT ROW
  ) AS moving_avg_count
FROM `project.analytics.real_time_counts`
WHERE window_end >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY);

require_partition_filter is the guard rail that stops a colleague from scanning the whole table at 2 dollars per TiB of the 5 dollar on-demand rate, and the materialized view refreshes itself as the underlying rows arrive so Looker never queries the raw stream directly.

Failure Modes You Will Meet in Production

The four failures that account for most streaming incidents all announce themselves in metrics before they reach a dashboard. A consumer that cannot keep up shows as rising unacked message count and a watermark that lags wall clock time, which means late data and widening windows. A poison message shows as a hot key retrying forever, which is why the dead letter policy exists. A schema change upstream shows as a sudden error rate on the write, since BigQuery rejects a field that no longer matches. And an autoscaler that reacts too slowly shows as worker CPU pinned while throughput plateaus, which is fixed by tuning the autoscaling algorithm rather than by adding workers by hand.

✨

Best Practice: Enable Streaming Engine so window state lives outside the worker VMs, set an early trigger when a dashboard needs provisional numbers, and keep every write idempotent because at least once delivery is the guarantee you actually get. Alert on watermark lag and unacked depth together; either one alone hides the real cause.

Common Interview Questions

Q1: At least once or exactly once?

Answer: At least once means every message is delivered at least one time but may be repeated after a redelivery, which is the default in Pub/Sub. Exactly once suppresses duplicates within the acknowledgement window and is available on the subscription and on the BigQuery Storage Write API. Most pipelines are correct with at least once plus an idempotent merge keyed on the event identifier.

Q2: How is backpressure handled?

Answer: Pub/Sub absorbs bursts as retention rather than pushing back, so backpressure appears in the consumer as growing unacked count and lag. Dataflow counters, flow control on the subscriber, and throughput based autoscaling regulate the read rate, while the dead letter policy protects against a single bad record.

Q3: Why does a streaming pipeline need windows at all?

Answer: Aggregation over an unbounded stream never finishes, so a window declares the set of elements a result covers. Fixed windows give regular counts, sliding windows give overlapping averages, and session windows group by behaviour gaps rather than by clock boundaries.

Q4: What contributes to end to end latency?

Answer: Publish to acknowledgement, trigger firing time, watermark confidence, the write path into BigQuery, the streaming buffer before the row is queryable, materialized view refresh, and finally the dashboard cache. Cutting any one of them rarely helps, so the budget is measured across the whole chain.

Q5: How do you monitor a streaming pipeline?

Answer: Watch Pub/Sub unacked message count and oldest unacked age, Dataflow watermark lag and system lag, worker CPU and autoscaling events, BigQuery insert error counts, and cost per hour against throughput. Alert on the combination, since a single metric rarely identifies which stage is at fault.

Interview Questions

Q1: What does AccumulationMode.DISCARDING change?

After each trigger firing the window state is cleared, so the emitted row contains only elements seen since the previous emission; ACCUMULATING repeats the full window and requires the sink to overwrite rather than append.

Q2: When is an ordering key the right choice in Pub/Sub?

When a single entity must be processed in sequence, such as one device or one account. Ordering trades away throughput and availability for the sequence, so it never belongs on a global topic.

Q3: Why can you not delete rows you just streamed into BigQuery?

Rows in the mutable streaming buffer cannot be modified or deleted for roughly thirty minutes, so a pipeline that writes and then compensates must tolerate that window or use the Storage Write API with first write wins.

Q4: How do you prove a duplicate did not double count?

Make the write idempotent by keying on the event identifier, then replay a known batch and assert the aggregate is unchanged; if the total moves, the sink is appending where it should be merging.

Common Mistakes

Creating a partition per event or per second

Fix: Partition by day or hour, because BigQuery caps streaming partitions at roughly a thousand per table per day and tiny partitions cost more to scan than they save.

Mixing accumulating and discarding emissions in one job

Fix: Declare one accumulation mode in the windowing step and make the sink match it, or every downstream total will drift.

Treating exactly once delivery as a substitute for idempotency

Fix: Keep a merge keyed on the event identifier, because redeliveries, replays and restores all happen outside the delivery guarantee.

Key Takeaways

  • Window decides the group, trigger decides the emission time, and accumulation mode decides what state survives, and the three are configured independently
  • At least once delivery plus an idempotent write is the honest default; exactly once is available but must be enabled and paid for at each hop
  • Streaming Engine moves state off worker VMs, early triggers give provisional numbers, and allowed lateness decides when a window is finally closed
  • BigQuery streaming rows sit in a mutable buffer for about thirty minutes and a table accepts roughly a thousand streaming partitions per day
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