Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Protocol Buffers Handbook
Protocol Buffers Handbook

Protocol Buffers Handbook: Getting deeper into Protobuf internals and its usage

eBook
$9.99 $31.99
Paperback
$39.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Protocol Buffers Handbook

Protobuf is a Language

It is time to discover the Protobuf language and its syntax. In this chapter, we are going to see all the concepts that we need in order to write Protobuf schemas. This chapter is, thus, designed as a kind of documentation that can be read from start to end but also can be referenced in future chapters. As such, you might not understand every implication of each concept, but that is fine. Be confident, and we will make sure that you get all the knowledge you need throughout this book.

In this chapter, we will learn about the following:

  • Top-level statements
  • User-defined types
  • Out-of-the-box types
  • Services

At the end of this chapter, you will know all the most common concepts in the Protobuf language. You will understand what they are used for, and you will be able to start writing proto files.

Technical requirements

All the code examples that you will see in this section can be found under the directory called chapter2 in the GitHub repository (https://github.com/PacktPublishing/Protocol-Buffers-Handbook).

In the following sections, I will be using some extended Backus-Naur form (EBNF) notation (https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to describe the syntax of all the elements. The following elements will be used:

|   alternation (or)
()  grouping
[]  option (zero or one time)
{}  repetition (any number of times)

Do not worry too much, though. I am only writing in the EBNF for people who are interested and to emphasize that Protobuf is a language. If you feel like this is too overwhelming, you can just skip this part and look at the examples I will be providing.

On top of that, I will be omitting details for simplicity. However, all the details are available in the official specifications:

...

Top-level statements

In this section, we will see all the top-level statements in the order they should appear in a proto file according to the Protobuf Style Guide (https://protobuf.dev/programming-guides/style/). We are going to go through their meaning, and we are going to see some simple examples.

Syntax

The syntax statement is one of the easiest statements to understand. This tells the compiler (protoc) the version we are using in the file and, therefore, the features we can and cannot access:

EBNF – Syntax statement

version = "proto2" | "proto3" | "editions"
syntax = "syntax" "=" ("'" version "'" | '"' version '"') ";"

As you can see, there are three versions that we can pass to the syntax statement:

  • proto2
  • proto3
  • editions

Now, all of this is a little bit obscure, and these names, especially proto2 and proto3, are...

User-defined types

enum

You are certainly already familiar with enums in your favorite language, and they are pretty much the same in Protobuf. When we know all the possible values of a type, we use enums to create a lightweight representation of each value:

EBNF – Enum syntax

enumValueOption = optionName "=" constant
enumField = ident "=" [ "-" ] intLit [ "[" enumValueOption { ","  enumValueOption } "]" ]";"
enumBody = "{" { option | enumField | reserved } "}"
enum = "enum" ident enumBody

As such, an enum in Protobuf looks like the following:

enum PhoneType {
  PHONE_TYPE_MOBILE = 0;
  PHONE_TYPE_HOME = 1;
  //...
}

You can see that we are adding the name of the enum (in UPPER_SNAKE_CASE) as the prefix of each value, and then we have this magic number following the equal sign. The naming is purely done according to convention...

Message

Messages are the most complex concept in Protobuf. This is why we are going to split this section into multiple subsections. We will talk about these concepts in the following order:

  • Options: They are repeated in all the following concepts
  • Field, reserved, map, and oneof: These concepts are all about defining fields and specifying some serialization behavior
  • Nested messages

EBNF – Message syntax

messageBody = "{" { field | enum | message | option | oneof | mapField | reserved } "}"
message = "message" ident messageBody

Option

Since we are already familiar with options at this point, we can skip them. However, I still want to mention all the types that you can look for in the descriptor.proto (check https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto) file so that you can check all the possible options available. Here is the list per concept:

message -> MessageOptions...

Services

Finally, the last concept we are going to see is service. service is designed for Protobuf interaction with RPC frameworks, such as gRPC. They define a type-safe contract that the server should implement and that the client can call:

EBNF – Service syntax

rpc = "rpc" ident "(" [ "stream" ] messageType ")" "returns" "(" [ "stream" ] messageType ")" (( "{" option "}" ) | ";")
service = "service" ident "{" { option | rpc } "}"

For example, we could have the following service:

service BookService {
  rpc ListBooks(ListBooksRequest) returns (ListBooksResponse);
  rpc GetBook(GetBookRequest) returns (Book);
  rpc CreateBook(CreateBookRequest) returns (Book);
  rpc UpdateBook(UpdateBookRequest) returns (Book);
  rpc DeleteBook(DeleteBookRequest) returns (google.protobuf.Empty...

Out-of-the-box types

On top of all the scalar types that Protobuf provides as part of the language, it also provides some already-defined types called well-known types (WKTs). All these types can be found in the src/google/protobuf folder in the GitHub repository (https://github.com/protocolbuffers/protobuf/tree/main/src/google/protobuf), and they are all defined under the google.protobuf package.

Here is a list of the most common WKTs available:

  • Duration
  • Timestamp
  • FieldMask
  • Any
  • Struct

Let’s go through all of these types and see what they are used for.

Duration and timestamp

These two types are pretty interesting because they show us the importance of naming, documenting with comments, and separating definitions into different files for reusability. In fact, these two types have the same definitions except for the message name. Here are the diff command results between those two (simplified):

-message Timestamp {
-  // Represents...

Summary

We have come a long way. This chapter was intense, and there are probably things that you are still not entirely sure about. That is normal; do not worry. You can refer to it later if you have questions about a certain Protobuf concept.

In this chapter, we saw how to write top-level statements such as Edition, Syntax, Import, Package, and Options. We then saw how to write enums and messages to create type definitions. After that, we saw what the services are. Finally, we talked about the well-known types that are provided out of the box when you use Protobuf.

In the next chapter, we will talk about the Protobuf text format and how we can set values to fields in a nonprogrammatic way.

Quiz

  1. Where can you find the proto files for the well-known types?
    1. Nowhere; this is hidden inside the Protobuf language.
    2. Nowhere; we need to define them ourselves.
    3. On the GitHub repository under the src/google/protobuf folder.
  2. Where can you find the message definitions for the option types?
    1. On the GitHub repository under the folder src/google/protobuf in the file called descriptor.proto.
    2. Nowhere; this is hidden inside the Protobuf language.
    3. Nowhere; we need to define them ourselves.
  3. Why do we define an UNSPECIFIED value in enums for proto3?
    1. In proto3, enums are closed, so we do not need to.
    2. In proto3, enums are open, and UNSPECIFIED is used as the default value.
    3. It is not needed in proto3, only in proto2.
  4. When do we need nesting types inside a message?
    1. When we want to specialize a type with fully qualified names.
    2. When a type is only relevant in the parent context.
    3. All the above.

Answers

  1. C
  2. A
  3. B
  4. C
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Encode and decode complex data structures, enhancing data interchange efficiency across systems
  • Understand Protobuf by mastering the syntax, schema evolution, customizations, and more
  • Integrate Protobuf into your preferred language ecosystem, ensuring interoperability and effective collaboration
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Explore how Protocol Buffers (Protobuf) serialize structured data and provides a language-neutral, platform-neutral, and extensible solution. With this guide to mastering Protobuf, you'll build your skills to effectively serialize, transmit, and manage data across diverse platforms and languages. This book will help you enter the world of Protocol Buffers by unraveling the intricate nuances of Protobuf syntax and showing you how to define complex data structures. As you progress, you’ll learn schema evolution, ensuring seamless compatibility as your projects evolve. The book also covers advanced topics such as custom options and plugins, allowing you to tailor validation processes to your specific requirements. You’ll understand how to automate project builds using cutting-edge tools such as Buf and Bazel, streamlining your development workflow. With hands-on projects in Go and Python programming, you’ll learn how to practically apply Protobuf concepts. Later chapters will show you how to integrate data interchange capabilities across different programming languages, enabling efficient collaboration and system interoperability. By the end of this book, you’ll have a solid understanding of Protobuf internals, enabling you to discern when and how to use and redefine your approach to data serialization.

Who is this book for?

This book is for software developers, from novices to experienced programmers, who are interested in harnessing the power of Protocol Buffers. It's particularly valuable for those seeking efficient data serialization solutions for APIs, microservices, and data-intensive applications. The content covered in this book accommodates diverse programming backgrounds, offering essential knowledge to both beginners and seasoned developers.

What you will learn

  • Focus on efficient data interchange with advanced serialization techniques
  • Master Protocol Buffers syntax and schema evolution
  • Perform custom validation via Protoc plugins for precise data integrity
  • Integrate languages seamlessly for versatile system development
  • Automate project building with Buf and Bazel
  • Get to grips with Go and Python integration for real-world Protobuf applications
  • Streamline collaboration through system interoperability with Protobuf
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2024
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781805124672
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Apr 30, 2024
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781805124672
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 144.97
Mastering Go
$54.99
Asynchronous Programming in Rust
$49.99
Protocol Buffers Handbook
$39.99
Total $ 144.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Chapter 1: Serialization Primer Chevron down icon Chevron up icon
Chapter 2: Protobuf is a Language Chevron down icon Chevron up icon
Chapter 3: Describing Data with Protobuf Text Format Chevron down icon Chevron up icon
Chapter 4: The Protobuf Compiler Chevron down icon Chevron up icon
Chapter 5: Serialization Internals Chevron down icon Chevron up icon
Chapter 6: Schema Evolution over Time Chevron down icon Chevron up icon
Chapter 7: Implementing the Address Book in Go Chevron down icon Chevron up icon
Chapter 8: Implementing the Address Book in Python Chevron down icon Chevron up icon
Chapter 9: Developing a Protoc Plugin in Golang Chevron down icon Chevron up icon
Chapter 10: Advanced Build Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Frequent buyer Jun 12, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an excellent resource for anyone looking to dive deep into the world of Protocol Buffers, whether you’re a beginner or have some prior knowledge.Author does a fantastic job of breaking down the basics and gradually building up to more advanced topics. The examples are practical and relevant, making it easy to see how Protocol Buffers can be applied in real-world scenarios.I particularly appreciated the section on best practices and optimization techniques.The insights provided have already helped me improve the performance of my own projects.Overall, “Protocol Buffers: The Definitive Guide” is well-structured, informative, and engaging. It has definitely earned a permanent spot on my bookshelf.
Amazon Verified review Amazon
Juan Cruz Viotti Jun 26, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have experience with binary serialisation from a research point of view (University of Oxford) and have worked with binary serialisation formats including Protocol Buffers in the context of IoT, and this book still managed to teach me a bunch of things I didn't know.First of all, Chapter 5 on serialisation internals is a gem. I really wish this book was there by the time I published some of my papers back in the day. I would have cited this book instead of attempting to write quite a lot about these things myself. Furthermore, the book teaches a very nice workflow for introducing readers on how to debug binary payloads, which people otherwise end up learning the hard way.Other than that, this book has a great introduction on writing your own "protoc" plugin/extensions (which I didn't even know was possible), and on using Protocol Buffers with more modern platforms like Buf.If you are into binary serialisation, schemas, or just need to learn Protocol Buffers to get something done, this well-written and pretty concise and to-the-point book might be all you need.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela