Skip to content

Latest commit

 

History

History
1605 lines (1318 loc) · 68.2 KB

CLAXON.adoc

File metadata and controls

1605 lines (1318 loc) · 68.2 KB

SmallMind Claxon

The smallmind-claxon module is an in-process metrics framework: application code calls Instrument.with(…​).update(…​) (or runs a timed block through on(…​)), a background registry thread rolls up the aggregates on a fixed cadence, and one or more Emitter instances ship the resulting Quantity readings to whatever backend is configured — CloudWatch, Datadog, Prometheus, JMX, a log stream, or a REST endpoint.

It is organised as a single parent POM (smallmind-claxon) with four child modules — claxon-registry, claxon-emitter (itself six subprojects), claxon-http, and claxon-exotic:

  • claxon-registry — the core. Defines ClaxonRegistry, the Meter / MeterBuilder family, the Aggregate primitives, the @Instrumented AOP annotation and advice, the JSON parsers used by that annotation, the Spring factory beans, and the Instrument façade that lets call sites request a meter without holding a reference to the registry.

  • claxon-emitter-* — concrete Emitter implementations, one per backend (aws, datadog, jmx, message, noop, prometheus). Each is a separate Maven artifact that pulls in only the dependencies its backend needs.

  • claxon-http — a single JAX-RS resource, EmitterResource, that exposes pull-style emitters (like Prometheus) over HTTP at /org/smallmind/claxon/emitter/{name}.

  • claxon-exotic — extra Feature implementations that produce registry-level measurements without a caller. Today the module ships ProfileFeature, which samples fifteen JVM and OS metrics per cycle.

Instrumenting a Java service is usually a tradeoff between three things: the shape of the metric primitives the application programmer sees, the cost of producing a reading on the hot path, and the flexibility of the emission side. Most metric libraries pick two of the three. Claxon aims at all three and makes a specific set of design decisions to keep them compatible:

  1. Call-site simplicity without coupling to a backend. Application code writes Instrument.with(MyClass.class, new TallyBuilder()).update(1) and never references CloudWatch, StatsD, Prometheus, or JMX. The backend is selected entirely at registry-construction time by binding emitters.

  2. Separation of measurement, aggregation, and emission. The four layers — Aggregate (lock-free / fine-grained concurrency primitives), Meter (domain-level concepts like Tally/Gauge/Histogram), Emitter (format and transport), and ClaxonRegistry (lifecycle and dispatch) — are orthogonal. A new aggregate, meter, or backend can be added without touching the others.

  3. A fail-safe façade that never crashes the caller. Instrument.with(…​) returns an UnpluggedInstrumentation when no registry is installed, and the registry substitutes a NoOpMeter when its NamingStrategy rejects a caller. Code that records metrics cannot accidentally NPE or throw because metrics are misconfigured or not yet wired; only the install step, Instrument.register, throws, and only on a thread with no per-application binding.

  4. AOP for mechanical instrumentation. @Instrumented on a method or constructor turns into an around-advice that resolves a MeterBuilder from a JSON string at weave time and records execution time on every invocation, with both constant and parameter-derived tags, without the call site having to be aware of Claxon at all.

  5. Push-and-pull emission in the same registry. Some backends want data pushed to them on a schedule (CloudWatch, Datadog, JMX, a logger); others expect to scrape a process (Prometheus). Claxon models this explicitly with PushEmitter / PullEmitter subclasses and an EmitterMethod enum, so a single registry can drive both.

The resulting API is small enough to hold in your head: one façade class, six meter types, seven emitter types, two naming strategies, one annotation. Most of the rest is wiring.

  • Keeps a registry of live meters, keyed by (caller class, tag array). ClaxonRegistry.register(…​) is lazy and idempotent; meters are built on first access via a MeterBuilder and cached for all subsequent calls.

  • Runs one daemon thread per registry that wakes on ClaxonConfiguration.getCollectionStint(), sweeps tracked objects for garbage-collected referents, polls every configured Feature, polls every cached Meter, and dispatches the resulting Quantity[] to every bound Emitter.

  • Provides six meter types for the common shapes of numeric measurement: Tally (running counter), Gauge (min/max/average), Speedometer (min/max
    count/rate over a sliding window), Tachometer (count/rate only), Histogram (HdrHistogram-backed with percentiles), Trace (multi-window EWMA in the Unix load-average style).

  • Attaches tags at three levels — registry-wide (registryTags), per-meter (meterTags), and per-call-site (passed through Instrument.with(…​)) — and merges them in that order on every emission.

  • Ships AOP instrumentation (@Instrumented) that turns a single annotation into a timed-and-tagged meter, with constant tags, parameter-derived tags, configurable TimeUnit, and an on/off switch.

  • Ships Spring factory beans for every wiring point (ClaxonRegistryFactoryBean, StintFactoryBean, TagFactoryBean, plus one per emitter) so a typical application can assemble a registry entirely in XML.

  • Exposes pull emitters over HTTP via EmitterResource, making the Prometheus scrape endpoint a one-line bean declaration rather than a hand-rolled servlet.

  • It does not expose a distributed tracing API. The Trace meter name refers to EWMAs in the Unix-load-average sense, not to span/trace primitives.

  • It does not define a wire format of its own. Serialisation is the emitter’s responsibility — CloudWatch dimensions, StatsD counters and gauges, JMX attributes, Prometheus text exposition, or a plain Consumer<String>.

  • It does not store or query historical data. The registry is transient; every collection round is independent, and readings are forwarded, not archived.

  • It does not orchestrate multi-node aggregation. Each process runs its own registry; rollup across nodes is the backend’s job.

The registry carries the core concepts and all the code the other modules link against.

Class Role

ClaxonRegistry

Central hub. Schedules a daemon collection task on a single-thread ScheduledExecutorService at creation, caches meters keyed by (caller class, tag array), maintains a MeasurableTracker for weakly-referenced tracked objects, dispatches readings to every bound Emitter on every collection interval, and owns graceful shutdown via stop().

ClaxonConfiguration

Configuration bag. Supplies the Clock, the collection Stint, the termination Stint (the bounded wait stop() allows the collection worker), the optional Feature[], the three tag levels (registry-wide, per-meter, per-call), and the NamingStrategy. calculateTags(name, instanceTags…​) is the method that merges the three tag levels in order on each emission.

Instrument

Static façade over the registry. Instrument.register(registry) installs a registry per application through ClaxonRegistryManager (writing to the PerApplicationScope bound on the calling thread and to the PerApplicationContext attached to it — to both when both are present; lookups read the scope first); Instrument.with(caller, builder, tags…​) returns a working or unplugged Instrumentation depending on whether a registry has been installed.

ClaxonRegistryContextManager, ClaxonRegistryScopeManager

The per-application registry holders. The context flavor stores the registry in PerApplicationContext. The scope flavor has the same register / getRegistry API resolved through PerApplicationScope; it throws MissingPerApplicationScopeException on a thread that is not inside the scope’s run / call, a carrier, or a wrapThreadFactory thread. Instrument reads and writes through ClaxonRegistryManager, which bridges them: register writes to every registry bound on the calling thread (the scope flavor when a scope is bound, the context flavor when a context is attached), and getRegistry reads the scope flavor first, falling back to the context flavor when the scope holds nothing and a context is attached. On a thread with neither bound, getRegistry returns null — so Instrument.with hands back an UnpluggedInstrumentation and metrics never fail the caller — while register fails with MissingPerApplicationContextException. Registrations made from a thread that has both are therefore visible to threads that later carry only one of them.

