This guide explains how Kill Bill produces metrics and health checks, which integrations already exist, and how to connect Kill Bill to other monitoring stacks, such as OpenTelemetry, Azure Monitor / Application Insights, Google Cloud Monitoring or any other backend.

AWS-specific instructions (CloudWatch, Datadog and New Relic on the Kill Bill AMI) are covered separately in the AWS section (see See also).

Architecture

Kill Bill’s metrics stack has three layers. Knowing which layer does what makes it easy to plug in a new backend.

  Kill Bill core + plugins
  (@Timed, @Counted, @Metered, @Gauge, explicit registry calls)
              │
              ▼
  ┌──────────────────────────────┐
  │ metrics-api (interfaces)     │   killbill-commons/metrics-api
  └──────────────────────────────┘
              │  proxy in core, resolved through OSGi
              ▼
  ┌──────────────────────────────┐
  │ killbill-metrics bundle      │   killbill-platform/osgi-bundles/bundles/metrics
  │ Dropwizard MetricRegistry    │   + JVM metrics, JMX reporter, deadlock health check
  └──────────────────────────────┘
              │  shared OSGi service (org.killbill.commons.metrics.api.MetricRegistry)
     ┌────────┼──────────────┬───────────────┐
     ▼        ▼              ▼               ▼
    JMX   prometheus      influxdb        graphite      ... your own reporter bundle
          (pull, HTTP)    (push)          (push)

The metrics API

The metrics-api module (in killbill-commons) defines the interfaces that Kill Bill and plugins write to: MetricRegistry, Counter, Gauge, Histogram, Meter, Timer and HealthCheck, plus the @Timed, @Counted, @Metered, @ExceptionMetered and @Gauge annotations. It has no dependency on any metrics library.

The implementation

The metrics module (also in killbill-commons) is based on Dropwizard Metrics. It contains:

  • Adapters between the Kill Bill API and Dropwizard (KillBillCodahaleMetricRegistry, CodahaleMetricRegistry, …​).

  • The Guice AOP instrumentation (a fork of metrics-guice) that records the annotated methods.

  • The servlets behind the /1.0/metrics and /1.0/healthcheck endpoints, the thread dump servlet, and a servlet filter that times each HTTP request.

OSGi wiring

Kill Bill core does not own a metrics registry. It uses a proxy that forwards every call to the MetricRegistry service registered in the OSGi container by a platform bundle:

  • If no registry is registered, all metrics are silently dropped. The base killbill-metrics bundle must be installed for any metric to be recorded.

  • Only one registry can be registered. Any later registration is ignored and a warning is logged.

Platform bundles are OSGi jars placed in the platform sub-directory of the bundle install directory (property org.killbill.osgi.bundle.install.dir, /var/tmp/bundles by default, so /var/tmp/bundles/platform/). They are published to Maven Central as org.kill-bill.billing:killbill-platform-osgi-bundles-<name>. Make sure the version you pick matches your Kill Bill version (the killbill-platform version used by your Kill Bill release).

Existing integrations

Bundle Model What it does

metrics

Base (required)

Creates the Dropwizard registry and shares it with Kill Bill and the plugins. Adds JVM metrics (gc., memory., threads., buffers., classloading.). Exposes all metrics as *JMX MBeans. Adds a thread-deadlock health check.

prometheus

Pull

Serves all metrics in the Prometheus text format at http://<host>:<port>/plugins/killbill-prometheus.

influxdb

Push

Sends metrics to InfluxDB (1.x or 2.x) at a fixed interval. Configured with the org.killbill.metrics.influxDb* properties (see below).

graphite

Push

Sends metrics to a Graphite server at a fixed interval.

In addition, Kill Bill always exposes:

  • GET /1.0/metrics: a JSON dump of the whole registry, useful for ad-hoc inspection.

  • GET /1.0/healthcheck: aggregated health checks. Use it in load balancer and Kubernetes probes.

Prometheus

Install killbill-platform-osgi-bundles-metrics and killbill-platform-osgi-bundles-prometheus in the platform bundle directory and restart Kill Bill. Then scrape the endpoint:

scrape_configs:
  - job_name: killbill
    scrape_interval: 30s
    scrape_timeout: 25s
    metrics_path: /plugins/killbill-prometheus
    static_configs:
      - targets: ['<killbill-host>:8080']

