Go gRPC lets one service call a function on another service, almost as if it were a local function. In this post, you will learn what gRPC is and how it differs from REST. Then we will build a small book service with a server and a client. By the end, you will have a working pattern you can reuse in real microservices.
This lesson builds on two earlier ones. First, you built JSON endpoints in the Go REST API tutorial. Then you learned timeouts and cancellation in Go context for beginners. Both ideas come back here, so keep them in mind.
What Is Go gRPC?
In short, gRPC is a framework for remote procedure calls, or RPC. An RPC simply means “call a function that lives on another machine”. You describe your functions and data once in a .proto file. Then a tool generates Go code for both the server and the client.
For example, think of a restaurant menu. The menu lists every dish and what goes into it, so the customer and the kitchen agree before anyone cooks. In the same way, the .proto file is a menu that both services agree on. So the client cannot ask for a dish that does not exist.
Under the hood, Go gRPC sends data in a compact binary format called Protocol Buffers, or protobuf for short. It also runs on HTTP/2, which keeps one connection open and sends many calls over it at once.
Why Go gRPC Matters
On one hand, REST with JSON works well for browsers and public APIs. However, inside a company, services often talk to each other thousands of times per second. In that case, small messages and strict types matter a lot.
Here are common places where teams pick gRPC.
- Service to service calls: an order service asks a payment service to charge a card.
- Streaming data: a server sends live stock prices or log lines as they happen.
- Many languages: a Go service and a Python service share one
.protofile. - Mobile apps on slow networks: smaller messages mean faster screens.
In short, Go gRPC shines when speed, strict contracts and streaming matter more than easy browser access.
How Go gRPC Works
The Go gRPC flow has four simple steps. First, you write the contract in a .proto file. Next, the protoc compiler generates Go code from it. Then you write a server that fills in the generated interface. Finally, the client calls the generated methods like normal Go functions.

Meanwhile, the generated client code does the hard work. First, it turns your Go struct into protobuf bytes and sends them. Then it waits for the reply and turns the bytes back into a struct. As a result, your own code stays short and readable.
Key Parts of a Go gRPC Service
In fact, every Go gRPC project has the same few building blocks. Once you know them, any gRPC codebase becomes easy to read.
The .proto File
First, this file defines messages, which are like structs, and services, which are like interfaces. Each field gets a number, such as = 1. These numbers identify fields on the wire, so never reuse or change them once a service is live.
Generated Code
Next, two plugins create the Go code. The protoc-gen-go plugin makes the message structs, while protoc-gen-go-grpc makes the server interface and the client. You never edit these files by hand.
The Server
Here, you write a struct that implements the service methods. Then you register it on a grpc.Server and start listening on a TCP port.
The Client
The client opens a connection with grpc.NewClient and calls methods on a generated client value. Each call takes a context, so timeouts work exactly like you learned before.
RPC Types
Every Go gRPC service can use four call styles. This table shows them with a simple example for each.
| Type | What happens | Example |
|---|---|---|
| Unary | One request, one response | Get one book by ID |
| Server streaming | One request, many responses | List all books by an author |
| Client streaming | Many requests, one response | Upload many log lines, get a summary |
| Bidirectional | Many requests and responses | A live chat between two services |
Go gRPC vs REST
Both styles move data between services. However, they make different trade-offs. The table below compares them side by side.
| Feature | gRPC | REST with JSON |
|---|---|---|
| Data format | Binary protobuf | Text JSON |
| Contract | Required .proto file | Optional, often OpenAPI |
| Transport | HTTP/2 | Usually HTTP/1.1 |
| Streaming | Built in, four styles | Needs extra tools |
| Browser support | Needs a proxy | Works directly |
| Easy to debug with curl | No | Yes |

