Youssef Ameachaq's Blog

Youssef Ameachaq

2️⃣ / 1️⃣ Introduction to gRPC and Protocol Buffers (Protobuf)


Introduction to gRPC and Protocol Buffers (Protobuf)

What is gRPC?

gRPC is a framework for building fast, efficient, and scalable APIs between different programs or services. It allows different applications to communicate with each other, even if they are on different machines or environments.

Why Use gRPC?


What is a .proto file?

A .proto file is the definition file used by gRPC to describe the contract between client and server. It specifies the functions (RPCs) the server can provide, the messages (data) exchanged, and their types. It’s like a menu for how your services communicate.

Structure of a .proto File

Here’s an example .proto file called hello.proto:

syntax = "proto3";

package hello;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

Explanation:


Why Use Protobuf Over JSON?

While JSON is popular for APIs, Protobuf offers several advantages for gRPC.

1. Protobuf is Faster 🚀

Example:
A simple JSON message:

{
  "name": "Youssef",
  "age": 30
}

Protobuf sends the same data as a binary stream, which is much smaller and faster to transmit.


2. Protobuf is Type-Safe 🔒


3. Protobuf Generates Code for You 🏗️

Example:

In .proto file:

message Person {
  string name = 1;
  int32 age = 2;
}

Protobuf generates the Go struct:

type Person struct {
  Name string
  Age  int32
}

4. Protobuf Supports Streaming 📡

Example:
In a live stock market app 📈, gRPC allows the server to push updates instantly, instead of the client having to keep asking (polling) for updates.


5. Protobuf is Used by Big Companies 🌍


TL;DR - Why Use Protobuf Over JSON?

FeatureJSONProtobuf
SpeedSlower 🚶Faster 🚀
SizeBigger 📦Smaller 🎯
Type SafetyNo ❌Yes ✅
Auto Code GenerationNo ❌Yes ✅
StreamingNo ❌Yes ✅
Best ForWeb APIs 🌍High-performance services ⚡

Conclusion


Example: Using gRPC with Go

  1. Install gRPC tools:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
  1. Define your service in a .proto file (hello.proto).

  2. Generate Go code:

protoc --go_out=. --go-grpc_out=. hello.proto
  1. Write the server in Go to handle client requests.

  2. Write the client in Go to send requests to the server.