Skip to Content
Course content

157: Building gRPC Services with ScalaPB

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was on a team managing a complex set of microservices for a logistics platform. We were using REST and JSON for everything. It worked fine until we hit a scale where we had twenty different services talking to each other. One Tuesday afternoon, a junior dev changed a field name in the "Shipping" service from delivery_date to estimated_arrival. They updated the producer and their own tests, but they missed three downstream consumers. The result? A cascade of 500 errors across the dashboard that took us four hours to track down. That's the "JSON tax"—you're essentially guessing that the other side of the wire is sending what you think they are.

That's why we use gRPC. Instead of hoping the JSON matches, we define a strict contract. If the contract changes, the code simply won't compile on the client or server side until it's fixed. In the Scala ecosystem, ScalaPB is the gold standard for this. It takes a .proto file and generates idiomatic Scala code, turning what would be a runtime nightmare into a compile-time certainty.

Defining the Contract with Protocol Buffers

With gRPC, we start with the .proto file. You aren't writing implementation logic here; you're designing the API surface. Let's imagine we're building an InventoryService for a warehouse. We need to check if an item is in stock and reserve it.

syntax = "proto3";

option java_package = "com.warehouse.inventory";

service InventoryService {
  rpc GetStock(StockRequest) returns (StockResponse);
  rpc ReserveItem(ReserveRequest) returns (ReserveResponse);
}

message StockRequest {
  string sku = 1;
}

message StockResponse {
  int32 quantity = 1;
  bool is_available = 2;
}

message ReserveRequest {
  string sku = 1;
  int32 amount = 2;
}

message ReserveResponse {
  bool success = 1;
  string reservation_id = 2;
}

Notice those numbers like = 1 and = 2. Those aren't values; they are field tags. gRPC uses these tags to identify fields in the binary format, which is why it's so much faster and smaller than JSON. One tip: never change these numbers once you've deployed to production, or you'll break backward compatibility for any client still using the old version.

Generating Scala Code and Implementing Logic

Once you've added the ScalaPB plugin to your plugins.sbt and configured the dependencies, running sbt compile does the heavy lifting. ScalaPB reads that .proto file and generates a trait. You don't have to worry about the binary serialization or the HTTP/2 framing; you just implement the trait.

I usually find that the most intuitive way to handle the service logic is to keep the gRPC layer thin and delegate the actual work to a separate domain service. Here is how you'd implement the InventoryService server:

import io.grpc.ServerBuilder
import com.warehouse.inventory.{InventoryServiceServer, StockRequest, StockResponse, ReserveRequest, ReserveResponse}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class InventoryServiceImpl extends InventoryServiceServer {
  // In a real app, this would be a database repository
  private val stockDb = Map("SKU-123" -> 10, "SKU-456" -> 0)

  override def getStock(request: StockRequest): Future[StockResponse] = {
    val qty = stockDb.getOrElse(request.sku, 0)
    Future.successful(StockResponse(quantity = qty, isAvailable = qty > 0))
  }

  override def reserveItem(request: ReserveRequest): Future[ReserveResponse] = {
    val currentStock = stockDb.getOrElse(request.sku, 0)
    if (currentStock >= request.amount) {
      Future.successful(ReserveResponse(success = true, reservationId = java.util.UUID.randomUUID().toString))
    } else {
      Future.successful(ReserveResponse(success = false, reservationId = ""))
    }
  }
}

Bootstrapping the gRPC Server

Now that the logic is implemented, we need to actually bind this to a port. The ServerBuilder from the gRPC library handles the networking. I've seen people try to wrap this in a complex framework, but for most use cases, a simple main method is all you need to get a service off the ground.

object InventoryServer extends App {
  val port = 50051
  val server = ServerBuilder
    .forPort(port)
    .addService(new InventoryServiceImpl())
    .build()

  println(s"Inventory Service starting on port $port...")
  server.start()
  
  // Keep the main thread alive
  sys.addShutdownHook {
    println("Shutting down gRPC server...")
    server.shutdown()
  }
  
  server.awaitTermination()
}

One thing to keep in mind: gRPC uses HTTP/2. This means if you're putting this behind a load balancer or a proxy (like Nginx), you have to ensure that your proxy is configured for HTTP/2 (h2c) or you'll see some very confusing connection reset errors. I've spent a whole afternoon debugging a "network issue" only to realize my proxy was trying to downgrade the connection to HTTP/1.1.




📋 Practical Task

Implementing a Price Quote Service with ScalaPB

You are tasked with building a PriceQuoteService for a financial application. The service must allow clients to request a quote for a specific currency pair (e.g., "EUR/USD") and provide a quoted price and a timestamp of when the quote was generated.

Requirements:

  • Create a .proto file defining a PriceQuoteService with a single RPC method: GetQuote.
  • The QuoteRequest should take a symbol (string).
  • The QuoteResponse should return a price (double) and a timestamp (int64).
  • Implement the generated Scala trait. For the logic, use a hardcoded Map to simulate a price feed (e.g., "EUR/USD" -> 1.08). If the symbol is not found, return a price of 0.0.
  • Write the main method to start the server on port 50052.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.