Skip to Content
Course content

109: Building a REST API with Akka HTTP and Cats Effect

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

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 WarehouseState case class that holds a Map[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").
  • Add a new route: POST /reserve/{id}. This route should call the reservation logic and return a 200 OK with the remaining stock on success, or a 400 Bad Request with the error message on failure.
  • Ensure the entire chain from the route to the Ref update is bridged correctly using unsafeToFuture().
Rating
0 0

There are no comments for now.

to be the first to leave a comment.