The gRPC Engineer designs and implements gRPC services using Protocol Buffers. gRPC outperforms REST for internal microservice communication: binary encoding, HTTP/2 multiplexing, and generated type-safe clients eliminate entire categories of integration bugs. Use gRPC for service-to-service; keep REST or GraphQL for public APIs and browser clients.
Proto Schema Design
// user_service.proto
syntax = "proto3";
package userservice.v1;
service UserService {
// Unary RPC - request/response
rpc GetUser(GetUserRequest) returns (GetUserResponse);
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
// Server streaming - one request, stream of responses
rpc WatchUserActivity(WatchRequest) returns (stream ActivityEvent);
// Bidirectional streaming - for real-time collaboration
rpc Collaborate(stream CollabMessage) returns (stream CollabMessage);
}
message GetUserRequest {
string user_id = 1; // Field number 1 - never reuse or remove numbers
}
message GetUserResponse {
User user = 1;
}
message User {
string id = 1;
string email = 2;
string name = 3;
int64 created_at_unix = 4; // Use unix timestamps, not strings
UserRole role = 5;
}
enum UserRole {
USER_ROLE_UNSPECIFIED = 0; // Proto3: first value must be 0
USER_ROLE_ADMIN = 1;
USER_ROLE_USER = 2;
}
Node.js Server Implementation
import { Server, ServerCredentials } from '@grpc/grpc-js';
import { UserServiceService } from './generated/user_service_grpc_pb';
const server = new Server();
server.addService(UserServiceService, {
async getUser(call, callback) {
const { userId } = call.request.toObject();
const user = await db.users.findById(userId);
if (!user) {
return callback({
code: Status.NOT_FOUND,
message: `User ${userId} not found`,
});
}
const response = new GetUserResponse();
const userMsg = new UserMessage();
userMsg.setId(user.id);
userMsg.setEmail(user.email);
response.setUser(userMsg);
callback(null, response);
},
watchUserActivity(call) {
const { userId } = call.request.toObject();
const unsubscribe = activityStream.subscribe(userId, (event) => {
const msg = new ActivityEvent();
msg.setType(event.type);
call.write(msg);
});
call.on('cancelled', unsubscribe);
},
});
server.bindAsync('0.0.0.0:50051', ServerCredentials.createInsecure(), () => {
server.start();
console.log('gRPC server listening on :50051');
});
Error Handling
- Use gRPC status codes:
NOT_FOUND,PERMISSION_DENIED,INVALID_ARGUMENT,UNAUTHENTICATED,INTERNAL - Never return
INTERNALwith sensitive details - log the full error server-side, return a generic message to callers - Use
google.rpc.Statuswith error details for structured validation errors - Implement deadlines: every client call should set a deadline (
deadline: Date.now() + 5000) to prevent cascading hangs