gRPC Example: Building a Unary and Streaming Greeter Service

Updated 5 min read
RPC service schemas exchanging structured messages

gRPC example projects usually start with a Greeter service, and for good reason: it is small enough to understand at a glance yet covers the complete workflow. This guide builds on that classic example, adds a streaming method and shows how to test the result from the command line.

The server code uses Go for clarity, but the contract and concepts apply equally to Python, Java, Node.js and every other supported language.

Designing the Service Contract

Every gRPC project begins with a .proto file. It declares the package, the service and its methods, and the messages they exchange, giving both client and server a single shared definition.

syntax = "proto3";
package helloworld;
option go_package = "example.com/helloworld";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc SayHelloStream (HelloRequest) returns (stream HelloReply) {}
}

message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }

Field numbers identify each field in the binary encoding, so they must never change once a message is in use. New fields receive new numbers, which allows older clients and newer servers to keep working together.

Generating Code for Go

Go uses two protoc plugins: one for messages and one for service stubs. After installing them with go install, a single command generates both files into the package declared by go_package.

$ protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld.proto

The output includes a helloworld.pb.go file for messages and a helloworld_grpc.pb.go file containing the client interface, the server interface and registration helpers.

Implementing the Unary Method

A unary method receives one request and returns one reply. In Go, the server type embeds UnimplementedGreeterServer, which keeps the code compiling when new methods are added to the contract later.

The method itself is a normal function that receives a context and a request message. The context carries the deadline and cancellation signal from the client, so long-running work should check it and stop early when the caller has given up.

Adding a Server-Streaming Method

Streaming methods send several messages over one call. For SayHelloStream, the server receives a stream object and calls Send repeatedly, which suits progress updates, search results arriving in batches or live data feeds.

  • Server streaming: one request, many replies.
  • Client streaming: many requests, one reply, such as uploading chunks of a file.
  • Bidirectional streaming: both sides send messages freely, as in chat or collaborative editing.

Each streaming style uses the same contract syntax with the stream keyword placed on the request, the reply or both. The generated code then offers methods appropriate to that direction.

Starting the Server

The server listens on a TCP port, registers the service and serves requests. Registering the reflection service as well allows tools to discover methods without needing the .proto file locally.

lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
reflection.Register(s)
s.Serve(lis)

Production code should handle the error from net.Listen, configure TLS and stop gracefully on shutdown signals. The shortened version keeps attention on the gRPC-specific steps.

Testing the Example With grpcurl

grpcurl behaves like curl for gRPC services. With reflection enabled, it lists services, describes methods and sends requests written as JSON, converting them to Protocol Buffers automatically.

Command purposeExample
List servicesgrpcurl -plaintext localhost:50051 list
Describe a methodgrpcurl -plaintext localhost:50051 describe helloworld.Greeter
Call a methodgrpcurl -plaintext -d '{"name":"Ada"}' localhost:50051 helloworld.Greeter/SayHello

The streaming method returns each reply as a separate JSON object, which makes it easy to confirm the order and number of messages the server sends.

Extending the Example

Once the basic flow works, several features turn it into a realistic service. Each can be added gradually without changing the existing contract.

  • Deadlines on every client call.
  • Interceptors for logging and metrics.
  • The standard health-checking service for load balancers.
  • TLS certificates for encrypted connections.

Add these features one at a time and repeat the grpcurl checks after each change. Small, verified steps make it obvious which change introduced a problem if something stops working.

Writing a Matching Client in Go

The generated client interface mirrors the service. A client dials the server, creates a GreeterClient and calls SayHello with a context that carries a deadline, receiving a typed reply or an error with a status code.

For the streaming method, the client receives a stream object and calls Recv in a loop until it returns io.EOF. Each received message is a complete HelloReply, so processing can begin before the server has finished sending everything.

Organizing the Project

Keeping contracts in a dedicated directory makes them easy to share. Many teams store .proto files in a separate repository or module, so that several services can generate code from the same source of truth.

DirectoryContents
protoService and message definitions
genGenerated code, rebuilt from the contracts
serverService implementation and start-up code
clientExample or production client code

Common Mistakes in First Examples

A few problems appear repeatedly in first projects. Most are quick to fix once recognized, and catching them early avoids confusing errors later.

  • Changing field numbers after messages are already in use.
  • Forgetting to register the service with the server.
  • Omitting deadlines on client calls.
  • Mixing generated code from different compiler versions.

Adding Error Handling to the Example

Real services return meaningful errors rather than generic failures. In Go, the status package creates errors with a specific code and message, such as codes.InvalidArgument when the request name is empty.

Clients can inspect that code and react appropriately. Validation errors should be shown to the caller, whereas UNAVAILABLE errors may justify an automatic retry with backoff.

Frequently Asked Questions

Can I write the client in a different language?

Yes. Generate client code from the same .proto file in any supported language, and it will communicate with the Go server without changes.

Is reflection safe to enable in production?

Reflection reveals service definitions, so many teams enable it only in development or restrict it with authentication in production.

Where can I find more official examples?

The main grpc/grpc repository and each language repository contain an examples directory with runnable programs, including routing and streaming samples.

Conclusion

gRPC example services like this Greeter demonstrate the entire development loop: define the contract, generate code, implement methods, start the server and test calls. Adding a streaming method shows how naturally the framework handles continuous data.

Use this pattern as a template for real services, then layer on deadlines, TLS, health checks and interceptors. Starting small and extending gradually keeps each step understandable and easy to debug.