# Embedded Agent

A JVM app can run the agent inside itself instead of beside it, as a separate process. The agent then connects out to
the proxy from within the app, and can read the app's metrics without an HTTP request.

## When to Embed { #when-to-use }

Embed the agent in an app you build and deploy yourself when:

- **There's nothing more to deploy.** The agent ships inside the app, so no sidecar, second process, or agent config
  runs beside each replica. The Ktor plugin and the Spring Boot starter start and stop it with the app.
- **The app can't open a metrics port, or shouldn't.** The agent reads the app's metrics registry in-process, so the
  app needs no `/metrics` endpoint, port, or credentials for a scraper. A worker with no HTTP server is scraped as a
  web app is.
- **The app keeps its secrets.** It can build the agent's settings in code, so no file on disk holds the token or
  the proxy's certificate.

Run a [standalone agent](https://prometheus-proxy.com/getting-started/index.md#start-the-agent) beside the app instead when:

- **One agent should scrape several services,** such as every service on a host. Embedding puts an agent in each app,
  and in each of its replicas.
- **The app isn't on the JVM, or isn't yours to rebuild.**
- **The agent should upgrade apart from the app.** An embedded agent changes only when the app is released. Its
  libraries, such as gRPC, Netty, and Ktor, share the app's classpath, so a Ktor or Spring Boot app lines their
  versions up with the agent's.

## Ways to Run It

Each of these runs the same agent from the same settings, the tree a config file holds under `agent` (see
[Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)):

| Your application                        | Start the agent with                                                                        | Its settings come from                                                                                  |
|:----------------------------------------|:--------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------|
| A Spring Boot app                       | The [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md), from a dependency                        | The `prometheus-proxy.agent.*` properties, and a customizer bean                                        |
| A Ktor app                              | The [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md), `install(PrometheusProxyAgent)`                          | `prometheus-proxy.agent` in `application.conf` or its YAML, and the install block                       |
| Any JVM program, its settings in code   | [`embeddedAgent { }`](#configuring-in-code), or `EmbeddedAgentConfig.builder()` from Java   | The builder's methods, [`fromEnvironment()`](#settings-from-the-environment), and `setting()`           |
| Any JVM program, its settings in a file | [`Agent.startAsyncAgent(file, false)`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent)                               | A HOCON config file or URL, as the standalone agent reads one                                           |
| Any JVM program, a `Config` it builds   | [`Agent.startAsyncAgent(config)`](#a-config-of-your-own)                                    | A Typesafe `Config`, rooted at `agent`                                                                  |

The starter and the plugin start the agent with the app, and stop it as the app stops. With the others, the app stops it
itself (see [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)). The starter and the plugin pass their settings to
the builder, and [Every Setting, Every Way](#every-setting-every-way) gives each setting's name in each of them.

## You Need a Proxy

The agent connects out to a proxy, which Prometheus scrapes, so start one first. To try it on your machine, run the
Quick Start's [steps 1 and 2](https://prometheus-proxy.com/getting-started/index.md#installation), then come back here;
[JVM Embed](https://prometheus-proxy.com/embed/index.md#you-need-a-proxy) gives the other ways. The builder's `proxy(...)` tells the agent where the
proxy is, or `fromEnvironment()` reads it from `PROMETHEUS_PROXY`, as the examples below do. Without one,
`startIfConfigured()` leaves the agent off.

## Adding the Dependency

=== "Gradle (Kotlin DSL)"

    ```kotlin
    // build.gradle.kts
    repositories {
      mavenCentral()
    }

    dependencies {
      implementation("com.pambrose:prometheus-proxy:4.9.0")
    }
    ```

=== "Maven"

    ```xml
    <!-- pom.xml -->
    <dependencies>
      <dependency>
        <groupId>com.pambrose</groupId>
        <artifactId>prometheus-proxy</artifactId>
        <version>4.9.0</version>
      </dependency>
    </dependencies>
    ```

The agent runs on Java 17 or later, and an app written in Kotlin compiles with Kotlin 2.4 or later.

## Configuring in Code

[`EmbeddedAgentConfig`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig) has a typed method for each setting. Build it with
`embeddedAgent { }` from Kotlin, or `EmbeddedAgentConfig.builder()` from Java, and start it. This worker has no HTTP
server: the agent reads its metrics registry in-process, on each scrape, and serves it at the proxy's `/worker_metrics`:

=== "Kotlin"

    ```kotlin
    import io.prometheus.agent.embeddedAgent
    import io.prometheus.metrics.model.registry.PrometheusRegistry

    // A worker with no HTTP server of its own: the agent reads its metrics from
    // the registry, in-process, for each scrape, and serves its own beside them.
    // Without PROMETHEUS_PROXY, as on a developer's machine, the worker runs
    // without it.
    fun runWorker(
      version: String,
      work: () -> Unit,
    ) {
      embeddedAgent {
        name = "worker-$version"
        fromEnvironment()
        // Where the worker's metrics are: Micrometer's PrometheusMeterRegistry
        // gives its own as prometheusRegistry
        source(
          path = "worker_metrics",
          registry = PrometheusRegistry.defaultRegistry,
        )
        // The agent's own, for the Agents dashboard
        agentMetricsAt(path = "worker_agent_metrics")
      }.startIfConfigured(logBanner = false).use { work() }
    }
    ```

=== "Java"

    ```java
    import io.prometheus.agent.EmbeddedAgentConfig;
    import io.prometheus.agent.EmbeddedAgentInfo;
    import io.prometheus.metrics.model.registry.PrometheusRegistry;

    public class EmbeddedAgentSourceJavaExample {
      // A worker with no HTTP server of its own: the agent reads its metrics
      // from the registry, in-process, for each scrape, and serves its own
      // beside them. Without PROMETHEUS_PROXY, as on a developer's machine, the
      // worker runs without it.
      public static void runWorker(String version, Runnable work) {
        EmbeddedAgentConfig config =
          EmbeddedAgentConfig.builder()
            .name("worker-" + version)
            .fromEnvironment()
            // Where the worker's metrics are: Micrometer's
            // PrometheusMeterRegistry gives its own with getPrometheusRegistry()
            .source("worker_metrics", PrometheusRegistry.defaultRegistry)
            // The agent's own, for the Agents dashboard
            .agentMetricsAt("worker_agent_metrics")
            .build();
        // Null when the agent stays off, which try-with-resources takes: the
        // worker runs either way
        try (EmbeddedAgentInfo agent = config.startIfConfigured(false)) {
          work.run();
        }
      }
    }
    ```

- **[`fromEnvironment()`](#settings-from-the-environment) reads the proxy** from `PROMETHEUS_PROXY`, and a token and
  the proxy's certificate where they're set.
- **[`source(path, registry)`](#metrics-served-in-process) serves the registry,** so the app needs no metrics
  endpoint, port, or credentials for the agent.
- **[`agentMetricsAt(path)`](#the-agents-own-metrics) serves the agent's own metrics** at a separate path.
- **[`startIfConfigured()`](#starting-where-theres-a-proxy) starts the agent only where there's a proxy,** and keeps
  the app running if the agent can't start. `use` stops the agent once the work is done.
- **The settings fall back to the built-in defaults,** as a config file's do. A setting the agent can't use throws
  `ConfigLoadException` from `start()`, and `startIfConfigured()` logs it and returns `null`.
- **The agent's variables for single settings still take precedence,** such as `AGENT_TOKEN` or `PROXY_HOSTNAME`, as
  they do over a config file. Give your application's settings other names, as the `PROMETHEUS_` ones
  `fromEnvironment()` reads are, unless you mean the agent to read them. `AGENT_CONFIG` isn't read.
  [Every Setting, Every Way](#every-setting-every-way) lists each setting's variable.

??? note "Which release added these"

    The builder, `embeddedAgent { }` and `EmbeddedAgentConfig.builder()`, came in 4.6.0; `fromEnvironment()`,
    `startIfConfigured()`, `source()`, and `agentMetricsAt()` in 4.7.0; and `stopTimeout` in 4.8.0.
    [Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md) lists what each release changed.

### See the First Scrape

Start the app with `PROMETHEUS_PROXY=localhost:50051` in its environment, for a proxy on the same machine. The agent
logs, through the app's [logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging), when it has connected and registered each path:

``` { .text .pp-output .pp-output--ok title="The app's log" }
Connected to proxy at localhost:50051 using plaintext
Registered in-process as /worker_metrics with labels {} (static)
Registered in-process as /worker_agent_metrics with labels {} (static)
```

Without `PROMETHEUS_PROXY`, it logs `No proxy is set, so the Prometheus agent stays off` instead, and the worker runs
without the agent. Scrape the path through the proxy, as Prometheus will:

```bash
curl -i http://localhost:8080/worker_metrics
```

<span class="pp-status pp-status--ok">HTTP/1.1 200 OK</span>, followed by the metrics in the worker's registry, means
every hop works: the proxy answers scrapes, and the agent is connected and reads the registry.
<span class="pp-status pp-status--crit">404 Not Found</span> means no agent has registered the path. Check the app's
log for the `Registered` line; [Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows where else to look.

Then give Prometheus a job for the path, with the proxy's host in place of `localhost` where Prometheus runs elsewhere,
and have it read the job:

```yaml
scrape_configs:
  - job_name: 'worker'
    metrics_path: '/worker_metrics'
    static_configs:
      - targets: ['localhost:8080']
```

!!! success "You're done when Prometheus shows `worker` up"

    After Prometheus's next scrape, its target page (Status → Target health) shows `worker` as up: Prometheus is
    scraping the worker's registry, in-process, through the proxy.

The agent's own metrics, at `/worker_agent_metrics`, take a separate job (see
[Agent's Metrics](#the-agents-own-metrics)).

### Metrics Served In-Process

Since 4.7.0, an app with a metrics registry can hand it to the agent instead of serving it at a URL, as the worker
above does. `source(path, registry)` takes the Prometheus Java client's `PrometheusRegistry`, which Micrometer's
`PrometheusMeterRegistry` gives with `getPrometheusRegistry()`. The agent reads it on each scrape, in-process. The app
then needs no metrics endpoint, port, or credentials for the agent, and the agent opens no connection to it. A program
with no HTTP server at all, such as a worker that consumes a queue, is scraped as a web app is, as the
[Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md)'s ovens are.

- **The agent writes the format Prometheus asks for:** the Prometheus text format or OpenMetrics, as Prometheus's
  `Accept` header allows, without the protobuf it can't carry, and only the metric families Prometheus names with
  `name[]` parameters, if it names any. It brings the Prometheus client's text formats itself, so the app declares
  nothing more.
- **It's read as a target's body is,** on a thread it can block: up to `agent.http.maxContentLengthMBytes`, past which
  the scrape is refused, and through the path's [metric filter](https://prometheus-proxy.com/configuration/agent/index.md#metric-filtering).
- **The agent's own metrics aren't among the app's.** With its metrics on, the agent keeps them in the default
  registry, `PrometheusRegistry.defaultRegistry`, which a plain program's metrics are often in too; a source of it
  leaves them out, so each series is served once. [`agentMetricsAt`](#the-agents-own-metrics) serves them at a
  separate path.
- **A source's trouble stays in its scrape.** At the scrape timeout, the agent answers without waiting for it, and
  whatever reading the registry throws, short of a `VirtualMachineError`, fails the scrape, as a target that can't be
  reached does, and the agent goes on.
- **The path's target shows as `in-process`** on both dashboards and in the agent's log, where a scraped path shows its
  URL, and Scrape now on the agent's dashboard reads the registry.
- **The path is checked as a `pathConfigs` entry is:** one that another path also names, or that has a character the
  proxy refuses (whitespace, a control character, `?`, or `#`), fails `start()`. A source is code, so `toConfig()`
  leaves it out: start the agent with the builder's `start()` or `startIfConfigured()`.

For metrics in another form, `source(path, source)` takes a `MetricsSource`, which the agent asks for the app's metrics
on each scrape. It writes them to the stream it's given, in a format the scrape's `Accept` header allows, and returns
the content type it wrote; an empty one means the text format. Calls can overlap, as scrapes do, so it must be safe to
call from several threads. At the scrape timeout, the agent interrupts the call; one that ignores the interrupt, such as
one blocked on a socket read, keeps its thread, and the source isn't called again until every such call has returned.
The agent's `agent_stuck_sources` gauge counts its sources with such a call ([Agent Metrics](https://prometheus-proxy.com/monitoring/index.md#agent-metrics)).
Whatever it throws, an `Error` included, fails only its scrape; only a `VirtualMachineError`, such as
`OutOfMemoryError`, isn't kept to it.
`MetricsSource.of(registry)` is the source `source(path, registry)` gives a registry.

### Scraping the App's Endpoint { #scraping-the-apps-own-endpoint }

An app whose metrics the agent can't read in-process can have it scrape the app's `/metrics` over HTTP instead, as a
standalone agent does. Settings the app holds itself, such as a token, the proxy's certificate, or the credentials for
that endpoint, are built in code, so no config file holds them on disk:

=== "Kotlin"

    ```kotlin
    import io.prometheus.agent.EmbeddedAgentInfo
    import io.prometheus.agent.embeddedAgent
    import kotlin.time.Duration.Companion.seconds

    // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password. Returns
    // null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics aren't worth
    // an outage.
    fun startPrometheusAgent(
      appVersion: String,
      appPort: Int,
    ): EmbeddedAgentInfo? =
      embeddedAgent {
        // The version tells the old and new revisions apart during a deploy
        name = "my-app-$appVersion"
        // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT
        fromEnvironment()
        // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth
        scrapeSelf(
          path = "my_app_metrics",
          port = appPort,
          username = env("METRICS_USER"),
          password = env("METRICS_PASSWORD"),
        )
        // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as
        // Cloud Run's 10 seconds
        stopTimeout = 8.seconds
      }.startIfConfigured(logBanner = false)

    private fun env(name: String) = System.getenv(name).orEmpty().trim()
    ```

=== "Java"

    ```java
    import io.prometheus.agent.EmbeddedAgentConfig;
    import io.prometheus.agent.EmbeddedAgentInfo;
    import java.time.Duration;

    public class EmbeddedAgentConfigJavaExample {
      // Starts the agent from the app's own settings, in memory, so no config file holds the token or the password.
      // Returns null when the agent is off, without PROMETHEUS_PROXY, or can't start, which it logs: the app's metrics
      // aren't worth an outage.
      public static EmbeddedAgentInfo startPrometheusAgent(String appVersion, int appPort) {
        return EmbeddedAgentConfig.builder()
          // The version tells the old and new revisions apart during a deploy
          .name("my-app-" + appVersion)
          // The proxy, its token, and its certificate: PROMETHEUS_PROXY, PROMETHEUS_AGENT_TOKEN, and PROMETHEUS_PROXY_CERT
          .fromEnvironment()
          // The app's own /metrics, on 127.0.0.1; the agent sends the credentials as Basic Auth
          .scrapeSelf("my_app_metrics", appPort, env("METRICS_USER"), env("METRICS_PASSWORD"))
          // How long the agent's stop may hold up the app's shutdown: inside the platform's window after SIGTERM, such as
          // Cloud Run's 10 seconds
          .stopTimeout(Duration.ofSeconds(8))
          .build()
          .startIfConfigured(false);
      }

      private static String env(String name) {
        String value = System.getenv(name);
        return value == null ? "" : value.trim();
      }
    }
    ```

- **The certificate is PEM text,** or its base64
  ([`agent.tls.trustCertCollectionPem`](https://prometheus-proxy.com/security/tls/index.md#certificates-as-environment-variables)).
- **`scrapeSelf` points the agent at the app's metrics** on `127.0.0.1`. It percent-encodes a username and password
  into the scrape URL, whatever their characters; the agent sends them as Basic Auth and leaves them out of its logs.
- **`stopTimeout` caps how long the agent's stop holds up the app's shutdown.** Set it inside the window the platform
  gives the app after `SIGTERM`. Once it's up, `shutdown()` returns, and the agent goes on stopping on its own
  ([`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)).

The agent's `Registered` line then names the app's URL, `http://127.0.0.1:<port>/metrics`, with any credentials shown
as `***`, where the worker's names `in-process`. The first scrape goes as [above](#see-the-first-scrape), at
`/my_app_metrics`.

### Agent's Metrics { #the-agents-own-metrics }

The [Agents dashboard](https://prometheus-proxy.com/grafana/index.md#dashboards) the project ships reads the agent's own metrics, `agent_connected`, its
scrapes, their latency, and its backlog among them. An embedded agent's metrics port would be no more reachable from
outside than the app's. So since 4.7.0, `agentMetricsAt(path)` has the agent serve them through the proxy, at a separate
path. They're read in-process, as the app's registry is, with no port opened for them. The example above serves
them at `/worker_agent_metrics`.

`agentMetricsAt(path, labels)` sets `agent.metrics.proxyPath` and `agent.metrics.proxyPathLabels`, the settings a
standalone agent uses to serve its metrics through the proxy. So `toConfig()` holds them, and a config file, a
`Config`, the starter's and the plugin's `metrics-proxy-path`, or `METRICS_PROXY_PATH` in the app's environment sets
the same:

- **They're the `agent_*` series, this agent's alone:** another agent in the same JVM serves its own, and the JVM's
  metrics stay with the app's path, which the dashboard doesn't read them from. A standalone agent's path serves its
  JVM's metrics too, since its JVM is its own, and so does an `Agent` an app constructs and starts itself: only one
  started with `startAsyncAgent()` or this builder, as the starter and the plugin start theirs, counts as embedded.
- **They're kept from the start,** whether or not the agent's metrics port is on (`agentMetrics(port)`,
  `METRICS_ENABLED`), and a source of the default registry leaves them out. The
  [agent's dashboard](https://prometheus-proxy.com/agent-dashboard/index.md) shows them as on in its Settings view, with their path, and their port when
  it's on too.
- **The path is checked as a `pathConfigs` entry is:** one another path also names, or that has a character the proxy
  refuses, fails `start()`, and the error names `agent.metrics.proxyPath`.
- **Give each of the app's replicas a separate path,** as the [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md) names its
  replicas' after their host names: replicas sharing one would have the proxy serve only one of them there.
- **Give the path a separate Prometheus job,** since the dashboard tells agents apart by `job`:

```yaml
scrape_configs:
  - job_name: worker-agent
    metrics_path: /worker_agent_metrics
    static_configs:
      - targets: [ 'proxy-host:8080' ]
```

The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) serves its coffee shop's agent's metrics this way, and its Grafana links to the
dashboard.

The metrics port, `agentMetrics(port)`, is for a scraper on the app's network, such as a Prometheus inside the
cluster, which can read the agent while it can't reach the proxy, when nothing reaches its path. The port serves
everything in the JVM's default registry, the app's metrics too when they're kept there, and the JVM metric groups the
agent's `agent.metrics` settings turn on. Without such a scraper, the path is all the agent needs (see
[Port or Proxy Path](https://prometheus-proxy.com/monitoring/index.md#port-or-proxy-path)).

### Settings from the Environment

Since 4.7.0, `fromEnvironment()` reads the proxy, and how to reach it, from the app's environment. Its variables have
names apart from the agent's own. The [Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md), the [Spring Boot Demo](https://prometheus-proxy.com/spring-boot-demo/index.md), and
[Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md) use them:

| Variable                     | Sets                                                                                                                              |
|:-----------------------------|:----------------------------------------------------------------------------------------------------------------------------------|
| `PROMETHEUS_PROXY`           | `proxy`: the proxy's agent port, as `host:port`, or several, separated by commas                                                  |
| `PROMETHEUS_AGENT_TOKEN`     | `token`: the token the agent presents to the proxy                                                                                |
| `PROMETHEUS_PROXY_CERT`      | `trustCertificatePem`: the certificate the agent trusts the proxy's by, as PEM or its base64, which turns TLS on                    |
| `PROMETHEUS_PROXY_AUTHORITY` | The certificate's authority, the name the proxy's certificate was issued to; `prometheus-proxy` when unset. Read only with the certificate |

- **The authority defaults to `prometheus-proxy`,** the name the certificate [Securing the Link](https://prometheus-proxy.com/cloud-platforms/index.md#securing-the-link)
  makes is issued to. To check the proxy's certificate against the host the agent connects to, as for a certificate
  from a public CA, set `PROMETHEUS_PROXY_AUTHORITY` to that host.
- **A variable that's unset, or blank, leaves its setting alone,** so a builder method called after `fromEnvironment()`
  takes precedence, and one called before it holds where the variable isn't set. A `setting()` of the same key takes
  precedence whatever its order, as it does over any builder method, and the variable's value then isn't checked.
- **Only `fromEnvironment()` reads these:** the agent doesn't, so an app that never calls it can use the names for
  anything.
- **A value the agent refuses names its variable.** A `PROMETHEUS_PROXY` endpoint the agent can't parse, or a
  `PROMETHEUS_PROXY_CERT` it can't read as a certificate, fails `start()`, or has `startIfConfigured()` log, with the
  variable, the setting, and the agent's reason: `Invalid configuration: PROMETHEUS_PROXY, read by fromEnvironment() for
  agent.proxy.endpoints: Invalid port in 'proxy:abc': 'abc' is not a valid integer`. An endpoint it can't parse is
  quoted, as here, but never a certificate. The agent takes any token or authority as it starts: a token the proxy
  refuses is logged once the agent connects
  ([Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#unauthenticated-missing-or-invalid-agent-token)), and a wrong authority fails
  the TLS handshake.

### Starting Where There's a Proxy

`start()` throws when the agent can't start, which suits an app that can't run without it. Since 4.7.0,
`startIfConfigured()` suits one that can, as most can, since their metrics aren't worth an outage:

- **Without a proxy,** as on a developer's machine, it logs one INFO line,
  `No proxy is set, so the Prometheus agent stays off`, and returns `null`. A proxy comes from the builder's `proxy`, a
  `setting()` of the proxy's endpoints or host name, or the agent's `PROXY_HOSTNAME`. `namesProxy()` tells whether
  the settings name one, for an app that decides for itself, as the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) and the
  [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) do.
- **A start that fails returns `null`,** so the app runs on. That covers a setting the agent rejects, and anything else,
  such as its admin port being in use or its start taking over 30 seconds. It's logged at ERROR, as
  `The Prometheus agent could not start, so it stays off:` and why, which holds no token, password, or PEM.
- **To report a failed start elsewhere,** such as to a chat channel, add a handler with the builder's `onFailure`,
  since 4.8.0. It's given why, as the log line has it, and what was thrown. Each handler added runs in turn, and one
  that throws is logged without failing the start. So a [Ktor](https://prometheus-proxy.com/ktor-plugin/index.md) `agent { }` block or a
  [Spring Boot](https://prometheus-proxy.com/spring-boot-starter/index.md) customizer can add one beside the app's own. `startIfConfigured(onFailure)`
  still takes one too, which runs after them. `start()` tells none of them: it throws, for its caller to handle.
- **A host that makes the settings from its configuration** before the app's code adds its handlers, as those two
  do, reports a value there that a builder method rejects with the builder's `reportFailure(cause)`. That logs it as a
  failed start is logged, and tells the handlers.
- **The handle is `AutoCloseable`,** and Kotlin's `use` and Java's try-with-resources both take a `null` one. So a
  program that runs while its agent does reads as `startIfConfigured().use { worker.run() }`. The worker runs whether
  or not the agent started, and the agent stops after it. Write `.use`, not `?.use`, which skips the block for `null`.
  A program that runs until it's stopped needs a shutdown hook too (see
  [`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo)).

=== "Kotlin"

    ```kotlin
    val agent =
      embeddedAgent {
        // The agent's other settings
        fromEnvironment()
        onFailure { reason, _ -> alerts.send("No metrics from this app: $reason") }
      }.startIfConfigured(logBanner = false)
    ```

=== "Java"

    ```java
    EmbeddedAgentInfo agent =
        EmbeddedAgentConfig.builder()
            // The agent's other settings
            .fromEnvironment()
            .onFailure((reason, e) -> alerts.send("No metrics from this app: " + reason))
            .build()
            .startIfConfigured(false);
    ```

A wrong token isn't a failure to start: the agent starts, and the proxy refuses it once it connects. The agent logs that
at ERROR, naming the setting, and keeps retrying (see [Troubleshooting](https://prometheus-proxy.com/troubleshooting/index.md#unauthenticated-missing-or-invalid-agent-token)).

### A `Config` of Your Own

For a setting the builder has no method for, `setting(key, value)` sets it by its key, relative to `agent`, such as
`setting("scrapeTimeoutSecs", 5)`. A key the agent doesn't know has no effect, and the agent warns about it as it
starts, naming the nearest setting. Or build the whole tree as a Typesafe `Config` rooted at `agent`, the tree a config
file holds, and start it with `Agent.startAsyncAgent(config)`. `ConfigFactory.parseString`, `ConfigFactory.parseMap`,
and `ConfigValueFactory.fromMap` build one, and a builder's `toConfig()` gives the one it holds. It's resolved, as a
config file is, so a `${?ENV_VAR}` substitution in it works.

[Cloud Platforms](https://prometheus-proxy.com/cloud-platforms/index.md) builds on this to run an embedded agent in an app on ECS on Fargate, Cloud Run,
Azure Container Apps, or another platform, with the proxy on AWS, GCP, Azure, DigitalOcean, or Railway. The
[Ktor Demo](https://prometheus-proxy.com/ktor-demo/index.md) runs an embedded agent on one machine, in a Ktor app, with the [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md).
The [Plain Kotlin Demo](https://prometheus-proxy.com/plain-kotlin-demo/index.md) runs one in each of a plain Kotlin program's replicas, with no framework
or HTTP server, scaled out and in.

## Configuring with a File { #usage }

An app that keeps the agent's settings in a file, as the standalone agent does, starts it with
[`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent), which reads the file or a URL:

=== "Kotlin"

    ```kotlin
    import io.prometheus.Agent

    fun main() {
      // Start the agent in the background. It stops when the block ends, however it ends.
      Agent.startAsyncAgent(
        configFilename = "agent-config.conf",
        exitOnMissingConfig = false,
      ).use { agentInfo ->
        println("Agent started: ${agentInfo.agentName}")

        // Your application code runs here...
        // The agent runs in background coroutines
      }
    }
    ```

=== "Java"

    ```java
    import io.prometheus.Agent;
    import io.prometheus.agent.EmbeddedAgentInfo;

    public class EmbeddedAgentJavaExample {
      public static void main(String[] args) {
        // Start the agent in the background. false makes a config error throw instead of exiting the JVM; a third
        // argument, false, would leave out the startup banner. The agent stops when the block ends, however it ends.
        try (EmbeddedAgentInfo agentInfo = Agent.startAsyncAgent("agent-config.conf", false)) {
          System.out.println("Agent started: " + agentInfo.getAgentName());

          // Your application code runs here...
          // The agent runs in background threads
        }
      }
    }
    ```

The file holds the same HOCON settings as the standalone agent's (see
[Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)):

```hocon
// Minimal config for an embedded agent:
agent {
  proxy.hostname = "proxy-host.example.com"

  pathConfigs: [
    {
      name: "My App metrics"
      path: my_app_metrics
      url: "http://localhost:9100/metrics"
    }
  ]
}
```

A relative file path is read from the app's working directory, so use an absolute path where that differs.

## Every Setting, Every Way

A setting has a name in each way of giving it. The builder's methods, the starter's properties, and the plugin's keys
all set the agent's config keys, the ones a config file holds. The agent reads each key's environment variable itself,
embedded or not:

| Setting                         | Builder                                             | Config key                                                                 | Starter property, plugin key                       | Environment variable                                   |
|:--------------------------------|:----------------------------------------------------|:---------------------------------------------------------------------------|:---------------------------------------------------|:-------------------------------------------------------|
| The proxy                       | `proxy(endpoints…)`                                 | `agent.proxy.endpoints`                                                    | `proxy`                                            | `PROXY_HOSTNAME`                                       |
| The token                       | `token(token)`                                      | `agent.agentToken`                                                         | `token`                                            | `AGENT_TOKEN`                                          |
| The proxy's certificate         | `trustCertificatePem(pem, authority)`               | `agent.tls.trustCertCollectionPem`, `agent.tls.overrideAuthority`          | `trust-certificate`, `authority`                   | `TRUST_CERT_COLLECTION_PEM`, `OVERRIDE_AUTHORITY`      |
| The agent's certificate and key | `clientCertificatePem(certChainPem, privateKeyPem)` | `agent.tls.certChainPem`, `agent.tls.privateKeyPem`                        | `client-certificate`, `client-key`                 | `CERT_CHAIN_PEM`, `PRIVATE_KEY_PEM`                    |
| The agent's name                | `name(name)`                                        | `agent.name`                                                               | `name`                                             | `AGENT_NAME`                                           |
| Consolidated mode               | `consolidated(consolidated)`                        | `agent.consolidated`                                                       | `consolidated`                                     | `CONSOLIDATED`                                         |
| Its metrics, on a port          | `agentMetrics(port)`                                | `agent.metrics.enabled`, `agent.metrics.port`                              | `metrics-port`                                     | `METRICS_ENABLED`, `METRICS_PORT`                      |
| Its metrics, through the proxy  | `agentMetricsAt(path, labels)`                      | `agent.metrics.proxyPath`, `agent.metrics.proxyPathLabels`                 | `metrics-proxy-path`, `metrics-proxy-path-labels`  | `METRICS_PROXY_PATH`                                   |
| Its direct dashboard            | `dashboard(port, host)`                             | `agent.dashboard.enabled`, `agent.dashboard.port`, `agent.dashboard.host`  | `dashboard.port`, `dashboard.host`                 | `DASHBOARD_ENABLED`, `DASHBOARD_PORT`, `DASHBOARD_HOST` |
| Its direct dashboard's login    | `dashboardLogin(password, username)`                | `agent.dashboard.password`, `agent.dashboard.username`                     | `dashboard.password`, `dashboard.username`         | `DASHBOARD_PASSWORD`, `DASHBOARD_USERNAME`             |
| Its direct dashboard's framing  | `setting("dashboard.framingEnabled", false)`        | `agent.dashboard.framingEnabled`                                           | `settings.dashboard.framingEnabled`                |                                                        |
| Its relayed dashboard           | `setting("dashboard.showOnProxy", false)`           | `agent.dashboard.showOnProxy`                                              | `settings.dashboard.showOnProxy`                   |                                                        |
| A target it scrapes             | `path(…)`, `scrapeSelf(…)`                          | `agent.pathConfigs`                                                        | `paths`                                            |                                                        |
| The app's registry              | `source(path, registry)`                            | none: it's code                                                            | `path` and `labels`, with the app's registry       |                                                        |
| Its stop's timeout              | `stopTimeout(timeout)`                              | none: it's the handle's                                                    | `stop-timeout`                                     |                                                        |
| Anything else                   | `setting(key, value)`                               | the key                                                                    | `settings.<key>`                                   | the key's, if it has one                               |

The starter serves the app's `PrometheusRegistry` bean at `path` unless its `source` is `none`. The plugin serves the
registry its install block gives. `fromEnvironment()`'s `PROMETHEUS_` variables are the app's, which only it reads
([Settings From the Environment](#settings-from-the-environment)). The variables above are the agent's own, which it
reads whether or not the app asks, so keep their names out of the app's environment unless you mean the agent to use
them.

Where one setting is given more than one way, the first of these that gives it wins:

1. **The agent's environment variable,** such as `AGENT_TOKEN`, read as the agent starts.
2. **`setting(key, value)`,** and the starter's and the plugin's `settings.<key>`, which call it.
3. **A builder method,** its last call; the starter's customizers and the plugin's install block run after the
   properties or the file, so their calls replace what those set.
4. **The built-in default** (see [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md)).

A config file or a `Config` takes the place of the second and third: its keys, then the defaults.

### Settings without a Builder Method

`setting(key, value)` sets any other setting by its key under `agent`, as the starter's and the plugin's
`settings.<key>` do. These are the ones an embedded agent most often needs:

| Config key                             | Default | What it sets                                                                                                           |
|:---------------------------------------|:--------|:-----------------------------------------------------------------------------------------------------------------------|
| `agent.scrapeTimeoutSecs`              | 15      | How long the agent waits for a target's answer, in seconds                                                             |
| `agent.scrapeMaxRetries`               | 0       | How many times it retries a failed scrape                                                                              |
| `agent.http.maxConcurrentClients`      | 1       | How many scrapes it runs at once; raise it when it scrapes several slow targets                                        |
| `agent.http.clientTimeoutSecs`         | 90      | Its HTTP client's timeout, in seconds                                                                                  |
| `agent.http.maxContentLengthMBytes`    | 10      | The largest scrape it takes, in megabytes                                                                              |
| `agent.http.trustStorePath`            | ""      | A trust store for HTTPS targets signed by a private CA, with `agent.http.trustStorePassword`                           |
| `agent.transportFilterDisabled`        | false   | Set it, as on the proxy, when [nginx fronts the proxy](https://prometheus-proxy.com/advanced/index.md#nginx-reverse-proxy)                                |
| `agent.admin.enabled`                  | false   | The admin endpoints, on `agent.admin.port`, and `/debug` with `agent.admin.debugEnabled` ([Admin and Debug Endpoints](https://prometheus-proxy.com/embedded-debugging/index.md#admin-and-debug-endpoints)) |
| `agent.logLevel`                       | ""      | The level of the agent's `io.prometheus` loggers, and no others; unset, they follow your application's logging ([Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging)) |
| `agent.metrics.standardExportsEnabled` | false   | The process metrics, one of the [JVM metric groups](https://prometheus-proxy.com/monitoring/index.md#jvm-metrics), which the agent's metrics port serves |

An embedded agent's JVM metrics are usually its app's, which its registry, such as Micrometer's, keeps and serves:
the agent's JVM metric groups add only to what its metrics port serves, and do nothing with the port off. A list or an
object, such as `filters` or `discovery`, is clearer in a config file or a `Config` (see
[A `Config` of Your Own](#a-config-of-your-own)); [Agent Configuration](https://prometheus-proxy.com/configuration/agent/index.md) describes every
setting.

## In Ktor

The [Ktor Plugin](https://prometheus-proxy.com/ktor-plugin/index.md) runs the agent in a Ktor app. `install(PrometheusProxyAgent)` starts it with the
app, stops it with the server, and serves the app's registry in-process.

## In Spring Boot

The [Spring Boot Starter](https://prometheus-proxy.com/spring-boot-starter/index.md) runs the agent in a Spring Boot app from a dependency and a few
properties, and reports its connection in Actuator's health. To wire the agent into the app yourself, see
[Without the Starter](https://prometheus-proxy.com/spring-boot-starter/index.md#without-the-starter).

## API Reference

[Embedded Agent API](https://prometheus-proxy.com/embedded-api/index.md) lists the methods and types:
[`Agent.startAsyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartasyncagent),
[`EmbeddedAgentConfig`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentconfig),
[`EmbeddedAgentInfo`](https://prometheus-proxy.com/embedded-api/index.md#embeddedagentinfo), and
[`Agent.startSyncAgent()`](https://prometheus-proxy.com/embedded-api/index.md#agentstartsyncagent).

## How It Works

When you call `startAsyncAgent()`:

1. The agent reads the configuration file, or the config you passed
2. Starts its admin, metrics, and dashboard servers, if enabled, and waits for them to come up
3. Returns with agent metadata, without waiting for a proxy connection
4. Connects to the proxy and registers paths in the background
5. Keeps running in the background, processing scrape requests

Your application code runs normally while the agent handles metrics scraping in the background.

??? info "The agent's metrics in your application's registry"

    With its metrics on, on their port (`agentMetrics(port)`, `agent.metrics.enabled`) or at a proxy path
    (`agentMetricsAt(path)`, `agent.metrics.proxyPath`), the embedded agent's metrics register in the Prometheus Java
    client 1.x default registry (`io.prometheus.metrics.model.registry.PrometheusRegistry.defaultRegistry`). A host
    that serves its metrics from that registry over HTTP exposes the agent's too, though the agent's
    `source(path, registry)` of it leaves them out; a host still on the 0.x client (`io.prometheus:simpleclient`) does
    not see them. Every agent in the JVM, two at once or one started again after `shutdown()`, shares one set of agent
    metrics, and each series carries the agent's `launch_id`. An agent's series go when it shuts down. A host metric
    with one of the agent metrics' names makes `startAsyncAgent()` throw.

## Logging

Your application configures the agent's logging, which goes through SLF4J. [Logging](https://prometheus-proxy.com/embedded-debugging/index.md#logging) says
how it goes with Logback, with another provider, and with none.

## Debugging

[Debugging an Embedded Agent](https://prometheus-proxy.com/embedded-debugging/index.md) shows how to see what the agent is doing: its admin and debug
endpoints, its dashboard, its log, and the proxy's view of it.

## Upgrading

What each release since 4.0 changed for code that embeds the agent, and what to do about it, is on
[Upgrading an Embedded Agent](https://prometheus-proxy.com/embedded-upgrading/index.md).
