DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Big Data
  4. Error Handling for Apache Beam and BigQuery (Java SDK)

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)!

Brachi Packter user avatar by
Brachi Packter
·
Feb. 15, 19 · Tutorial
Like (5)
Save
Tweet
Share
22.11K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Database Software development kit Apache Beam kafka

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • The Quest for REST
  • A Brief Overview of the Spring Cloud Framework
  • How To Create and Edit Excel XLSX Documents in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: