Go gRPC Tutorial: Build Your First gRPC Service

Updated 9 min read
Go gRPC featured image: cards for the proto contract, the server and the client

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 .proto file.
  • 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.

Go gRPC diagram showing a .proto contract generating client and server code over one HTTP/2 connection
A .proto contract generates Go code for both sides, and the client calls the server over one HTTP/2 connection using protobuf messages.

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.

TypeWhat happensExample
UnaryOne request, one responseGet one book by ID
Server streamingOne request, many responsesList all books by an author
Client streamingMany requests, one responseUpload many log lines, get a summary
BidirectionalMany requests and responsesA 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.

FeaturegRPCREST with JSON
Data formatBinary protobufText JSON
ContractRequired .proto fileOptional, often OpenAPI
TransportHTTP/2Usually HTTP/1.1
StreamingBuilt in, four stylesNeeds extra tools
Browser supportNeeds a proxyWorks directly
Easy to debug with curlNoYes
Go gRPC vs REST diagram comparing data format, contract, transport and streaming
REST sends readable JSON over plain HTTP, while gRPC sends compact protobuf over HTTP/2 using generated code on both sides.

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: protoc then fails with “protoc-gen-go: program not found”. Add the Go bin folder to your PATH.
  • 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.New becomes codes.Unknown on the client. Use status.Errorf with a real code instead.
  • Editing generated files: your changes vanish on the next protoc run. Change the .proto file and regenerate.

Best Practices for Go gRPC

  • **Keep .proto files in one shared place**, because every client must use the same contract.
  • Use TLS outside your laptop, since insecure sends 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 Recap

  • Go gRPC calls functions on other services using a shared .proto contract.
  • protoc generates 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.Errorf and a code such as codes.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