Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Error Handling for Apache Beam and BigQuery (Java SDK)

DZone 's Guide to

Error Handling for Apache Beam and BigQuery (Java SDK)

If you've ever encountered frustrating errors when working with these big data frameworks, read on to learn how to solve them (and stop pulling your hair out)!

· Big Data Zone ·
Free Resource

Design the Pipeline

Let’s assume we have a simple scenario: events are streaming to Kafka, and we want to consume the events in our pipeline, making some transformations and writing the results to BigQuery tables, to make the data available for analytics. 

The BigQuery table can be created before the job has started, or, the Beam itself can create it.

The code will look pretty simple:

EventsProcessingOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                    .as(EventsProcessingOptions.class);

Pipeline p = Pipeline.create(options);

PCollection tableRows =
                  // read kafka topic
                   p.apply("kafka-topic-read", kafkaReader)
                    .apply("kafka-values", MapElements.into(TypeDescriptors.strings())
                            .via(record ->record.getKV().getValue()))
                    // convert value to JsonNode
                    .apply("string-to-json", ParseJsons.of(JsonNode.class))
                    // create TableRow
                    .apply("Build-table-row", ParDo.of(new EventsRowFn()))

                    // save table row to BigQuery
                    .apply("BQ-write", BigQueryIO.<TableRowWithEvent>write()
                            .to(tableSpec)
                            .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER)
                            .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND);

What's Missing?

In the real world, errors may occur, and in most situations, we will be required to handle them.

In the above pipeline, errors can occur when we try to parse the event from Kafka into JsonNode, during the transformation, and in the BigQuery insert phase.

Error Handling Plan

For each error, we will create a row in a different BigQuery table, which contains more information, like the origin event from Kafka.

Once the error occurs, we can analyze the error record and get a full picture of it.

Then, we can either fix the pipeline code, reset/change Kafka consumer group offsets, and replay events again, now with the fixed code.

We can also fix the event itself (for example, in JSON parsing errors) and resend it to Kafka.

Handling Transforming Errors

Let’s have a quick look at our transformation function:

@ProcessElement
public void processElement(@Element JsonNode> element, OutputReceiver<TableRowWithEvent> out) {

  TableRow convertedRow = new TableRow();

  insertLong(element.get("server_time"), "server_time", convertedRow);
  insertFloat(element.get("screen_dpi"), "screen_dpi", convertedRow);

  // more transformation to come

  context.output(output);

}  


private void insertLong(JsonNode value, String key, TableRow convertedRow) {
        String valueToInsert = value.asText();
        if (valueToInsert != null && !valueToInsert.isEmpty()) {
            long longValue = Long.parseLong(valueToInsert);
            convertedRow.set(key, longValue);
        }
}

private void insertFloat(JsonNode value, String key, TableRow convertedRow) {
        String valueToInsert = getStringValue(value);
        if (valueToInsert != null )  {
            float floatValue = Float.parseFloat(valueToInsert);
            convertedRow.set(key, floatValue);
        }
}

Yes, we may fail during parsing, as we parse the string to Float/Long and this fail on data that can’t be converted. 

We need to exclude failed data from the main function output and send this data to a different path in the pipeline, then we will save them to an error table in BigQuery.

How? Let’s Use Tags

When we output an element at the end of the ParDo function, we can output it within a tag. Then we can get all the elements tagged by specific name, and perform some processes on them.

Here we will use two tags, one is the MAIN tag, which holds all the succeeded records, and the onother one contains all the errors with some context, such as DEADLETTER_OUT.

That main tag must be in the same type as the OUTPUT type of the ParDo function itself, amd all other tags can be of different types.

Now, our ParDo function will look like this (notice the tag addition):

@ProcessElement
public void processElement(@Element JsonNode> element, OutputReceiver<TableRowWithEvent> out) {

  public static final TupleTag<JsonNode> MAIN_OUT = new TupleTag<JsonNode>() {};
  public static final TupleTag<BigQueryProcessError> DEADLETTER_OUT = new TupleTag<BigQueryProcessError>() {};

  TableRow convertedRow = new TableRow();

  try {

      insertLong(element.get("server_time"), "server_time", convertedRow);
      insertFloat(element.get("screen_dpi"), "screen_dpi", convertedRow);

      // more transformation to come

      context.output(output);

  } catch (Exception e) {
      logger.error("Failed transform "+e.getMessage(),e);
      context.output(DEADLETTER_OUT, new BigQueryProcessError(convertedRow.toString(), e.getMessage(), ERROR_TYPE.BQ_PROCESS, originEvent));

  }  

}  

And how we can process elements by tag? Let’s change the pipeline, and make the split. The MAIN elements are going to the BigQuery table and the DEADLETTER_OUT elements will get sent to the error table.

EventsProcessingOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                    .as(EventsProcessingOptions.class);

Pipeline p = Pipeline.create(options);

PCollectionTuple tableRows =
                  // read kafka topic
                   p.apply("kafka-topic-read", kafkaReader)
                    .apply("kafka-values", MapElements.into(TypeDescriptors.strings())
                            .via(record ->record.getKV().getValue()))
                    // convert value to JsonNode
                    .apply("string-to-json", ParseJsons.of(JsonNode.class))
                    // create TableRow
                    .apply("Build-table-row", ParDo.of(new EventsRowFn()).withOutputTags(MAIN_OUT, TupleTagList.of(DEADLETTER_OUT)));


                  // save the MAIN tag to BQ
                  tableRows
                      .get(MAIN_OUT)
                      .apply("BQ-write", BigQueryIO.<TableRowWithEvent>write()
                      .to(tableSpec)
                      .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER)
                      .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND);

                  // save the DEADLETTER_OUT to BQ error table
                  tableRows
                    .get(DEADLETTER_OUT)
                    .apply("BQ-process-error-extract", ParDo.of(new BigQueryProcessErrorExtracFn()))
                    .apply("BQ-process-error-write", BigQueryIO.writeTableRows()
                            .to(errTableSpec)
                            .withJsonSchema(errSchema)
                            .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                            .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
  p.run();

Handle BigQuery Insert Errors

In order to handle errors during BigQuery insertion, we will have to use the BiqQueryIO API. 

Let’s zoom in on the write phase. and change it a bit:

WriteResult writeResult = tableRowToInsertCollection
        .apply("BQ-write", BigQueryIO.write()
        // specify that failed rows will be returned with their error
                .withExtendedErrorInfo()
                .to(tableSpec)
                .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
        //Specfies a policy for handling failed inserts.
                .withFailedInsertRetryPolicy(InsertRetryPolicy.retryTransientErrors()));


// write failed rows with their error to error table                
writeResult
        .getFailedInsertsWithErr()
        .apply(Window.into(FixedWindows.of(Duration.standardMinutes(5))))
        .apply("BQ-insert-error-extract", ParDo.of(new BigQueryInsertErrorExtractFn(tableRowToInsertView)).withSideInputs(tableRowToInsertView))
        .apply("BQ-insert-error-write", BigQueryIO.writeTableRows()
                .to(errTableSpec)
                .withJsonSchema(errSchema)
                .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));

In the above snippet, we get the failed TableRows with their error from BigQueryIO. Now we can transform them into another TableRow and write them to an error table. In this case, we let the job to create the table when needed.

Topics:
apache beam ,bigquery ,big data ,data processing ,error handling

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}