Sobes.tech
Senior

Tell me about gRPC: how it works, what are its advantages over REST?

sobes.tech AI

Answer from AI

gRPC is a modern framework for remote procedure calls (RPC) developed by Google. It uses HTTP/2 for transport, Protocol Buffers (protobuf) for data serialization, and supports bidirectional streaming.

How it works:

  • The client calls methods defined in the protobuf file as if they were local.
  • The request is serialized into a compact binary format using protobuf and sent over HTTP/2.
  • The server deserializes the request, executes the logic, and returns a response in protobuf.

Advantages over REST:

  • Performance: Binary protocol and HTTP/2 provide lower latency and smaller message sizes.
  • Strong typing: Protobuf describes the API contract, reducing errors and simplifying code generation.
  • Stream support: gRPC supports server, client, and bidirectional streams, unlike traditional REST.
  • Automatic code generation: For many languages, including Java, speeding up development.

Example of a simple gRPC service in Java:

// Service definition in protobuf
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// Service implementation
public class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}

Thus, gRPC is well-suited for microservice architectures where high performance and a clear contract between services are important.