πŸ—οΈ Architecture

Protocol Buffers

Protobuf

Google's binary serialization format. Language-neutral and efficient.

πŸ“– Detailed Explanation

Protocol Buffers (Protobuf) is a language-neutral, platform-neutral data serialization format that Google released as open source in 2008. It was originally developed within Google for efficient RPC communication, and it is now widely used as the default serialization method of gRPC. Unlike JSON or XML, it is encoded in a binary format, so data size is small and parsing is fast.

The core of Protobuf is the schema defined in a .proto file. Message structures, field types, and field numbers are declared explicitly, and the protoc compiler generates code from them for various languages (Python, Go, Java, C++, JavaScript, etc.). Field numbers are used to identify fields in the binary encoding, and once assigned they must not be changed. This makes it possible to maintain backward/forward compatibility.

There are two syntax versions, proto2 and proto3. proto3 is the latest version, released in 2016, which simplified the concept of default values and removed required fields. All fields are optional by default, and when a field is set to its default value it is not sent over the wire, so messages become smaller. In addition, proto3 officially supports JSON mapping, which improves interoperability with REST APIs.

In the AI/ML field, Protobuf is used for TensorFlow's model storage format (SavedModel), training data serialization (TFRecord), and serving API (TensorFlow Serving). It has also been adopted as a core communication protocol across cloud-native infrastructure such as Kubernetes, Envoy Proxy, and Etcd. With sizes 3-10 times smaller than JSON and parsing performance 20-100 times faster, it can significantly reduce network costs and latency in large-scale distributed systems.

πŸ’» Code Example

.proto Schema Definition

// user.proto
syntax = "proto3";

package example.user;

option go_package = "github.com/example/user/pb";
option java_package = "com.example.user";

import "google/protobuf/timestamp.proto";

// μ‚¬μš©μž λ©”μ‹œμ§€ μ •μ˜
message User {
    int64 id = 1;                    // ν•„λ“œ λ²ˆν˜ΈλŠ” λ³€κ²½ λΆˆκ°€
    string email = 2;
    string name = 3;
    UserStatus status = 4;
    repeated string roles = 5;       // λ°°μ—΄ νƒ€μž…
    Address address = 6;             // 쀑첩 λ©”μ‹œμ§€
    google.protobuf.Timestamp created_at = 7;

    // reserved둜 μ‚­μ œλœ ν•„λ“œ 번호 보호
    reserved 8, 9;
    reserved "old_field", "deprecated_field";
}

// μ—΄κ±°ν˜• μ •μ˜
enum UserStatus {
    USER_STATUS_UNSPECIFIED = 0;     // proto3λŠ” 0번 ν•„μˆ˜
    USER_STATUS_ACTIVE = 1;
    USER_STATUS_INACTIVE = 2;
    USER_STATUS_SUSPENDED = 3;
}

// 쀑첩 λ©”μ‹œμ§€
message Address {
    string street = 1;
    string city = 2;
    string country = 3;
    string postal_code = 4;
}

// gRPC μ„œλΉ„μŠ€ μ •μ˜
service UserService {
    rpc GetUser(GetUserRequest) returns (User);
    rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
    rpc CreateUser(CreateUserRequest) returns (User);
    rpc UpdateUser(UpdateUserRequest) returns (User);
    rpc DeleteUser(DeleteUserRequest) returns (google.protobuf.Empty);

    // 슀트리밍 RPC
    rpc WatchUsers(WatchUsersRequest) returns (stream User);
}

message GetUserRequest {
    int64 user_id = 1;
}

message ListUsersRequest {
    int32 page_size = 1;
    string page_token = 2;
    string filter = 3;
}

message ListUsersResponse {
    repeated User users = 1;
    string next_page_token = 2;
    int32 total_count = 3;
}

Using Protobuf in Python

# protoc둜 Python μ½”λ“œ 생성
# protoc --python_out=. --pyi_out=. user.proto

from google.protobuf.timestamp_pb2 import Timestamp
from google.protobuf.json_format import MessageToJson, Parse
from datetime import datetime
import user_pb2

# λ©”μ‹œμ§€ 생성
user = user_pb2.User()
user.id = 12345
user.email = "user@example.com"
user.name = "홍길동"
user.status = user_pb2.USER_STATUS_ACTIVE
user.roles.extend(["admin", "developer"])

# 쀑첩 λ©”μ‹œμ§€ μ„€μ •
user.address.street = "ν…Œν—€λž€λ‘œ 123"
user.address.city = "μ„œμšΈ"
user.address.country = "KR"

# Timestamp μ„€μ •
user.created_at.FromDatetime(datetime.now())

# 직렬화 (λ°”μ΄λ„ˆλ¦¬)
binary_data = user.SerializeToString()
print(f"Binary size: {len(binary_data)} bytes")  # ~100 bytes

# 역직렬화
loaded_user = user_pb2.User()
loaded_user.ParseFromString(binary_data)
print(f"Loaded user: {loaded_user.name}")

# JSON λ³€ν™˜ (디버깅/REST API ν˜Έν™˜)
json_str = MessageToJson(user, preserving_proto_field_name=True)
print(json_str)
# {
#   "id": "12345",
#   "email": "user@example.com",
#   "name": "홍길동",
#   "status": "USER_STATUS_ACTIVE",
#   "roles": ["admin", "developer"],
#   "address": { ... }
# }

# JSONμ—μ„œ νŒŒμ‹±
user_from_json = Parse(json_str, user_pb2.User())

# λ©”μ‹œμ§€ 비ꡐ 및 병합
user2 = user_pb2.User()
user2.CopyFrom(user)
user2.MergeFrom(loaded_user)
print(user == user2)  # True

