30

Spark 2.2 introduced a Kafka's structured streaming source. As I understand, it's relying on HDFS checkpoint directory to store offsets and guarantee an "exactly-once" message delivery.

But old docks (like https://blog.cloudera.com/blog/2017/06/offset-management-for-apache-kafka-with-apache-spark-streaming/) says that Spark Streaming checkpoints are not recoverable across applications or Spark upgrades and hence not very reliable. As a solution, there is a practice to support storing offsets in external storage that supports transactions like MySQL or RedshiftDB.

If I want to store offsets from Kafka source to a transactional DB, how can I obtain offset from a structured stream batch?

Previously, it can be done by casting RDD to HasOffsetRanges:

val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges    

But with new Streaming API, I have an Dataset of InternalRow and I can't find an easy way to fetch offsets. The Sink API has only addBatch(batchId: Long, data: DataFrame) method and how can I suppose to get an offset for given batch id?

zero323
  • 322,348
  • 103
  • 959
  • 935
dnaumenko
  • 591
  • 1
  • 4
  • 10

3 Answers3

61

Spark 2.2 introduced a Kafka's structured streaming source. As I understand, it's relying on HDFS checkpoint dir to store offsets and guarantee an "exactly-once" message delivery.

Correct.

Every trigger Spark Structured Streaming will save offsets to offset directory in the checkpoint location (defined using checkpointLocation option or spark.sql.streaming.checkpointLocation Spark property or randomly assigned) that is supposed to guarantee that offsets are processed at most once. The feature is called Write Ahead Logs.

The other directory in the checkpoint location is commits directory for completed streaming batches with a single file per batch (with a file name being the batch id).

Quoting the official documentation in Fault Tolerance Semantics:

To achieve that, we have designed the Structured Streaming sources, the sinks and the execution engine to reliably track the exact progress of the processing so that it can handle any kind of failure by restarting and/or reprocessing. Every streaming source is assumed to have offsets (similar to Kafka offsets, or Kinesis sequence numbers) to track the read position in the stream. The engine uses checkpointing and write ahead logs to record the offset range of the data being processed in each trigger. The streaming sinks are designed to be idempotent for handling reprocessing. Together, using replayable sources and idempotent sinks, Structured Streaming can ensure end-to-end exactly-once semantics under any failure.

Every time a trigger is executed StreamExecution checks the directories and "computes" what offsets have been processed already. That gives you at least once semantics and exactly once in total.

But old docs (...) says that Spark Streaming checkpoints are not recoverable across applications or Spark upgrades and hence not very reliable.

There was a reason why you called them "old", wasn't there?

They refer to the old and (in my opinion) dead Spark Streaming that kept not only offsets but the entire query code that led to situations where the checkpointing were almost unusable, e.g. when you change the code.

The times are over now and Structured Streaming is more cautious what and when is checkpointed.

If I want to store offsets from Kafka source to a transactional DB, how can I obtain offset from a structured stream batch?

A solution could be to implement or somehow use MetadataLog interface that is used to deal with offset checkpointing. That could work.

how can I suppose to get an offset for given batch id?

It is not currently possible.

My understanding is that you will not be able to do it as the semantics of streaming are hidden from you. You simply should not be dealing with this low-level "thing" called offsets that Spark Structured Streaming uses to offer exactly once guarantees.

Quoting Michael Armbrust from his talk at Spark Summit Easy, Scalable, Fault Tolerant Stream Processing with Structured Streaming in Apache Spark:

you should not have to reason about streaming

and further in the talk (on the next slide):

you should write simple queries & Spark should continuously update the answer


There is a way to get offsets (from any source, Kafka including) using StreamingQueryProgress that you can intercept using StreamingQueryListener and onQueryProgress callback.

onQueryProgress(event: QueryProgressEvent): Unit Called when there is some status update (ingestion rate updated, etc.)

With StreamingQueryProgress you can access sources property with SourceProgress that gives you what you want.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
  • 2
    Wow, nice answer :) But last point should be the first :) However, up vote is deserved :) – T. Gawęda Sep 12 '17 at 18:28
  • 2
    "You should not. Period." - that's not an answer I was looking for :) If you follow the JIRA ticket on Spark, getting offsets is still a valid use-case. For example, what's about not-locking myself to Spark? If I have offsets in external storage, I can re-write my ETL's to Apache Flink and just let it pick up latest offsets from my storage (which is reliable by default because all data/offsets updates happen in one transaction) – dnaumenko Sep 12 '17 at 18:47
  • Looks like StreamingQueryListener is needed for some other purposes like monitoring, debugging, etc. I can't see how I can use it inside of custom sinks. – dnaumenko Sep 12 '17 at 18:50
  • Mind sharing the link to the JIRA ticket? `StreamingQueryListener` is not for custom sinks. That's for sure. You are right. I only mentioned it to have the whole picture of how deep are offsets hidden from you :) – Jacek Laskowski Sep 12 '17 at 20:59
  • @JacekLaskowski Sure, https://issues-test.apache.org/jira/browse/SPARK-18258. The idea is to have an offset in addBatch() method. – dnaumenko Sep 13 '17 at 08:00
  • It's being discussed as we speak so my recommendation still holds, _doesn't it?_ – Jacek Laskowski Sep 13 '17 at 10:16
  • 2
    @JacekLaskowski I don't think so. It has a nice explanation of what is going on and it helps me to get better understanding, but it's misleading in part that say "you shouldn't do it". Maybe it would be better to say, that's is hard to do this currently - you either pass the topic/partition and offset from Source to Sink, or read offsets from batch id from checkpoint directory. – dnaumenko Sep 14 '17 at 09:09
  • Reworded the answer and added the note about `MetadataLog`. That _could_ work, but haven't tried it out myself. – Jacek Laskowski Sep 14 '17 at 13:32
  • @JacekLaskowski great answer, thanks. I've read "Furthermore, this same mechanism allows you to upgrade your query between restarts, as long as the input sources and output schema remain the same." on this blog article https://databricks.com/blog/2017/01/19/real-time-streaming-etl-structured-streaming-apache-spark-2-1.html Just because in real life applications schema changes, we should not rely on the offsets saved inside checkpoint folder, as we won't be able to retrieve them, and store them ourselves (https://github.com/polomarcus/Spark-Structured-Streaming-Examples). Would you agree? – Paul Leclercq Sep 15 '17 at 19:49
  • @PaulLeclercq Offsets are the integral part of a streaming source and it rarely if ever changes. I would not worry about them. They're stable. I wish I could see an example that would show I'm wrong. Do you have one? State seems risky (as state rows are persisted in checkpoint location). – Jacek Laskowski Sep 15 '17 at 21:27
  • @JacekLaskowski sorry for the misunderstanding. I was not talking about the offsets changing, but the actual message's schema changing (adding a new column for example). This is how I've understood "as long as the input sources and output schema remain the same" in the databricks' article I mentioned. I need to test that! I'll get back to you – Paul Leclercq Sep 18 '17 at 19:21
  • _"the actual message's schema changing (adding a new column for example)"_ unless elaborate, I'm here to say that it _is_ possible. – Jacek Laskowski Sep 19 '17 at 06:26
5

Relevant Spark DEV mailing list discussion thread is here.

Summary from it:

Spark Streaming will support getting offsets in future versions (> 2.2.0). JIRA ticket to follow - https://issues-test.apache.org/jira/browse/SPARK-18258

For Spark <= 2.2.0, you can get offsets for the given batch by reading a json from checkpoint directory (the API is not stable, so be cautious):

val checkpointRoot = // read 'checkpointLocation' from custom sink params
val checkpointDir = new Path(new Path(checkpointRoot), "offsets").toUri.toString
val offsetSeqLog = new OffsetSeqLog(sparkSession, checkpointDir)

val endOffset: Map[TopicPartition, Long] = offsetSeqLog.get(batchId).map { endOffset =>
  endOffset.offsets.filter(_.isDefined).map { str =>
    JsonUtilsWrapper.jsonToOffsets(str.get.json)
  }
}


/**
  * Hack to access private API
  * Put this class into org.apache.spark.sql.kafka010 package
  */
object JsonUtilsWrapper {
  def offsetsToJson(partitionOffsets: Map[TopicPartition, Long]): String = {
    JsonUtils.partitionOffsets(partitionOffsets)
  }

  def jsonToOffsets(str: String): Map[TopicPartition, Long] = {
    JsonUtils.partitionOffsets(str)
  }
}

This endOffset will contain the until offset for each topic/partition. Getting the start offsets is problematic, cause you have to read the 'commit' checkpoint dir. But usually, you don't care about start offsets, because storing end offsets is enough for reliable Spark job re-start.

Please, note that you have to store the processed batch id in your storage as well. Spark can re-run failed batch with the same batch id in some cases, so make sure to initialize a Custom Sink with latest processed batch id (which you should read from external storage) and ignore any batch with id < latestProcessedBatchId. Btw, batch id is not unique across queries, so you have to store batch id for each query separately.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
dnaumenko
  • 591
  • 1
  • 4
  • 10
2

Streaming Dataset with Kafka source has offset as one of the field. You can simply query for all offsets in query and save them into JDBC Sink

T. Gawęda
  • 15,706
  • 4
  • 46
  • 61
  • For simple query, I need to make an additional Spark operation with group by partition, topic and aggregate max offset? – dnaumenko Sep 11 '17 at 10:59
  • Seems like this approach shouldn't be recommended because the information about an obtained offset ranges is already there (it's in KafkaSourceRDD), but since it's get mapped to InternalRow, I have no access to it. It's just lost and a client has to waste the cluster resources to get it back. – dnaumenko Sep 11 '17 at 11:02
  • Yes. From code side it will be easy, however it will be necessary – T. Gawęda Sep 11 '17 at 11:02
  • Sorry for off-top discussion, but is it would be better to pass the optional offset via addBatch() method? Looks like having a replayable streaming source with some notion of offsets, is a requirement, so it should be in public API. Currently, it's hidden in implementation details (internal row and Kafka schema). It makes it harder to implement a reliable custom sink. – dnaumenko Sep 11 '17 at 11:11
  • @dnaumenko Maybe not offset, but general Metadata of source :) – T. Gawęda Sep 11 '17 at 11:28
  • @t-gawęda Agreed – dnaumenko Sep 11 '17 at 11:42
  • @dnaumenko If it's helpful, please up vote answer and accept. You can also ask Spark developers on mailing list if it's possible to add metadata – T. Gawęda Sep 11 '17 at 12:03