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.
Register a loop on the Boot with b.Loop(name, background.Options, func):
b.Loop("sweeper", background.Options{Interval: 50 * time.Millisecond, Gate: gate}, func(ctx context.Context, _ background.Tick) error { <-ctx.Done() return nil })The task gets a context, cancelled when the application shuts down or a gate loses its lock, and a
background.Tick with Loop, Run (counting from 1) and Fence() (the fencing token when a lock
gate admitted the run). A long task checks the context and returns. The options are:
| Option | Meaning |
|---|---|
Interval |
the wait after a run ends before the next starts: 10 ms to 24 h |
InitialDelay |
the wait before the first run (default none) |
Gate |
decides before each run whether it may run (nil: always) |
Critical |
makes the background:<name> health check critical |
DownAfter |
consecutive failed runs that make the check down: 1 to 1000, zero means 3 |
StuckAfter |
makes the check down while one run lasts longer than this |
- 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
launchnever starts loops. - Schedule. The interval is a fixed delay: the next run starts
intervalafter the previous one ended, so runs never overlap. Intervals are 10 ms to 24 h. In Java that isLoopOptions.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.
Health
Section titled “Health”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).
One replica at a time: the lock gate
Section titled “One replica at a time: the lock gate”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.
gate, err := locks.ServiceGate(all, "sweeper", 5*time.Second)locks.ServiceGate(all, name, lease) gates on the default lock store with the service key name;
locks.NewGate(lock, key, lease) takes any lock and key. A gate implements background.Gate and
decides each run: Ran, Skipped 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.
Metrics
Section titled “Metrics”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 exportedcounter.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.
b.Metrics() is the application’s *metrics.Registry (never global):
orders, err := reg.Counter("app_orders_total", "Orders placed.", "kind")orders.With("web").Inc()
jobs, err := reg.TimerWithBuckets("app_job_seconds", "Job time.", []float64{0.1, 1.0}, "job")jobs.With("export").Record(50 * time.Millisecond)
err = reg.GaugeFunc("app_pool_size", "Pool size.", func() float64 { return float64(depth.Load()) })The instruments are Counter (Inc, Add), Gauge (Set, Add), GaugeFunc (read when exported)
and Timer (Record); each family has With(values...) for a series. Go has no removeSeries
equivalent.
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_]*, notle,quantileor 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.
Drivers
Section titled “Drivers”app.metrics.driver |
Behaviour |
|---|---|
memory (default) |
in-process; a snapshot and the Prometheus endpoint read it |
noop |
records nothing; names are still checked |
Built-in metrics
Section titled “Built-in metrics”| 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.
The Prometheus endpoint
Section titled “The Prometheus endpoint”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/metricsWith 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"} 1Without the HTTP module, serve it yourself: MetricsEndpoint.handler(metrics, token) in Java,
metrics.Handler(registry, bearerToken) in Go. See also HTTP.
Testing
Section titled “Testing”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).
metrics.NewRegistry(metrics.WithMaxSeries(n)) is a plain registry for a unit test; read it with
Snapshot(). For loops, build the loops with background.NewLoops(logger, registry, clock), or start a
real application and wait for a condition.