Protocol Buffers (proto3) Cheat Sheet
Quick reference guide for Protocol Buffers (proto3): Syntax, scalar types, messages, enums, services, and protoc CLI.
Web & Network
grpc
protobuf
proto3
Protocol Buffers (Protobuf) is a language-neutral, platform-neutral, extensible mechanism for serializing structured data developed by Google.
`proto3` Syntax & Message Definition
protobuf
syntax = "proto3";
package user.v1;
option go_package = "github.com/example/user/v1;userv1";
// Enum definition
enum UserStatus {
USER_STATUS_UNSPECIFIED = 0;
USER_STATUS_ACTIVE = 1;
USER_STATUS_SUSPENDED = 2;
}
// Message definition
message User {
int64 id = 1;
string name = 2;
string email = 3;
UserStatus status = 4;
repeated string tags = 5; // Array / List of strings
map<string, string> metadata = 6;
}
message GetUserRequest {
int64 user_id = 1;
}
gRPC Service Definition (RPC Types)
Table
| RPC Type | Definition Example | Communication Pattern |
|---|---|---|
| Unary RPC | rpc GetUser (GetUserRequest) returns (User); | Single request -> Single response |
| Server Streaming | rpc ListUsers (ListUsersRequest) returns (stream User); | Single request -> Stream of responses |
| Client Streaming | rpc RecordTelemetry (stream Metrics) returns (Summary); | Stream of requests -> Single response |
| Bidirectional | rpc Chat (stream Message) returns (stream Message); | Stream of requests <-> Stream of responses |
protobuf
service UserService {
rpc GetUser (GetUserRequest) returns (User);
rpc StreamUsers (GetUserRequest) returns (stream User);
}
Essential `protoc` CLI Commands
bash
# Generate Go code from .proto file
protoc --go_out=. --go_opt=paths=source_relative user.proto
# Generate TypeScript code using ts-proto plugin
protoc --plugin=protoc-gen-ts_proto=./node_modules/.bin/protoc-gen-ts_proto \
--ts_proto_out=./src user.proto
Common Pitfalls & Tips
[!WARNING] Never change or reuse field tag numbers (e.g.
int64 id = 1;) in existing.protofiles! Tag numbers identify fields in binary wire format.
[!TIP] Always assign the
0enum tag value toUNSPECIFIEDas the proto3 default fallback value.