Instrumentation / WorkingInstrumentation / UnpluggedInstrumentation

The fluent call-site API. update(value), on(executable), track(object, fn), as(TimeUnit). UnpluggedInstrumentation is a null object that still runs the caller’s executable — so on(…​) never silently skips work even when metrics are disabled.

Meter (and subtypes in meter/)

The aggregation shapes. Tally, Gauge, Speedometer, Tachometer, Histogram, Trace, plus the sentinel NoOpMeter.

MeterBuilder / MeterFactory / BuilderConstructor

The @FunctionalInterface that register(…​) uses to lazily build a meter on first access. MeterFactory adapts a BuilderConstructor (a Supplier<MeterBuilder<M>>) when each registration needs a freshly initialised builder, not a shared one.

Emitter / PushEmitter / PullEmitter / EmitterMethod

The transport contract. record(meterName, tags, quantities) is called on every interval for every meter. EmitterMethod labels whether an emitter is push- or pull-driven; push emitters receive each reading as it is collected, pull emitters buffer internally and expose an emit() method for external consumption.

Quantity / QuantityType

The wire unit. Quantity(name, value, type) — name identifies the reading within its meter (e.g. "count", "rate", "p99"), type is COUNT or NONE so that an emitter that distinguishes counters from gauges can pick the right API.

Tag

An immutable (key, value) pair. The constructor enforces that both components are non-null and non-empty; equality and hashing are over both.

Clock / SystemClock

Abstraction over System.currentTimeMillis() and System.nanoTime(). Replaceable for tests; every meter that needs a clock receives the one the registry was configured with.

NamingStrategy / ImpliedNamingStrategy / ObviousNamingStrategy

Maps caller classes to meter names. ImpliedNamingStrategy picks the strongest-matching DotNotation pattern and returns its associated prefix string. ObviousNamingStrategy uses the fully qualified class name itself, but only when the caller matches a whitelist pattern. Either may return null, which tells the registry to substitute a NoOpMeter and remember that decision forever for that key.

MeasurableTracker

Holds tracked objects in WeakReference`s. Each sweep polls the `ReferenceQueue, unregisters the meter for any collected referent, then applies the caller-supplied Function<T, Long> to every survivor and pushes the result into its meter.

Feature (in feature/)

Registry-level metric source with no caller — name, tags, and a record() method that returns a Quantity[]. Polled on every interval alongside the regular meters. Returning null or an empty array skips the cycle, which is how ProfileFeature implements its throttle.

Percentile / Window

JSON-carrier records for histogram percentiles (name, fractional value) and trace windows (name, numeric size). The @Doppelganger annotation makes them reachable from the JSON parsers.

These are the lock-free or fine-grained-locking primitives that sit under the meters. They are exposed as a package because they are independently useful: Bounded alone is a running min/max; Paced alone is a rate counter.

Aggregate Role

Tallied

Monotonic counter backed by AtomicLong.addAndGet. Retains state across reads; suitable for cumulative totals.

Averaged

Running arithmetic mean. Uses tryLock with a ConcurrentLinkedQueue overflow path so writers are wait-free when the lock is contended. Resets on each getAverage() call.

Bounded

Running minimum and maximum via paired LongAccumulator instances with an AtomicBoolean flip flag, so reads can toggle the active accumulator without blocking writes.

Paced

Count and rate over a sliding window. Uses a LongAdder for increments; getMeasurements() returns [count, rate] where rate = count * nanosecondsInWindow / elapsedNanos.

Stratified

HdrHistogram with double-buffered Recorder instances. update(value) is wait-free on the volatile write-recorder; get() swaps recorders and returns a HistogramTime carrying the snapshot together with the elapsedNanos / nominalWindowNanos time factor used to normalise rates.

ExponentiallyWeightedMovingAverage

Continuous-decay EWMA: average += (1 - exp(-elapsed/windowNanos)) * (instantaneousMean - average). First update seeds the average with the plain mean of the batch; subsequent updates apply the decay formula.

Pursued

A collection of EWMAs with one per configured window, evaluated in parallel. Default configuration matches Unix uptime — 1, 5, 15 minutes.

HistogramTime

Record: Histogram (HdrHistogram snapshot) + double timeFactor. Produced by Stratified.get() and consumed by Histogram.record() to scale counts to the nominal window.

The six concrete meter implementations, each with a corresponding MeterBuilder. Every meter accepts update(long) and returns a Quantity[] from record(); the differences are what they measure and what quantities they emit.

Meter Emits Aggregates

Tally

count

Tallied — running cumulative total; update adds a delta, record reads without resetting.

Gauge

minimum (when observed), maximum (when observed), average

Bounded + Averaged. Useful for arbitrary-valued samples (queue depth, CPU percent, payload size).

Speedometer

minimum, maximum, count, rate

Bounded (of the value) + Paced (of +1 per call). The value itself influences min/max but not the count — one call is one event.

Tachometer

count, rate

Paced only. Each update(value) is a single event; the argument is ignored. Cheapest way to count throughput.

Histogram

count, rate, minimum, maximum, mean, plus one quantity per configured Percentile (defaults: p75, p95, p98, p99, p999).

Stratified — HdrHistogram snapshot per collection interval. Default bounds are [1, 3_600_000] with two significant digits; the window is one second.

Trace

One quantity per Window (defaults: m1, m5, m15).

Pursued — a parallel collection of EWMAs. Default time unit for window sizes is minutes, matching Unix load averages.

AOP advice and annotation wiring, built on the dev.aspectj compile-time weaver configured in claxon/pom.xml.

Element Role

@Instrumented

Method/constructor annotation. Parameters: caller (class used for meter naming; default is the declaring type), parser (an InstrumentedParser implementation class), json (the string passed verbatim to the parser; default "{}"), constants (array of @ConstantTag), parameters (array of @ParameterTag), timeUnit (default MILLISECONDS), active (default true; false bypasses the advice with no overhead).

InstrumentedAspect

