Skip to content

Background work and metrics

Two things every service needs, owned by the framework: loops that run work again and again (a sweeper, a retry pass, a cache refresh) and metrics (counters, gauges, timers, a Prometheus endpoint). Both are part of the core and always available. The normative rules are in the background and metrics specification.

A loop is a named task the framework runs on a schedule, with health, metrics, graceful shutdown and an optional lock so that only one replica does each run.

Register a loop in boot (or later) through app.get(Background.class):

app.get(Background.class)
.loop(
"flaky",
LoopOptions.every(FAST).downAfterFailures(3),
tick -> {
if (fail.get()) {
throw new IllegalStateException("secret detail: password=hunter2");
}
});

The task gets a LoopTick: loop(), run() (1, 2, …), fencingToken() (present when a lock gate admitted the run) and stopping(), which turns true when shutdown begins; a long run should check it and return.

  • Names match [a-z][a-z0-9-]* (at most 100 characters) and are unique.
  • When it runs. Loops registered during start-up begin only after every module has started, so a loop never sees a half-started application; one registered later begins at once. In Java, a command run through launch never starts loops.
  • Schedule. The interval is a fixed delay: the next run starts interval after the previous one ended, so runs never overlap. Intervals are 10 ms to 24 h. In Java that is LoopOptions.every(interval) with .initialDelay(d).
  • A failed run is logged at ERROR and counted; the loop carries on. In Java an exception is a failed run and an Error (out of memory, stack overflow) ends the loop. In Go a returned error is a failed run and a panic is recovered, logged, and ends the loop with its health check down.
  • Shutdown. Loops stop first, before any module’s shutdown hook. A waiting loop ends at once; a running task gets app.shutdown.drain, then it is interrupted (Java) or left behind with a warning.

Each loop adds the check background:<name>. It is Down when the last N runs (default 3) all failed, when the loop ended abnormally, or, with a stuck threshold (.stuckAfter(d) in Java, StuckAfter in Go), while one run lasts longer than that. In Java the reason names the exception class only, never its message, because health is served without authentication.

The check is informational by default (reported, never makes the application not ready); mark the loop critical (.critical() in Java, Critical: true in Go) to make it decide readiness. app.health.critical and app.health.informational override either way (see health checks).

With several replicas, each runs every loop. To have only one do each run, gate the loop with a lock (see Locks).

bg.loop(
name,
LoopOptions.every(Duration.ofMillis(10))
.gatedBy(LockGate.service(app.get(Locks.class), "sweeper", Duration.ofSeconds(5))),
tick -> {
assertThat(tick.fencingToken()).isPresent();
// ... the work
});

LockGate.of(store, key, lease) takes any store and key. A gate is a LoopGate: enter(loop, work) returns Ran, Skipped(reason) or Lost.

Each run takes the lock with a wait of zero: if another replica holds it, this run is skipped (not delayed) and counted as skipped. While the run lasts the lease is refreshed (every third of it). If the lock is lost mid-run, the task is interrupted (Java) or its context cancelled (Go) and the run counts as lost (a failure for health): it ran without exclusion. Pass the fencing token to whatever the run writes so a write from a run that lost its lock can be refused. A lock store that is down is a failed run.

A loop that works per client does the fan-out inside its tick: see Context.

An instrument is a family with fixed label names; you ask for the series for a set of label values and record on it, and may keep the series for hot paths. A family without labels records directly.

Counter c = metrics.counter("app_orders_total", "Orders placed.", "kind");
c.labels("web").inc();
Timer t = metrics.timer("app_job_seconds", "Job time.", List.of(0.1, 1.0), "job");
t.labels("export").record(Duration.ofMillis(50));
metrics.gauge("app_pool_size", "Pool size.", depth::get); // read when exported

counter.inc(), gauge.set(v) and timer.record(d) work directly on a family without labels. A timer’s series also has time(callable), which records even when the work throws.

A label value that will never be recorded again (a closed client, a finished tenant) is dropped with counter.removeSeries("label", "value") (also on Timer), which returns how many series it removed and frees their share of app.metrics.max-series. A series handle kept from before is detached: ask labels(...) again to start a new series.

Checked when the instrument is created (an error from the constructor, in Java an IllegalArgumentException, is a bug in your code):

  • names [a-z][a-z0-9_]*, at most 200 characters; counters end in _total, timers in _seconds (they record seconds), gauges in neither. Prefix with your component (orders_); fw_ is the framework’s.
  • help text 1 to 500 characters; at most 10 label names, [a-z][a-z0-9_]*, not le, quantile or starting with __;
  • creating an instrument again with the same definition returns the same family; a different help, type, labels or buckets for the same name is refused.

At run time recording never throws for a label value: null becomes empty and values longer than 200 characters are cut. Only a wrong number of values is an error.

Cardinality is bounded. A family holds at most app.metrics.max-series series (default 1000, range 1 to 100 000). Past that, recordings for new label combinations are dropped, counted in fw_metrics_dropped_series_total{metric="..."}, and logged once. So never use ids, request paths, user input or exception messages as label values.

app.metrics.driver Behaviour
memory (default) in-process; a snapshot and the Prometheus endpoint read it
noop records nothing; names are still checked
Name Type Labels
fw_http_server_requests_total counter method, route, status
fw_http_server_request_duration_seconds timer method, route
fw_usecase_runs_total counter usecase, outcome (committed or the failure kind: validation, authorization, not_found, conflict, business_rule, internal)
fw_usecase_duration_seconds timer usecase (all attempts)
fw_background_runs_total counter loop, outcome (success, failure, skipped, lost)
fw_background_run_duration_seconds timer loop (skipped runs are not timed)
fw_metrics_dropped_series_total counter metric

route is the matched route pattern (/orders/{id}), or <unmatched>, so a scan of random paths cannot create series.

Off by default; metrics reveal routes and volumes, so exposing them is your decision. The HTTP module mounts it:

Key Default Meaning
http.metrics.enabled false mount the endpoint
http.metrics.path /metrics literal segments, no trailing slash
http.metrics.bearer-token none a secret, from the environment (HTTP_METRICS_BEARER_TOKEN)
http:
metrics:
enabled: true
path: /internal/metrics

With a token set, scrapes need Authorization: Bearer <token> (compared in constant time); otherwise 401. Start-up warns when the endpoint is enabled without a token, or with the noop driver. The body is the Prometheus text format 0.0.4; timers appear as histograms (_bucket, _sum, _count). Java and Go write the same text byte for byte (numbers in Java’s Double.toString form), checked by a conformance vector.

fw_http_server_requests_total{method="GET",route="/ping",status="200"} 1

Without the HTTP module, serve it yourself: MetricsEndpoint.handler(metrics, token) in Java, metrics.Handler(registry, bearerToken) in Go. See also HTTP.

Metrics.memory(maxSeries, clock) is a plain registry you can create in a unit test and read with snapshot(); TestClient.of(routes, resolver, metrics) records the request metrics into it. To replace the registry in an application test use AppBuilder.override(Metrics.class, ...) (see Testing). For loops, start a real App and wait for a condition (the loop runs on real time).