Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
157: Building gRPC Services with ScalaPB
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
.protofile defining aPriceQuoteServicewith a single RPC method:GetQuote. - The
QuoteRequestshould take asymbol(string). - The
QuoteResponseshould return aprice(double) and atimestamp(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 of0.0. - Write the
mainmethod to start the server on port50052.
There are no comments for now.