Protocol Buffers

suggest change

Protocol Buffers (protobuf) is Google's language-neutral format for structured data. You describe messages in a .proto schema file, the protoc compiler generates code for each language, and messages are serialized to a compact binary encoding (or to a canonical JSON form). Unlike JSON or YAML, the schema is required: field names are not stored on the wire, only field numbers, which is why the encoding is small and why old and new programs can still read each other's data.

In Ruby you need two things:

For text formats see JSON with Ruby and YAML; for working with raw binary Strings see Bytes and binary data.

The examples were run with Ruby 4.0, google-protobuf 4.36.2 and protoc 36.2.

Installation

gem install google-protobuf
# or in a Gemfile:
#   gem "google-protobuf", "~> 4.36"

protoc is a separate binary. Download protoc-<version>-<platform>.zip from the GitHub releases page of protocolbuffers/protobuf (it contains bin/protoc and an include/ directory with the well-known .proto files), or install it with a package manager (brew install protobuf, apt install protobuf-compiler). The gem and the compiler versions are related: gem 4.36.x goes with protoc 36.x. Generated code works with a runtime of the same or a newer version, so keep them in step.

Defining a schema

proto/addressbook.proto:

syntax = "proto3";

package tutorial;

import "google/protobuf/timestamp.proto";

message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;

  enum PhoneType {
    PHONE_TYPE_UNSPECIFIED = 0;
    PHONE_TYPE_MOBILE = 1;
    PHONE_TYPE_HOME = 2;
    PHONE_TYPE_WORK = 3;
  }

  message PhoneNumber {
    string number = 1;
    PhoneType type = 2;
  }

  repeated PhoneNumber phones = 4;
  map<string, string> labels = 5;
  optional string nickname = 6;
  google.protobuf.Timestamp last_updated = 7;

  oneof contact {
    string twitter = 8;
    string mastodon = 9;
  }
}

message AddressBook {
  repeated Person people = 1;
}

The number after each field (= 1, = 2) is the field's identity on the wire. Once data has been written, never change a field's number or type. Numbers 1-15 take one byte to encode, so use them for the most common fields.

Generating Ruby code

protoc -I proto -I /path/to/protoc/include --ruby_out=lib proto/addressbook.proto

