Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Cloud and Serverless

Service Discovery and Distributed Configuration

Register Micronaut services, find them by name with @Client(id), load balance, use Consul and Kubernetes discovery, and share configuration. Runnable stand-ins.

In a cloud setup, services come and go. An instance of the billing service may start on a new IP address after every deployment, and you may run three of them. Hard-coding http://10.0.0.17:8080 in the order service cannot work. Service discovery solves this: services register themselves under a logical name, and callers ask a registry "where is billing right now?".

Micronaut has discovery built in, with client-side load balancing, so no extra proxy is required. The real integration needs a registry such as Consul, which is not available here, so its code is read-only. The runnable examples simulate a registry with health checks and round-robin balancing, and layered configuration.

Registering and finding services

Micronaut supports Consul, Eureka, Kubernetes and others. The idea is the same for all. With Consul:

GROOVY
implementation("io.micronaut:micronaut-discovery-client")
YAML
micronaut:
  application:
    name: billing           # the logical service name
consul:
  client:
    registration:
      enabled: true
    defaultZone: "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"

When billing starts, it registers its address with Consul, and Consul polls its health endpoint (see Metrics, Health and Tracing). When it shuts down it deregisters itself. A crashed instance fails its health check and drops out of the list.

Calling a service by name

A declarative HTTP client can use the service id instead of a URL:

Java
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.annotation.Client;

@Client(id = "billing")
public interface BillingClient {

    @Get("/invoices/{id}")
    Invoice find(long id);
}

At the first call, Micronaut asks the registry for all healthy instances of billing and picks one for each request, using round-robin by default. The list is refreshed periodically, so a new instance starts receiving traffic and a dead one stops. For local development you can bypass the registry with configuration:

YAML
micronaut:
  http:
    services:
      billing:
        urls:
          - http://localhost:8081
          - http://localhost:8082

This static list gets the same client-side load balancing, which is also how you run in environments without a registry.

Discovery at a glance

Register Service announces name and address.
Health check Registry removes unhealthy instances.
1 / 2

Resilience around remote calls

Remote calls fail. Micronaut offers annotations for the usual defences, applied to any bean method or client interface:

Java
@Client(id = "billing")
@Retryable(attempts = "3", delay = "200ms")
@CircuitBreaker(reset = "30s")
public interface BillingClient { /* ... */ }
  • @Retryable repeats a failed call, with optional back-off.
  • @CircuitBreaker stops calling a failing service for a while and fails fast, then tries again.
  • @Fallback supplies a substitute client or default answer when the call cannot succeed.

Only retry operations that are safe to repeat (idempotent), such as GET.

Distributed configuration

If you run ten services you do not want to edit ten application.yml files to change a shared setting. A distributed configuration source lets services read settings at startup from a central place: Consul's key/value store, HashiCorp Vault for secrets, AWS Parameter Store or Secrets Manager, Google Cloud, Kubernetes ConfigMaps and Secrets, and so on. Enable it in a special file named bootstrap.yml, which Micronaut reads before the main configuration:

YAML
micronaut:
  application:
    name: billing
  config-client:
    enabled: true
consul:
  client:
    config:
      format: yaml

Values from the central store join the property sources described in Configuration Files and Environments: common settings are shared by all services, and a key named for your service or environment (for example config/billing,prod) overrides them for one service.

Try it: registry, health checks and round-robin

Java A tiny service registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: retry with a circuit breaker

This stand-in wraps a flaky remote call in a retry and a very small circuit breaker, mirroring @Retryable and @CircuitBreaker.

Java Retry and circuit breaker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical notes

  • On Kubernetes you can skip a separate registry: Micronaut's Kubernetes discovery uses the cluster's own service API, and ConfigMaps and Secrets can feed configuration.
  • Give every service a stable micronaut.application.name; it is the key everything else uses.
  • Decide timeouts on purpose: a client with no read timeout can hold threads forever.
  • Do not store secrets in a plain configuration store; use Vault, a cloud secrets manager or Kubernetes Secrets, and see Security Fundamentals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @Client(id = "billing") use instead of a fixed URL?

    The id is resolved through service discovery or micronaut.http.services configuration, and requests are load balanced.
  2. 2. Why does a registry run health checks?

    Callers should only be sent to instances that can answer.
  3. 3. Which pattern stops calling a failing service for a while?

    A circuit breaker fails fast once failures pass a threshold, then lets calls through again after a reset time.
  4. 4. Which file is read before the main configuration so that a remote source can be set up?

    bootstrap.yml enables the config client, which then adds remote property sources.
  5. 5. Which calls are safe to retry automatically?

    Retrying a non-idempotent call can apply it twice.

Summary

  • Services register under a logical name; clients resolve it with @Client(id = ...) and are load balanced on the client side.
  • Health checks keep dead instances out of rotation.
  • @Retryable, @CircuitBreaker and @Fallback add resilience to remote calls.
  • Distributed configuration loads shared settings from Consul, Vault, cloud stores or Kubernetes through bootstrap.yml.

Next: AWS Lambda and Serverless Functions