So when should you use which? Use REST for public APIs and browser apps. On the other hand, use Go gRPC for fast internal calls between your own services.
Hands-On: Build a Go gRPC Book Service
Let’s build a small Go gRPC library service. It will have two methods: GetBook returns one book, and ListBooks streams all books by an author.
Step 1: Install the Tools
First, install the protoc compiler from your package manager or the protobuf releases page. Then install the two Go plugins with these commands.
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
export PATH="$PATH:$(go env GOPATH)/bin"
The last line puts the plugins on your PATH, so protoc can find them.
Step 2: Write the Contract
Create the file library/library.proto with the following content.
syntax = "proto3";
package library;
option go_package = "example.com/library/librarypb";
// BookService lets clients read books from our library.
service BookService {
rpc GetBook(GetBookRequest) returns (Book);
rpc ListBooks(ListBooksRequest) returns (stream Book);
}
message Book {
int32 id = 1;
string title = 2;
string author = 3;
}
message GetBookRequest {
int32 id = 1;
}
message ListBooksRequest {
string author = 1;
}
Here, the word stream before Book makes ListBooks a server streaming call. Also, go_package tells the generator which Go import path to use.
Step 3: Generate the Go Code
Now run protoc from the project root.
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
library/library.proto
As a result, this creates library.pb.go and library_grpc.pb.go next to the proto file. One small surprise for beginners is the field names. Because protobuf follows Go naming rules, the field id becomes Id in Go, and the getter is GetId().
Step 4: Write the Server
Here is the full server. To stay simple, it keeps books in a slice instead of a database. Later in this series, we will swap the slice for PostgreSQL.
type server struct {
pb.UnimplementedBookServiceServer
books []*pb.Book
}
func (s *server) GetBook(ctx context.Context, req *pb.GetBookRequest) (*pb.Book, error) {
for _, b := range s.books {
if b.GetId() == req.GetId() {
return b, nil
}
}
return nil, status.Errorf(codes.NotFound, "book %d not found", req.GetId())
}
func (s *server) ListBooks(req *pb.ListBooksRequest, stream pb.BookService_ListBooksServer) error {
for _, b := range s.books {
if b.GetAuthor() == req.GetAuthor() {
if err := stream.Send(b); err != nil {
return err
}
}
}
return nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterBookServiceServer(s, &server{books: []*pb.Book{
{Id: 1, Title: "Go Basics", Author: "Asha"},
{Id: 2, Title: "Go Testing", Author: "Asha"},
{Id: 3, Title: "Go Web", Author: "Ravi"},
}})
log.Println("gRPC server listening on :50051")
log.Fatal(s.Serve(lis))
}
Let’s walk through the important lines. The embedded UnimplementedBookServiceServer keeps the code compiling if the contract later gains new methods. You saw this idea in Go struct embedding. Next, status.Errorf with codes.NotFound returns a proper gRPC error, much like a 404 in REST. Finally, stream.Send pushes each matching book to the client one at a time.
Step 5: Write the Client
The client connects and asks for one book. Then it asks for a missing book and finally reads the stream.
func main() {
conn, err := grpc.NewClient("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewBookServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
book, err := c.GetBook(ctx, &pb.GetBookRequest{Id: 1})
if err != nil {
log.Fatalf("could not get book: %v", err)
}
fmt.Println("Book:", book.GetTitle())
_, err = c.GetBook(ctx, &pb.GetBookRequest{Id: 99})
if status.Code(err) == codes.NotFound {
fmt.Println("Error:", err)
}
stream, err := c.ListBooks(ctx, &pb.ListBooksRequest{Author: "Asha"})
if err != nil {
log.Fatal(err)
}
for {
b, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println("Streamed:", b.GetTitle())
}
}
insecure.NewCredentials() turns off TLS, which is fine on your laptop. In production, however, you must use TLS. Also, status.Code(err) reads the gRPC code from any error. So you can treat “not found” differently from a network failure.
Now start the server in one terminal and run the client in another. Because both use port 50051, make sure nothing else is using it. You should see this output.
Book: Go Basics
Error: rpc error: code = NotFound desc = book 99 not found
Streamed: Go Basics
Streamed: Go Testing
In other words, the stream ends when the server’s ListBooks method returns. Then Recv gives io.EOF, and the loop stops.
Common Mistakes with Go gRPC
- Forgetting the PATH export:
protocthen fails with “protoc-gen-go: program not found”. Add the Go bin folder to yourPATH. - Changing field numbers: old clients then read the wrong data silently. So only add new numbers and never reuse old ones.
- No timeout on calls: a slow server can block your client forever. Always pass a context with a deadline.
- Returning plain errors:
errors.Newbecomescodes.Unknownon the client. Usestatus.Errorfwith a real code instead. - Editing generated files: your changes vanish on the next
protocrun. Change the.protofile and regenerate.
Best Practices for Go gRPC
- **Keep
.protofiles in one shared place**, because every client must use the same contract. - Use TLS outside your laptop, since
insecuresends data as plain bytes. - Set deadlines on every call, so one slow service cannot freeze the chain.
- Return precise status codes, because clients can then retry only when it makes sense.
- Close streams and connections, as open connections hold memory on both sides.
- Add new fields instead of changing old ones, so old and new versions keep working together.
Practice Task
To practise Go gRPC, add a CreateBook method to the contract. It should take a title and an author and return the new book with an ID. Regenerate the code, then write the server method and call it from the client.
Hint: return codes.InvalidArgument when the title is empty.
Official Resources
These pages come from the gRPC and Go teams, so they stay accurate and current.
- Quick start for gRPC in Go
- Basics tutorial for gRPC in Go
- grpc package on pkg.go.dev
- Protocol Buffers proto3 language guide
Quick Recap
- Go gRPC calls functions on other services using a shared
.protocontract. protocgenerates message structs, a server interface and a client.- gRPC uses compact protobuf messages over HTTP/2.
- There are four call styles: unary, server streaming, client streaming and bidirectional.
- Return errors with
status.Errorfand a code such ascodes.NotFound. - Use REST for browsers and public APIs, and gRPC for fast internal calls.
What’s Next?
Go gRPC streams are great between services. However, browsers need something else for live updates. Next, we will build a real-time chat server with WebSockets.
Next lesson: Go WebSockets: Build a Real-Time Chat Server


