Build an Application from Services and Layers
Welcome! In this tutorial we build a small signup application out of several services. We start with three services that depend on each other, and we end with an application that reads its settings from the environment, opens a database when it starts, closes it when it stops, and lets us choose how users are stored without changing the business code.
You should know basic Scala and have read Services and Layers. That page shows how to define one service, build it with ZLayer.apply and ZLayer.fromFunction, and supply it with ZIO#provide. We use those without explaining them again.
Learning Objectivesโ
By the end of this tutorial, you will understand:
- How services that depend on each other are built from layers
- When to build a layer with
ZLayer.deriveand when to useZLayer.fromFunction - How a layer loads its configuration with
ZIO.config - How
ZLayer.scopedopens a resource when the application starts and closes it when the application stops - How to read the compile error for a missing layer, and how
ZLayer.Debug.treeshows the layer graph - What shared and
freshlayers are, and how to choose an implementation of a service at start-up
We learn these through:
- Three Services That Depend on Each Other
- Building Layers with
ZLayer.derive - Loading Configuration
- Holding a Resource in a Layer
- Wiring the Application
- Shared and Fresh Layers
- Choosing an Implementation at Start-Up
- Putting It Together
We recommend reading from top to bottom. Each section builds on the one before.
Backgroundโ
In ZIO a program lists the services it needs in the R type parameter of ZIO[R, E, A], and a layer is a recipe that builds a service. A real application has many services, and they need each other: a signup service needs a place to store users and a way to send email, and that place may need a database connection. The layers describe who needs whom, and ZIO works out the order in which to build them.
This tutorial grows one application step by step. The application lets a person sign up with an email address and a name. It saves the user, and then sends a welcome email.
Setupโ
The code needs only ZIO core:
// ZIO core
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
Every snippet below assumes import zio._:
import zio._
1. Three Services That Depend on Each Otherโ
Our application has three services. A UserRepo stores users. A Notifier sends the welcome email. A SignupService is the business logic: it uses the other two. The first two are the building blocks, and the third depends on both:
final case class User(email: String, name: String)
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
The case classes that implement them follow the pattern from Services and Layers. The in-memory repository keeps its users in a Ref, so its layer creates the Ref first. The notifier prints the email to the console, so it needs nothing. The signup service takes its two dependencies as constructor parameters:
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final case class ConsoleNotifier() extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ULayer[Notifier] = ZLayer.succeed(ConsoleNotifier())
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier) extends SignupService {
def signUp(email: String, name: String): Task[User] = {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: URLayer[UserRepo & Notifier, SignupService] =
ZLayer.fromFunction(SignupServiceLive(_, _))
}
The type of SignupServiceLive.layer tells the whole story: it needs a UserRepo and a Notifier, and it builds a SignupService. The program at the end of the section signs up two users and counts them. We give provide the three layers in any order, and it works out that the repository and the notifier must be built before the signup service.
Run Step1Services. The output is:
[email] Welcome, Ada!
[email] Welcome, Grace!
Registered users: 2
package serviceslayers.step1
import zio._
final case class User(email: String, name: String)
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final case class ConsoleNotifier() extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ULayer[Notifier] = ZLayer.succeed(ConsoleNotifier())
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier) extends SignupService {
def signUp(email: String, name: String): Task[User] = {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: URLayer[UserRepo & Notifier, SignupService] =
ZLayer.fromFunction(SignupServiceLive(_, _))
}
object Step1Services extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace"))
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
InMemoryUserRepo.layer,
ConsoleNotifier.layer
)
}
2. Building Layers with ZLayer.deriveโ
ZLayer.fromFunction(SignupServiceLive(_, _)) repeats what the constructor already says. ZLayer.derive reads the primary constructor of a class and builds the layer for us. Each constructor parameter becomes a service that the layer requires:
object DerivedLayers {
val notifier: ULayer[Notifier] = ZLayer.derive[ConsoleNotifier]
val signup: URLayer[UserRepo & Notifier, SignupService] = ZLayer.derive[SignupServiceLive]
}
The first layer needs nothing, because ConsoleNotifier has no constructor parameters. The second needs a UserRepo and a Notifier, the same as the layer we wrote by hand. The layers have the type of the trait on the left, even though derive builds the class on the right.
ZLayer.derive works only for a class with a constructor. It does not compile for a trait or an abstract class. It also cannot create something that is not a service. If we try ZLayer.derive[InMemoryUserRepo], the layer requires a Ref[Map[String, User]] from the environment, because nothing in the constructor says how to make one. That is why InMemoryUserRepo.layer stays a ZLayer { ... } that creates the Ref.
A good rule: use ZLayer.derive when every constructor parameter is a service or a configuration, and use ZLayer.apply or ZLayer.fromFunction when the layer must do some work first, such as creating a Ref. In the rest of the tutorial, the layers use derive wherever they can.
Run Step2Derive. The output is the same as before, because only the way the layers are built has changed:
[email] Welcome, Ada!
[email] Welcome, Grace!
Registered users: 2
package serviceslayers.step2
import zio._
final case class User(email: String, name: String)
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final case class ConsoleNotifier() extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ULayer[Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier) extends SignupService {
def signUp(email: String, name: String): Task[User] = {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: URLayer[UserRepo & Notifier, SignupService] =
ZLayer.derive[SignupServiceLive]
}
object Step2Derive extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace"))
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
InMemoryUserRepo.layer,
ConsoleNotifier.layer
)
}
3. Loading Configurationโ
Real applications read settings, such as the address that emails come from. We describe the settings with a Config descriptor, and ZIO.config loads them from the current config provider. The default provider reads environment variables first, and system properties if the variable is not set.
Our SignupConfig has two settings. Each has a default, so the application also runs with nothing set:
final case class SignupConfig(maxNameLength: Int, sender: String)
object SignupConfig {
implicit val config: Config[SignupConfig] =
(Config.int("max-name-length").withDefault(20) zip
Config.string("sender").withDefault("welcome@example.com"))
.nested("signup")
.map { case (maxNameLength, sender) => SignupConfig(maxNameLength, sender) }
}
The code above:
Config.int("max-name-length")andConfig.string("sender")describe the two values, andwithDefaultsupplies a value when nothing is setzipcombines the two descriptors into one that reads bothnested("signup")puts both names undersignup, so the environment variables areSIGNUP_MAX_NAME_LENGTHandSIGNUP_SENDER. The environment provider writes names in upper case and replaces-with_
Because SignupConfig has an implicit Config in its companion, ZLayer.derive knows how to get one. A constructor parameter of type SignupConfig is not a requirement of the layer; the layer loads it with ZIO.config. So we change ConsoleNotifier and SignupServiceLive to take a SignupConfig, and their derived layers still need only the services:
final case class ConsoleNotifier(config: SignupConfig) extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email from ${config.sender}] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ZLayer[Any, Config.Error, Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier, config: SignupConfig) extends SignupService {
def signUp(email: String, name: String): Task[User] =
if (name.length > config.maxNameLength)
ZIO.fail(new IllegalArgumentException(s"Name '$name' is longer than ${config.maxNameLength} characters"))
else {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: ZLayer[UserRepo & Notifier, Config.Error, SignupService] =
ZLayer.derive[SignupServiceLive]
}
Loading a config can fail, so the error type of the layer is now Config.Error. The program in Step3Config signs up Ada with a short name and Grace with a long one. With no variables set, the defaults apply, and the second signup is refused:
[email from welcome@example.com] Welcome, Ada!
Signup failed: Name 'Grace Brewster Murray Hopper' is longer than 20 characters
Registered users: 1
Now set two environment variables and run it again, for example SIGNUP_MAX_NAME_LENGTH=5 SIGNUP_SENDER=team@zio.dev sbt "runMain serviceslayers.step3.Step3Config". The settings change and the code does not:
[email from team@zio.dev] Welcome, Ada!
Signup failed: Name 'Grace Brewster Murray Hopper' is longer than 5 characters
Registered users: 1
A default replaces only a value that is missing. If the variable is set to something that is not valid, such as SIGNUP_MAX_NAME_LENGTH=abc, the layer fails to build, and the program stops with a message that names the setting:
zio.Config$Error$Or: ((Invalid data at signup.max_name_length: Expected an integer value, but found abc) or (Missing data at signup.max-name-length: Expected signup.max-name-length to be set in properties))
The message has two parts because the default provider tried the environment first and the system properties second, and both failed.
package serviceslayers.step3
import zio._
final case class User(email: String, name: String)
final case class SignupConfig(maxNameLength: Int, sender: String)
object SignupConfig {
implicit val config: Config[SignupConfig] =
(Config.int("max-name-length").withDefault(20) zip
Config.string("sender").withDefault("welcome@example.com"))
.nested("signup")
.map { case (maxNameLength, sender) => SignupConfig(maxNameLength, sender) }
}
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final case class ConsoleNotifier(config: SignupConfig) extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email from ${config.sender}] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ZLayer[Any, Config.Error, Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier, config: SignupConfig) extends SignupService {
def signUp(email: String, name: String): Task[User] =
if (name.length > config.maxNameLength)
ZIO.fail(new IllegalArgumentException(s"Name '$name' is longer than ${config.maxNameLength} characters"))
else {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: ZLayer[UserRepo & Notifier, Config.Error, SignupService] =
ZLayer.derive[SignupServiceLive]
}
object Step3Config extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO
.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace Brewster Murray Hopper"))
.tapError(e => Console.printLine(s"Signup failed: ${e.getMessage}"))
.ignore
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
InMemoryUserRepo.layer,
ConsoleNotifier.layer
)
}
4. Holding a Resource in a Layerโ
A repository usually talks to a database, and a database connection must be opened before the application uses it and closed after the application is done. A layer built with ZLayer.scoped does exactly that. Its effect runs in a Scope: the resource opens when the layer is built, and its finalizer runs when the layer is released at the end of the program.
Our Database is a stand-in that prints a line when it opens and when it closes:
final class Database private (val users: Ref[Map[String, User]])
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie *>
Ref.make(Map.empty[String, User]).map(new Database(_))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class DatabaseUserRepo(db: Database) extends UserRepo {
def save(user: User): Task[Unit] = db.users.update(_ + (user.email -> user))
def count: Task[Int] = db.users.get.map(_.size)
}
object DatabaseUserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[DatabaseUserRepo]
}
The code above:
ZIO.acquireRelease(acquire)(release)opens the database and registers the release step. The release step cannot fail, which is why it ends withorDieZLayer.scopedturns that effect into a layer and ties the release step to the lifetime of the layerDatabaseUserRepois an ordinary service that needs aDatabase. The service that uses a resource does not know that the resource must be closed
In Step4Resource the program prints Program started first, so we can see when each thing happens:
Opening database
Program started
[email from welcome@example.com] Welcome, Ada!
Signup failed: Name 'Grace Brewster Murray Hopper' is longer than 20 characters
Registered users: 1
Closing database
The database opens before the program starts and closes after the program ends, even though no line of the program mentions it. If the program fails or is interrupted, the database still closes.
package serviceslayers.step4
import zio._
final case class User(email: String, name: String)
final case class SignupConfig(maxNameLength: Int, sender: String)
object SignupConfig {
implicit val config: Config[SignupConfig] =
(Config.int("max-name-length").withDefault(20) zip
Config.string("sender").withDefault("welcome@example.com"))
.nested("signup")
.map { case (maxNameLength, sender) => SignupConfig(maxNameLength, sender) }
}
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final class Database private (val users: Ref[Map[String, User]])
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie *>
Ref.make(Map.empty[String, User]).map(new Database(_))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class DatabaseUserRepo(db: Database) extends UserRepo {
def save(user: User): Task[Unit] = db.users.update(_ + (user.email -> user))
def count: Task[Int] = db.users.get.map(_.size)
}
object DatabaseUserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[DatabaseUserRepo]
}
final case class ConsoleNotifier(config: SignupConfig) extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email from ${config.sender}] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ZLayer[Any, Config.Error, Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier, config: SignupConfig) extends SignupService {
def signUp(email: String, name: String): Task[User] =
if (name.length > config.maxNameLength)
ZIO.fail(new IllegalArgumentException(s"Name '$name' is longer than ${config.maxNameLength} characters"))
else {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: ZLayer[UserRepo & Notifier, Config.Error, SignupService] =
ZLayer.derive[SignupServiceLive]
}
object Step4Resource extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- Console.printLine("Program started")
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO
.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace Brewster Murray Hopper"))
.tapError(e => Console.printLine(s"Signup failed: ${e.getMessage}"))
.ignore
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
DatabaseUserRepo.layer,
Database.layer,
ConsoleNotifier.layer
)
}
5. Wiring the Applicationโ
Now the application has four layers. We give all of them to provide, in any order, and the compiler checks the wiring:
object Wiring {
val program: ZIO[SignupService, Throwable, User] =
ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
val app: ZIO[Any, Throwable, User] =
program.provide(
SignupServiceLive.layer,
DatabaseUserRepo.layer,
Database.layer,
ConsoleNotifier.layer
)
}
What if we forget a layer? Take the provide call of Step5Wiring (shown at the end of this section) and leave out DatabaseUserRepo.layer. The call does not compile:
program.provide(
SignupServiceLive.layer,
Database.layer,
ConsoleNotifier.layer
)
The compiler reports:
โโโโ ZLAYER ERROR โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Please provide a layer for the following type:
1. serviceslayers.step5.UserRepo
Required by SignupServiceLive.layer
1. serviceslayers.step5.UserRepo
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The message names the missing service, UserRepo, and the layer that needs it. A layer that is missing in the middle of a big graph is found when we compile, not when we run.
When the graph is big, we can ask the compiler to draw it. Adding ZLayer.Debug.tree to the list of layers makes the compiler print the graph as a warning. It does not change the program:
object WiringWithTree {
val program: ZIO[SignupService, Throwable, User] =
ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
val app: ZIO[Any, Throwable, User] =
program.provide(
SignupServiceLive.layer,
DatabaseUserRepo.layer,
Database.layer,
ConsoleNotifier.layer,
ZLayer.Debug.tree
)
}
The warning for Step5Wiring shows each layer with the layers it needs below it. That program needs both a SignupService and a UserRepo, so the graph has two roots:
โ SignupServiceLive.layer
โโโ DatabaseUserRepo.layer
โ โฐโโ Database.layer
โฐโโ ConsoleNotifier.layer
โ DatabaseUserRepo.layer
โฐโโ Database.layer
ZLayer.Debug.mermaid prints the same tree and adds a link to a diagram. Step5Wiring is Step4Resource with ZLayer.Debug.tree added, so compile it to see the warning, and run it to see the same output as before.
package serviceslayers.step5
import zio._
final case class User(email: String, name: String)
final case class SignupConfig(maxNameLength: Int, sender: String)
object SignupConfig {
implicit val config: Config[SignupConfig] =
(Config.int("max-name-length").withDefault(20) zip
Config.string("sender").withDefault("welcome@example.com"))
.nested("signup")
.map { case (maxNameLength, sender) => SignupConfig(maxNameLength, sender) }
}
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final class Database private (val users: Ref[Map[String, User]])
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie *>
Ref.make(Map.empty[String, User]).map(new Database(_))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class DatabaseUserRepo(db: Database) extends UserRepo {
def save(user: User): Task[Unit] = db.users.update(_ + (user.email -> user))
def count: Task[Int] = db.users.get.map(_.size)
}
object DatabaseUserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[DatabaseUserRepo]
}
final case class ConsoleNotifier(config: SignupConfig) extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email from ${config.sender}] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ZLayer[Any, Config.Error, Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier, config: SignupConfig) extends SignupService {
def signUp(email: String, name: String): Task[User] =
if (name.length > config.maxNameLength)
ZIO.fail(new IllegalArgumentException(s"Name '$name' is longer than ${config.maxNameLength} characters"))
else {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: ZLayer[UserRepo & Notifier, Config.Error, SignupService] =
ZLayer.derive[SignupServiceLive]
}
object Step5Wiring extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- Console.printLine("Program started")
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO
.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace Brewster Murray Hopper"))
.tapError(e => Console.printLine(s"Signup failed: ${e.getMessage}"))
.ignore
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
DatabaseUserRepo.layer,
Database.layer,
ConsoleNotifier.layer,
ZLayer.Debug.tree
)
}
6. Shared and Fresh Layersโ
In Step4Resource the Database is used by one service. What happens when two services use it? By default, a layer is built once for the whole graph, and every service that needs it gets the same value. That is what we want for a database connection pool, which should be shared.
Step6SharedAndFresh adds an AuditLog that also needs a Database, and builds two graphs with >>> (feed the layer on the left into the layer on the right) and ++ (build both in parallel). In the first graph, both services use Database.layer. In the second, Database.layer.fresh asks for a new copy:
object Fresh {
final case class AuditLog(db: Database)
val shared: ULayer[UserRepo & AuditLog] =
(Database.layer >>> DatabaseUserRepo.layer) ++ (Database.layer >>> ZLayer.derive[AuditLog])
val separate: ULayer[UserRepo & AuditLog] =
(Database.layer >>> DatabaseUserRepo.layer) ++ (Database.layer.fresh >>> ZLayer.derive[AuditLog])
}
Here is the output of building the two graphs:
--- shared ---
Opening database
Closing database
--- fresh ---
Opening database
Opening database
Closing database
Closing database
The shared graph opens one database. The fresh graph opens two, and closes both. Use fresh when a service needs its own copy of a layer, for example a separate connection for a long-running job.
package serviceslayers.step6
import zio._
final class Database private (val name: String)
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie.as(new Database("main"))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class UserRepo(db: Database)
final case class AuditLog(db: Database)
object UserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[UserRepo]
}
object AuditLog {
val layer: URLayer[Database, AuditLog] = ZLayer.derive[AuditLog]
}
object Step6SharedAndFresh extends ZIOAppDefault {
// Both services use the same Database.layer value, so it is built once.
val shared: ULayer[UserRepo & AuditLog] =
(Database.layer >>> UserRepo.layer) ++ (Database.layer >>> AuditLog.layer)
// `fresh` gives AuditLog its own Database.
val separate: ULayer[UserRepo & AuditLog] =
(Database.layer >>> UserRepo.layer) ++ (Database.layer.fresh >>> AuditLog.layer)
def run =
for {
_ <- Console.printLine("--- shared ---")
_ <- ZIO.scoped(shared.build)
_ <- Console.printLine("--- fresh ---")
_ <- ZIO.scoped(separate.build)
} yield ()
}
7. Choosing an Implementation at Start-Upโ
So far SignupServiceLive has never changed. It depends on the UserRepo trait, so we can give it any implementation. Let's choose one when the application starts, from a setting called signup.storage: memory uses InMemoryUserRepo, and database uses DatabaseUserRepo with its Database.
object UserRepoChoice {
private val storage: Config[String] =
Config.string("storage").nested("signup").withDefault("memory")
val layer: ZLayer[Any, Config.Error, UserRepo] =
ZLayer.fromZIO(ZIO.config(storage)).flatMap { chosen =>
chosen.get match {
case "database" => Database.layer >>> DatabaseUserRepo.layer
case _ => InMemoryUserRepo.layer
}
}
}
The code above:
ZLayer.fromZIO(ZIO.config(storage))is a layer that loads the setting. Its output is the stringflatMapuses that string to pick the layer to build next. Only the chosen layer is built, so the database opens only when we ask for it- The result is a
ZLayer[Any, Config.Error, UserRepo], the same shape as any otherUserRepolayer, so the wiring and the signup service do not change
Run Step7ChooseImplementation with nothing set. It uses the in-memory repository, and the database is never opened:
[email] Welcome, Ada!
Run it with SIGNUP_STORAGE=database. The database now opens and closes around the same program:
Opening database
[email] Welcome, Ada!
Closing database
The same trick works for any service. A test, a local run and production can each choose different layers, and the business code stays the same. Providing Different Implementations of a Service covers more ways to do it.
package serviceslayers.step7
import zio._
final case class User(email: String, name: String)
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final class Database private (val users: Ref[Map[String, User]])
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie *>
Ref.make(Map.empty[String, User]).map(new Database(_))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class DatabaseUserRepo(db: Database) extends UserRepo {
def save(user: User): Task[Unit] = db.users.update(_ + (user.email -> user))
def count: Task[Int] = db.users.get.map(_.size)
}
object DatabaseUserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[DatabaseUserRepo]
}
object UserRepoChoice {
private val storage: Config[String] =
Config.string("storage").nested("signup").withDefault("memory")
val layer: ZLayer[Any, Config.Error, UserRepo] =
ZLayer.fromZIO(ZIO.config(storage)).flatMap { chosen =>
chosen.get match {
case "database" => Database.layer >>> DatabaseUserRepo.layer
case _ => InMemoryUserRepo.layer
}
}
}
final case class ConsoleNotifier() extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ULayer[Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier) extends SignupService {
def signUp(email: String, name: String): Task[User] = {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: URLayer[UserRepo & Notifier, SignupService] = ZLayer.derive[SignupServiceLive]
}
object Step7ChooseImplementation extends ZIOAppDefault {
val program: ZIO[SignupService, Throwable, User] =
ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
def run =
program.provide(
SignupServiceLive.layer,
UserRepoChoice.layer,
ConsoleNotifier.layer
)
}
8. Putting It Togetherโ
The complete example combines everything: a SignupConfig loaded with ZIO.config, layers built with ZLayer.derive, a Database that opens and closes with the application, and a UserRepo chosen at start-up. It signs up three users, and the third name is too long:
package serviceslayers
import zio._
final case class User(email: String, name: String)
final case class SignupConfig(maxNameLength: Int, sender: String)
object SignupConfig {
implicit val config: Config[SignupConfig] =
(Config.int("max-name-length").withDefault(20) zip
Config.string("sender").withDefault("welcome@example.com"))
.nested("signup")
.map { case (maxNameLength, sender) => SignupConfig(maxNameLength, sender) }
}
trait UserRepo {
def save(user: User): Task[Unit]
def count: Task[Int]
}
trait Notifier {
def welcome(user: User): Task[Unit]
}
trait SignupService {
def signUp(email: String, name: String): Task[User]
}
final case class InMemoryUserRepo(users: Ref[Map[String, User]]) extends UserRepo {
def save(user: User): Task[Unit] = users.update(_ + (user.email -> user))
def count: Task[Int] = users.get.map(_.size)
}
object InMemoryUserRepo {
val layer: ULayer[UserRepo] =
ZLayer {
Ref.make(Map.empty[String, User]).map(InMemoryUserRepo(_))
}
}
final class Database private (val users: Ref[Map[String, User]])
object Database {
val layer: ULayer[Database] =
ZLayer.scoped {
ZIO.acquireRelease(
Console.printLine("Opening database").orDie *>
Ref.make(Map.empty[String, User]).map(new Database(_))
)(_ => Console.printLine("Closing database").orDie)
}
}
final case class DatabaseUserRepo(db: Database) extends UserRepo {
def save(user: User): Task[Unit] = db.users.update(_ + (user.email -> user))
def count: Task[Int] = db.users.get.map(_.size)
}
object DatabaseUserRepo {
val layer: URLayer[Database, UserRepo] = ZLayer.derive[DatabaseUserRepo]
}
object UserRepoChoice {
private val storage: Config[String] =
Config.string("storage").nested("signup").withDefault("memory")
val layer: ZLayer[Any, Config.Error, UserRepo] =
ZLayer.fromZIO(ZIO.config(storage)).flatMap { chosen =>
chosen.get match {
case "database" => Database.layer >>> DatabaseUserRepo.layer
case _ => InMemoryUserRepo.layer
}
}
}
final case class ConsoleNotifier(config: SignupConfig) extends Notifier {
def welcome(user: User): Task[Unit] =
Console.printLine(s"[email from ${config.sender}] Welcome, ${user.name}!")
}
object ConsoleNotifier {
val layer: ZLayer[Any, Config.Error, Notifier] = ZLayer.derive[ConsoleNotifier]
}
final case class SignupServiceLive(repo: UserRepo, notifier: Notifier, config: SignupConfig) extends SignupService {
def signUp(email: String, name: String): Task[User] =
if (name.length > config.maxNameLength)
ZIO.fail(new IllegalArgumentException(s"Name '$name' is longer than ${config.maxNameLength} characters"))
else {
val user = User(email, name)
repo.save(user) *> notifier.welcome(user).as(user)
}
}
object SignupServiceLive {
val layer: ZLayer[UserRepo & Notifier, Config.Error, SignupService] =
ZLayer.derive[SignupServiceLive]
}
object CompleteExample extends ZIOAppDefault {
val program: ZIO[SignupService & UserRepo, Throwable, Unit] =
for {
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("ada@example.com", "Ada"))
_ <- ZIO.serviceWithZIO[SignupService](_.signUp("grace@example.com", "Grace"))
_ <- ZIO
.serviceWithZIO[SignupService](_.signUp("long@example.com", "A Name That Is Far Too Long"))
.tapError(e => Console.printLine(s"Signup failed: ${e.getMessage}"))
.ignore
count <- ZIO.serviceWithZIO[UserRepo](_.count)
_ <- Console.printLine(s"Registered users: $count")
} yield ()
def run =
program.provide(
SignupServiceLive.layer,
UserRepoChoice.layer,
ConsoleNotifier.layer
)
}
With the defaults, the output is:
[email from welcome@example.com] Welcome, Ada!
[email from welcome@example.com] Welcome, Grace!
Signup failed: Name 'A Name That Is Far Too Long' is longer than 20 characters
Registered users: 2
Running the Examplesโ
All runnable code from this tutorial is in zio-examples/services-and-layers/src/main/scala/serviceslayers/. From the zio-examples/services-and-layers folder, run any file with sbt "runMain serviceslayers.<package>.<ObjectName>", for example sbt "runMain serviceslayers.step4.Step4Resource". There is one file for each of Sections 1 to 7, named Step1Services to Step7ChooseImplementation, each in its own package step1 to step7, and CompleteExample in the package serviceslayers for Section 8.
What You've Learnedโ
In this tutorial, you learned:
- How a signup service, a repository and a notifier are separate services, each with its own layer, and how
providebuilds them in the right order - How
ZLayer.derivebuilds a layer from a class constructor, and why a layer that must do some work first, such as creating aRef, still usesZLayer.apply - How a
Configdescriptor andZIO.configload settings from environment variables, and howZLayer.deriveloads a configuration for us - How
ZLayer.scopedwithZIO.acquireReleaseopens a resource when the application starts and closes it when the application stops - How to read the compile error for a missing layer, and how
ZLayer.Debug.treeshows the graph - How a layer is shared by default, how
freshcreates a new copy, and how a layer built from a setting chooses an implementation at start-up
Where to Go Nextโ
- To go deeper on layers, read the Dependency Injection section and the reference page for
ZLayer - To go deeper on settings, read Configuration
- To see a service replaced while the application is running, read Hot-Swap Services with Reloadable
- To test the services we built with stubs instead of the real implementations, read Writing Tests