๐Ÿ“Š Data Engineering

Avro

Apache Avro

A row-oriented serialization format. Supports schema evolution.

Detailed Explanation

Apache Avro is a row-oriented data serialization system widely used in the Hadoop ecosystem that stores the schema together with the data, making it self-describing. Developed by Doug Cutting, it stores data in a compact binary format based on a schema defined in JSON.

Avro's key advantage is schema evolution. You can add new fields, remove fields that have default values, and rename fields (using aliases), and data can be read even when the writer schema and reader schema differ, as long as the compatibility rules are met. This allows producers and consumers in a data pipeline to be deployed independently.

Avro supports a variety of data types. Primitive types (null, boolean, int, long, float, double, bytes, string) and complex types (record, enum, array, map, union, fixed) can be combined to represent complex data structures. In particular, the union type is essential for implementing nullable fields, and lets you choose one of several types, as in ["null", "string"].

It is used as the standard serialization format across the big data ecosystem, including Kafka, Spark, Flink, and Hive. Combined with Confluent Schema Registry, you can manage schemas centrally and verify compatibility automatically. It also supports an RPC protocol, so it is used for service-to-service communication through Avro IPC.

Code Example

# Apache Avro ์Šคํ‚ค๋งˆ ์ •์˜ ๋ฐ ์ง๋ ฌํ™” ์˜ˆ์ œ

# ============================================
# 1. Avro ์Šคํ‚ค๋งˆ ์ •์˜ (user_event.avsc)
# ============================================
{
  "type": "record",
  "name": "UserEvent",
  "namespace": "com.example.events",
  "doc": "์‚ฌ์šฉ์ž ์ด๋ฒคํŠธ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์Šคํ‚ค๋งˆ",
  "fields": [
    {
      "name": "event_id",
      "type": "string",
      "doc": "๊ณ ์œ  ์ด๋ฒคํŠธ ID"
    },
    {
      "name": "user_id",
      "type": "string",
      "doc": "์‚ฌ์šฉ์ž ID"
    },
    {
      "name": "event_type",
      "type": {
        "type": "enum",
        "name": "EventType",
        "symbols": ["CLICK", "VIEW", "PURCHASE", "SIGNUP"]
      },
      "doc": "์ด๋ฒคํŠธ ์œ ํ˜•"
    },
    {
      "name": "timestamp",
      "type": "long",
      "logicalType": "timestamp-millis",
      "doc": "์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ๊ฐ„ (๋ฐ€๋ฆฌ์ดˆ)"
    },
    {
      "name": "metadata",
      "type": ["null", {
        "type": "map",
        "values": "string"
      }],
      "default": null,
      "doc": "์ถ”๊ฐ€ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ (์„ ํƒ์ )"
    },
    {
      "name": "amount",
      "type": ["null", "double"],
      "default": null,
      "doc": "๊ธˆ์•ก (๊ตฌ๋งค ์ด๋ฒคํŠธ์šฉ)"
    },
    {
      "name": "tags",
      "type": {
        "type": "array",
        "items": "string"
      },
      "default": [],
      "doc": "ํƒœ๊ทธ ๋ชฉ๋ก"
    },
    {
      "name": "device_info",
      "type": ["null", {
        "type": "record",
        "name": "DeviceInfo",
        "fields": [
          {"name": "device_type", "type": "string"},
          {"name": "os_version", "type": "string"},
          {"name": "app_version", "type": ["null", "string"], "default": null}
        ]
      }],
      "default": null,
      "doc": "๋””๋ฐ”์ด์Šค ์ •๋ณด"
    }
  ]
}

# ============================================
# 2. Python fastavro ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ
# ============================================
import fastavro
from fastavro import writer, reader, parse_schema
import io
import json

# ์Šคํ‚ค๋งˆ ํŒŒ์‹ฑ
schema = {
    "type": "record",
    "name": "UserEvent",
    "namespace": "com.example.events",
    "fields": [
        {"name": "event_id", "type": "string"},
        {"name": "user_id", "type": "string"},
        {"name": "event_type", "type": {
            "type": "enum",
            "name": "EventType",
            "symbols": ["CLICK", "VIEW", "PURCHASE", "SIGNUP"]
        }},
        {"name": "timestamp", "type": "long"},
        {"name": "metadata", "type": ["null", {"type": "map", "values": "string"}], "default": None},
        {"name": "amount", "type": ["null", "double"], "default": None},
        {"name": "tags", "type": {"type": "array", "items": "string"}, "default": []}
    ]
}

parsed_schema = parse_schema(schema)

