Getting Started with RPC Using gRPC
A beginner's guide to Remote Procedure Call (RPC) using gRPC. In this tutorial, we will cover the basics of gRPC and how to create a simple client-server application using gRPC for seamless microservice communication.
Originally published on June 15, 2024 on my previous blog.
In this blog post, we will learn about gRPC and how it can be used in microservices architecture. I will explain what gRPC is, how it works, and why it is a good choice for building microservices. We will also look at some examples of using gRPC in node.js and how to get started with gRPC in your own projects.
What is gRPC?
gRPC is a high-performance, open-source RPC (Remote Procedure Call) framework developed by Google. It is based on the HTTP/2 protocol and uses Protocol Buffers as the interface definition language. gRPC allows you to define services and message types using Protocol Buffers and automatically generates client and server code in multiple languages.Source
How does gRPC work?
gRPC works by defining services and message types using Protocol Buffers. You define a service in a .proto file, which contains the service definition and message types. gRPC uses Protocol Buffers to define the structure of the messages that are sent and received between the client and server. The gRPC compiler generates client and server code in multiple languages based on the .proto file. The client and server communicate over HTTP/2, which provides features such as multiplexing, flow control, and header compression.
Why use gRPC for microservices?
gRPC is a good choice for building microservices for several reasons:
- Performance: gRPC is built on top of HTTP/2, which provides features such as multiplexing, flow control, and header compression. This makes gRPC faster and more efficient than traditional REST APIs.
- Interoperability: gRPC supports multiple languages and platforms, making it easy to build microservices in different languages and have them communicate with each other.
- Code Generation: gRPC uses Protocol Buffers to define services and message types, which allows you to generate client and server code in multiple languages. This reduces the amount of boilerplate code you need to write.
- Streaming: gRPC supports streaming, which allows you to send and receive multiple messages in a single call. This is useful for building real-time applications.
- Error Handling: gRPC provides rich error handling features, such as status codes and metadata, which makes it easier to handle errors in your microservices.
When not to use gRPC?
While gRPC is a good choice for building microservices, there are some cases where it may not be the best option:
- Simple APIs: If you are building simple APIs that do not require high performance or streaming capabilities, gRPC may be overkill. In such cases, a traditional REST API may be a better choice.
- Legacy Systems: If you need to integrate with legacy systems that do not support gRPC, you may need to use a different communication protocol.
- Complexity: gRPC can be more complex to set up and use compared to traditional REST APIs. If you are not familiar with gRPC or Protocol Buffers, there may be a learning curve involved.
Getting started with gRPC in node.js
To get started with gRPC in node.js, you need to create the project and install the grpc packages:
yarn init -y
yarn add @grpc/grpc-js @grpc/proto-loader
Next, you need to define the service and message types in a .proto file. Here is an example of a simple service definition:
syntax = "proto3";
package example;
service ExampleService {
rpc UnaryCall (Request) returns (Response);
rpc StreamCall (stream Request) returns (stream Response);
}
message Request {
string message = 1;
}
message Response {
string message = 1;
}
Now we will write the server code in node.js:
const grpc = require('@grpc/grpc-js')
const protoLoader = require('@grpc/proto-loader')
const PROTO_PATH = __dirname + '/../service.proto'
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {})
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition)
const server = new grpc.Server()
server.addService(protoDescriptor.example.ExampleService.service, {
UnaryCall: (call, callback) => {
console.log('UnaryCall:', call.request.message)
callback(null, { message: 'Hello from gRPC Server' })
},
StreamCall: (call) => {
call.on('data', (request) => {
console.log('StreamCall:', request.message)
call.write({ message: 'Hello from gRPC Server' })
})
call.on('end', () => {
call.end()
})
},
})
server.bindAsync('localhost:50055', grpc.ServerCredentials.createInsecure(), (error, port) => {
if (error) {
console.error(error)
} else {
console.log(`gRPC Server started on port ${port}`)
}
})
Finally, we will write the client code in node.js:
const grpc = require('@grpc/grpc-js')
const protoLoader = require('@grpc/proto-loader')
const PROTO_PATH = __dirname + '/../service.proto'
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {})
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition).example
const client = new protoDescriptor.ExampleService('localhost:50055', grpc.credentials.createInsecure())
// Unary Call
const unaryCall = () => {
client.UnaryCall({ message: 'Hello from Node.js' }, (error, response) => {
if (error) {
console.error(error)
} else {
console.log('Unary Response:', response.message)
}
})
}
// Stream Call
const streamCall = () => {
const call = client.StreamCall()
call.on('data', (response) => {
console.log('Stream Response:', response.message)
})
call.on('end', () => {
console.log('Stream Ended')
})
call.write({ message: 'Hello from Node.js' })
call.write({ message: 'Hello again from Node.js' })
call.end()
}
unaryCall()
streamCall()
To run the server and client code, you can use the following commands:
node server.js
node client.js
This will start the gRPC server on port 50055 and make unary and stream calls to the server from the client.
Conclusion
gRPC is a high-performance RPC framework that is well-suited for building microservices. It provides features such as performance, interoperability, code generation, streaming, and error handling, which make it a good choice for building microservices. By using gRPC, you can build efficient and scalable microservices that communicate with each other seamlessly. I hope this article has given you a good introduction to gRPC and how to get started with it in node.js.
Comments
Join the discussionNo comments yet. Be the first to comment.