Kafka-to-BigQuery Streaming with Apache Beam
Kafka provides a durable, replayable input log, while BigQuery provides an analytical destination. Apache Beam is the boundary between them: it decodes the source contract, assigns event time, validates records, and controls how data is written and retried. A reliable Kafka-to-BigQuery pipeline must describe all three positions: Kafka offset, Beam bundle/checkpoint, and BigQuery write.
The example below runs a Beam Java pipeline on Google Kubernetes Engine (GKE), reads an external Kafka cluster over an approved private route, validates checkout events, and writes successful records to a partitioned BigQuery table. Invalid events go to a queryable dead-letter queue (DLQ).
Establish the event contract
Treat Kafka as a byte transport, not a substitute for a schema. A producer contract should define the key, event identifier, event timestamp, field types, nullability, and compatibility policy:
{
"schemaVersion": 2,
"eventId": "7e2df26b-5ac0-4de8-8cf6-fc1da6be2d6b",
"checkoutId": "co-1842",
"accountId": "a-82",
"amountCents": 12495,
"currency": "CAD",
"region": "CA-ON",
"eventTime": "2020-07-23T14:31:22.314Z"
}
Use eventId as the end-to-end identity. Use checkoutId or accountId as the Kafka key when ordering matters. Do not infer an identity from the event body: two retries with changed metadata would then look like different events.
Schema evolution needs an explicit decoder policy. A newly added nullable field is usually backward compatible. Renaming a field, changing a numeric field to a string, or making a formerly optional field required is not. Publish the schema version, test old and new fixtures, and keep the Beam job able to decode every version still present in Kafka retention.
Connect Beam on GKE to external Kafka
KafkaIO is an unbounded source in a Dataflow-style Beam model. On a self-managed Kubernetes runner, the worker pods need:
- DNS resolution for every bootstrap host;
- a stable private network path and firewall rule;
- TLS trust material and SASL credentials;
- Kafka ACLs for the source topic and consumer group;
- Google credentials for BigQuery, storage, DLQ, and metrics.
Bootstrap addresses are a small discovery surface, but brokers may advertise addresses that a pod cannot reach. Test advertised listeners from inside the namespace rather than only from a workstation. Keep credentials in a Kubernetes Secret or external secret manager; inject their path into the Beam job container.
Start with Kafka partitions as the upper bound on useful source parallelism. A 24-partition topic does not benefit from 100 concurrent Kafka readers, although later stages can use more workers if validation or serialization is expensive.
Java Beam pipeline
The following pipeline retains topic, partition, and offset in a processing context. Those values are useful in the DLQ and in controlled replays:
public final class KafkaCheckoutPipeline {
static final String PROJECT = "example-analytics";
static final String DATASET = "commerce";
public static void main(String[] args) {
Options options = PipelineOptionsFactory.fromArgs(args)
.withValidation().as(Options.class);
Pipeline pipeline = Pipeline.create(options);
PCollection<KafkaRecord<String, byte[]>> raw =
pipeline.apply("Read Kafka",
KafkaIO.<String, byte[]>read()
.withBootstrapServers(options.getBootstrapServers())
.withTopic("checkout-events-v2")
.withConsumerConfigUpdates(Map.of(
"group.id", "beam-bigquery-checkouts-v1"))
.withKeyDeserializer(StringDeserializer.class)
.withValueDeserializer(ByteArrayDeserializer.class)
.withReadCommitted()
.withoutMetadata());
PCollection<Checkout> decoded = raw
.apply("Decode and validate",
ParDo.of(new DecodeCheckout(options.getDlqTopic())))
.apply("Event timestamps",
WithTimestamps.<Checkout>of(
event -> new Instant(event.eventTimeMillis()))
.withAllowedTimestampSkew(Duration.standardDays(30)));
decoded.apply("Write BigQuery",
BigQueryIO.<Checkout>write()
.to(CHECKOUT_TABLE)
.withSchema(CHECKOUT_SCHEMA)
.withFormatFunction(CheckoutFormat::toTableRow)
.withWriteDisposition(
BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
.withCreateDisposition(
BigQueryIO.Write.CreateDisposition.CREATE_NEVER)
.withTimePartitioning(new TimePartitioning()
.setType("DAY")
.setField("event_time"))
.withMethod(BigQueryIO.Write.Method.STREAMING_INSERTS)
.withFailedInserts(new BigQueryDlqFn(options.getDlqTopic())));
pipeline.run();
}
}
This is intentionally framework-oriented rather than a complete build file. Pin the Beam, Kafka, and Google Cloud client versions together, compile with the same Java version used by the worker image, and stage a self-contained uber-JAR for GKE.
KafkaIO.withoutMetadata() makes the sample simpler, but production DLQ records should retain Kafka metadata. Use the metadata-bearing transform before stripping it, or place topic, partition, and offset into an envelope immediately after source reading.
Validation as a side-output boundary
Validation must be deterministic. Do not contact an external service from the transform on every record:
final class DecodeCheckout extends DoFn<KafkaRecord<String, byte[]>, Checkout> {
private final TupleTag<Checkout> valid = new TupleTag<Checkout>() {};
private final TupleTag<String> deadLetters = new TupleTag<String>() {};
private transient ObjectMapper mapper;
@Setup
public void setup() {
mapper = new ObjectMapper();
}
@ProcessElement
public void processElement(ProcessContext context) {
KafkaRecord<String, byte[]> source = context.element();
try {
Checkout event = mapper.readValue(source.getKV().getValue(), Checkout.class);
requireKnownVersion(event.schemaVersion());
requireNonBlank(event.eventId());
require(event.amountCents() >= 0, "negative amount");
require(Instant.parse(event.eventTime()).isBefore(
Instant.now().plus(Duration.standardHours(24))),
"timestamp too far in the future");
context.output(valid, event);
} catch (Exception error) {
DlqRecord failed = DlqRecord.from(
source.getTopic(), source.getPartition(), source.getOffset(),
source.getKV().getValue(), "VALIDATION_ERROR", error.getMessage());
context.output(deadLetters, mapper.writeValueAsString(failed));
}
}
}
The DLQ envelope should contain the original bytes (encoded safely), pipeline version, schema version, source coordinates, first-seen time, and a stable failure category. Avoid writing only a free-form exception message; it is difficult to trend or repair consistently.
Validation policy is a product decision. Required-field failures are usually poison records. Unknown newer schema versions can be quarantined until a compatible job is deployed. A temporarily unavailable lookup is an infrastructure failure and should retry or fail the job, not permanently reject the event.
BigQueryIO methods
BigQueryIO has two useful loading modes:
| Mode | When to use it | Main constraint |
|---|---|---|
| Streaming inserts | Low-latency dashboards and variable records | Per-row API behavior and insert costs; failed inserts must be captured |
| File loads | Throughput, cost control, bounded trigger windows | Data is staged and committed in load jobs; higher result latency |
STREAMING_INSERTS is appropriate when p95 freshness in seconds or low minutes matters. Set a worker cap, batch to BigQuery where supported by the runner, and use withFailedInserts so a rejected row is not silently lost. A streaming insert can be retried; a source event ID stored in BigQuery enables downstream idempotency checks.
FILE_LOADS is a throughput-oriented alternative:
BigQueryIO.<Checkout>write()
.to(CHECKOUT_TABLE)
.withSchema(CHECKOUT_SCHEMA)
.withFormatFunction(CheckoutFormat::toTableRow)
.withMethod(BigQueryIO.Write.Method.FILE_LOADS)
.withTriggeringFrequency(Duration.standardMinutes(2))
.withNumFileShards(8)
.withWriteDisposition(
BigQueryIO.Write.WriteDisposition.WRITE_APPEND);
File loads can lower request and byte overhead, but cannot promise the same sub-minute freshness. The trigger frequency, shard count, and allowable late data together determine load cadence. File names and job identifiers should be runner-managed and retry-safe.
For a table partitioned by event_time, be careful with extremely late data. BigQuery can route it to an old partition, but queries, maintenance, and billing must account for old-partition scans. Reject or separately route events outside the business retention window, then backfill them deliberately.
Event time, lateness, and replay
Kafka record timestamp is not automatically the correct business timestamp. Beam timestamps should come from the event’s eventTime, and the watermark should be based on a measured bound. A 30-minute bound is a promise about skew from the producer to Beam; it is not a substitute for a service-level objective.
A simple event-time policy has three outcomes:
- process records inside the allowed window normally;
- route late-but-valid records to an append-only late-data topic or table;
- reject implausibly old records to the DLQ after recording the policy.
Measure lateness by partition:
SELECT
DATE(event_time) AS event_day,
APPROX_QUANTILES(
TIMESTAMP_DIFF(ingest_time, event_time, SECOND), 100
)[OFFSET(95)] AS p95_lateness_seconds
FROM `example-analytics.commerce.checkouts`
WHERE ingest_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)
GROUP BY event_day;
Keep checkpoints and Kafka retention aligned. If a GKE Beam job is down for 36 hours but Kafka retains only 24 hours, a checkpoint cannot replay missing inputs. Retain source data for at least the maximum credible restart plus the time needed to recover and catch up.
DLQ and repair
Use a DLQ as an addressable recovery system, not as a discarded topic. A useful shape is:
{
"failureId": "beam-bigquery-checkouts-v1:orders:3:819204",
"eventId": "7e2df26b-5ac0-4de8-8cf6-fc1da6be2d6b",
"topic": "checkout-events-v2",
"partition": 3,
"offset": 819204,
"failureStage": "VALIDATION",
"failureCode": "UNKNOWN_SCHEMA_VERSION",
"pipelineVersion": "2020.07.23-4",
"rawPayloadBase64": "eyJzY2hlbWFWZXJzaW9uIjo..."
}
An operator should be able to filter by code, inspect samples, deploy a decoder, and replay by a controlled offset range. Replay through a repair topic rather than editing a production topic. Preserve the original event ID and source identity so reconciliation can distinguish a correction from a duplicate.
A DLQ requires its own SLO: for example, less than 0.1% of source events over five minutes, and zero unrepaired records older than one day. Alert on sustained growth as well as rate; a low-volume DLQ with a permanently stuck schema failure can still hide important records.
Backfill and schema evolution
Never backfill by resetting the production consumer group and hoping downstream rows remain correct. Use a separately named job and checkpoint, an explicit Kafka offset range, a bounded replay time, and an isolated BigQuery destination.
One controlled procedure is:
- select the exact start and end Kafka offsets by partition;
- record the source schema versions and retention boundary;
- create
commerce.checkouts_backfill_YYYYMMDD; - run workers with a unique consumer group and checkpoint path;
- compare event IDs, counts, aggregate cents, and min/max event time;
- swap the promoted table or use an idempotent merge into production;
- preserve the checkpoint and offset manifest for audit.
For schema evolution, use BigQuery’s compatible additions first: add nullable columns with defaults at read time. During a breaking change, publish a new versioned table, dual-write for the overlap window, compare the two representations, and cut over consumers. Do not let arbitrary producer JSON cause implicit table mutation.
Reliability and operations on GKE
The Beam deployment should separate job orchestration from worker lifecycle. Configure resource requests, limits, graceful shutdown, pod disruption budgets, and a durable checkpoint/savepoint location. A rolling pod replacement is expected; a simultaneous loss of all workers is not.
Measure these signals:
- Kafka lag in messages and estimated seconds per partition;
- Beam bundle latency, backlog, failed elements, and pod restarts;
- schema and validation rejection rate by version and reason;
- BigQuery failed insert/load count, load duration, and bytes charged;
- end-to-end freshness from event time to table visibility;
- late-record rate and DLQ age.
Example initial SLOs are p95 freshness under five seconds for streaming inserts, p99 under 30 seconds, Kafka backlog below five minutes during normal load, fewer than 0.1% validation failures, and checkpoint/restart recovery under 15 minutes. Load-test at twice the expected peak and then halt BigQuery writes for ten minutes to prove catch-up behavior.
Cost controls
Streaming insert cost is driven by sustained row volume and operational retries; file-load cost is dominated by worker time, staging storage, load behavior, and scan patterns. Choose a mode from measured latency requirements, not preference.
Control cost by:
- retaining only fields used by downstream models;
- compressing Kafka payloads and Beam staging files;
- partitioning BigQuery by event time and clustering repeated filters;
- avoiding
SELECT *over broad historical partitions; - autoscaling Beam workers with a bounded maximum;
- monitoring duplicate event IDs and retry amplification;
- reconciling late data in a separate controlled job.
The pipeline is reliable when every record has one of four observable destinations: a BigQuery row, an explicit DLQ record, a recognized late-data path, or a still-replayable Kafka offset. Anything outside those states is operational debt.