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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Control Your Services With OTEL, Jaeger, and Prometheus
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Keeping Two Multi-Master Databases Aligned With a Vector Clock
  • Effortless Concurrency: Leveraging the Actor Model in Financial Transaction Systems

Trending

  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Docker Base Images Demystified: A Practical Guide
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Building an AI/ML Data Lake With Apache Iceberg
  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)!

By 
Brachi Packter user avatar
Brachi Packter
·
Feb. 15, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.2K 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.

Related

  • Control Your Services With OTEL, Jaeger, and Prometheus
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Keeping Two Multi-Master Databases Aligned With a Vector Clock
  • Effortless Concurrency: Leveraging the Actor Model in Financial Transaction Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!