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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Exploring JSON Schema for Form Validation in Web Components
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Handling Dynamic Data Using Schema Evolution in Delta
  • Automate Azure Databricks Unity Catalog Permissions at the Schema Level

Trending

  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  1. DZone
  2. Data Engineering
  3. Data
  4. Getting Started With AVRO

Getting Started With AVRO

Evaluating different protocols like AVRO, Thrift, Protobuff, and MessagePack. Let's cover each one in-depth starting with AVRO—a data serialization framework.

By 
Milind Deobhankar user avatar
Milind Deobhankar
·
Jul. 09, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.3K Views

Join the DZone community and get the full member experience.

Join For Free

Recently we want very fast communication between our distributed system, our payload was also considered so we try to evaluate different protocols like AVRO, Thrift, Protobuff, and MessagePack. I will try to cover each one in-depth starting with AVRO, so stay tuned for others.

So what is AVRO?

AVRO is a data serialization framework. It uses JSON to define the schema and serialize data into a binary compact format that can be store in persistent storage or transfer across the wire. We are not going to go in details of definition but will concentrate on implementation and its pros and cons.

You can get more details about AVRO from here and here.

Why Would We Want to Move Out of JSON?

Even though JSON is widely accepted, flexible, and can send dynamic data but there is no schema enforcing. JSON objects can be quite big because of repeated keys when we want to send the list of the same items.

Let’s get into implementation with a simple use-case. Use-case is that ordered service will call order confirmation service to confirm the order added in the cart. Communication between the two services will happen with AVRO+binary encoding over Rest. Other communication mechanisms like AVRO+JSON encoding, AVRO+JSON+gzip are there in the code repository we are not going to explore here but will be useful in comparison.

 communication between avro objects


AVRO is schema-based so first let’s try to create the schema. We are going to construct AVRO schema from JSON using the online tool.
AVRO Schema:

JSON
 




x
43


 
1
{
2
  "name": "Order",
3
  "type": "record",
4
  "namespace": "com.milind.avro.order.request",
5
  "fields": [
6
   ...
7
    {
8
      "name": "orderId",
9
      "type": "string"
10
    },
11
    {
12
      "name": "cartUrl",
13
      "type": [
14
        "string",
15
        "null"
16
      ]
17
    },
18
    {
19
      "name": "lineItems",
20
      "type": {
21
        "type": "array",
22
        "items": {
23
          "name": "LineItemRecord",
24
          "type": "record",
25
          "fields": [
26
            {
27
              "name": "sku",
28
              "type": "string"
29
            },
30
            {
31
              "name": "description",
32
              "type": [
33
                "string",
34
                "null"
35
              ]
36
            },
37
           ...
38
          ]
39
        }
40
      }
41
    }
42
  ]
43
}


If you notice cartUrl and description there are two types of string and null. This is called union in AVRO schema where the value can be of type null or string. Note AVRO schema is strong types so when you don’t set any field while creating the object you will get an exception while building the object itself. After finalizing the schema we need to compile the schema and generate the POJO classes. There are two ways to do it:
1) Via Command Line
java -jar /path/to/avro-tools-1.10.0.jar compile schema java -jar /path/to/avro-tools-1.10.0.jar compile schema

java -jar /path/to/avro-tools-1.10.0.jar compile schema orderrequest.avsc .
2) Via Maven Plugin

XML
 




xxxxxxxxxx
1
20


 
1
          <plugin>
2
                <groupId>org.apache.avro</groupId>
3
                <artifactId>avro-maven-plugin</artifactId>
4
                <version>${avro.version}</version>
5
                <executions>
6
                    <execution>
7
                        <id>schemas</id>
8
                        <phase>generate-sources</phase>
9
                        <goals>
10
                            <goal>schema</goal>
11
                            <goal>protocol</goal>
12
                            <goal>idl-protocol</goal>
13
                        </goals>
14
                        <configuration>
15
                            <sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
16
                            <outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
17
                        </configuration>
18
                    </execution>
19
                </executions>
20
        </plugin>


To generate the code execute mvn clean install.


AVRO specifies two serialization encodings: binary and JSON. Most applications will use binary encoding, as it is smaller and faster. But, for debugging and web-based applications, the JSON encoding may sometimes be appropriate. Following is the generic serialization and de-serialization using the binary. For JSON serialization please go through the code.

Serialization

Java
 




xxxxxxxxxx
1
11


 
1
 public byte[] serializeBinary(SpecificRecordBase request)
2
            throws IOException{
3
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
4
        DatumWriter<SpecificRecordBase> outputDatumWriter =
5
                new SpecificDatumWriter<>(request.getSchema());
6
        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(baos,
7
                null);
8
        outputDatumWriter.write(request,encoder);
9
        encoder.flush();
10
        return baos.toByteArray();
11
    }



De-Serialization

Java
 




xxxxxxxxxx
1


 
1
public <T> T  deSerializeBinary(byte[] data, Class<T> t)
2
            throws IOException {
3
        DatumReader<SpecificRecordBase> reader
4
                = new SpecificDatumReader(t);
5
        BinaryDecoder decoder = new DecoderFactory().binaryDecoder(data,
6
                null);
7
        return (T) reader.read(null,decoder);
8
}


I had created the spring boot application to test all these and you can get the entire code in Github here. Following are the URLs to test different protocols:
1) AVRO + Binary Encoding: http://localhost:8080/test
2) AVRO + JSON Encoding: http://localhost:8080/testjson
3) AVRO + JSON Encoding + Gzip: http://localhost:880/testzip

Following is the comparison of the payload size with the same request data:

payload size vs bytes


Conclusion

If you see the above graph the main advantage of AVRO is payload reduction. For our case, there is almost a 55% reduction in payload size when we use AVRO binary compared to JSON and a 26.5% reduction in payload size compared to JSON+Gzip. Apart from this following are the other advantages:

1) Data is fully typed.

2) Data is always accompanied by a schema that permits full processing of that data without code generation, static datatypes, etc.

3) As data is compressed lesser CPU usage.

4) Supports major programming language.

5) Schema can evolve which can benefit both consumer and producer.

The only thing which can create the problem is that data cannot be print without using the AVRO tools which can become a bottleneck for debugging.

Hope you got some familiarity with AVRO.
Happy Coding.

Get the entire code here.

avro Schema JSON Data (computing)

Published at DZone with permission of Milind Deobhankar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring JSON Schema for Form Validation in Web Components
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Handling Dynamic Data Using Schema Evolution in Delta
  • Automate Azure Databricks Unity Catalog Permissions at the Schema Level

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!