The Prometheus endpoint is also the easiest way to reach any backend that can scrape Prometheus, which today means almost all of them, OpenTelemetry Collector included (see A. OpenTelemetry Collector scraping Prometheus).

InfluxDB

Install killbill-platform-osgi-bundles-metrics and killbill-platform-osgi-bundles-influxdb, then set:

org.killbill.metrics.influxDb=true
org.killbill.metrics.influxDb.host=localhost
org.killbill.metrics.influxDb.port=8086
org.killbill.metrics.influxDb.senderType=HTTP
org.killbill.metrics.influxDb.interval=30
# InfluxDB 1.x
org.killbill.metrics.influxDb.database=killbill
# InfluxDB 2.x
org.killbill.metrics.influxDb.organization=killbill
org.killbill.metrics.influxDb.bucket=killbill
org.killbill.metrics.influxDb.token=<token>
# Optional prefix for every metric name
org.killbill.metrics.influxDb.prefix=

JMX

With the base metrics bundle installed, every metric is also an MBean on the platform MBean server. You can browse them with VisualVM or jconsole (see the debugging guide to enable remote JMX). Any agent that reads JMX, such as the Datadog, New Relic or Azure Application Insights Java agents or the Prometheus JMX exporter, can collect them.

What to monitor

Beyond JVM and HTTP metrics, these Kill Bill-specific signals matter most in production:

  • Bus and notification queues. The bus_events table should almost always be empty, and the notifications table should never hold an AVAILABLE entry whose effective date is in the past. A growing backlog means invoices or payments are running late: page on it.

  • Health check. Alert when /1.0/healthcheck is unhealthy.

  • API latency and errors. Per-resource timers, plus HTTP 5xx rates.

  • Payment plugin latency and errors. Calls to gateways (Stripe, Adyen, …​).

  • Logs. Review any WARN or ERROR entry, and any stack trace.

See also the Going to Production guide.

Extending to other backends

There are three ways to send Kill Bill telemetry to a backend that has no dedicated bundle. They can be combined.

Approach Pros Cons

A. Scrape the Prometheus endpoint (for example with an OpenTelemetry Collector)

No code. All Kill Bill metrics. Works with almost any backend.

One more component to run (collector or sidecar). Pull model.

B. A vendor’s Java agent (OpenTelemetry Java agent, Azure Application Insights agent, …​)

No code. Adds distributed traces, request and database telemetry, and logs.

Kill Bill business metrics are only available through JMX (selected one by one). Instrumentation inside OSGi plugins should be tested.

C. A custom reporter bundle (for example native OTLP push)

No extra component. All Kill Bill metrics, pushed natively. Reusable.

Requires writing and maintaining a small OSGi bundle.

A. OpenTelemetry Collector scraping Prometheus

Install the prometheus bundle, then run an OpenTelemetry Collector (contrib distribution) next to Kill Bill. On Kubernetes this is usually a sidecar container in the Kill Bill pod. The collector scrapes Kill Bill and forwards to any exporter:

receivers:
  prometheus:
    config:
      scrape_configs:
        - job_name: killbill
          scrape_interval: 30s
          metrics_path: /plugins/killbill-prometheus
          static_configs:
            - targets: ['localhost:8080']

processors:
  batch: {}

exporters:
  # Any OTLP backend
  otlp:
    endpoint: <your-otlp-endpoint>:4317
  # Or Azure Monitor / Application Insights
  azuremonitor:
    connection_string: ${env:APPLICATIONINSIGHTS_CONNECTION_STRING}

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [batch]
      exporters: [azuremonitor]

Swap the exporter for the backend you use: googlemanagedprometheus, awsemf, datadog, otlphttp, and so on.

Note

Managed Prometheus scrapers. On Kubernetes, managed Prometheus offerings (Azure Monitor managed service for Prometheus, Google Managed Service for Prometheus, Amazon Managed Service for Prometheus) can scrape /plugins/killbill-prometheus directly through pod annotations or a PodMonitor, without a collector.

B. Java agents (traces, requests, logs)

Kill Bill’s own metrics don’t include distributed traces. To get request traces, database calls, outbound gateway calls and correlated logs, attach a Java agent to the Kill Bill JVM, for example through JAVA_OPTS or CATALINA_OPTS:

# OpenTelemetry Java agent (any OTLP backend)
-javaagent:/opt/otel/opentelemetry-javaagent.jar
-Dotel.service.name=killbill
-Dotel.exporter.otlp.endpoint=http://localhost:4318
# The agent defaults to OTLP over HTTP (port 4318). For gRPC (port 4317), also set:
# -Dotel.exporter.otlp.protocol=grpc

