Google Cloud Run Service With gRPC Using Spring Boot

Ramesh Lingappan
Mar 31, 2020 · 6 min read
Cloud Run + gRPC + Spring Boot

Welcome to another article on Google Cloud Platform. If you are building services using GCP then you might already know the several limitations that come with it. One of them being a lack of support for gRPC in their easy to use solutions such as Google AppEngine (Standard and Flexible), Cloud Functions or in the initial days of Cloud Run.

So if we need to support or have our own gRPC services then we need to use either Google Compute Engine or Google Kubernetes Engine, which is not an easy solution for several small use cases.

If you are new to gRPC, then I highly recommend giving a readout, https://grpc.io. In short,

gRPC is a modern open source high performance RPC framework that can run in any environment, efficiently connecting distributed services.

gRPC communication

gRPC offers several benefits over HTTP APIs with JSON, some of them are,

  • Strong Contract-based communication
  • uses improved HTTP/2 protocol
  • Protobuf (efficient binary message format)
  • Great support for code generation on several languages

So gRPC is a great fit for communication between microservices.

gRPC support in Cloud Run

Google Cloud Run — Image from Internet

Yes now you can use gRPC in Cloud Run which supports Unary RPCs since cloud run natively handles HTTP/2, the gRPC’s transport is well-supported, and they are working to add support for Streaming RPCs.

Unary RPCs — where the client sends a single request to the server and gets a single response back, just like a normal function call.

  • It has a limitation on payload size which should be under 32MB, but I think it's for the better.
  • Cloud Run proxy also provides a TLS-encrypted layer that handles all the messy work of setting up certificates. The traffic from the proxy to the container with our gRPC server goes through an encrypted tunnel, so we don’t have to worry about handling it ourselves.

gRPC Server using Spring Boot

Let's build a simple service using spring boot & gRPC and deploy it to Google Cloud Run. The complete code sample is available on GitHub,

project setup

One of the nice features of gRPC service is that it requires a strict type-safe contract definition, so both server & client can communicate using that. For this, gRPC widely uses Protobuf as its messaging format.

Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data. Protobuf serializes very quickly on the server and client, thus resulting in smaller message payload.

Java-to-Java communication time — Image From Auth0

This is similar to the OpenAPI specification for the REST APIs. If you like to read more about this, check out End to End Restful API development using OpenAPI Specification.

Here is a sample Greeting ProtoBuf definition greeting.protowhich we will be using in this example,

Protobuf definition

It contains one service definition GreetingService.Greet (consider this as method or function), which takes one argument of type GreetingRequest and returns a response of type GreetingResponse .

With the proto file defined, we can able to generate both server & client code in several languages. Let's see how we can generate server-side code in java, for this, we are using protobuf-gradle-plugin.

In build.gradle, include the following code,

build.gradle file

In the protobuf section, we are configuring the grpc plugin to generate the code under $projectDir/gen folder, which will be added as sourceSet. Now running the following Gradle task will generate java code under the gen folder,

./gradlew generateProto

For our protobuf service definition, it would have created a java class something like this,

@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.4.0)",
comments = "Source: greeting.proto")
public final class GreetingServiceGrpc {
/**
* <pre>
* The greeting service definition.
* </pre>
*/
public static abstract class GreetingServiceImplBase implements io.grpc.BindableService {
......
}

....
}

For the server-side, we are using spring-boot starter project and to quickly configure the gRPC server we are using LogNet grpc-spring-boot-starter library (pretty much no other configuration is required for this library expect PORT).

For our example, the GreetingService.Greet definition create an abstract class called GreetingServiceImplBase, we just need to extend this class and override the method with our custom logic,

Implementing gRPC service contract

It is important to mark the implementation class with @GRpcService annotation, this will register the service implementation in the gRPC server during startup. Now we can start the server using ./gradlew bootRun command, you should see the gRPC server is running and listening on port 8081,

Also, you can see GreetingServiceImpl is registered successfully.

With the same greeting.proto file definition, we can able to create client stub in several languages. Now that we have a gRPC server running, let's see if we can able to send a request and get a response. But for this, we are not going to create another client project. Instead, for the sake of simplicity, we are going to use a nice gRPC GUI Client called bloomRPC. Since protobuf is a binary protocol, a tool like this helps us to visualize request & response,

bloomRPC — request & response

You can add the proto file, select the desired gRPC service and send a request in the form of JSON and also view the response in JSON format (but the underlying message format is still Protobuf).

Deploying service to Cloud Run

In order to deploy our service to the Cloud Run, we need to do two things,

  • Build a docker image and upload to Container Registry (using Cloud Build)
  • Use the docker image to create a new Cloud Run Service (gcloud run deploy)

Below is the Dockerfile configuration, we are using the multi-stage build setup to generate the jar and then build the docker image, all in the cloud build so that we dont have to download those heavy images in local,

Dockerfile

Also, I have made a small Makefile script which has two functions,

build — which generates the docker image and upload to a registry using cloud build,

deploy — which deploys the docker image to the cloud run service

here are the actual gcloud commands,

gcloud builds submit --tag gcr.io/$(GCP_PROJECT)/$(SERVICE_NAME):0.1 --project $(GCP_PROJECT)gcloud run deploy $(SERVICE_NAME) \
--image gcr.io/$(GCP_PROJECT)/$(SERVICE_NAME):0.1 \
--project $(GCP_PROJECT) \
--platform managed \
--allow-unauthenticated

Now you can simply run the following make command to build the image and deploy it,

make deploy GCP_PROJECT=demo-service SERVICE_NAME=greeting-service

Replace GCP_PROJECT & SERVICE_NAME with your gcloud project & desired cloud run service name.

That’s it, we now have a functional gRPC server hosted in scalable Cloud Run Service.

cloud run gRPC server demo

Conclusion

gRPC offers a lot of benefits over traditional APIs over HTTP and its a great fit for microservices providing fast & efficient communications. With gRPC support on Cloud Run, its lot easier to spinup microservices capable of handling gRPC calls. Go ahead give it a try!

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Ramesh Lingappan

Written by

Senior Software Engineer @payconiq | rameshl.com

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Ramesh Lingappan

Written by

Senior Software Engineer @payconiq | rameshl.com

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store