# ์ƒ˜ํ”Œ ๋ ˆ์ฝ”๋“œ ์ƒ์„ฑ
records = [
    {
        "event_id": "evt_001",
        "user_id": "user_123",
        "event_type": "CLICK",
        "timestamp": 1705312800000,
        "metadata": {"page": "home", "button": "cta"},
        "amount": None,
        "tags": ["web", "mobile"]
    },
    {
        "event_id": "evt_002",
        "user_id": "user_456",
        "event_type": "PURCHASE",
        "timestamp": 1705312860000,
        "metadata": {"product_id": "P001"},
        "amount": 99.99,
        "tags": ["mobile", "ios"]
    }
]

# ํŒŒ์ผ๋กœ ์“ฐ๊ธฐ
with open('events.avro', 'wb') as f:
    writer(f, parsed_schema, records)

# ํŒŒ์ผ์—์„œ ์ฝ๊ธฐ
with open('events.avro', 'rb') as f:
    avro_reader = reader(f)
    for record in avro_reader:
        print(record)

# ============================================
# 3. ๋ฐ”์ดํŠธ ์ŠคํŠธ๋ฆผ ์ง๋ ฌํ™”/์—ญ์ง๋ ฌํ™” (Kafka์šฉ)
# ============================================
from fastavro import schemaless_writer, schemaless_reader

def serialize_avro(record, schema):
    """๋ ˆ์ฝ”๋“œ๋ฅผ Avro ๋ฐ”์ดํŠธ๋กœ ์ง๋ ฌํ™”"""
    buffer = io.BytesIO()
    schemaless_writer(buffer, schema, record)
    return buffer.getvalue()

def deserialize_avro(data, schema):
    """Avro ๋ฐ”์ดํŠธ๋ฅผ ๋ ˆ์ฝ”๋“œ๋กœ ์—ญ์ง๋ ฌํ™”"""
    buffer = io.BytesIO(data)
    return schemaless_reader(buffer, schema)

# ์ง๋ ฌํ™”
event = {
    "event_id": "evt_003",
    "user_id": "user_789",
    "event_type": "VIEW",
    "timestamp": 1705312900000,
    "metadata": None,
    "amount": None,
    "tags": []
}

serialized = serialize_avro(event, parsed_schema)
print(f"์ง๋ ฌํ™”๋œ ํฌ๊ธฐ: {len(serialized)} bytes")

# ์—ญ์ง๋ ฌํ™”
deserialized = deserialize_avro(serialized, parsed_schema)
print(f"์—ญ์ง๋ ฌํ™”๋œ ๋ ˆ์ฝ”๋“œ: {deserialized}")

# ============================================
# 4. ์Šคํ‚ค๋งˆ ์ง„ํ™” (Schema Evolution)
# ============================================

# ์›๋ณธ ์Šคํ‚ค๋งˆ (v1)
schema_v1 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "string"},
        {"name": "name", "type": "string"},
        {"name": "email", "type": "string"}
    ]
}

# ์ง„ํ™”๋œ ์Šคํ‚ค๋งˆ (v2) - ํ•„๋“œ ์ถ”๊ฐ€, ๊ธฐ๋ณธ๊ฐ’ ์„ค์ •
schema_v2 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "string"},
        {"name": "name", "type": "string"},
        {"name": "email", "type": "string"},
        # ์ƒˆ ํ•„๋“œ (๊ธฐ๋ณธ๊ฐ’ ์žˆ์Œ - ํ•˜์œ„ ํ˜ธํ™˜)
        {"name": "phone", "type": ["null", "string"], "default": None},
        {"name": "created_at", "type": "long", "default": 0}
    ]
}

# v1์œผ๋กœ ์ž‘์„ฑ๋œ ๋ฐ์ดํ„ฐ
user_v1 = {"id": "u001", "name": "ํ™๊ธธ๋™", "email": "hong@example.com"}

# v1 ์Šคํ‚ค๋งˆ๋กœ ์ง๋ ฌํ™”
buffer = io.BytesIO()
schemaless_writer(buffer, parse_schema(schema_v1), user_v1)
data = buffer.getvalue()

# v2 ์Šคํ‚ค๋งˆ๋กœ ์—ญ์ง๋ ฌํ™” (๊ธฐ๋ณธ๊ฐ’ ์ ์šฉ)
buffer = io.BytesIO(data)
# writer_schema: ์“ธ ๋•Œ ์‚ฌ์šฉํ•œ ์Šคํ‚ค๋งˆ, reader_schema: ์ฝ์„ ๋•Œ ์‚ฌ์šฉํ•  ์Šคํ‚ค๋งˆ
user_v2 = schemaless_reader(
    buffer,
    parse_schema(schema_v1),  # writer schema
    parse_schema(schema_v2)   # reader schema
)
print(f"์Šคํ‚ค๋งˆ ์ง„ํ™” ๊ฒฐ๊ณผ: {user_v2}")
# {'id': 'u001', 'name': 'ํ™๊ธธ๋™', 'email': 'hong@example.com', 'phone': None, 'created_at': 0}