-I adds import paths (the second one is only needed if protoc can't find google/protobuf/timestamp.proto on its own). This produces lib/addressbook_pb.rb:

# frozen_string_literal: true
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: addressbook.proto

require 'google/protobuf'

require 'google/protobuf/timestamp_pb'


descriptor_data = "\n\x11\x61\x64\x64ressbook.proto\x12\x08tutorial..."  # shortened

pool = ::Google::Protobuf::DescriptorPool.generated_pool
pool.add_serialized_file(descriptor_data)

module Tutorial
  Person = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("tutorial.Person").msgclass
  Person::PhoneNumber = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("tutorial.Person.PhoneNumber").msgclass
  Person::PhoneType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("tutorial.Person.PhoneType").enummodule
  AddressBook = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("tutorial.AddressBook").msgclass
end

The file embeds the compiled schema and asks the runtime to build classes from it. The package tutorial becomes the module Tutorial, and nested messages and enums become nested constants. There are no Ruby methods to read in the file; accessors are defined by the runtime.

protoc can also write RBS type signatures for the generated classes with --rbs_out=sig, which helps Steep and editors that understand RBS.

Creating messages

require_relative 'lib/addressbook_pb'

person = Tutorial::Person.new(
  name: 'Alice',
  id: 1234,
  email: 'alice@example.com',
  phones: [{ number: '555-0100', type: :PHONE_TYPE_MOBILE }]
)
person.phones << Tutorial::Person::PhoneNumber.new(number: '555-0199', type: :PHONE_TYPE_WORK)
person.labels['team'] = 'platform'

p person
puts person.name
puts person.phones.size
puts person.phones[1].type.inspect
puts person.labels['team']
<Tutorial::Person: name: "Alice", id: 1234, email: "alice@example.com", phones: [<Tutorial::Person::PhoneNumber: number: "555-0100", type: :PHONE_TYPE_MOBILE>, <Tutorial::Person::PhoneNumber: number: "555-0199", type: :PHONE_TYPE_WORK>], labels: {"team"=>"platform"}>
Alice
2
:PHONE_TYPE_WORK
platform

The constructor takes a Hash of field values. Nested messages can be given as Hashes and are converted for you.

Binary encoding and decoding

require_relative 'lib/addressbook_pb'

person = Tutorial::Person.new(name: 'Alice', id: 1234)

bytes = Tutorial::Person.encode(person)   # same as person.to_proto
p bytes
p bytes.encoding
p bytes.bytesize
puts bytes.unpack1('H*')

copy = Tutorial::Person.decode(bytes)
p copy
p copy == person

File.binwrite('person.bin', bytes)
p Tutorial::Person.decode(File.binread('person.bin')).name

require 'json'
p({ name: 'Alice', id: 1234 }.to_json.bytesize)
"\n\x05Alice\x10\xD2\t"
#<Encoding:BINARY (ASCII-8BIT)>
10
0a05416c69636510d209
<Tutorial::Person: name: "Alice", id: 1234, email: "", phones: [], labels: {}>
true
"Alice"
26

The 10 bytes are: 0a (field 1, length-delimited), 05 (length), Alice, 10 (field 2, varint), d2 09 (1234 as a varint). Fields with default values ("", 0, empty lists) are not written at all. The result is a binary String, so use File.binwrite/File.binread (or open files with "wb"/"rb") to avoid newline translation and encoding problems.

When you are debugging, protoc can decode binary data, with or without the schema:

$ protoc --decode_raw < person.bin
1: "Alice"
2: 1234
$ protoc -I proto --decode=tutorial.Person proto/addressbook.proto < person.bin
name: "Alice"
id: 1234

Decoding errors

require_relative 'lib/user_v1_pb'   # message User { string name = 1; int32 age = 2; }

begin
  Users::V1::User.decode("\xFF\xFF\xFF".b)
rescue Google::Protobuf::ParseError => e
  puts "#{e.class}: #{e.message}"
end

# Bytes that happen to be valid protobuf decode "successfully" into the wrong type
p Users::V1::User.decode("\x10\x05".b)
Google::Protobuf::ParseError: Error occurred during parsing
<Users::V1::User: name: "", age: 5>

The binary format doesn't say which message type it holds. Decoding with the wrong class often succeeds and gives nonsense, so the reader must know the type from context (a file format, an RPC method, a topic name) or the data must be wrapped in an Any (see below).

Default values, presence and type checks

require_relative 'lib/addressbook_pb'

person = Tutorial::Person.new
p person.name          # ""
p person.id            # 0
p person.phones        # []
p person.nickname      # "" (optional, but still returns default)
p person.has_nickname?
p person.last_updated  # nil for unset message fields
p person.has_last_updated?

person.nickname = ''
p person.has_nickname?   # true: explicitly set, even to the default
person.clear_nickname
p person.has_nickname?

begin
  person.has_name?
rescue NoMethodError => e
  puts e.message
end
""
0
[]
""
false
nil
false
true
false
undefined method 'has_name?' for an instance of Tutorial::Person

In proto3 a plain scalar field like name has no presence: an empty string and "not set" are the same thing, so there is no has_name?. Mark the field optional (like nickname) when you need to tell them apart; that gives you has_nickname? and clear_nickname. Message fields (last_updated) always track presence and return nil when unset.

Setters check types and raise immediately:

require_relative 'lib/addressbook_pb'
person = Tutorial::Person.new

[
  -> { person.id = 'abc' },
  -> { person.id = 1.5 },
  -> { person.name = 42 },
  -> { person.phones << 'not a phone' },
  -> { Tutorial::Person.new(age: 30) }
].each do |f|
  f.call
rescue => e
  puts "#{e.class}: #{e.message}"
end

person.id = 7.0      # floats with no fractional part are accepted
p person.id
person.name = :bob   # symbols are converted to strings
p person.name
Google::Protobuf::TypeError: Expected number type for integral field 'id' (given String).
RangeError: Non-integral floating point value assigned to integer field 'id' (given Float).
Google::Protobuf::TypeError: Invalid argument for string field 'name' (given Integer).
Google::Protobuf::TypeError: Invalid type String to assign to submessage field ''.
ArgumentError: Unknown field name 'age' in initialization map entry.
7
"bob"

Integers outside the field's range (for example 3_000_000_000 for an int32) raise RangeError too.

Repeated and map fields

Repeated fields are Google::Protobuf::RepeatedField and map fields are Google::Protobuf::Map. They behave like Array and Hash, but check the type of every element.

require_relative 'lib/addressbook_pb'
PN = Tutorial::Person::PhoneNumber
person = Tutorial::Person.new(name: 'Bob')

p person.phones.class
person.phones << PN.new(number: '1')
person.phones.push(PN.new(number: '2'), PN.new(number: '3'))
person.phones += [PN.new(number: '4')]   # returns a new RepeatedField, then assigns it
p person.phones.map(&:number)
p person.phones.select { |ph| ph.number.to_i.even? }.map(&:number)
person.phones.delete_at(0)
p person.phones.map(&:number)
p person.phones.to_a.class

begin
  person.phones = [PN.new(number: '9')]
rescue => e
  puts "#{e.class}: #{e.message}"
end
person.phones.replace([PN.new(number: '9')])
p person.phones.map(&:number)
person.phones.clear
p person.phones.empty?

p person.labels.class
person.labels['env'] = 'prod'
person.labels['tier'] = 'web'
p person.labels.keys.sort
person.labels.delete('tier')
p person.labels.to_h
begin
  person.labels['count'] = 5
rescue => e
  puts "#{e.class}: #{e.message}"
end
Google::Protobuf::RepeatedField
["1", "2", "3", "4"]
["2", "4"]
["2", "3", "4"]
Array
Google::Protobuf::TypeError: Expected repeated field array
["9"]
true
Google::Protobuf::Map
["env", "tier"]
{"env" => "prod"}
Google::Protobuf::TypeError: Invalid argument for string field '' (given Integer).

You can't assign a plain Array to a repeated field after construction; use replace, clear and <<, or pass the Array to new. Map iteration order is not defined, so sort keys when order matters.

Enums

require_relative 'lib/addressbook_pb'

ph = Tutorial::Person::PhoneNumber.new(number: '1', type: :PHONE_TYPE_HOME)
p ph.type
ph.type = 3
p ph.type
p Tutorial::Person::PhoneType::PHONE_TYPE_HOME
p Tutorial::Person::PhoneType.lookup(1)
p Tutorial::Person::PhoneType.resolve(:PHONE_TYPE_WORK)
p Tutorial::Person::PhoneType.descriptor.map { |name, num| [name, num] }

ph.type = 42            # unknown values are kept as integers (open enum)
p ph.type
begin
  ph.type = :PHONE_TYPE_FAX
rescue => e
  puts "#{e.class}: #{e.message}"
end
:PHONE_TYPE_HOME
:PHONE_TYPE_WORK
2
:PHONE_TYPE_MOBILE
3
[[:PHONE_TYPE_UNSPECIFIED, 0], [:PHONE_TYPE_MOBILE, 1], [:PHONE_TYPE_HOME, 2], [:PHONE_TYPE_WORK, 3]]
42
RangeError: Unknown symbol value for enum field 'type'.

Enum fields return Symbols for known values and Integers for values the schema doesn't know about, for example ones added by a newer version of the schema. Code that uses case on an enum should have an else branch for that. The first value must be 0 and is the default, so give it a name like ..._UNSPECIFIED rather than a real meaning.

oneof

At most one field of a oneof group is set at a time:

require_relative 'lib/addressbook_pb'
person = Tutorial::Person.new(name: 'Alice')

p person.contact           # nil: nothing set
person.twitter = '@alice'
p person.contact           # :twitter
person.mastodon = '@alice@ruby.social'
p person.contact           # setting one member clears the others
p person.twitter
p person.has_mastodon?
person.clear_contact
p person.contact
nil
:twitter
:mastodon
""
true
nil

The method named after the group (contact) returns the Symbol of the field that is set, which works well with case.

JSON

Every message also has a canonical JSON mapping, which is handy for debugging, logs and HTTP APIs:

require_relative 'lib/addressbook_pb'

person = Tutorial::Person.new(
  name: 'Alice', id: 1234,
  phones: [{ number: '555-0100', type: :PHONE_TYPE_MOBILE }],
  last_updated: Google::Protobuf::Timestamp.new(seconds: 1_792_224_000)
)

json = Tutorial::Person.encode_json(person)   # same as person.to_json
puts json
puts Tutorial::Person.encode_json(person, preserve_proto_fieldnames: true)
puts Tutorial::Person.encode_json(Tutorial::Person.new(name: 'Bob'), emit_defaults: true)

back = Tutorial::Person.decode_json(json)
p back == person

# proto field names are accepted as well as lowerCamelCase
p Tutorial::Person.decode_json('{"name":"C","last_updated":"2026-10-17T09:30:00Z"}').last_updated.seconds
# enums can be given as name or number
p Tutorial::Person::PhoneNumber.decode_json('{"type":2}').type

begin
  Tutorial::Person.decode_json('{"name":"D","age":30}')
rescue Google::Protobuf::ParseError => e
  puts "ParseError: #{e.message}"
end
p Tutorial::Person.decode_json('{"name":"D","age":30}', ignore_unknown_fields: true).name

p person.to_h
{"name":"Alice","id":1234,"phones":[{"number":"555-0100","type":"PHONE_TYPE_MOBILE"}],"lastUpdated":"2026-10-17T08:00:00Z"}
{"name":"Alice","id":1234,"phones":[{"number":"555-0100","type":"PHONE_TYPE_MOBILE"}],"last_updated":"2026-10-17T08:00:00Z"}
{"name":"Bob","id":0,"email":"","phones":[],"labels":{}}
true
1792229400
:PHONE_TYPE_HOME
ParseError: Error occurred during parsing: Error parsing JSON @1:18: No such field: age
"D"
{name: "Alice", id: 1234, phones: [{number: "555-0100", type: :PHONE_TYPE_MOBILE}], last_updated: {seconds: 1792224000}}

Points to note:

Well-known types

The google/protobuf/*.proto files that come with protoc define common types. Their Ruby classes ship with the gem; require 'google/protobuf/well_known_types' adds helper methods to them:

require 'google/protobuf/well_known_types'
require 'google/protobuf/duration_pb'
require 'google/protobuf/struct_pb'
require 'google/protobuf/any_pb'
require_relative 'lib/addressbook_pb'

# Timestamp
t = Time.utc(2026, 10, 17, 9, 30, 15.25r)
ts = Google::Protobuf::Timestamp.from_time(t)
p ts
p ts.to_time.utc
p ts.to_time == t
now = Google::Protobuf::Timestamp.new
now.from_time(Time.now)
p now.seconds > 0

person = Tutorial::Person.new(name: 'Alice', last_updated: ts)
p person.last_updated.to_time.utc.iso8601(3)

# Duration
d = Google::Protobuf::Duration.new(seconds: 90, nanos: 500_000_000)
p d.to_f
puts d.to_json

# Struct / Value: arbitrary JSON-like data
s = Google::Protobuf::Struct.from_hash({ 'retries' => 3, 'tags' => ['a', 'b'], 'debug' => true, 'extra' => nil })
p s['retries']
p s.to_h
puts s.to_json

# Any: a message of any type plus its type URL
any = Google::Protobuf::Any.pack(person)
p any.type_url
p any.type_name
p any.is(Tutorial::Person)
p any.is(Tutorial::AddressBook)
p any.unpack(Tutorial::Person).name
p any.unpack(Tutorial::AddressBook)
<Google::Protobuf::Timestamp: seconds: 1792229415, nanos: 250000000>
2026-10-17 09:30:15.25 UTC
true
true
"2026-10-17T09:30:15.250Z"
90.5
"90.500s"
3.0
{"retries" => 3.0, "tags" => ["a", "b"], "debug" => true, "extra" => nil}
{"retries":3,"tags":["a","b"],"debug":true,"extra":null}
"type.googleapis.com/tutorial.Person"
"tutorial.Person"
true
false
"Alice"
nil

Schema evolution

The rules that keep old and new code compatible:

Two versions of a schema:

// proto/user_v1.proto
syntax = "proto3";
package users.v1;

message User {
  string name = 1;
  int32 age = 2;
}
// proto/user_v2.proto
syntax = "proto3";
package users.v2;

message User {
  string name = 1;
  reserved 2;           // "age" was removed; never reuse the number
  reserved "age";
  string email = 3;
  repeated string roles = 4;
}
require_relative 'lib/user_v1_pb'
require_relative 'lib/user_v2_pb'

# a new client writes v2 data
new_bytes = Users::V2::User.encode(
  Users::V2::User.new(name: 'Ann', email: 'ann@example.com', roles: %w[admin dev])
)

# an old server reads it with the v1 schema
old = Users::V1::User.decode(new_bytes)
p old                     # email and roles are unknown to v1
p old.age                 # missing field -> default

# ... changes a field it knows about and writes it back
old.name = 'Ann Lee'
round_trip = Users::V1::User.encode(old)

# unknown fields survived the round trip
p Users::V2::User.decode(round_trip)

# old data read by new code
p Users::V2::User.decode(Users::V1::User.encode(Users::V1::User.new(name: 'Zed', age: 40)))
<Users::V1::User: name: "Ann", age: 0>
0
<Users::V2::User: name: "Ann Lee", email: "ann@example.com", roles: ["admin", "dev"]>
<Users::V2::User: name: "Zed", email: "", roles: []>

The v1 code didn't know about email and roles, but kept their bytes and wrote them back unchanged. The age written by v1 is silently skipped by v2. If v2 had reused number 2 for a different field, protoc would refuse to compile it:

proto/user_v2.proto:...: Field "age" uses reserved number 2.

To drop unknown fields (for example before storing data from an untrusted newer client), call Google::Protobuf.discard_unknown(msg); it works recursively.

Writing many messages to one stream

A protobuf message has no end marker, so you can't simply concatenate messages: decoding the concatenation merges them into one. The usual convention, also used by Java's writeDelimitedTo and C++'s SerializeDelimitedToOstream, is to prefix each message with its length as a varint. The Ruby gem doesn't include helpers for it, but they are short:

require_relative 'lib/addressbook_pb'

module Delimited
  module_function

  def write_varint(io, n)
    loop do
      byte = n & 0x7f
      n >>= 7
      if n.zero?
        io.write(byte.chr)
        return
      end
      io.write((byte | 0x80).chr)
    end
  end

  def read_varint(io)
    result = 0
    shift = 0
    loop do
      byte = io.getbyte or return nil   # clean EOF before a message
      result |= (byte & 0x7f) << shift
      return result if byte < 0x80
      shift += 7
      raise 'varint too long' if shift > 63
    end
  end

  def write(io, msg)
    data = msg.to_proto
    write_varint(io, data.bytesize)
    io.write(data)
  end

  def each(io, klass)
    return enum_for(:each, io, klass) unless block_given?
    while (len = read_varint(io))
      data = io.read(len)
      raise EOFError, 'truncated message' if data.nil? || data.bytesize < len
      yield klass.decode(data)
    end
  end
end

File.open('people.bin', 'wb') do |f|
  1.upto(3) { |i| Delimited.write(f, Tutorial::Person.new(id: i, name: "user#{i}")) }
end
p File.size('people.bin')

File.open('people.bin', 'rb') do |f|
  Delimited.each(f, Tutorial::Person) { |person| puts "#{person.id}: #{person.name}" }
end

File.open('people.bin', 'rb') { |f| p Delimited.each(f, Tutorial::Person).map(&:id).sum }
30
1: user1
2: user2
3: user3
6

The same framing works over sockets. This lets you process a large file one message at a time instead of decoding one huge AddressBook.

A small file-backed store

require 'google/protobuf/well_known_types'
require_relative 'lib/addressbook_pb'

PATH = 'addressbook.bin'

def load_book
  File.exist?(PATH) ? Tutorial::AddressBook.decode(File.binread(PATH)) : Tutorial::AddressBook.new
end

def save_book(book)
  tmp = "#{PATH}.tmp"
  File.binwrite(tmp, Tutorial::AddressBook.encode(book))
  File.rename(tmp, PATH)   # atomic replace
end

book = load_book
book.people << Tutorial::Person.new(
  id: book.people.size + 1,
  name: "Person #{book.people.size + 1}",
  last_updated: Google::Protobuf::Timestamp.from_time(Time.utc(2026, 10, 17))
)
save_book(book)

load_book.people.each do |person|
  puts "#{person.id} #{person.name} #{person.last_updated.to_time.utc.strftime("%F")}"
end
puts "#{File.size(PATH)} bytes"

Running it twice:

1 Person 1 2026-10-17
22 bytes
1 Person 1 2026-10-17
2 Person 2 2026-10-17
44 bytes

Equality, copying and freezing

require_relative 'lib/addressbook_pb'

a = Tutorial::Person.new(name: 'Alice', phones: [{ number: '1' }])
b = Tutorial::Person.new(name: 'Alice', phones: [{ number: '1' }])
p a == b
p a.equal?(b)
p a.hash == b.hash
p({ a => :seen }.key?(b))

c = a.dup             # dup/clone are shallow: nested messages are shared
c.name = 'Carol'
c.phones[0].number = '2'
p [a.name, a.phones[0].number]

d = Tutorial::Person.decode(a.to_proto)   # deep copy
d.phones[0].number = '3'
p a.phones[0].number

a.freeze
p a.frozen?
p a.phones.frozen?
begin
  a.name = 'Eve'
rescue FrozenError => e
  puts e.class
end
true
false
true
true
["Alice", "2"]
"2"
true
true
FrozenError

Messages compare by value and can be Hash keys. dup copies only the top level; encoding and decoding gives a deep copy. freeze is deep: it also freezes repeated fields, maps and sub-messages, which makes a frozen message safe to share between threads.

Reflection

Each message class has a descriptor that describes its fields. This is useful for generic code such as validators, admin UIs or converters:

require_relative 'lib/addressbook_pb'

desc = Tutorial::Person.descriptor
p desc.name
desc.each do |f|
  info = f.repeated? ? 'repeated' : (f.has_presence? ? 'presence' : '')
  sub = f.subtype ? " -> #{f.subtype.name}" : ''
  puts format('%d %-12s %-13s %-8s %-8s%s', f.number, f.name, f.json_name, f.type, info, sub).rstrip
end
desc.each_oneof { |o| p [o.name, o.map(&:name)] }

person = Tutorial::Person.new(name: 'Alice')
field = desc.lookup('email')
field.set(person, 'alice@example.com')
p field.get(person)

# [] and []= work by field name
p person['name']
person['id'] = 99
p person.id

# look up any message class by its full name
klass = Google::Protobuf::DescriptorPool.generated_pool.lookup('tutorial.AddressBook').msgclass
p klass
"tutorial.Person"
1 name         name          string
2 id           id            int32
3 email        email         string
4 phones       phones        message  repeated -> tutorial.Person.PhoneNumber
5 labels       labels        message  repeated -> tutorial.Person.LabelsEntry
6 nickname     nickname      string   presence
7 last_updated lastUpdated   message  presence -> google.protobuf.Timestamp
8 twitter      twitter       string   presence
9 mastodon     mastodon      string   presence
["contact", ["twitter", "mastodon"]]
["_nickname", ["nickname"]]
"alice@example.com"
"Alice"
99
Tutorial::AddressBook

A map field is a repeated field of a generated ...Entry message. A proto3 optional field is a one-field "synthetic" oneof (_nickname), which is how its presence is tracked.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents