CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 2 · Lesson 13/45

    Streaming from Kafka, Kinesis and Pub/Sub: connectors, offsets and payload decoding

    Develop data ingestion pipelines to ingest a variety of data formats, including Delta Lake, Parquet, JSON, Iceberg, CSV, and Binary from diverse sources such as message buses (Kafka, Kinesis, Pub/Sub) and cloud storage.

    13 min read
    2.4% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Configure Kafka, Kinesis and Pub/Sub streaming reads with the required connection and authentication options
    • Decode binary key, value, data and payload columns with cast, from_json and from_avro
    • Set startingOffsets and failOnDataLoss so a Kafka stream survives restarts and topic retention
    • Avoid the Kinesis and Pub/Sub settings that cause duplicates or data loss

    1.Every message bus hands you bytes

    Message buses deliver records, not files, and all three connectors return the message body as raw bytes. Kafka gives a binary key and value plus topic, partition, offset and timestamp. Kinesis gives a binary data blob plus partitionKey, stream, shardId, sequenceNumber and approximateArrivalTimestamp. Pub/Sub gives a byte-array payload plus messageId, a JSON-string attributes and publishTimestampInMillis. None of them knows your schema. Decoding is always a step you write yourself.

    Where the message body lives in each connector's output
    Connectorformat()Body column(s)Useful metadata columns
    Kafkakafkakey, value (binary)topic, partition, offset, timestamp
    Kinesiskinesisdata (binary)partitionKey, shardId, sequenceNumber
    Pub/Subpubsubpayload (bytes)messageId, attributes, publishTimestampInMillis

    Choose the decoding from how the producer serialized the data. Plain text or JSON is cast to a string and then parsed with from_json against a schema. Avro goes through from_avro, Protobuf through from_protobuf, and both can be wired to a schema registry. The example below parses the key and the value separately, each with its own small DDL schema, then flattens both into top-level columns.

    Kafka read with a service credential, decoding JSON key and valuepython
    kafka_options = {
      "kafka.bootstrap.servers": "<bootstrap-server>:9092",
      "subscribe": "<topic-name>",
      "databricks.serviceCredential": "<service-credential-name>",
    }
    
    # Read from Kafka and parse JSON
    parsed_df = (spark.readStream
      .format("kafka")
      .options(**kafka_options)
      .load()
      .select(
        from_json(col("key").cast("string"), key_schema).alias("key"),
        from_json(col("value").cast("string"), value_schema).alias("value")
      )
      .select("key.*", "value.*")
    )

    Checkpoint 1 of 7· Fill the gap

    This stream reads JSON-encoded events from a message-bus topic and decodes the key and value itself. Which format keyword completes the reader?

    kafka_options = {
      "kafka.bootstrap.servers": "<bootstrap-server>:9092",
      "subscribe": "<topic-name>",
      "databricks.serviceCredential": "<service-credential-name>",
    }
    
    # Read from Kafka and parse JSON
    parsed_df = (spark.readStream
      .format(" ? ")
      .options(**kafka_options)
      .load()
      .select(
        from_json(col("key").cast("string"), key_schema).alias("key"),
        from_json(col("value").cast("string"), value_schema).alias("value")
      )
      .select("key.*", "value.*")
    )

    Checkpoint 2 of 7· Check yourself

    A producer writes Avro-serialized records to a Kafka topic. Your bronze stream reads the topic with format("kafka"). How do you turn the value into usable columns?

    Sources12

    2.Connecting to Kafka: servers, topics and credentials

    A Kafka read needs exactly two things: kafka.bootstrap.servers, a comma-separated list of host:port, and one way of choosing what to read. subscribe takes a comma-separated list of topic names. subscribePattern takes a Java regex for topics that come and go, such as a orders_.* family. assign takes a JSON map of specific topic partitions, such as {"topicA":[0,1]}. assign is the narrowest of the three, not a way to read everything on the cluster.

    For authentication, a Unity Catalog service credential is the cleanest option because no secret appears in code. In Python it is databricks.serviceCredential; in SQL read_kafka it is serviceCredential. SASL/SSL and cloud-specific options cover AWS MSK, Azure Event Hubs and Google Cloud Managed Kafka. The same source works in batch with spark.read and an endingOffsets bound. For incremental batch loads, Databricks recommends a stream with Trigger.AvailableNow, which is also the recommended trigger on serverless compute.

    Watch lag through the source metrics avgOffsetsBehindLatest, maxOffsetsBehindLatest and minOffsetsBehindLatest. Use estimatedTotalBytesBehindLatest for a byte estimate. On Databricks Runtime 17.1 and above, a busy topic can show a small, constant non-zero backlog. That is expected and does not mean the stream is falling behind.

    Checkpoint 3 of 7· Match them up

    Match each Kafka source option to what it tells the reader.

    Tap a term, then the definition that fits it.

    Sources1

    3.startingOffsets, the checkpoint and failOnDataLoss

    startingOffsets answers one question: where does a brand-new query begin? For streaming the default is latest, which reads only messages produced after the stream starts. Messages already sitting in the topic are never seen, a common reason a new bronze table looks short. Set earliest on the first run to start from the oldest retained offset. For batch reads the default is already earliest.

    After the first run, the checkpoint takes over. Kafka partition offsets are stored in the streaming checkpoint, so a restart resumes exactly where the last committed batch ended, whatever startingOffsets says. Leaving it at latest therefore does not prevent reprocessing on restarts. The checkpoint does that. Without a durable checkpointLocation, every restart is a new query, and latest silently skips whatever arrived during the downtime.

    Topic retention causes the remaining failure. If the stream is down longer than the topic keeps data, the offsets in its checkpoint no longer exist. With failOnDataLoss at its default of true, the query fails. Setting it to false skips the missing range and continues. Choose that only when a gap is acceptable and a crash is not, because the check is conservative and can also fire on false alarms.

    Checkpoint 4 of 7· Check yourself

    After a two-week outage, a Kafka bronze stream restarts from its durable checkpoint. The topic only keeps data for seven days, and failOnDataLoss is left at its default. What happens?

    Checkpoint 5 of 7· Exam question

    A data engineer is building a Structured Streaming job that reads order events directly from a Kafka topic into a bronze Delta table: df = (spark.readStream .format("kafka") .option("kafka.bootstrap.servers", bootstrap) .option("subscribe", "orders") .option("startingOffsets", "latest") .load()) The job must survive restarts without reprocessing or silently skipping messages, and must not crash the first time offsets fall outside the topic's retention window. Which changes should the engineer make? (Select all that apply.)(Select 3)

    0 of 3 selected

    Sources34

    4.Kinesis: stream identity, auth and latency

    A Kinesis read uses format("kinesis") and names its source with either streamName or streamARN, never both. streamARN needs Databricks Runtime 16.1 or above. Pick one at the start and keep it. Switching between them on a running query can cause duplicates or data loss on restart. The safe move is a new query with a fresh checkpoint. Authentication uses a Unity Catalog connection or a service credential, or falls back to an instance profile or access keys. Decode data by casting it to a string.

    Kinesis is more flexible about growth than about shrinking. You can add shards without restarting the stream. On Databricks Runtime 19 and above you can also add a stream to the streamName list. The new stream is read from its earliest available offset. Removing a stream makes the restart fail with KINESIS_SOURCE_STREAMS_REMOVED_ON_RESTART so that unread records are not silently skipped. To remove one deliberately, restart once with failOnDataLoss set to false, then set it back to true.

    For alerting-style latency, make the query the only consumer of the stream. Set maxFetchDuration low (around 200ms) and minFetchPeriod to 210ms. Size the cluster so cores are at least twice the shard count divided by shardsPerTask. A low maxFetchDuration trades freshness for speed, so an availableNow run can finish slightly behind the newest records.

    Checkpoint 6 of 7· Put it in order

    Your Kinesis query reads streamName "stream1,stream2,stream3", and you want to stop reading stream3 for good. If you just remove it, the restart fails with KINESIS_SOURCE_STREAMS_REMOVED_ON_RESTART. Put the steps for removing it safely in order.

    1. 1.Stop the running query
    2. 2.Set failOnDataLoss back to true and restart on the same checkpoint
    3. 3.Change streamName to "stream1,stream2" and set failOnDataLoss to false
    4. 4.Restart the query once with these settings so it stops reading stream3

    Sources2

    5.Pub/Sub: credentials, roles and duplicates

    The Pub/Sub connector authenticates with a service account key. It needs four options: clientId, clientEmail, privateKey and privateKeyId. Keep them in secrets, not in notebook code. The SQL form reads them from a secret scope, as shown below. subscriptionId, topicId and projectId identify what to read.

    Streaming table over Pub/Sub with key material pulled from secretssql
    CREATE OR REFRESH STREAMING TABLE pubsub_raw
    AS SELECT * FROM STREAM read_pubsub(
      subscriptionId => 'mysub',
      projectId => 'myproject',
      topicId => 'mytopic',
      clientEmail => secret('pubsub-scope', 'clientEmail'),
      clientId => secret('pubsub-scope', 'clientId'),
      privateKeyId => secret('pubsub-scope', 'privateKeyId'),
      privateKey => secret('pubsub-scope', 'privateKey')
    );

    Missing IAM roles are the usual first failure. The credential needs roles/pubsub.viewer (or roles/viewer) to check the subscription and roles/pubsub.subscriber to fetch data. If you grant these on resources rather than on the project, grant both on both the topic and the subscription. roles/pubsub.editor is optional. It lets the connector create the subscription if it is missing and allows deleteSubscriptionOnStreamStop.

    Exactly-once here means once per row the subscriber received, not once per business event. Pub/Sub itself can publish duplicates and deliver rows out of order, so your pipeline must deduplicate, typically on messageId, and must tolerate late rows. The progress metric numDuplicatesSinceStreamStart shows how often this happens. Trigger.AvailableNow works for incremental batches. spark.speculation is not supported.

    Checkpoint 7 of 7· Fill the gap

    In this streaming table definition over Google Pub/Sub, which named argument identifies the subscription the connector reads from?

    CREATE OR REFRESH STREAMING TABLE pubsub_raw
    AS SELECT * FROM STREAM read_pubsub(
       ?  => 'mysub',
      projectId => 'myproject',
      topicId => 'mytopic',
      clientEmail => secret('pubsub-scope', 'clientEmail'),
      clientId => secret('pubsub-scope', 'clientId'),
      privateKeyId => secret('pubsub-scope', 'privateKeyId'),
      privateKey => secret('pubsub-scope', 'privateKey')
    );

    Sources5

    Practise it for real

    Land a Kafka topic in a Delta table as an incremental batch that resumes cleanly on every run

    1. 1.Build an options dict with kafka.bootstrap.servers, subscribe and databricks.serviceCredential, and add startingOffsets set to earliest.

      Why: The service credential keeps secrets out of code, and earliest makes the first run pick up messages already in the topic.

      You should see: spark.readStream.format("kafka").options(**kafka_options).load() returns columns key, value, topic, partition, offset, timestamp, timestampType.

    2. 2.Cast key and value to string and parse each with from_json and a DDL schema such as "event_type STRING, event_ts TIMESTAMP", then select "key.*", "value.*".

      Why: Kafka always delivers key and value as byte arrays, so you have to deserialize them yourself.

      You should see: A flat DataFrame with typed columns such as user_id, event_type and event_ts.

    3. 3.Write with writeStream.format("delta"), a checkpointLocation and trigger(availableNow=True) to a catalog.schema table, then call awaitTermination().

      Why: The checkpoint stores the Kafka offsets, and availableNow processes the backlog and stops.

      You should see: The query finishes after consuming everything that was available, and the table holds the parsed events.

    4. 4.Produce a few more messages and run the same code again with the same checkpoint.

      Why: Shows that startingOffsets is ignored once a checkpoint exists.

      You should see: Only the new messages are appended; earlier ones are not duplicated.

    Stuck? Get a nudge

    If the second run re-reads everything, check that the checkpointLocation path did not change between runs.

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “The key and the value are always deserialized as byte arrays with the ByteArrayDeserializer.”
      ↩︎ Every message bus hands you bytes
      “This example uses a fixed JSON schema. For other formats like Avro or Protobuf, use from_avro or from_protobuf.”
      ↩︎ Every message bus hands you bytes
      “including Unity Catalog service credentials, SASL/SSL, and cloud-specific options for AWS MSK, Azure Event Hubs, and Google Cloud Managed Kafka”
      ↩︎ Connecting to Kafka: servers, topics and credentials
      “For incremental batch loading, Databricks recommends using Kafka with Trigger.AvailableNow.”
      ↩︎ Connecting to Kafka: servers, topics and credentials
      “Specific topicPartitions to consume.”
      ↩︎ Exam trap 2
      “assign | JSON string {"topicA":[0,1],"topic":[2,4]}. | Specific topicPartitions to consume.”
      ↩︎ Checkpoint
    2. 2.
      “To deserialize the data in the data column, cast the field to a string.”
      ↩︎ Every message bus hands you bytes
      “For all Databricks Runtime versions, you must specify either streamName or streamARN, but not both.”
      ↩︎ Kinesis: stream identity, auth and latency
      “Kinesis supports authentication with a Unity Catalog connection, a service credential, or alternate methods such as an instance profile or access keys.”
      ↩︎ Kinesis: stream identity, auth and latency
      “This guarantees that the query doesn't silently skip unread records from the removed stream.”
      ↩︎ Kinesis: stream identity, auth and latency
      “Set failOnDataLoss back to true and restart using the same checkpoint. This restores data-loss checks.”
      ↩︎ Checkpoint
      “Set failOnDataLoss back to true and restart using the same checkpoint. This restores data-loss checks.”
      ↩︎ Checkpoint
    3. 3.
      “The default value is latest, which only reads new data arriving after the stream starts.”
      ↩︎ startingOffsets, the checkpoint and failOnDataLoss
    4. 4.
      “Whether to fail the query if data might have been lost, for example, due to deleted topics or offset truncation.”
      ↩︎ startingOffsets, the checkpoint and failOnDataLoss
      “Set to false to skip missing data and continue.”
      ↩︎ startingOffsets, the checkpoint and failOnDataLoss
      “For streaming queries, this option only applies when a new query starts. Resumed queries always use the checkpoint.”
      ↩︎ Exam trap 1
    5. 5.
      “This connector has exactly-once processing semantics for rows from the subscriber.”
      ↩︎ Pub/Sub: credentials, roles and duplicates
      “Databricks recommends that you use secrets when using keys.”
      ↩︎ Pub/Sub: credentials, roles and duplicates
      “you must apply both roles to both the topic and the subscription”
      ↩︎ Pub/Sub: credentials, roles and duplicates
      “Pub/Sub might publish duplicate rows, or rows might arrive to the subscriber out of order.”
      ↩︎ Exam trap 3

    Also cited

    Spotted a mistake, or was something unclear? Tell us.