It is Google’s language neutral and platform neutral mechanism for serialisation of data. Protobufs serialise data into a compact binary format which makes it more efficient than JSON and XML in terms of speed and size.

Protocol buffers can generate language specific code for various languages like Go, Typescript or Java which enables communication between services that are in different languages.

How to use Protocol Buffers

  1. Create a .proto file and define messages/services
  2. Compile it using the protoc complier to generate language specific code
  3. Use the generated code in your app to serialise/deserialise data

Example of .proto file

syntax = "proto3";  
//   
package todo;  
  
message NoParam {  
}  
  
message TodoItem {  
  int32 id = 1;  
  string text = 2;  
}  
  
message TodoItems {  
  // Repeated is an array  
  repeated TodoItem items = 1;  
}   
  
service Todo {  
  rpc create(TodoItem) returns (TodoItem);  
  rpc read(NoParam) returns (TodoItems);  
  rpc readStream(NoParam) returns (stream TodoItem);  
}  

Pros

  • Uses binary for encoding instead of text based languages like JSON and XML, which makes the payload smaller
  • Adding new fields won’t break the functionality which means that it is backwards compatible
  • Integrates very well with gRPC.