Exactly-Once Processing Patterns with Beam and Google Cloud Pub/Sub
“Exactly once” is not one switch on a Pub/Sub subscription. It is a guarantee assembled across four boundaries: message delivery, Beam state, state or sink commits, and observable recovery. Pub/Sub can acknowledge a message after a subscriber handles it, and Beam can restore consistent processing state, but a failure between an external side effect and an acknowledgement can still produce a retry.
The useful production goal is narrower and testable: every accepted event must be applied once in the materialized business result, and duplicates must be measurable and repairable. This article shows the failure windows and the patterns that close them.
Start with at-least-once delivery
Google Cloud Pub/Sub is a distributed delivery system with an acknowledgement protocol. With an ordinary pull subscriber, a message remains eligible for redelivery until it is acknowledged or expires. If a subscriber:
- processes and acknowledges normally, the message is complete;
- crashes before processing, Pub/Sub redelivers it;
- crashes after an external write but before acknowledgement, Pub/Sub redelivers it.
The third case is the central failure window. An at-least-once source does not reveal whether the prior process completed a side effect. Retrying safely therefore requires a stable event identity and idempotent or transactional work.
Keep eventId in the immutable message envelope:
{
"eventId": "pay-2e5c8a1d",
"eventVersion": 1,
"eventTime": "2019-12-05T14:31:22.314Z",
"accountId": "account-82",
"type": "PAYMENT_CAPTURED",
"amountCents": 12900
}
Generate this identity at the producer’s business operation boundary and retain it through redelivery, replay, and reserialization. Do not derive it only from Pub/Sub message ID if a producer retry creates a second Pub/Sub message for the same payment.
What Beam guarantees
Beam’s processing model connects element time, windows, state, timers, and runner checkpoints. A capable streaming runner saves source progress and deterministic pipeline state in a coherent checkpoint. After a worker failure, the runner restores that checkpoint and may process elements after it again.
The guarantee is often described as effectively-once output for supported deterministic transforms and sinks, but the guarantee still stops at the runner-managed boundary. If a ParDo calls an external API and later crashes, Beam does not know whether that request committed. An arbitrary HTTP side effect is not made transactional by putting it inside a Beam transform.
Stateful processing is useful for deduplication:
public final class DedupePayment
extends DoFn<Payment, Payment> {
@StateId("seen")
private final StateSpec<SetStateSpec<String>> seen =
StateSpecs.set();
@StateId("ttl")
private final StateSpec<ValueStateSpec<Long>> expiry =
StateSpecs.value(VarLongCoder.of());
@TimerId("expire")
private final TimerSpec expiryTimer =
TimerSpecs.timer(TimeDomain.EVENT_TIME);
@ProcessElement
public void processElement(
ProcessContext context,
@Element Payment payment,
@StateId("seen") SetState<String> seen,
@StateId("ttl") ValueState<Long> expiry,
@TimerId("expire") Timer expire) {
if (seen.contains(payment.eventId()).read() == null) {
seen.add(payment.eventId());
context.output(payment);
}
}
}
The real implementation needs a retention policy matching the maximum credible duplicate delay. Set an event-time timer, persist a dedupe window boundary, and clear old IDs rather than growing state forever. The key for this transform must be the event identity or another stable dedupe partition. A process-wide in-memory cache is not sufficient: it disappears at restart and is split incorrectly across workers.
Idempotency before exactly-once claims
An idempotent consumer accepts the same logical operation repeatedly but leaves the business result equivalent to applying it once.
For a relational sink, the transaction can insert the event identity and update the aggregate in the same commit:
BEGIN;
INSERT INTO processed_event (
event_id, event_type, received_at, payload_hash
) VALUES (
'pay-2e5c8a1d', 'PAYMENT_CAPTURED', CURRENT_TIMESTAMP, '...'
)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;
-- The account update runs only if the insert returned a row.
UPDATE account_balance
SET captured_cents = captured_cents + 12900
WHERE account_id = 'account-82';
COMMIT;
The application must test the returned identity and skip the update when the insert conflicts. A unique index on event_id is what closes the race between two retries or workers.
For object storage, use a deterministic object key:
gs://payments-normalized/date=2019-12-05/event_id=pay-2e5c8a1d.json
The writer uses create-if-absent semantics or a commit manifest. If overwriting is allowed, require canonical serialization so that retry bytes are identical. An unordered retry that overwrites a newer logical version is still a correctness bug even if it avoids extra files.
For an API that supports an idempotency key, send the event ID as that key and store the remote result. If the remote API has no idempotency facility, place the request behind a transactionally owned outbox and document the residual at-most once or at-least-once boundary.
Transactional sink pattern
The strongest practical pattern combines the Beam source checkpoint with a sink transaction only when the sink and runner can participate in a coordinated commit. Otherwise, make the sink idempotent.
A generic transaction pattern has these stages:
- Beam prepares a deterministic bundle or window.
- The sink stages rows under a transaction identifier.
- Beam commits the bundle as part of runner finalization.
- The sink makes the rows visible atomically.
- A retry discovers the committed transaction or writes a no-op.
For BigQuery, an event ID plus append-only load history may support effectively-once materialization. For Cloud Spanner or another transactional database, event-ID uniqueness can make retries converge. The exact implementation must match the Beam sink connector’s documented capabilities; “I called commit after context.output” is not a transactional protocol.
Dedupe is bounded, not absolute
A stateful dedupe key is valid only within a configured time horizon. Define the horizon from the duplication envelope:
maximum duplicate age =
producer retry window
+ Pub/Sub acknowledgment/retention time
+ Beam outage and restore time
+ replay window
If Beam keeps event IDs for 24 hours, a deliberate seven-day replay can legitimately arrive after expiry. Replay should therefore use a separate idempotency key or sink-level uniqueness. Do not make the in-memory/stateful dedupe layer the sole correctness mechanism.
Choose dedupe keys to match the operation. A profile update with version 9 should be sequence-aware: a delayed duplicate version 9 is ignored, but a late version 8 must not overwrite version 9. For additive events, a unique event ID is appropriate. For current state, use a monotonic source sequence or transaction LSN as well as the operation ID.
Duplicate test
A test should intentionally stop processing after a simulated sink commit and before Beam checkpoint progress. The duplicate result must not change the sink:
@Test
void committedEventRemainsIdempotentAfterReplay() {
PipelineOptions options = PipelineOptionsFactory.create();
TestStream<Envelope> input = TestStream.create(EnvelopeCoder.of())
.addElements(
event("pay-100", 12900),
event("pay-100", 12900))
.advanceWatermarkToInfinity();
Pipeline pipeline = Pipeline.create(options);
PCollection<EventResult> results = pipeline
.apply(input)
.apply(Keyed.by(Envelope::eventId))
.apply("Transactional apply", ParDo.of(new TestIdempotentSink()));
PAssert.that(results)
.satisfies(rows -> {
assertEquals(1, rows.size());
assertEquals(12900L, rows.iterator().next().balanceDeltaCents());
return null;
});
pipeline.run().waitUntilFinish();
}
TestIdempotentSink must model the real persistence rule: insert event ID first, then apply the delta only when insertion wins. Merely counting inputs through an in-memory Set tests Beam grouping, not the actual crash boundary.
Add a failure-injection test that:
- writes the event identity;
- returns an injected failure before returning the sink result;
- retries the exact message;
- verifies one durable account effect and two attempted deliveries.
Also test two concurrent workers applying the same ID. A correct unique-index pattern yields one winner. A read-then-write implementation without a transaction usually fails this race.
Acknowledgements and sink progress
In a Beam-managed Pub/Sub source, acknowledgement is associated with successful source/snapshot progress; it is not a prompt to add a manual acknowledge call from an arbitrary transform. If the application also uses a direct Pub/Sub client outside Beam, never acknowledge before committing the side effect. Ack only after the external idempotency record or transaction is durable.
Acknowledgement-deadline tuning reduces unnecessary redelivery but does not manufacture exactly-once behavior. For long work, extend the lease where the subscriber library permits. Still assume a long message may be redelivered after a worker loss.
Dead-letter handling is another sink boundary. A poison message rejected after fixed attempts must be written with the original Pub/Sub attributes, message ID, event ID, schema version, and failure category. If the DLQ subscription is also at-least-once, assign the rejection a deterministic failure ID and preserve the source identity during repair.
Guarantee matrix
| Boundary | Typical guarantee | What closes the gap |
|---|---|---|
| Producer to Pub/Sub | At-least-once with publish retries | Stable business eventId and retry-aware producer |
| Pub/Sub to Beam | At-least-once redelivery from checkpoints | Runner progress, acknowledgment, source retention |
| Beam deterministic state | Restored snapshot/state | Compatible state schema and bounded durable dedupe |
| Beam to HTTP endpoint | No built-in transaction | Endpoint idempotency key or durable outbox |
| Beam to transactional DB | Sink transaction plus unique key | Atomic insert-ID + business update |
| Beam to object storage | Staging then manifest/overwrite | Deterministic key and visible-after-commit protocol |
| Repair replay | Deliberate second delivery | Original event identity and sink-level idempotency |
Document this matrix next to the pipeline instead of saying only “exactly once.” It identifies who can prove the guarantee and what happens during each uncertain commit.
Operations and service objectives
The most useful metric is not duplicate attempts; it is duplicate business effects. Instrument both:
- Pub/Sub undelivered message age and acknowledgement latency;
- Beam backlog, failed bundles, checkpoint duration, and restored state bytes;
- source messages and accepted logical events by event ID;
- repeated-event attempts by dedupe horizon;
- idempotent conflict/insert-skipped count;
- DLQ count, oldest age, and replay completion;
- sink commit latency and ambiguous-error retries;
- end-to-end freshness from producer event time.
An initial target might be zero duplicate business effects in fault tests, fewer than 0.01% late idempotent insert conflicts under normal operation, undelivered message age below five minutes, and failed worker recovery under 15 minutes. Measure the expected duplicate rate separately; a zero duplicate-delivery metric is not realistic for an at-least-once transport.
Run a quarterly game day:
1. Create a known event and record its event ID.
2. Pause the sink acknowledgement response after commit.
3. Kill the Beam worker.
4. Wait for redelivery.
5. Assert one business row and two source attempts.
6. Compare Pub/Sub age, Beam lag, and sink result.
7. Replay the event again manually and repeat the assertion.
Exactly-once behavior is therefore not a quality adjective. It is an externally observable invariant produced by stable identity, bounded dedupe, atomic sink behavior, and a recovery test that crosses the real boundaries.