DEV Community

Alex Spinov
Alex Spinov

Posted on

gRPC Has a Free API: High-Performance RPC Framework by Google

gRPC is a modern, high-performance RPC framework that uses Protocol Buffers and HTTP/2. It enables efficient communication between microservices with features like streaming, load balancing, and automatic code generation.

What Is gRPC?

gRPC (gRPC Remote Procedure Calls) is a CNCF incubating project originally developed by Google. It uses Protocol Buffers for serialization (10x smaller than JSON) and HTTP/2 for transport (multiplexing, header compression).

Key Features:

  • Protocol Buffers (protobuf) serialization
  • HTTP/2 transport (multiplexing, streaming)
  • Bidirectional streaming
  • Code generation for 11+ languages
  • Built-in authentication (TLS, token)
  • Load balancing
  • Deadline/timeout propagation
  • Interceptors (middleware)

Define Your Service

// order.proto
syntax = "proto3";

package order;

service OrderService {
  rpc CreateOrder (CreateOrderRequest) returns (Order);
  rpc GetOrder (GetOrderRequest) returns (Order);
  rpc ListOrders (ListOrdersRequest) returns (stream Order);
  rpc StreamUpdates (stream OrderUpdate) returns (stream OrderStatus);
}

message Order {
  string id = 1;
  string customer_email = 2;
  double total = 3;
  string status = 4;
  int64 created_at = 5;
}

message CreateOrderRequest {
  string customer_email = 1;
  repeated OrderItem items = 2;
}

message OrderItem {
  string product_id = 1;
  int32 quantity = 2;
  double price = 3;
}

message GetOrderRequest {
  string id = 1;
}

message ListOrdersRequest {
  string customer_email = 1;
  int32 limit = 2;
}

message OrderUpdate {
  string order_id = 1;
  string new_status = 2;
}

message OrderStatus {
  string order_id = 1;
  string status = 2;
  string updated_at = 3;
}
Enter fullscreen mode Exit fullscreen mode

Python Server

import grpc
from concurrent import futures
import order_pb2
import order_pb2_grpc

class OrderServicer(order_pb2_grpc.OrderServiceServicer):
    def __init__(self):
        self.orders = {}

    def CreateOrder(self, request, context):
        order_id = f"ORD-{len(self.orders)+1}"
        total = sum(item.price * item.quantity for item in request.items)
        order = order_pb2.Order(
            id=order_id,
            customer_email=request.customer_email,
            total=total,
            status="pending"
        )
        self.orders[order_id] = order
        return order

    def GetOrder(self, request, context):
        if request.id in self.orders:
            return self.orders[request.id]
        context.abort(grpc.StatusCode.NOT_FOUND, "Order not found")

    def ListOrders(self, request, context):
        for order in self.orders.values():
            if order.customer_email == request.customer_email:
                yield order

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
order_pb2_grpc.add_OrderServiceServicer_to_server(OrderServicer(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
Enter fullscreen mode Exit fullscreen mode

Python Client

import grpc
import order_pb2
import order_pb2_grpc

channel = grpc.insecure_channel("localhost:50051")
stub = order_pb2_grpc.OrderServiceStub(channel)

# Create order
order = stub.CreateOrder(order_pb2.CreateOrderRequest(
    customer_email="alice@example.com",
    items=[
        order_pb2.OrderItem(product_id="PROD-1", quantity=2, price=29.99),
        order_pb2.OrderItem(product_id="PROD-2", quantity=1, price=49.99)
    ]
))
print(f"Created: {order.id}, Total: ${order.total}")

# Get order
result = stub.GetOrder(order_pb2.GetOrderRequest(id=order.id))
print(f"Order {result.id}: {result.status}")

# Stream orders
for order in stub.ListOrders(order_pb2.ListOrdersRequest(
    customer_email="alice@example.com", limit=10
)):
    print(f"Order: {order.id} - ${order.total}")
Enter fullscreen mode Exit fullscreen mode

gRPC vs REST

Feature gRPC REST
Protocol HTTP/2 HTTP/1.1
Payload Protobuf (binary) JSON (text)
Streaming Bidirectional SSE/WebSocket
Code gen Automatic Manual/OpenAPI
Size ~10x smaller Baseline
Speed ~7x faster Baseline
Browser grpc-web needed Native

Resources


Need to scrape web data for your microservices? Check out my web scraping tools on Apify — production-ready actors for Reddit, Google Maps, and more. Questions? Email me at spinov001@gmail.com

Top comments (0)