Video in progress
How do you collect metrics from short-lived batch jobs that Prometheus doesn't get a chance to scrape?
In a pull model, if the job finishes before the scrape, the metrics are lost. The options: push the metric to a Pushgateway at the end of the job, push through OTLP, or turn the result into a metric through a long-lived service. Each has its own subtle points.
📖 Answer
For example, a Kubernetes CronJob runs for 40 seconds every night. Prometheus scrapes once every 30 seconds, and it also needs time to discover the pod. Often nothing is collected and the metrics have no answer to "did the job finish successfully?".
The Pushgateway is the classic solution:
PushGateway pg = new PushGateway("pushgateway:9091");
// at the end of the job
Gauge lastSuccess = Gauge.build()
.name("billing_job_last_success_timestamp_seconds")
.help("Oxirgi muvaffaqiyatli ishga tushish").register(registry);
lastSuccess.setToCurrentTime();
pg.pushAdd(registry, "billing_job");
Micrometer also has PrometheusPushGatewayManager, and Boot configures it with the management.prometheus.metrics.export.pushgateway.* properties (the exact names have changed between versions, check the docs).
Subtle points:
- The Pushgateway doesn't delete metrics itself. If the job dies, the old value stays forever and gives the impression that everything is fine. So you send a "last success time" gauge and write the alert as
time() - billing_job_last_success_timestamp_seconds > 26*3600, so you get an alert even when the job stops running. - Counters make less sense here: every run overwrites its own value.
- The Pushgateway is a single point: if it goes down, no batch jobs are visible.
- You don't have to send an
instancelabel, otherwise every pod becomes a separate group and garbage piles up.
Alternatives:
- with OpenTelemetry the job pushes metrics to the Collector through OTLP, and the Collector exposes them to Prometheus;
- write the job's result (how many records were processed, when it finished) to the database, and have a long-running service expose it as a gauge;
- in Kubernetes, check the job state with
kube_job_status_failedandkube_cronjob_status_last_successful_timefrom kube-state-metrics, which is often enough on its own.
Sign up to mark studied questions and save your progress.