Backend Actor logic

In this example, the backend only uses one basic actor. In a real system, we would have many actors interacting with each other and perhaps, multiple data stores and microservices.

An interesting side-note to add here is perhaps about when using actors in applications like this adds value over just providing functions that would return Futures. In fact, if your logic is stateless and very simple request/reply style, you may not need to back it with an Actor. actors do shine however when you need to keep some form of state and allow various requests to access something in (or through) an Actor. The other stellar feature of actors, that futures would not handle, is scaling-out onto a cluster very easily, by using Cluster Sharding or other location-transparent techniques.

However, the focus of this tutorial is on how to interact with an Actor backend from within Akka HTTP – not on the actor itself, so we’ll keep it very simple.

The sample code in the UserRegistryActor is very simple. It keeps registered users in a Set. Once it receives messages it matches them to the defined cases to determine which action to take:

import{ Actor, ActorLogging, Props }

final case class User(name: String, age: Int, countryOfResidence: String)
final case class Users(users: Seq[User])

object UserRegistryActor {
  final case class ActionPerformed(description: String)
  final case object GetUsers
  final case class CreateUser(user: User)
  final case class GetUser(name: String)
  final case class DeleteUser(name: String)

  def props: Props = Props[UserRegistryActor]

class UserRegistryActor extends Actor with ActorLogging {
  import UserRegistryActor._

  var users = Set.empty[User]

  def receive: Receive = {
    case GetUsers =>
      sender() ! Users(users.toSeq)
    case CreateUser(user) =>
      users += user
      sender() ! ActionPerformed(s"User \${} created.")
    case GetUser(name) =>
      sender() ! users.find( == name)
    case DeleteUser(name) =>
      users.find( == name) foreach { user => users -= user }
      sender() ! ActionPerformed(s"User \${name} deleted.")

If you feel you need to brush up on your Akka Actor knowledge, the Getting Started Guide reviews actor concepts in the context of a simple Internet of Things (IoT) example.