# oneof (택일 ν•„λ“œ) 예제
# message Event {
#     oneof payload {
#         UserCreated user_created = 1;
#         UserUpdated user_updated = 2;
#         UserDeleted user_deleted = 3;
#     }
# }
# event.HasField("user_created")  # True/False
# event.WhichOneof("payload")     # "user_created"

Implementing a gRPC Service (Python)

# gRPC μ„œλ²„
import grpc
from concurrent import futures
import user_pb2
import user_pb2_grpc

class UserServiceServicer(user_pb2_grpc.UserServiceServicer):
    def __init__(self):
        self.users = {}  # μ‹€μ œλ‘œλŠ” DB μ‚¬μš©

    def GetUser(self, request, context):
        user_id = request.user_id
        if user_id not in self.users:
            context.abort(grpc.StatusCode.NOT_FOUND, f"User {user_id} not found")
        return self.users[user_id]

    def ListUsers(self, request, context):
        page_size = request.page_size or 10
        users = list(self.users.values())[:page_size]
        return user_pb2.ListUsersResponse(
            users=users,
            total_count=len(self.users)
        )

    def CreateUser(self, request, context):
        user = user_pb2.User()
        user.CopyFrom(request.user)
        user.id = len(self.users) + 1
        self.users[user.id] = user
        return user

    def WatchUsers(self, request, context):
        """μ„œλ²„ 슀트리밍 RPC"""
        for user in self.users.values():
            yield user

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    user_pb2_grpc.add_UserServiceServicer_to_server(
        UserServiceServicer(), server
    )
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

# gRPC ν΄λΌμ΄μ–ΈνŠΈ
def client_example():
    channel = grpc.insecure_channel('localhost:50051')
    stub = user_pb2_grpc.UserServiceStub(channel)

    # Unary RPC
    try:
        user = stub.GetUser(user_pb2.GetUserRequest(user_id=1))
        print(f"Got user: {user.name}")
    except grpc.RpcError as e:
        print(f"Error: {e.code()} - {e.details()}")

    # 슀트리밍 RPC
    for user in stub.WatchUsers(user_pb2.WatchUsersRequest()):
        print(f"Received: {user.name}")

Using Protobuf in Go

package main

import (
    "fmt"
    "log"

    "google.golang.org/protobuf/proto"
    "google.golang.org/protobuf/encoding/protojson"
    "google.golang.org/protobuf/types/known/timestamppb"

    pb "github.com/example/user/pb"
)

func main() {
    // λ©”μ‹œμ§€ 생성
    user := &pb.User{
        Id:     12345,
        Email:  "user@example.com",
        Name:   "홍길동",
        Status: pb.UserStatus_USER_STATUS_ACTIVE,
        Roles:  []string{"admin", "developer"},
        Address: &pb.Address{
            Street:  "ν…Œν—€λž€λ‘œ 123",
            City:    "μ„œμšΈ",
            Country: "KR",
        },
        CreatedAt: timestamppb.Now(),
    }

    // 직렬화
    data, err := proto.Marshal(user)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Binary size: %d bytes\n", len(data))

    // 역직렬화
    newUser := &pb.User{}
    if err := proto.Unmarshal(data, newUser); err != nil {
        log.Fatal(err)
    }

    // JSON λ³€ν™˜
    jsonBytes, _ := protojson.Marshal(user)
    fmt.Println(string(jsonBytes))

    // κΉŠμ€ 볡사
    clone := proto.Clone(user).(*pb.User)

    // λ©”μ‹œμ§€ 비ꡐ
    if proto.Equal(user, clone) {
        fmt.Println("Messages are equal")
    }
}

πŸ—£οΈ How It's Said in Practice

  • "If we switch communication between microservices from JSON to gRPC/Protobuf, the payload size drops to one fifth and parsing is much faster, too."
  • "Since the schema is clearly defined in the proto file, you can tell right away which fields exist, even without API documentation."
  • "We're adding a field this time, so just use number 10. The deleted 8 and 9 are marked as reserved, so they can't be reused."
  • "For external partners, I'll also expose a REST endpoint through gRPC-Gateway so they can communicate using JSON."
  • "Please compare the pros and cons of Protocol Buffers and JSON. When would you choose each?"
  • "Why are field numbers important in a proto file? How are they related to backward/forward compatibility?"
  • "What are the main differences between proto2 and proto3? Why were required fields removed?"
  • "Please explain the 4 communication patterns of gRPC (Unary, Server Streaming, Client Streaming, Bidirectional)."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

  • "This field number 5 is a number that was used by a field that has already been deleted. Please use numbers from 15 onward."
  • "In proto3, you have to write the optional keyword explicitly for the presence check to work. If you want to use HasField, please add optional."
  • "packed=true on repeated fields is the default in proto3, so you don't need to specify it explicitly."

⚠️ Cautions

Managing Field Numbers

Once assigned, a field number must never be changed or reused. Mark deleted fields as reserved to protect them from being accidentally reused. Field numbers 1-15 are encoded in 1 byte, so assign them first to frequently used fields.

Default Values and Presence

In proto3, scalar fields are not sent over the wire when they hold their default value (0, "", false). If you need to distinguish between "value not set" and "default value set," explicitly use the optional keyword or use a wrapper type (such as google.protobuf.Int64Value).

Handling Large Messages

Protobuf messages have a 4MB size limit by default. Split large data into chunks using streaming RPC, or use separate binary storage. Also, be careful about memory usage with messages that are deeply nested or have large repeated fields.

πŸ”— Related Terms

πŸ“š Learn More