Protocol Buffers
Protobuf
Google's binary serialization format. Language-neutral and efficient.
Protobuf
Google's binary serialization format. Language-neutral and efficient.
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.
// 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;
}
# 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"
# 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}")
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")
}
}
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
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.
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).
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.