Pub/Sub and Dataflow streaming for the PDE exam: windows, watermarks and late data
The Professional Data Engineer exam guide places streaming in Section 2, "Ingesting and processing the data" (~25%), with "windowing, late arriving data" as examples, and lists Pub/Sub, Dataflow and Apache Beam among the services to know. Streaming questions rarely just ask "which service". They ask why records are duplicated, where late data ends up, when a BigQuery subscription is enough, and how to stop a pipeline without losing data. This article goes deep on those decisions, with comparison tables, short code and example practice questions.
Key takeaways
- The familiar streaming chain: Pub/Sub receives, Dataflow processes, BigQuery stores; Pub/Sub delivers at least once by default, while Dataflow streams in exactly-once mode by default.
- To window and use watermarks on event time, configure reading the timestamp from an attribute (
timestamp_attribute); by default Dataflow uses the Pub/Sub timestamp. - Exactly-once doesn't keep late data: the default window configuration has allowed lateness of 0, so late data is dropped.
- Don't turn on Pub/Sub exactly-once delivery or ordering for Dataflow; to stop without losing data, use drain, not cancel.
The big picture: Pub/Sub ingests, Dataflow processes, BigQuery stores
Pub/Sub decouples producers from consumers and holds messages when consumers fall behind. Dataflow (running Apache Beam pipelines) cleans, transforms and aggregates over time. BigQuery stores the results for analysis. When a question describes thousands of IoT devices sending data that must be analyzed in real time, this chain is usually the answer (practice question #23). The hard part is in the details: Pub/Sub delivers at least once with no ordering guarantee by default, while Dataflow streaming runs in exactly-once mode by default.
Event time: where the timestamp comes from
A Pub/Sub message timestamp is when Pub/Sub received the message. Your data usually also has an event time, when the event happened at the source. By default, Dataflow's Pub/Sub connector uses the Pub/Sub timestamp. For event-time windows and watermarks, configure the connector to read the timestamp from a message attribute (withTimestampAttribute in Java, timestamp_attribute in Python). So if data must be analyzed over time, attach the timestamp and an ID at the publishing device, not when the subscriber receives it, and don't rely on Pub/Sub's generated timestamp (question #37).
Choosing a window
Streaming data is unbounded, so you can't group by key alone. Windows split the stream into finite pieces by element timestamp. Dataflow and Beam use two names for the same ideas, and a question can use either. In the Python SDK they are window.FixedWindows(size), window.SlidingWindows(size, period) and window.Sessions(gap_size), in seconds:
| Requirement in the question | Window | Notes |
|---|---|---|
| Reports for fixed, non-overlapping intervals | Tumbling (Beam: fixed) | Each element belongs to exactly one window |
| Running average: one minute of data, updated every 30 seconds | Hopping (Beam: sliding) | Windows overlap; the interval between starts is the period |
| Group a user's activity until they are idle for X minutes | Session, X-minute gap | Computed per key |
| Running totals with no time split | Global window + non-default trigger | For streaming data the default trigger waits for all data, which never happens |
Watermarks, triggers and late data
A watermark is the threshold at which Dataflow expects all data for a window to have arrived. An element that belongs to a window but arrives after the watermark has passed the end of that window is late data. Triggers decide when results are emitted. By default, results are emitted when the watermark passes the end of the window. Per the Apache Beam programming guide, the default windowing configuration has an allowed lateness of 0, so late data is discarded (in the Python SDK, WindowInto defaults to allowed_lateness=0).
To keep late data, set allowed lateness and add late firings. For speculative results before a window closes, add early firings. When a trigger fires several times, accumulating mode emits everything so far, while discarding mode emits only what is new since the last firing.
import apache_beam as beam
from apache_beam.transforms import trigger, window
events = (
p
| beam.io.ReadFromPubSub(
subscription=SUB,
timestamp_attribute="event_ts",
id_label="event_id")
| beam.Map(parse)
| beam.WindowInto(
window.FixedWindows(60),
trigger=trigger.AfterWatermark(
early=trigger.AfterProcessingTime(10),
late=trigger.AfterCount(1)),
accumulation_mode=(
trigger.AccumulationMode.ACCUMULATING),
allowed_lateness=600))
This Python snippet only illustrates the structure. It uses event time from the event_ts attribute and deduplicates on event_id. It then builds one-minute windows, emits speculative results on processing time, emits the main result when the watermark passes the window end, and fires again for late elements up to 600 seconds late. Per the SDK reference, event_ts must be milliseconds since the Unix epoch or an RFC 3339 string in UTC. Without timestamp_attribute, Beam uses the publish time.
Exactly-once guarantees accurate results for processed records, not complete results. Records later than your threshold are still dropped (see "Exactly-once in Dataflow", Late data).
How Pub/Sub delivers messages
- At-least-once is the default. A subscriber must ack within the acknowledgment deadline, or the message is redelivered. Per the subscription properties docs, the default is 10 seconds and the maximum is 600 seconds, and you can extend it with
ModifyAckDeadline. Rarely, a message is redelivered even after a successful ack, so subscribers should be idempotent. - Push and duplicates: a push endpoint acks by returning a success response. If it doesn't respond within the deadline, Pub/Sub redelivers and you see many duplicates (question #20).
- Exactly-once delivery in Pub/Sub works only with pull subscriptions, not push or export subscriptions. It only holds when subscribers connect within a single region, and it adds significant latency.
- Ordering keys: give related messages the same key, publish them in the same region, and enable message ordering when you create the subscription (it can't be changed later). Order is only guaranteed within a key.
Exactly-once in Dataflow: know the scope
Dataflow has two streaming modes. Exactly-once is the default: records are neither lost nor duplicated inside the pipeline. At-least-once (the streaming_mode_at_least_once service option) can produce duplicates but can significantly lower cost and latency. It suits per-element pipelines, or cases where a downstream step already deduplicates.
With a Pub/Sub source, Dataflow deduplicates by message ID. If a publisher sends the same record as two messages, the IDs differ, so deduplicate on an attribute the publisher sets (withIdAttribute / id_label). The docs say duplicates must be published within 10 minutes of each other to be detected. Also, side effects such as calling an external API inside a DoFn can run more than once because of retries. Prefer Beam's built-in sinks, or make your sink idempotent.
| Pub/Sub feature | Use with Dataflow? | Reason, per Dataflow docs |
|---|---|---|
| Exactly-once delivery | Not recommended | Dataflow has its own mechanism; enabling it limits parallel processing |
| Message ordering | Not recommended | The connector might not preserve order; adds latency |
| Dead-letter topic | Don't use | Dataflow can nack for internal reasons and acks after the first stage, so later-stage failures never reach it |
| One subscription for several pipelines | No | Each pipeline gets part of the data, causing duplicates, watermark lag and poor autoscaling |
Dead letters: in Pub/Sub or in the pipeline
For ordinary subscribers, a dead-letter topic forwards messages that can't be acked to another topic after a number of delivery attempts. It is a property of the subscription. Per the handling failures docs, the default maximum is 5 delivery attempts (allowed range 5–100), forwarding is best effort, and the Pub/Sub service agent needs the matching publisher and subscriber roles.
With Dataflow, build the dead-letter pattern inside the pipeline: route failed records to a separate output (a table or bucket) for later processing. With the Storage Write API, rows that can't be written land in a separate PCollection (getFailedStorageApiInserts in Java).
Writing to BigQuery: subscription or Dataflow
| Option | When to choose it | Semantics |
|---|---|---|
| BigQuery subscription | Messages need no transformation (or only light changes via a Single Message Transform); you want to avoid running Dataflow | At-least-once |
Dataflow + STORAGE_WRITE_API | You need windows, aggregations or enrichment, and no duplicates | Exactly-once |
Dataflow + STORAGE_API_AT_LEAST_ONCE | Duplicates are acceptable in exchange for lower cost and latency; pairs with at-least-once mode | At-least-once |
Dataflow + FILE_LOADS | Mainly batch; in streaming it needs windowing and adds delay | Incompatible with at-least-once mode |
Dataflow + STREAMING_INSERTS | Legacy systems and older questions | Best-effort deduplication; not recommended for new projects |
A BigQuery subscription also writes through the Storage Write API. It supports CDC (UPSERT/DELETE via a _CHANGE_TYPE field; the table needs a primary key) and can have a dead-letter topic, where failed messages carry an attribute with the reason. If a question says minimize operational overhead and no transformation is needed, this is usually the simplest answer.
Operating streaming pipelines
Streaming Engine and autoscaling
Streaming Engine moves pipeline execution from worker VMs into the Dataflow service backend. Workers then use less CPU, memory and Persistent Disk, and autoscaling responds more smoothly. Horizontal Autoscaling is on by default for streaming jobs that use Streaming Engine, with the upper bound set by --maxNumWorkers. When a question asks which setting lets Dataflow scale its compute up, the answer is the maximum number of workers, not the initial count (question #38).
Update, drain, cancel
- Update (replacement job): Dataflow runs a compatibility check so state and buffered data carry over to the new job.
- Drain: stops reading new data, finishes buffered work, then shuts down. It is the best way to avoid data loss when stopping.
- Cancel: stops immediately and can lose in-flight data.
- Replay: don't seek backwards on a running pipeline. Snapshot the subscription, create a new subscription from the snapshot, drain or cancel the old job, then rerun on the new subscription.
Common traps
- Enabling Pub/Sub exactly-once delivery or ordering for Dataflow: unnecessary, and it hurts performance.
- "No data loss" but picking cancel: only drain keeps buffered data.
- Assuming exactly-once keeps late data: data later than the allowed lateness is still dropped.
Reading the question
- out of order, late arriving: event time, watermarks, allowed lateness, triggers.
- without losing data when changing code: update if compatible, otherwise drain.
- no transformation: BigQuery subscription. aggregate, window, enrich: Dataflow.
- duplicates are acceptable, lower cost: at-least-once mode +
STORAGE_API_AT_LEAST_ONCE.
Start practicing
Try the 60 free PDE questions and watch for the Pub/Sub and Dataflow ones, then a timed exam (Pro). For the exam overview, see the Professional Data Engineer study guide.