Consuming services

§Consuming services

We’ve seen how to define service descriptors and how to implement them, now we need to consume them. The service descriptor contains everything Lagom needs to know about how to invoke a service, consequently, Lagom is able to implement service descriptor interfaces for you.

§Binding a service client

The first thing necessary to consume a service is to create an implementation of it. Lagom provides a macro to do this on the ServiceClient class, called implement. The ServiceClient is provided by the LagomServiceClientComponents, which is already implemented by LagomApplication, so to create a service client from a Lagom application, you just have to do the following:

abstract class MyApplication(context: LagomApplicationContext)
  extends LagomApplication(context)
    with AhcWSComponents {

  lazy val helloService = serviceClient.implement[HelloService]
}

§Using a service client

Having bound the client, you can now use it anywhere in your Lagom application. Typically this will be done by passing it to another component, such as a service implementation, via that components constructor, which will be done automatically for you if you’re using Macwire. Here’s an example of consuming one service from another service:

class MyServiceImpl(helloService: HelloService)
  (implicit ec: ExecutionContext) extends MyService {

  override def sayHelloLagom = ServiceCall { _ =>
    val result: Future[String] =
      helloService.sayHello.invoke("Lagom")

    result.map { response =>
      s"Hello service said: $response"
    }
  }
}

§Circuit Breakers

A circuit breaker is used to provide stability and prevent cascading failures in distributed systems. These should be used in conjunction with judicious timeouts at the interfaces between services to prevent the failure of a single service from bringing down other services.

As an example, we have a web application interacting with a third-party web service. Let’s say the third-party has oversold their capacity and their database melts down under load. Assume that the database fails in such a way that it takes a very long time to hand back an error to the third-party web service. This in turn makes calls fail after a long period of time. Back to our web application, the users have noticed that their form submissions take much longer seeming to hang. The users do what they know to do which is use the refresh button, adding more requests to their already running requests. This eventually causes the failure of the web application due to resource exhaustion.

Introducing circuit breakers on the web service call would cause the requests to begin to fail-fast, letting the user know that something is wrong and that they need not refresh their request. This also confines the failure behavior to only those users that are using functionality dependent on the third-party, other users are no longer affected as there is no resource exhaustion. Circuit breakers can also allow savvy developers to mark portions of the site that use the functionality unavailable, or perhaps show some cached content as appropriate while the breaker is open.

A circuit breaker has 3 states:

During normal operation, a circuit breaker is in the Closed state:

  • Exceptions or calls exceeding the configured call-timeout increment a failure counter
  • Successes reset the failure count to zero
  • When the failure counter reaches a max-failures count, the breaker is tripped into Open state

While in Open state:

  • All calls fail-fast with a CircuitBreakerOpenException
  • After the configured reset-timeout, the circuit breaker enters a Half-Open state

In Half-Open state:

  • The first call attempted is allowed through without failing fast
  • All other calls fail-fast with an exception just as in Open state
  • If the first call succeeds, the breaker is reset back to Closed state
  • If the first call fails, the breaker is tripped again into the Open state for another full resetTimeout

All service calls with Lagom service clients are by default using circuit breakers. Circuit Breakers are used and configured on the client side, but the granularity and configuration identifiers are defined by the service provider. By default, one circuit breaker instance is used for all calls (methods) to another service. It is possible to set a unique circuit breaker identifier for each method to use a separate circuit breaker instance for each method. It is also possible to group related methods by using the same identifier on several methods.

import com.lightbend.lagom.scaladsl.api.CircuitBreaker

def descriptor: Descriptor = {
  import Service._

  named("hello").withCalls(
    namedCall("hi", this.sayHi),
    namedCall("hiAgain", this.hiAgain)
      .withCircuitBreaker(CircuitBreaker.identifiedBy("hello2"))
  )
}

In the above example the default identifier is used for the sayHi method, since no specific identifier is given. The default identifier is the same as the service name, i.e. "hello" in this example. The hiAgain method will use another circuit breaker instance, since "hello2" is specified as circuit breaker identifier.

On the client side you can configure the circuit breakers. The default configuration is:

# Circuit breakers for calls to other services are configured
# in this section. A child configuration section with the same
# name as the circuit breaker identifier will be used, with fallback
# to the `lagom.circuit-breaker.default` section.
lagom.circuit-breaker {

  # Default configuration that is used if a configuration section
  # with the circuit breaker identifier is not defined.
  default {
    # Possibility to disable a given circuit breaker.
    enabled = on

    # Number of failures before opening the circuit.
    max-failures = 10

    # Duration of time after which to consider a call a failure.
    call-timeout = 10s

    # Duration of time in open state after which to attempt to close
    # the circuit, by first entering the half-open state.
    reset-timeout = 15s
  }
}

That configuration will be used if you don’t define any configuration yourself.

With the above “hello” example we could adjust the configuration by defining properties in application.conf such as:

lagom.circuit-breaker {

  # will be used by sayHi method
  hello.max-failures = 5

  # will be used by hiAgain method
  hello2 {
    max-failures = 7
    reset-timeout = 30s
  }

  # Change the default call-timeout
  # will be used for both sayHi and hiAgain methods
  default.call-timeout = 5s
}

§Circuit breaker metrics

Lagom allows you to publish metrics for circuit breakers via a metrics service. To enable this service, mix in the MetricsServiceComponents trait into your application, and add the provided metricsServiceBinding to your service bindings in your lagomServer declaration, like so:

import com.lightbend.lagom.scaladsl.server.status.MetricsServiceComponents

abstract class MyApplication(context: LagomApplicationContext)
  extends LagomApplication(context)
    with AhcWSComponents {

  lazy val lagomServer = LagomServer.forServices(
    bindService[HelloService].to(wire[HelloServiceImpl]),
    metricsServiceBinding
  )
}

The service provides the following endpoints:

  • /_status/circuit-breaker/current - Snapshot of current circuit breaker status
  • /_status/circuit-breaker/stream - Stream of circuit breaker status

Lightbend Monitoring will provide metrics for Lagom circuit breakers, including aggregated views of the information for all nodes in the cluster.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.