# ============================================
# 5. Confluent Schema Registry ์—ฐ๋™
# ============================================
from confluent_kafka import SerializingProducer, DeserializingConsumer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer, AvroDeserializer

# Schema Registry ํด๋ผ์ด์–ธํŠธ
schema_registry_conf = {'url': 'http://localhost:8081'}
schema_registry_client = SchemaRegistryClient(schema_registry_conf)

# Avro ์Šคํ‚ค๋งˆ ๋ฌธ์ž์—ด
avro_schema_str = json.dumps(schema)

# ์ง๋ ฌํ™”/์—ญ์ง๋ ฌํ™” ์„ค์ •
avro_serializer = AvroSerializer(
    schema_registry_client,
    avro_schema_str,
    lambda obj, ctx: obj  # dict๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ
)

avro_deserializer = AvroDeserializer(
    schema_registry_client,
    avro_schema_str,
    lambda obj, ctx: obj
)

# Producer ์„ค์ •
producer_conf = {
    'bootstrap.servers': 'localhost:9092',
    'key.serializer': lambda k, ctx: k.encode('utf-8') if k else None,
    'value.serializer': avro_serializer
}

producer = SerializingProducer(producer_conf)

# ๋ฉ”์‹œ์ง€ ์ „์†ก
producer.produce(
    topic='user-events',
    key='user_123',
    value=event,
    on_delivery=lambda err, msg: print(f"Delivered: {msg.topic()}")
)
producer.flush()

# Consumer ์„ค์ •
consumer_conf = {
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'avro-consumer-group',
    'key.deserializer': lambda k, ctx: k.decode('utf-8') if k else None,
    'value.deserializer': avro_deserializer,
    'auto.offset.reset': 'earliest'
}

consumer = DeserializingConsumer(consumer_conf)
consumer.subscribe(['user-events'])

# ๋ฉ”์‹œ์ง€ ์ˆ˜์‹ 
msg = consumer.poll(timeout=1.0)
if msg and not msg.error():
    print(f"Received: {msg.value()}")

# ============================================
# 6. Spark์—์„œ Avro ์‚ฌ์šฉ
# ============================================
"""
from pyspark.sql import SparkSession

spark = SparkSession.builder \\
    .appName("AvroExample") \\
    .config("spark.jars.packages", "org.apache.spark:spark-avro_2.12:3.5.0") \\
    .getOrCreate()

# Avro ํŒŒ์ผ ์ฝ๊ธฐ
df = spark.read.format("avro").load("events.avro")
df.show()

# Avro ํŒŒ์ผ ์“ฐ๊ธฐ
df.write.format("avro").save("output_events.avro")

# ์Šคํ‚ค๋งˆ ์ง€์ •ํ•˜์—ฌ ์ฝ๊ธฐ
avro_schema = open("user_event.avsc").read()
df = spark.read.format("avro") \\
    .option("avroSchema", avro_schema) \\
    .load("events.avro")
"""

print("Avro ์˜ˆ์ œ ์™„๋ฃŒ")

How it is used in practice

Backend developer: "We want to move the Kafka message format away from JSON. Which is better, Avro or Protobuf?"

Data engineer: "If schema evolution is frequent, Avro has the edge. Used with Schema Registry, compatibility checks are automatic, and it's well supported in the Kafka ecosystem."

Backend developer: "How do we stay compatible with the existing JSON data?"

Data engineer: "Start a new topic with Avro and have the consumers handle both formats. Migrate gradually and deprecate the JSON topic."

Interviewer: "Please explain the types of schema compatibility in Avro and when each is used."

Candidate: "Avro has three kinds of schema compatibility. BACKWARD compatibility means the new schema can read old data, allowing fields to be added (a default is required) or deleted. FORWARD compatibility means the old schema can read new data, allowing fields to be deleted (a default is required) or added. FULL compatibility means both directions work, and it is the strictest. BACKWARD compatibility is generally recommended, because it allows consumers to be deployed before producers."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "You defined the nullable field as ["string", "null"], but the order matters."

Developer: "Does the order make a difference?"

Reviewer: "Yes, Avro uses the first type in the union as the default. You need to write ["null", "string"] and specify default: null explicitly. Otherwise, a deserialization error can occur when the field is missing."

Cautions

Related Terms

Learn More