Golang / GoLang Production Patterns and Web Standards Interview Questions
How does gRPC work in Go and when would you choose it over REST/JSON?
gRPC is a high-performance RPC framework using Protocol Buffers (binary serialisation) over HTTP/2. Go has first-class gRPC support through google.golang.org/grpc. It is the standard for inter-service communication in Go microservices.
// user.proto defines the service contract // service UserService { // rpc GetUser(GetUserRequest) returns (User); // rpc StreamUsers(Empty) returns (stream User); // } // Generated Go code Γ’ΒΒ implement the server interface type userServiceServer struct { pb.UnimplementedUserServiceServer // embed for forward compatibility repo UserRepository } func (s *userServiceServer) GetUser( ctx context.Context, req *pb.GetUserRequest,
) (*pb.User, error) { user, err := s.repo.FindByID(ctx, int(req.Id)) if err != nil { if errors.Is(err, ErrNotFound) { return nil, status.Errorf(codes.NotFound, "user %d not found", req.Id) } return nil, status.Errorf(codes.Internal, "internal error: %v", err) } return &pb.User{Id: int64(user.ID), Name: user.Name, Email: user.Email}, nil } // Start gRPC server func main() { lis, err := net.Listen("tcp", ":9090") if err != nil { log.Fatal(err) } grpcServer := grpc.NewServer( grpc.ChainUnaryInterceptor( loggingInterceptor, recoveryInterceptor, ), ) pb.RegisterUserServiceServer(grpcServer, &userServiceServer{repo: repo}) grpcServer.Serve(lis) }
| Aspect | REST/JSON | gRPC/Protobuf |
|---|---|---|
| Serialisation | JSON (text, ~30 bytes/field) | Protobuf (binary, ~3 bytes/field) |
| Browser support | Native | Requires grpc-web proxy |
| Code generation | Optional | Required (protoc) |
| Streaming | SSE or WebSocket workarounds | Built-in bidirectional streaming |
| Best for | Public APIs, browser clients | Internal service-to-service RPC |
More Related questions...