# or Azure Monitor OpenTelemetry Java agent (Application Insights)
-javaagent:/opt/appinsights/applicationinsights-agent.jar
# with APPLICATIONINSIGHTS_CONNECTION_STRING set in the environment

Both agents can also read JMX MBeans. With the Application Insights agent, list the Kill Bill MBeans you want under jmxMetrics in applicationinsights.json.

Combining A (Kill Bill metrics) with B (traces and logs) gives full coverage without writing any code.

Tip

Kill Bill plugins run inside an OSGi (Apache Felix) container. Automatic instrumentation of code running inside plugins (for example the HTTP client of a payment plugin) may require exposing the agent’s packages to the bundles through org.osgi.framework.bootdelegation. Validate it in a test environment first.

C. Writing a reporter bundle

Every existing reporter bundle follows the same pattern, so supporting a new backend natively, for example OTLP push, takes one small bundle:

  1. Extend KillbillActivatorBase (from killbill-platform-osgi-bundles-lib-killbill).

  2. In start(), get the shared registry with metricRegistry.getMetricRegistry(). It exposes getCounters(), getGauges(), getHistograms(), getMeters() and getTimers().

  3. Read configuration from configProperties (system and killbill.properties properties), for example org.killbill.metrics.otlp.*.

  4. Either push on a schedule, like the influxdb bundle with a Dropwizard ScheduledReporter, or expose an endpoint by registering a Servlet OSGi service, like the prometheus bundle (served under /plugins/<bundle-name>).

  5. Stop your reporter in stop().

  6. Package it as an OSGi bundle (see the existing pom.xml files) and drop it in the platform bundle directory, next to the metrics bundle.

The sketch below bridges the Kill Bill registry to the OpenTelemetry SDK. Kill Bill registers metrics lazily, so a periodic task picks up new metric names and creates an OpenTelemetry observable instrument for each one:

public class Activator extends KillbillActivatorBase {

    private SdkMeterProvider meterProvider;
    private ScheduledExecutorService scheduler;
    private final Set<String> bridged = ConcurrentHashMap.newKeySet();

    @Override
    public void start(final BundleContext context) throws Exception {
        super.start(context);
        final MetricRegistry kbRegistry = metricRegistry.getMetricRegistry();

        final String endpoint = configProperties.getString("org.killbill.metrics.otlp.endpoint"); // e.g. http://localhost:4317
        meterProvider = SdkMeterProvider.builder()
                .setResource(Resource.getDefault().merge(Resource.create(Attributes.of(stringKey("service.name"), "killbill"))))
                .registerMetricReader(PeriodicMetricReader.builder(
                        OtlpGrpcMetricExporter.builder().setEndpoint(endpoint).build())
                        .setInterval(Duration.ofSeconds(30)).build())
                .build();
        final Meter meter = meterProvider.get("org.killbill");

        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            // Kill Bill counters can go down (@Counted is non-monotonic by default): use UpDownCounters
            kbRegistry.getCounters().forEach((name, counter) -> {
                if (bridged.add(name)) {
                    meter.upDownCounterBuilder(name).buildWithCallback(m -> m.record(counter.getCount()));
                }
            });
            kbRegistry.getTimers().forEach((name, timer) -> {
                if (bridged.add(name)) {
                    meter.counterBuilder(name + ".count").buildWithCallback(m -> m.record(timer.getCount()));
                    meter.gaugeBuilder(name + ".p99").setUnit("ns")
                         .buildWithCallback(m -> m.record(timer.getSnapshot().get99thPercentile()));
                }
            });
            // Same for gauges, meters and histograms
        }, 0, 30, TimeUnit.SECONDS);
    }

    @Override
    public void stop(final BundleContext context) throws Exception {
        try {
            if (scheduler != null) { scheduler.shutdownNow(); }
            if (meterProvider != null) { meterProvider.close(); }
        } finally {
            super.stop(context);
        }
    }
}

Once such a bundle exists, a cloud-specific integration is only a matter of configuration. For Azure, for example, you can either point the OTLP endpoint at a collector that uses the azuremonitor exporter, or replace the OTLP exporter in the bundle with the Azure Monitor OpenTelemetry exporter.

Contributions of new reporter bundles to killbill-platform are welcome.

See also