The around-advice. Pointcut: `(execution(@Instrumented * * (..))

initialization(@Instrumented new(..))) && @annotation(instrumented). On each invocation it builds the tag array, instantiates the parser via its no-arg constructor, produces a `MeterBuilder from the JSON, and delegates to Instrument.with(caller, builder, tags).as(timeUnit).on) → joinPoint.proceed(.

@ConstantTag / @ParameterTag

Nested-only annotations (@Target({})). @ConstantTag(key, constant) is a fixed string tag. @ParameterTag(key, parameter) pulls its value at each invocation via org.smallmind.nutsnbolts.reflection.aop.AOPUtility.getParameterValue, which accepts either a source-level parameter name or a zero-based index string.

InstrumentedParser<M>

@FunctionalInterface. parse(String json) → MeterBuilder<M>. Instantiated reflectively by the aspect on every call, so implementations must have a public no-arg constructor and should be inexpensive to construct.

InstrumentationException

RuntimeException wrapper thrown for unrecoverable parser/reflection failures inside the aspect.

Five ready-to-use InstrumentedParser implementations — one per configurable meter type — plus the @Doppelganger-generated view classes they read.

Parser Behaviour

GaugeParser / TallyParser

JSON is ignored; returns a default-constructed GaugeBuilder or TallyBuilder. The two meter types have no configurable knobs.

SpeedometerParser / TachometerParser

Deserialises a SpeedometerProperties / TachometerProperties; only resolutionStint is transferred (and only if non-null).

HistogramParser

Transfers lowestDiscernibleValue, highestTrackableValue, numberOfSignificantValueDigits, percentiles[], resolutionStint. Every field is optional.

TraceParser

Transfers windowTimeUnit, windows[]. Both optional.

The Stint and TimeUnit fields in the properties use StintXmlAdapter / TimeUnitEnumXmlAdapter to accept shorthand forms like {"time": 2, "timeUnit": "SECONDS"}.

The registry’s own Spring wiring. One FactoryBean per bean that cannot be configured with bean references alone.

Factory bean Produces

ClaxonRegistryFactoryBean

ClaxonRegistry singleton. afterPropertiesSet constructs the registry from the configuration property, iterates emitterMap calling registry.bind(name, emitter) on each entry, then calls registry.initializeInstrumentation() to install the registry as the per-application source for Instrument. destroy calls registry.stop() so Spring context shutdown drains the collection worker cleanly.

StintFactoryBean

Stint singleton from an injected time (long) and timeUnit (TimeUnit).

TagFactoryBean

Tag singleton from injected key and value. Fails fast at startup if either is null or empty.

Each emitter artifact is a self-contained jar that depends on claxon-registry and, where relevant, on one backend SDK.

Artifact Class Behaviour

claxon-emitter-aws

AWSEmitter (push)

Converts tags to CloudWatch Dimension[] and each Quantity to a MetricDatum with unit NONE; submits a single PutMetricData request per meter per collection cycle. CloudWatchClientFactory is a Spring FactoryBean that builds a CloudWatchClient from static access/secret keys and a Region.

claxon-emitter-datadog

DataDogEmitter (push)

Forwards to a non-blocking StatsD client at localhost:8125 by default. Quantities tagged QuantityType.COUNT are sent via StatsDClient.count when countAsCount is true (the default); everything else is sent via gauge. Tags are translated from key=value to the Datadog key:value format.

claxon-emitter-jmx

JMXEmitter (push)

Registers a MeterDynamicMbean in the supplied MBeanServer on first emission for each meter+tag combination; subsequent emissions update the MBean’s attributes in place. ObjectName domain is the meter name; key-properties are the tag set.

claxon-emitter-message

MessageEmitter (push)

Formats each reading as meterName[k1=v1, k2=v2].quantityName=value and passes it to a Consumer<String>. Default consumer is System.out::println. ScribeLoggerConsumer bridges the output to a Scribe logger at a configurable Level.

claxon-emitter-noop

NoopEmitter (push)

Discards every reading. Useful as a placeholder when metrics are disabled or during tests.

claxon-emitter-prometheus

PrometheusEmitter (pull)

Buffers readings in a ConcurrentHashMap<PrometheusKey, Double> with a double-buffered swap on every emit() call. Output is the Prometheus text exposition format, with # EOF sentinel and name/label mangling to [a-zA-Z_:][a-zA-Z0-9_:]*.

Single class: EmitterResource, a JAX-RS resource under /org/smallmind/claxon/emitter/{name}. Looks up the named emitter, verifies its method is PULL, and returns the result of emit() as an HTTP 200 body. Pushing emitters accessed through this endpoint raise InvalidEmitterException; missing ones raise UnknownEmitterException.

Currently ships one feature: ProfileFeature in the jvm sub-package. It reports fifteen JVM/OS quantities on each collection cycle (heapMemoryMax, heapMemoryUsed, youngCollectionCount, youngCollectionTime, processCPUTime, compilationTime, and so on) via a cluster of helper classes (JVMState, MemoryPools, OSFacts, GarbageFacts, CompilationAndHeapFacts) that resolve their MXBeans by name and fall back to zero-valued sentinels when a generational collector is not in use (e.g. ZGC, Shenandoah). An optional minimumRecordingDelayMilliseconds throttle has the feature return null (skipping the cycle) when called too soon after the previous emission.

A handful of terms show up throughout the module and are worth pinning down.

Meter

A stateful object that accepts update(long value) and produces a Quantity[] when the registry calls record(). The instance is keyed by (caller class, tag array) and is constructed lazily from a MeterBuilder on the first register for that key.

Aggregate

The low-level primitive inside a meter (Tallied, Bounded, Averaged, Paced, Stratified, Pursued, ExponentiallyWeightedMovingAverage). A single aggregate does one job well; a meter composes one or more of them to form a domain-level metric shape. The distinction matters for testing — aggregates are easy to unit-test in isolation — and for performance — aggregates use the most forgiving concurrency primitive that still guarantees no lost updates.

Emitter

A consumer of collected readings. PushEmitter.record(…​) is called on every collection interval by the registry’s worker thread for every meter that produced a non-empty reading. PullEmitter.emit() is called by whatever outside consumer wants the current buffer (typically Prometheus scraping claxon-http).

Collection stint

The interval between successive polls of the meters. Stint(time, TimeUnit) from smallmind-nutsnbolts is used throughout the module to carry scalar-plus-unit durations without losing precision. Default is 2 seconds.

Termination stint

The bounded time stop() waits for the background collection worker to terminate before throwing a TimeoutException. Default is 10 seconds; when set to null the registry falls back to five times the collection stint.

Naming strategy

The function that maps a caller class to a meter name. The registry asks the strategy exactly once per (caller, tags) key and caches the answer — including the negative answer — so a null return persists as a NoOpMeter entry in the noopSet for the life of the registry. Callers that should not be measured can therefore be silenced by the naming strategy alone, with no call-site changes.

Registry tag, meter tag, instance tag

Three orthogonal levels of tagging, merged in that order by ClaxonConfiguration.calculateTags(name, instanceTags…​). Registry tags apply to every reading; meter tags apply to every reading from the named meter; instance tags are supplied at each call site. The result is a single Tag[] passed to the emitter, so downstream code does not need to know how it was assembled.

Quantity

A single numeric measurement inside a meter. A meter emits several of them per reading (count, rate, p99, and so on). QuantityType.COUNT vs NONE allows emitters that distinguish counters from gauges (Datadog StatsD, Prometheus) to route each quantity correctly.

Unplugged instrumentation

The UnpluggedInstrumentation returned by Instrument.with(…​) when no registry has been installed, when the calling thread has neither a PerApplicationScope nor a PerApplicationContext binding, or when neither binding it has holds a registry. All metric-facing methods are no-ops, but on(executable) still runs the executable and propagates its result or exception. That keeps the call-site contract honest even when metrics are disabled.

Artifacts are published under org.smallmind with version ${project.version}.

An application always depends on claxon-registry (plus one or more emitter artifacts):

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>claxon-registry</artifactId>
  <version>${project.version}</version>
</dependency>

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>claxon-emitter-message</artifactId>                  (1)
  <version>${project.version}</version>
</dependency>
  1. Pick whichever emitter(s) match the backends you want to push to. The artifact ids are claxon-emitter-aws, claxon-emitter-datadog, claxon-emitter-jmx, claxon-emitter-message, claxon-emitter-noop, and claxon-emitter-prometheus. Each brings in only its own backend SDK.

Artifact Module name

claxon-registry

org.smallmind.claxon.registry

claxon-emitter-aws

org.smallmind.claxon.emitter.aws

claxon-emitter-datadog

org.smallmind.claxon.emitter.datadog

claxon-emitter-jmx

org.smallmind.claxon.emitter.jmx

claxon-emitter-message

org.smallmind.claxon.emitter.message

claxon-emitter-noop

org.smallmind.claxon.emitter.noop

claxon-emitter-prometheus

org.smallmind.claxon.emitter.prometheus

Optional add-ons:

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>claxon-http</artifactId>                             (1)
  <version>${project.version}</version>
</dependency>

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>claxon-exotic</artifactId>                           (2)
  <version>${project.version}</version>
</dependency>
  1. Adds EmitterResource for exposing pull emitters (typically Prometheus) over HTTP via JAX-RS.

  2. Adds ProfileFeature for JVM/OS metrics. The exotic module is weaved with the same AspectJ plugin as the registry, so it can be annotated with @Instrumented if a caller wants to measure its own sampling cost.

Artifact Module name

claxon-http

org.smallmind.claxon.http

claxon-exotic

org.smallmind.claxon.exotic

@Instrumented only works when AspectJ weaves InstrumentedAspect into the target classes. The project’s parent claxon/pom.xml already configures the dev.aspectj:aspectj-maven-plugin; inheriting that build section (or adding it explicitly) is what activates the advice. Without weaving, the annotation is inert — the method runs normally and no meter is produced.

The woven advice lands in your classes, so your application supplies org.aspectj:aspectjrt at run time; claxon-registry declares it optional and does not bring it.

  • claxon-registry pulls in HdrHistogram, jakarta.xml.bind-api, spring-beans, jackson-databind, and the SmallMind support libraries (scribe-pen, smallmind-nutsnbolts, and web-json-scaffold, which the generated JSON views use at runtime). web-json-doppelganger and jakarta.annotation-api are optional dependencies: the registry needs them only to build (the Doppelganger annotations and processor, and the source-retention @Generated on the generated views), so neither reaches your classpath.

  • claxon-emitter-aws brings in the AWS SDK v2 (cloudwatch, auth, regions, aws-core).

  • claxon-emitter-datadog brings in com.datadoghq:java-dogstatsd-client.

  • claxon-emitter-message brings in scribe-pen (only needed if you use ScribeLoggerConsumer; MessageEmitter itself has no logging dependency).

  • claxon-emitter-prometheus and claxon-emitter-jmx are SDK-free — they only depend on claxon-registry and, for Prometheus, smallmind-nutsnbolts.

Every Claxon artifact ships an explicit module descriptor under the name in the tables above, exporting all of its packages. On the classpath the descriptors are ignored. See Module Path And Classpath for the repository-wide rules.

For org.smallmind.claxon.registry:

  • It re-exports (requires transitive) org.smallmind.nutsnbolts, jakarta.xml.bind, and tools.jackson.databind, and requires org.smallmind.scribe.pen, org.smallmind.web.json.scaffold, and the automatic modules spring.beans and HdrHistogram. Automatic modules are never re-exported: a module that uses the Spring factory beans in org.smallmind.claxon.registry.spring also requires spring.beans, and one that calls the HistogramTime constructor or getHistogram() also requires HdrHistogram. That name is derived from the jar’s file name (the HdrHistogram jar declares none), so it changes if the jar is renamed.

  • org.aspectj.runtime, org.smallmind.web.json.doppelganger, and jakarta.annotation are requires static, matching their optional POM dependencies. An application that weaves @Instrumented requires org.aspectj.runtime itself.

  • It opens org.smallmind.claxon.registry unconditionally so classpath:org/smallmind/claxon/registry/claxon.xml stays loadable from other modules, org.smallmind.claxon.registry.json to jakarta.xml.bind and tools.jackson.databind for the generated *InView classes the meter parsers read, and org.smallmind.claxon.registry.spring to spring.core and spring.beans.

For the emitters and add-ons, each re-exports org.smallmind.claxon.registry (requires transitive), so requiring one artifact is enough to use the registry API:

  • org.smallmind.claxon.emitter.aws requires the AWS SDK automatic modules (software.amazon.awssdk.auth, .awscore, .regions, .services.cloudwatch) and spring.beans. AWSEmitter(CloudWatchClient, String) and CloudWatchClientFactory.setRegion(Region) expose SDK types, so a module that calls them requires software.amazon.awssdk.services.cloudwatch and software.amazon.awssdk.regions itself. It opens org.smallmind.claxon.emitter.aws to spring.core and spring.beans.

  • org.smallmind.claxon.emitter.datadog requires java.dogstatsd.client, a name derived from the jar’s file name (the DogStatsD jar declares none), and spring.beans. It opens org.smallmind.claxon.emitter.datadog.spring to spring.core and spring.beans.

  • org.smallmind.claxon.emitter.jmx and org.smallmind.claxon.exotic re-export java.management; claxon-exotic also requires jdk.management for the com.sun.management beans OSFacts reads.

  • org.smallmind.claxon.emitter.message re-exports org.smallmind.scribe.pen and opens org.smallmind.claxon.emitter.message.spring to spring.core and spring.beans; org.smallmind.claxon.emitter.noop opens org.smallmind.claxon.emitter.noop.spring the same way.

  • org.smallmind.claxon.emitter.prometheus requires org.smallmind.nutsnbolts.

  • org.smallmind.claxon.http re-exports jakarta.ws.rs and needs no opens: EmitterResource is public with public constructors and no injected fields. The host follows the web-jersey module-path rules in WEB.adoc.

  • A module that uses the Spring factory beans of any of these artifacts requires spring.beans itself, because automatic modules are never re-exported.

The smallest meaningful Claxon setup is four lines at startup, one line at each call site, and one bound emitter.

import org.smallmind.claxon.registry.ClaxonConfiguration;
import org.smallmind.claxon.registry.ClaxonRegistry;
import org.smallmind.claxon.emitter.message.MessageEmitter;
import org.smallmind.nutsnbolts.context.PerApplicationContext;

public class Startup {

  public static void main (String[] args) {

    ClaxonRegistry registry = new ClaxonRegistry(new ClaxonConfiguration());   (1)

    registry.bind("console", new MessageEmitter());                            (2)

    new PerApplicationContext();                                               (3)
    registry.initializeInstrumentation();                                      (4)
  }
}
  1. Constructs a registry with all defaults: SystemClock, a 2-second collection stint, a 10-second termination stint, no features, no tags, an ImpliedNamingStrategy with no prefix map.

  2. Binds an emitter. MessageEmitter without a consumer prints every reading to System.out.

  3. Attaches a PerApplicationContext to the thread. The install on the next line writes through ClaxonRegistryManager.register, which throws MissingPerApplicationContextException on a thread with neither a PerApplicationContext attached nor a PerApplicationScope bound, and a bare main has neither. Running the install inside scope.run(…​) works as well, but then every Instrument.with(…​) call site must run inside that same scope, or on a thread handed it, or it gets an UnpluggedInstrumentation. Containers that already attach a context (WebContextLoaderListener, the Tanuki wrapper) make this line unnecessary.

  4. Installs the registry in every per-application binding on the thread so that Instrument.with(…​) at a call site can find it. Skip this step and every call site gets an UnpluggedInstrumentation.

Note

The default ImpliedNamingStrategy has no prefix map, so the strategy will return null for every caller and every meter registration will turn into a NoOpMeter. A realistic startup either installs a prefix map on the strategy or swaps the strategy out entirely — see Naming strategies.

At each call site:

import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.Tag;
import org.smallmind.claxon.registry.meter.TallyBuilder;

public class RequestHandler {

  public void handle (String userId) {

    Instrument.with(RequestHandler.class, new TallyBuilder(),                  (1)
                    new Tag("userId", userId))                                 (2)
              .update(1);                                                      (3)
  }
}
  1. caller determines the meter’s name via the registry’s naming strategy.

  2. Tags are the dimensional metadata attached to every reading from this meter. Tags plus caller form the meter key — two calls with the same tags reuse the same meter; different tag values give you a distinct meter.

  3. For a Tally, update(1) adds 1 to a cumulative counter.

The equivalent XML form uses the factory beans:

<bean id="claxonRegistry" class="org.smallmind.claxon.registry.spring.ClaxonRegistryFactoryBean">
  <property name="configuration">
    <bean class="org.smallmind.claxon.registry.ClaxonConfiguration">
      <property name="collectionStint">
        <bean class="org.smallmind.claxon.registry.spring.StintFactoryBean">
          <property name="time" value="10"/>
          <property name="timeUnit" value="SECONDS"/>
        </bean>
      </property>
      <property name="registryTags">
        <list>
          <bean class="org.smallmind.claxon.registry.spring.TagFactoryBean">
            <property name="key" value="env"/>
            <property name="value" value="production"/>
          </bean>
        </list>
      </property>
      <property name="namingStrategy">
        <bean class="org.smallmind.claxon.registry.ImpliedNamingStrategy">
          <property name="prefixMap">
            <map>
              <entry value="app.request">
                <key>
                  <bean class="org.smallmind.nutsnbolts.util.DotNotation">
                    <property name="notation" value="com.example.request.*"/>
                  </bean>
                </key>
              </entry>
            </map>
          </property>
        </bean>
      </property>
    </bean>
  </property>
  <property name="emitterMap">
    <map>
      <entry key="console">
        <bean class="org.smallmind.claxon.emitter.message.MessageEmitter"/>
      </entry>
    </map>
  </property>
</bean>

Because ClaxonRegistryFactoryBean calls initializeInstrumentation() inside afterPropertiesSet, the registry is live as soon as Spring finishes constructing it. That install goes through ClaxonRegistryManager.register, so the thread refreshing the context must carry a binding — a PerApplicationContext attached (WebContextLoaderListener, the Tanuki wrapper, the testbench foundation) or a PerApplicationScope bound around the refresh; with neither, the refresh fails with a BeanCreationException caused by MissingPerApplicationContextException.

Instrumentation.on(…​) records the elapsed time around an executable. The unit is chosen via as(TimeUnit); the default is milliseconds.

import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.Tag;
import org.smallmind.claxon.registry.meter.HistogramBuilder;

public class DatabaseQuery {

  public List<Row> run (String sql)
    throws Throwable {

    return Instrument.with(DatabaseQuery.class, new HistogramBuilder(),       (1)
                           new Tag("table", tableOf(sql)))
                     .as(TimeUnit.MICROSECONDS)                                (2)
                     .on(() -> driver.execute(sql));                           (3)
  }
}
  1. A histogram produces count, rate, min, max, mean, and five default percentiles — the canonical instrumentation for a latency-sensitive operation.

  2. Override the reporting unit. The wall-to-wall duration is measured in nanoseconds via the registry’s Clock.monotonicTime() and converted to microseconds before being fed to the meter.

  3. WithResultExecutable<T>; use the overload without a return type for Runnable-style blocks.

Choose the meter type by what you want the backend to see.

// Cumulative counter — Datadog counter, Prometheus counter, CloudWatch total
Instrument.with(Orders.class, new TallyBuilder()).update(1);

// Throughput — count + rate, where rate is events per window
Instrument.with(Login.class, new TachometerBuilder()).update(0);

// Throughput plus value envelope — adds min/max of the recorded values
Instrument.with(Upload.class, new SpeedometerBuilder()).update(bytes);

TachometerBuilder and SpeedometerBuilder default to a 1-second window; pass .resolution(new Stint(5, TimeUnit.SECONDS)) to change it.

When the value you care about is already tracked by an object you control, use Instrumentation.track(object, fn) instead of pushing values by hand. The registry polls the function on every collection interval until the object is garbage-collected.

import java.util.concurrent.ArrayBlockingQueue;
import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.meter.GaugeBuilder;

public class WorkQueue {

  private final ArrayBlockingQueue<Task> queue;

  public WorkQueue () {

    queue = Instrument.with(WorkQueue.class, new GaugeBuilder())               (1)
                       .track(new ArrayBlockingQueue<>(1024),                  (2)
                              q -> (long)q.size());                            (3)
  }
}
  1. GaugeBuilder picks min/max/average. A TallyBuilder would give a running total; HistogramBuilder would give percentiles.

  2. track holds a WeakReference so it does not prevent the queue from being garbage-collected when the owning WorkQueue goes away. The method returns the queue unchanged to support fluent assignment.

  3. The function is sampled once per collection interval (2 seconds by default); it is not called on every queue operation.

@Instrumented turns mechanical timing into a one-line declarative statement. The parser class picks the meter type; the JSON string configures it.

import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.registry.aop.ConstantTag;
import org.smallmind.claxon.registry.aop.Instrumented;
import org.smallmind.claxon.registry.aop.ParameterTag;
import org.smallmind.claxon.registry.json.HistogramParser;

public class CheckoutService {

  @Instrumented(
    parser     = HistogramParser.class,                                        (1)
    json       = "{\"percentiles\":[{\"name\":\"p99\",\"value\":99.0}]}",     (2)
    constants  = {@ConstantTag(key = "service", constant = "checkout")},      (3)
    parameters = {@ParameterTag(key = "method", parameter = "paymentMethod")},(4)
    timeUnit   = TimeUnit.MILLISECONDS
  )
  public Receipt checkout (String userId, String paymentMethod) {

    // ... real work ...
  }
}
  1. Any InstrumentedParser implementation can be used here, including application-supplied ones. The built-in set is GaugeParser, TallyParser, SpeedometerParser, TachometerParser, HistogramParser, TraceParser.

  2. JSON configuration for the parser. Fields absent from the JSON retain builder defaults — so "{}" is always a legal value.

  3. Constant tags do not vary between calls.

  4. Parameter tags are resolved at each invocation. parameter can be a source-level name (requires -parameters at compile time or an ASM fallback) or a zero-based index string like "1".

A global kill switch:

@Instrumented(parser = GaugeParser.class, active = false)
public void hotPath () { ... }

With active = false, the aspect passes through with zero overhead.

Prometheus is a pull model: the emitter buffers, and an external scraper asks for the current payload. Claxon wires that with PrometheusEmitter plus EmitterResource:

<bean id="prometheusEmitter" class="org.smallmind.claxon.emitter.prometheus.PrometheusEmitter"/>

<bean id="claxonRegistry" class="org.smallmind.claxon.registry.spring.ClaxonRegistryFactoryBean">
  <!-- configuration omitted -->
  <property name="emitterMap">
    <map>
      <entry key="prometheus" value-ref="prometheusEmitter"/>                 (1)
    </map>
  </property>
</bean>

<bean id="claxonEmitterResource" class="org.smallmind.claxon.http.EmitterResource">  (2)
  <property name="registry" ref="claxonRegistry"/>
</bean>
  1. The binding key becomes the name in the HTTP path.

  2. The JAX-RS resource exposes every pull emitter registered under the given name. Wire it into your JAX-RS runtime the same way you wire any other resource.

A Prometheus scraper that hits /org/smallmind/claxon/emitter/prometheus receives output like:

com_example_request:count{env="production",userId="42"} 128
com_example_request:rate{env="production",userId="42"} 12.8
# EOF

JMXEmitter registers one MeterDynamicMbean per meter+tag combination and keeps its attributes in sync on every cycle.

import java.lang.management.ManagementFactory;
import org.smallmind.claxon.emitter.jmx.JMXEmitter;

ClaxonRegistry registry = new ClaxonRegistry(configuration);

registry.bind("jmx", new JMXEmitter(ManagementFactory.getPlatformMBeanServer()));
registry.initializeInstrumentation();

After this, any metric produced through the registry shows up as a dynamic MBean with one attribute per Quantity.getName(). ObjectName domains are the meter names; key-properties are the tags.

DataDogEmitter is push-only (UDP StatsD) and routes QuantityType.COUNT through StatsDClient.count; everything else goes through gauge.

import org.smallmind.claxon.emitter.datadog.DataDogEmitter;

Emitter emitter = new DataDogEmitter(
    "myapp",                 // prefix
    "localhost",             // agent host
    8125,                    // UDP port
    true);                   // COUNT-typed quantities as StatsD counters

registry.bind("datadog", emitter);

The constructor accepts an optional trailing Tag…​ constantTags varargs parameter; the four-argument form above simply omits it.

AWSEmitter takes a pre-built CloudWatchClient and a namespace. For a Spring application, wire both with CloudWatchClientFactory:

<bean id="cloudWatchClient"
      class="org.smallmind.claxon.emitter.aws.CloudWatchClientFactory">
  <property name="awsAccessKey" value="${aws.access.key}"/>
  <property name="awsSecretKey" value="${aws.secret.key}"/>
  <property name="region" value="#{T(software.amazon.awssdk.regions.Region).US_EAST_1}"/>
</bean>

<bean id="awsEmitter" class="org.smallmind.claxon.emitter.aws.AWSEmitter">
  <constructor-arg ref="cloudWatchClient"/>
  <constructor-arg value="MyApp/Production"/>
</bean>

Every collection cycle produces one PutMetricData call per meter+tag combination, batching all quantities for that meter into a single request.

ProfileFeature plugs into ClaxonConfiguration.setFeatures and runs alongside normal meters.

import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.exotic.jvm.ProfileFeature;
import org.smallmind.claxon.registry.ClaxonConfiguration;
import org.smallmind.claxon.registry.feature.Feature;
import org.smallmind.nutsnbolts.time.Stint;

ClaxonConfiguration configuration = new ClaxonConfiguration();

configuration.setCollectionStint(new Stint(5, TimeUnit.SECONDS));
configuration.setFeatures(new Feature[] {
    new ProfileFeature(
        "jvm.profile",                 // meter name
        30_000L,                       // minimum 30s between emissions
        true)                          // prepend host=<local hostname>
});

ClaxonRegistry registry = new ClaxonRegistry(configuration);

The resulting reading carries fifteen quantities per cycle (see the class Javadoc for the full list) under the meter name jvm.profile, with whatever registry/meter tags are in effect plus the automatic host tag.

InstrumentedParser is a @FunctionalInterface, so a custom parser can be a lambda — but @Instrumented needs a Class<? extends InstrumentedParser> with a no-arg constructor. In practice, custom parsers are tiny concrete classes:

public class FixedLoadAverageParser implements InstrumentedParser<Trace> {

  @Override
  public MeterBuilder<Trace> parse (String json) {

    return new TraceBuilder()
             .windowTimeUnit(TimeUnit.MINUTES)
             .windows(new Window[] {new Window("m1", 1), new Window("m30", 30)});
  }
}

NamingStrategy.from(Class<?>) returns the meter name for the caller or null to mean "don’t measure this caller". The registry remembers null answers in an internal noopSet, so a rejected caller is rejected forever for that tag combination — the strategy is not consulted again.

  • ImpliedNamingStrategy — scans a Map<DotNotation, String> and returns the string associated with the pattern that produces the highest positive match score against the caller’s fully qualified name. An empty or unset map rejects everything. A wildcard key (* notation) is a useful catch-all when you want the strategy to accept every caller but route unknowns to a single "unknown" namespace.

  • ObviousNamingStrategy — accepts the caller iff any whitelist pattern matches its name; returns the fully qualified name itself with $ replaced by .. Useful when the metric backend already has your package structure and you don’t want to invent a second one.

A typical mixed configuration keeps well-known namespaces under a friendly prefix and everything else under a single bucket:

Map<DotNotation, String> prefixMap = new LinkedHashMap<>();

prefixMap.put(new DotNotation("com.example.request.*"), "app.request");
prefixMap.put(new DotNotation("com.example.db.*"),      "app.db");
prefixMap.put(new DotNotation("*"),                     "app.other");

configuration.setNamingStrategy(new ImpliedNamingStrategy().setPrefixMap(prefixMap));

ClaxonConfiguration.calculateTags(name, instanceTags…​) produces the final Tag[] passed to the emitter. It concatenates, in order:

  1. registryTags (set on the configuration — applied to every reading).

  2. The meter-specific tags from meterTags.get(name) (set on the configuration — applied only when the resolved meter name matches).

  3. instanceTags (passed at the call site through Instrument.with(…​, tags)).

If all three levels are empty, calculateTags returns null rather than a zero-length array. That is what lets an emitter distinguish "no tags configured" from "tag set was explicitly emptied".

The registry keys meters on a composite of (caller class, tag array). Two registrations with the same caller class but different tag arrays produce two distinct meters. A typical mistake is to include a high-cardinality value (a user id, a session id, a UUID) as a tag; because every distinct value becomes a new meter, the registry’s map grows unboundedly. Use track(object, fn) for per-object metrics, or accept the cardinality tradeoff deliberately.

ClaxonRegistry.collect() is scheduled on a single-thread ScheduledExecutorService with scheduleWithFixedDelay, so it runs once per collectionStint (measured from the end of the previous pass). Each pass:

  1. Calls measurableTracker.sweepAndUpdate() — drains the weak-reference queue and pushes fresh measurements into every surviving tracked object’s meter.

  2. For each configured Feature, calls record(); if the result is non-null and non-empty, dispatches it to every bound emitter.

  3. For each cached meter, calls record(); if the result is non-null and non-empty, dispatches it to every bound emitter.

Exceptions raised by an individual emitter are caught and logged via scribe-pen; any other failure of the pass is caught and logged as a whole, so a single bad collection cannot cancel future runs. stop() calls shutdown() on the executor and then awaitTermination bounded by the configured termination stint; if the in-flight pass does not finish within that window, stop() throws a TimeoutException.

  • ClaxonRegistry, ClaxonConfiguration, MeasurableTracker, and the six built-in meters are safe for concurrent use from any thread. All mutation happens through ConcurrentHashMap, AtomicLong, LongAdder, LongAccumulator, ReentrantLock, or HdrHistogram’s Recorder.

  • The Averaged and ExponentiallyWeightedMovingAverage aggregates use tryLock + overflow queue so writers are non-blocking in the common case; queued values are folded in the next time the lock is available.

  • Stratified reads are serialised on this; writes are wait-free on the volatile writeRecorder.

  • Emitters are responsible for their own thread safety. The registry calls record from its worker thread only, so emitters that don’t maintain external state can rely on single-threaded invocation during the push path. PullEmitter implementations (e.g. PrometheusEmitter) additionally need to guard the pull path; the built-in Prometheus emitter uses a double-buffer swap plus a synchronized emit().

  • Instrument is backed by ClaxonRegistryManager, which registers into every PerApplicationScope or PerApplicationContext bound on the registering thread and resolves scope first, then context — one registry per application. That is the right boundary for OSGi, app-server, and multi-tenant deployments.

  • Pointcut is (execution || initialization) && @annotation. Both methods and constructors are advisable.

  • The parser is instantiated via its public no-arg constructor on every invocation. Parsers that do meaningful work on construction should be cheap, or the overhead will show up on the hot path. The built-in parsers are all trivial.

  • Tag array order is constants first, then parameters. If two tags share a key, both are emitted; the emitter decides how to resolve the collision (most backends accept duplicate keys).

  • Reflective failures (no-arg constructor missing, parse throws, parameter cannot be resolved) surface as InstrumentationException — an unchecked wrapper — rather than as checked exceptions in the caller’s signature.

QuantityType.COUNT is set by meters whose value is a cumulative event count: Tally.record emits a single count; Tachometer.record and Speedometer.record emit count; Histogram.record emits count. All other quantities use QuantityType.NONE. Emitters that distinguish counters from gauges (Datadog, Prometheus) inspect the type; emitters that don’t (AWSEmitter, JMXEmitter, MessageEmitter) ignore it.

The Prometheus text exposition format restricts metric and label names to [a-zA-Z_:]. PrometheusEmitter.mangle(…​) normalises the meter name, quantity name, and tag keys as follows: prepend when the first character is a digit, insert at every lower-to-upper transition while lowercasing the uppercase character itself (so httpRequests becomes http_requests), and substitute every non-alphanumeric character with _. Tag *values are not mangled, but they are quoted in the output (label="value").

PrometheusEmitter.record(…​) writes to a volatile writeMap; emit() is synchronized, swaps read and write maps, renders every entry in the new read map, and clears it. That means a scrape gets only the readings that arrived between it and the previous scrape. If your scrape interval is longer than your collection interval, intermediate readings for the same meter+tag+quantity key overwrite each other; that is by design for a pull-on-demand backend.

JMXEmitter.record(…​) checks server.isRegistered(objectName) and, when false, grabs the MBeanServer monitor with a double-checked locking pattern before registering a new MeterDynamicMbean. Unregistration is not automatic — MBeans linger until the process exits or the registry’s meter cache is evicted. If your callers produce unbounded tag values, you will accumulate JMX entries; treat this the same way you would treat any other high-cardinality-tag issue.

A Feature can return null from record() to skip an interval without producing a reading. ProfileFeature uses this to cap emission frequency independently of the registry’s collection stint: set minimumRecordingDelayMilliseconds to a value larger than the stint, and the feature will quietly drop cycles in between. The registry treats null and zero-length arrays equivalently: neither reaches the emitter.

The module distinguishes three broad groups of failure.

Call-site failures

IllegalArgumentException from new Tag(key, value) when either component is null or empty — surfaced at startup or when tags are built dynamically. The constructor fails fast; there is no silent coercion.

Registry / configuration failures

No dedicated exception type — misconfiguration (missing naming strategy, empty prefix map, forgotten initializeInstrumentation() call) shows up as "my metrics aren’t appearing". The registry does not throw for these cases; callers of Instrument.with(…​) receive an UnpluggedInstrumentation or a NoOpMeter and keep running. The one install-time exception: initializeInstrumentation() (and so Instrument.register) on a thread with neither a PerApplicationContext attached nor a PerApplicationScope bound throws MissingPerApplicationContextException.

Emitter failures

Emitter implementations may throw any checked or unchecked exception from their record(…​) method — the signature allows throws Exception so backend-specific exceptions can propagate without wrapping. The registry’s collection worker catches every exception from an emitter, logs it through scribe-pen at ERROR, and continues. The worker thread never exits because an emitter misbehaves.

HTTP endpoint failures

EmitterResource raises UnknownEmitterException when no emitter is bound under the requested name, and InvalidEmitterException when the emitter is not of type PULL. Both extend FormattedException so diagnostic context (the missing name or the actual method) can be embedded in the message without a separate String.format call at the throw site. Map both to HTTP 404 / 400 in the JAX-RS layer.

AOP failures

InstrumentationException (a RuntimeException) wraps reflective or JSON-parse errors from inside the aspect. The advised method itself never sees this exception path — it is raised only when the aspect cannot assemble its metering apparatus.

Setting Default Source

ClaxonConfiguration.clock

SystemClock singleton

ClaxonConfiguration field initialiser

ClaxonConfiguration.collectionStint

new Stint(2, SECONDS)

ClaxonConfiguration field initialiser

ClaxonConfiguration.terminationStint

new Stint(10, SECONDS)

ClaxonConfiguration field initialiser

ClaxonConfiguration.registryTags

empty Tag[]

ClaxonConfiguration field initialiser

ClaxonConfiguration.namingStrategy

new ImpliedNamingStrategy() with no prefix map

ClaxonConfiguration field initialiser

HistogramBuilder.lowestDiscernibleValue

1

HistogramBuilder

HistogramBuilder.highestTrackableValue

3_600_000 (one hour in ms)

HistogramBuilder

HistogramBuilder.numberOfSignificantValueDigits

2

HistogramBuilder

HistogramBuilder.resolutionStint

new Stint(1, SECONDS)

HistogramBuilder

HistogramBuilder.percentiles

p75, p95, p98, p99, p999

HistogramBuilder.DEFAULT_PERCENTILES

SpeedometerBuilder.resolutionStint

new Stint(1, SECONDS)

SpeedometerBuilder

TachometerBuilder.resolutionStint

new Stint(1, SECONDS)

TachometerBuilder

TraceBuilder.windowTimeUnit

MINUTES

TraceBuilder

TraceBuilder.windows

m1, m5, m15

TraceBuilder.DEFAULT_WINDOWS

DataDogEmitter default agent

localhost:8125, countAsCount=true, no prefix

DataDogEmitter() no-arg

WorkingInstrumentation.timeUnit

MILLISECONDS

WorkingInstrumentation

@Instrumented.timeUnit

MILLISECONDS

Instrumented annotation default

@Instrumented.json

"{}"

Instrumented annotation default

@Instrumented.active

true

Instrumented annotation default

Registry lifecycle

Construct once at startup; call initializeInstrumentation() before any Instrument.with(…​) call runs. Call stop() during shutdown so the collection worker exits cleanly and any in-flight emitter receives a final flush opportunity. stop() shuts the executor down and waits up to the configured termination stint for the in-flight pass to finish, throwing TimeoutException if it does not; it also propagates InterruptedException if the caller is interrupted while waiting. ClaxonRegistryFactoryBean.destroy() does this for Spring contexts.

Background thread naming

The collection executor’s worker is created through a ThreadFactory that names it claxon-collection and marks it a daemon, so it appears under that name in thread dumps.

Choosing between push and pull

CloudWatch, Datadog, JMX, and the message emitter are push. Prometheus is pull. You can bind several emitters of either kind simultaneously — the collection loop forwards the same readings to all of them. The trade-off is not exclusive.

High-cardinality tags

The registry’s meter map keys on the whole tag array. A tag whose value is effectively unbounded (user id, UUID, incoming URL) will cause unbounded meter creation. If that’s what you want (for example for a small whitelisted set of users), fine — otherwise keep tags coarse.

Precision of Stratified

HdrHistogram allocates memory proportional to log(highestTrackableValue / lowestDiscernibleValue) * significantDigits. The default [1, 3_600_000] with two digits is a comfortable choice for millisecond latencies. If you record nanosecond values, bump highestTrackableValue or you’ll overflow.

Prometheus output inclusion in Spring context

claxon.xml (under claxon-registry/src/main/resources/spring/org/smallmind/claxon/registry/) ships an example Spring configuration that declares a claxonRegistry bean and a claxonEmitterResource pointing at it. It is intended as a reference, not a drop-in import — real applications will want to customise the naming strategy, tags, and emitter set rather than inherit the placeholder values in the example.

Readings never appear in the backend

Check, in order: (a) that registry.initializeInstrumentation() was called — otherwise Instrument.with(…​) returns UnpluggedInstrumentation and every update is silently discarded; (b) that the recording thread carries a binding whose registry was written — a thread with neither a PerApplicationScope nor a PerApplicationContext, a scope the install never ran inside, or a context attached after the install all make Instrument.with(…​) return UnpluggedInstrumentation silently; Claxon logs nothing. The phalanx transports and MockMessageRouter (when constructed) and the quorum ComponentPool (when started) adopt the scope bound on that thread if they were given none, so their worker threads record through the registry the install wrote into that scope; (c) that the naming strategy does not return null for the caller class — drop a breakpoint in ImpliedNamingStrategy.from or switch to ObviousNamingStrategy with a permissive whitelist to confirm; (d) that at least one Emitter is bound; (e) that the collection stint has had time to elapse since the first update.

Every caller is measured into the same meter

You’ve only mapped new DotNotation("*") to a single prefix and your callers aren’t providing distinct tags. Either add caller-specific entries to the prefix map, or use ObviousNamingStrategy so each class gets its own fully-qualified meter name.

IllegalArgumentException: Both key and value must be neither null nor empty

Raised by new Tag(key, value). Check the tag construction path — a @ParameterTag whose parameter resolves to null, or a Spring TagFactoryBean with an unresolved ${} placeholder, will hit this.

@Instrumented annotation appears to do nothing

AspectJ weaving did not run. Inherit the claxon/pom.xml build section or add dev.aspectj:aspectj-maven-plugin to your build directly, with claxon-registry listed as a weaveDependency. Without the weaver, @Instrumented is just metadata.

MeterDynamicMbean registrations accumulate in JMX

You are emitting tags with unbounded values. JMXEmitter never evicts an MBean once registered; the remedy is to constrain tag cardinality on the call side. ClaxonRegistry.unregister(caller, tags) is available if you need to remove a specific meter (and by extension, trigger JMX cleanup on the next emission of a different-tagged reading from the same caller — the MBean is still there until you restart).

Prometheus scrape output has garbled metric names

Your caller name or tag key contains characters outside [A-Za-z0-9]. PrometheusEmitter.mangle converts them to _; if you want deterministic names, choose a naming strategy whose output is already Prometheus-legal.

Histogram.record() returns NaN for minimum/maximum

HdrHistogram’s getMinValue and getMaxValue produce Long.MAX_VALUE and 0 for empty intervals, which cast to Double.MAX_VALUE and 0.0 in the Quantity. Treat any minimum/maximum from an interval with count == 0 as an absent measurement, regardless of the numeric value.

Single-process scope

One ClaxonRegistry covers one JVM process. Cross-process rollup is the backend’s job. A registry is installed per PerApplicationContext / PerApplicationScope binding, so each application sharing a JVM can host its own registry, but they do not share state.

Meter eviction

The registry evicts a meter only when an application explicitly calls unregister(caller, tags) or when a tracked object is garbage-collected (via MeasurableTracker). Meters built for one-off tag values are not reclaimed automatically.

No typed boolean or string tag system for @Instrumented

Both @ConstantTag and @ParameterTag produce string-valued tags. @ParameterTag calls toString() on the resolved argument; any complex object is serialised with its default toString unless you override it. For controlled formatting, use call-site Instrument.with(…​) and construct the Tag explicitly.

@Instrumented parser construction on every call

The aspect instantiates the parser via reflection on every intercepted call. The built-in parsers are stateless and trivial, but application code that supplies a heavy parser (for example, one that loads configuration from disk) will pay that cost per invocation. Cache externally if the parser does real work.

ProfileFeature duplicate-entry bug

In the current record() implementation, the three memory-pool quantities edenMemoryUsed, survivorMemoryUsed, and tenuredMemoryUsed are all sourced from JVMState.getCompilationTime() instead of the corresponding memory-pool accessors. Treat those three quantities as unreliable until fixed; heapMemoryMax, heapMemoryUsed, and the GC counters are correct.

No built-in rate-limiting or back-pressure on emitters

If an emitter is slower than the collection stint, the worker thread blocks on it, deferring the next cycle. Network-bound emitters (CloudWatch, Datadog) should use SDKs that buffer asynchronously — both built-in emitters already do so.

Claxon is a small, opinionated metrics framework made of four moving parts: a registry that polls on a fixed cadence, a family of meter types composed out of concurrency-friendly aggregates, a static façade that lets call sites request instrumentation without holding a registry, and a set of emitter artifacts that each bind the registry to a specific backend. The registry is stable across call sites (same (caller, tags) means the same meter instance), fail-safe at the edges (no registry means UnpluggedInstrumentation; no name means NoOpMeter), and emitter-agnostic at the core — a single application can bind JMX, CloudWatch, Prometheus, and a log stream to the same registry and have every meter reach all of them on every cycle. Pick the meter type that matches the shape of the reading, pick the emitter that matches the backend, and leave the collection loop to take care of the rest.