{{announcement.body}}
{{announcement.title}}

Getting Started With AVRO

DZone 's Guide to

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.

· Web Dev Zone ·
Free Resource

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.

Topics:
apache avro, protocol, rest api

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}