-
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
109: Building a REST API with Akka HTTP and Cats Effect
A few years ago, I was reviewing a service for a colleague who had built a high-throughput order processing API. On paper, it looked great, but in staging, the whole thing would occasionally just... freeze. He had a few slow downstream database calls, and because he was using a standard blocking approach, those slow calls were eating up every single thread in the pool. One lagging query in the warehouse database triggered a cascading failure that took down the entire API. He was staring at a wall of TimeoutExceptions and didn't know why, because the CPU usage was nearly zero. He had thread starvation.
This is exactly why we combine Akka HTTP with Cats Effect. Akka HTTP gives us a powerful, battle-tested routing DSL to handle the "edge" of our application, while Cats Effect gives us the tools to manage concurrency, side effects, and resource safety without locking up our threads. The trick is knowing how to bridge the two, since Akka HTTP is built around Scala's Future, whereas we want to live in the world of IO.
Taming the Future with IO Bridges
When you define a route in Akka HTTP, the complete directive expects a Future. However, if your business logic is wrapped in IO, you can't just pass it in. You need a bridge. I usually handle this by creating a small utility or calling unsafeToFuture() at the very edge of the route.
Let's look at a real example: a simple Inventory API. Instead of putting logic in the route, we'll delegate to a service that returns an IO. This keeps our business logic pure and testable, while the route remains a thin orchestration layer.
import akka.http.scaladsl.server.Directives._
import cats.effect.IO
import cats.effect.unsafe.implicits.global
import scala.concurrent.ExecutionContext.Implicits.global
case class InventoryItem(id: String, quantity: Int)
class InventoryService {
// In a real app, this would hit a DB
def getStock(id: String): IO[InventoryItem] = IO {
println(s"Fetching stock for $id")
InventoryItem(id, 42)
}
}
val inventoryService = new InventoryService
val route =
path("inventory" / Segment) { itemId =>
get {
// We bridge IO to Future here at the edge
val result = inventoryService.getStock(itemId).unsafeToFuture()
complete(result)
}
}
I want to be clear: calling unsafeToFuture() feels like "cheating" the purity of Cats Effect, but that's precisely where it belongs. The routing layer is the "end of the world"—it's where the abstract description of your program finally meets the real world of HTTP requests and responses.
Managing Shared State with Ref
In a REST API, you often need to track something in memory—like a cache or a request counter—without introducing the nightmare of synchronized blocks or volatile variables. Since we're using Cats Effect, we can use Ref. A Ref is essentially a purely functional atomic reference.
If we want our Inventory API to track how many times the stock has been checked across all concurrent requests, we can't just use a var. That would be a recipe for race conditions. Instead, we inject a Ref into our service. Notice how the service method now returns an IO that describes both the fetch and the counter increment.
import cats.effect.Ref
class InventoryService(counter: Ref[IO, Int]) {
def getStock(id: String): IO[InventoryItem] = for {
_ <- counter.update(_ + 1) // Atomically increment
count <- counter.get
item = InventoryItem(id, 42)
_ <- IO.println(s"Stock check #$count for item $id")
} yield item
}
// In your main app setup:
// Ref.unsafeMake([0]).unsafeRunSync() would be used to initialize this
By wrapping the state in Ref, we ensure that no matter how many thousands of requests Akka HTTP throws at us concurrently, our counter remains accurate and we never block a thread. We've moved from the "stop-the-world" locking of traditional Java/Scala to a non-blocking, optimistic concurrency model.
📋 Practical Task
Exercise: Implementing a Concurrent Warehouse Reservation System
You need to extend the Inventory API to support "reservations." Instead of just checking stock, the API must allow a user to reserve an item, which decrements the available quantity.
Requirements:
- Create a
WarehouseStatecase class that holds aMap[String, Int]representing item IDs and their current stock levels. - Initialize a
Ref[IO, WarehouseState]with some starting data (e.g.,"laptop" -> 10, "mouse" -> 50). - Implement a
reserveItem(id: String): IO[Either[String, Int]]method in your service.- If the item exists and quantity > 0, decrement the stock and return
Right(newQuantity). - If the item is out of stock or doesn't exist, return
Left("Out of stock").
- If the item exists and quantity > 0, decrement the stock and return
- Add a new route:
POST /reserve/{id}. This route should call the reservation logic and return a200 OKwith the remaining stock on success, or a400 Bad Requestwith the error message on failure. - Ensure the entire chain from the route to the
Refupdate is bridged correctly usingunsafeToFuture().
There are no comments for now.