Protobuf and the Wire Format
The schema language, and the five bytes it produces.
The schema language, and the bytes it produces.
Scalar types
Eleven of them, and the Go type each becomes:
syntax = "proto3";
package nums;
option go_package = "xz/grpc/numspb";
message N {
int32 a = 1;
int64 b = 2;
uint32 c = 3;
sint32 d = 4;
fixed32 e = 5;
bool f = 6;
bytes g = 7;
double h = 8;
}Field name, Go type, and the wire encoding from the struct tag:
grep -E '^\t[A-H] +' numspb/nums.pb.go \
| awk -F'"' '{split($1,a," "); split($2,b,","); \
printf "%-8s %-8s %s\n", a[1], a[2], b[1]}'sint32 is a Go int32 too, encoded zigzag32. There is no int.
Chapter 7 shows you cannot swap int32 for int64 once deployed.
5 bytes versus 14
Chapter 1’s schema, and the same data in both encodings:
syntax = "proto3";
package greet;
option go_package = "xz/grpc/greetpb";
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/greetpb"
)
func main() {
b, _ := proto.Marshal(&greetpb.HelloRequest{Name: "ada"})
fmt.Println(hex.EncodeToString(b), len(b))
j, _ := json.Marshal(map[string]string{"name": "ada"})
fmt.Println(string(j), len(j))
}Nine of the JSON bytes are the key and its punctuation. Protobuf sends neither.
Reading a tag byte
Five bytes, decoded by hand:
| Bytes | Means |
|---|---|
0a |
field 1, wire type 2 |
03 |
the value is 3 bytes long |
616461 |
a, d, a |
0a is 00001010: the low three bits are the wire type, the rest the field number.
package main
import "fmt"
func main() {
tag := byte(0x0a)
fmt.Printf("tag %02x -> field %d wire type %d\n", tag, tag>>3, tag&0x07)
}Five exist, three are in use:
| Type | Name | Carries |
|---|---|---|
| 0 | varint | int32, int64, bool, enum |
| 1 | 64-bit | fixed64, double |
| 2 | length-delimited | string, bytes, messages, repeated |
| 5 | 32-bit | fixed32, float |
Wire types 3 and 4 were proto2 groups, now deprecated.
Field numbers 1-15
The field number lives in the tag, so a bigger number is a bigger message:
syntax = "proto3";
package tags;
option go_package = "xz/grpc/tagspb";
message T {
string f1 = 1;
string f15 = 15;
string f16 = 16;
}One character, three different fields:
package main
import (
"encoding/hex"
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/tagspb"
)
func main() {
for _, m := range []*tagspb.T{{F1: "a"}, {F15: "a"}, {F16: "a"}} {
b, _ := proto.Marshal(m)
fmt.Println(hex.EncodeToString(b), len(b))
}
}Field 16’s tag is 8201 — two bytes. Fields 1 to 15 fit theirs in one.
Varints
Small numbers take fewer bytes:
package main
import (
"encoding/hex"
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/numspb"
)
func main() {
b1, _ := proto.Marshal(&numspb.N{A: 1})
fmt.Println("1 =", hex.EncodeToString(b1))
b2, _ := proto.Marshal(&numspb.N{A: 300})
fmt.Println("300 =", hex.EncodeToString(b2))
}300 needs two value bytes, 1 needs one. Negative numbers are the exception:
package main
import (
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/numspb"
)
func sz(m proto.Message) int { b, _ := proto.Marshal(m); return len(b) }
func main() {
fmt.Println("int32(1) ", sz(&numspb.N{A: 1}))
fmt.Println("int32(300) ", sz(&numspb.N{A: 300}))
fmt.Println("int32(-1) ", sz(&numspb.N{A: -1}))
fmt.Println("sint32(-1) ", sz(&numspb.N{D: -1}))
fmt.Println("fixed32(1) ", sz(&numspb.N{E: 1}))
}Field numbers are the contract
Decode HelloRequest’s bytes as a HelloReply:
package main
import (
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/greetpb"
)
func main() {
b, _ := proto.Marshal(&greetpb.HelloRequest{Name: "ada"})
var r greetpb.HelloReply
proto.Unmarshal(b, &r)
fmt.Printf("%q\n", r.GetMessage())
}Different types, different field names, one shared number — and the value arrives.
optional and presence
Without optional, unset and empty are the same value. With it, you get a pointer:
syntax = "proto3";
package shop;
option go_package = "xz/grpc/shoppb";
import "google/protobuf/timestamp.proto";
enum Status {
STATUS_UNSPECIFIED = 0;
STATUS_ACTIVE = 1;
STATUS_CLOSED = 2;
}
message Address {
string city = 1;
}
message Order {
string id = 1;
optional string note = 2;
repeated string items = 3;
map<string, int32> counts = 4;
Status status = 5;
Address ship_to = 6;
google.protobuf.Timestamp created = 7;
oneof payment {
string card = 8;
string invoice = 9;
}
}package main
import (
"fmt"
"xz/grpc/shoppb"
)
func main() {
o := &shoppb.Order{Id: "a1"}
fmt.Println("note set?", o.Note != nil, "value", o.GetNote())
n := "gift"
o.Note = &n
fmt.Println("note set?", o.Note != nil, "value", o.GetNote())
}proto3 removed optional, then restored it in 2020: nothing else expresses this.
repeated and map
Both arrive as ordinary Go types:
package main
import (
"fmt"
"xz/grpc/shoppb"
)
func main() {
o := &shoppb.Order{Items: []string{"x", "y"}, Counts: map[string]int32{"x": 2}}
fmt.Println("items", o.GetItems(), "counts[x]", o.GetCounts()["x"])
}A map<K,V> is not a wire type. It compiles to a repeated message with key = 1 and
value = 2, so entries have no order.
enum
The zero value is mandatory, and the name matters:
package main
import (
"fmt"
"xz/grpc/shoppb"
)
func main() {
fmt.Println(shoppb.Status(0), int32(shoppb.Status_STATUS_UNSPECIFIED))
}An unset enum decodes as zero.
Nested and imported messages
A message field holds another message:
package main
import (
"encoding/hex"
"fmt"
"time"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"xz/grpc/shoppb"
)
func main() {
o := &shoppb.Order{
ShipTo: &shoppb.Address{City: "Berlin"},
Created: timestamppb.New(time.Unix(1764200000, 0)),
}
fmt.Println("city", o.GetShipTo().GetCity())
fmt.Println("seconds", o.GetCreated().GetSeconds())
b, _ := proto.Marshal(o)
fmt.Println("bytes", hex.EncodeToString(b))
}32 is field 6 wire type 2, 08 its length, then a complete Address: 0a06 and Berlin. A
nested message is length-delimited like a string, so decoding is recursive.
Timestamp is a well-known type: the import needs no file of yours.
oneof
At most one field set. The generated type is an interface:
package main
import (
"encoding/hex"
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/shoppb"
)
func main() {
o := &shoppb.Order{Payment: &shoppb.Order_Card{Card: "4242"}}
switch p := o.GetPayment().(type) {
case *shoppb.Order_Card:
fmt.Println("paid by card", p.Card)
case *shoppb.Order_Invoice:
fmt.Println("invoice", p.Invoice)
}
b, _ := proto.Marshal(o)
fmt.Println("oneof bytes", hex.EncodeToString(b))
}42 is field 8: on the wire a oneof is whichever field was set. The grouping exists only in the
schema.
Unknown fields are preserved
A field a binary has never heard of survives a round trip:
syntax = "proto3";
package v1;
option go_package = "xz/grpc/v1pb";
message User {
string name = 1;
}syntax = "proto3";
package v2;
option go_package = "xz/grpc/v2pb";
message User {
string name = 1;
string email = 2;
}package main
import (
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/v1pb"
"xz/grpc/v2pb"
)
func main() {
wire, _ := proto.Marshal(&v2pb.User{Name: "ada", Email: "[email protected]"})
fmt.Println("new binary wrote", len(wire), "bytes")
var old v1pb.User
proto.Unmarshal(wire, &old)
fmt.Println("old sees name:", old.GetName())
back, _ := proto.Marshal(&old)
fmt.Println("old re-wrote", len(back), "bytes")
var again v2pb.User
proto.Unmarshal(back, &again)
fmt.Printf("email survived: %q\n", again.GetEmail())
}15 bytes in, 15 back. The old binary cannot read email and does not lose it.
What this costs you
One field set, on the wire:
package main
import (
"encoding/hex"
"fmt"
"google.golang.org/protobuf/proto"
"xz/grpc/shoppb"
)
func main() {
b, _ := proto.Marshal(&shoppb.Order{Id: "ada"})
fmt.Println(hex.EncodeToString(b))
}The same five bytes as HelloRequest{Name: "ada"}. Without the schema, you cannot tell which
message you hold.
No curl, no eyeballing a log line. When you need text, protojson uses the schema:
package main
import (
"fmt"
"google.golang.org/protobuf/encoding/protojson"
"xz/grpc/shoppb"
)
func main() {
o := &shoppb.Order{Items: []string{"x", "y"}, Counts: map[string]int32{"x": 2}}
j, _ := protojson.Marshal(o)
fmt.Println(string(j))
}That spacing is deliberately unstable, so nobody diffs the output. Parse it, never string-compare it.