Exercise — Metrics and Monitoring: expose a custom business metric and alert on it.
Topic: microservices, Observability. Level: Intermediate.
Answer
Instrument the code with a counter/gauge, expose it on `/actuator/prometheus`, scrape with Prometheus, and write an alert rule on a rate/threshold. Below tracks failed payments and alerts when the failure rate is high.
```java
meterRegistry.counter("payments.total", "result", result).increment();
```
```yaml
# Prometheus alert: fire when >5% of payments fail over 5 min
- alert: HighPaymentFailureRate
expr: |
sum(rate(payments_total{result="failed"}[5m]))
/ sum(rate(payments_total[5m])) > 0.05
for: 5m
labels: { severity: page }
```