Spring Boot アプリケーションを Prometheus で監視する

Actuator と Micrometer で収集用エンドポイントを設定し、注文の受理件数、処理中の件数、処理時間の P95 を計測します。

ベストプラクティス
Prometheus の監視とダッシュボードのイメージ

注文 API で拒否が増え始めても、HTTP のリクエスト件数には受理と拒否の両方が含まれます。何が変わったのかを見るには、Spring Boot の HTTP メトリクスに加え、受理した注文だけを数える業務カウンターが必要です。処理時間の分布はヒストグラムで確認します。

スクレイプ用の待ち受け先を分ける

例では Java 21、Spring Boot 3.5.16、Spring Boot がバージョンを管理する Micrometer 1.15.12 を使います。次の Maven プロジェクト定義を pom.xml として保存します。

<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.16</version>
        <relativePath/>
    </parent>
    <groupId>example</groupId>
    <artifactId>checkout-metrics</artifactId>
    <version>1.0.0</version>
    <properties><java.version>21</java.version></properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

次の設定を src/main/resources/application.properties として保存します。アプリケーションと管理用の待ち受け先をどちらもループバックに限定し、管理ポートでは health と Prometheus を HTTP で公開します。

server.address=127.0.0.1
server.port=8080
management.server.address=127.0.0.1
management.server.port=9091
management.endpoints.web.exposure.include=health,prometheus

後述のアプリケーションコードを配置し、mvn spring-boot:run を実行します。同じネットワーク名前空間から http://127.0.0.1:9091/actuator/prometheus にアクセスしてください。Actuator は Prometheus 用レジストリのデータを返し、公開対象は設定の一覧で決まります。管理ポートを分けるだけでは認証は設定されません。リモートから収集する場合は、管理アドレスへの経路を確保し、収集元を制限します。Spring Security のフィルターチェーンを独自定義する場合は、Actuator のアクセス規則も確認してください。Spring Boot の Actuator エンドポイント(英語) · 管理ポートとアドレスの設定(英語)

JVM と HTTP の時系列を先に確認する

jvm_memory_used_bytes でメモリプールごとの使用量を、jvm_threads_live_threads で生存スレッド数を見ます。JVM や GC の発生状況によっては jvm_gc_pause_seconds_count や _sum も取得できます。ヒープやスレッド数が増えていたら、同程度の負荷で比較し、保持されているオブジェクトやスレッドのスタックを確認します。Spring Boot 3.5 の組み込み Tomcat でスレッドプールのメトリクスを取るには、server.tomcat.mbeanregistry.enabled=true で MBean レジストリを有効にします。

Spring MVC は HTTP リクエストを http.server.requests として計測します。実際にルートを呼び出すと、Prometheus の出力で http_server_requests_seconds_count や _sum を確認できます。uri のルートテンプレートとステータスを見れば、/checkout/{orderId} の受理と拒否を分けられます。既定の Timer ではレイテンシのバケットが出力されるとは限りません。分位数を表示する前に _bucket があるかを確認します。Spring Boot の HTTP・JVM メトリクス(英語)

受理件数と処理時間を個別に測る

次のコードを src/main/java/example/checkout/CheckoutApplication.java に保存します。例では特定の注文 ID を意図的に拒否します。受理件数、処理中の件数、ハンドラー内の処理時間を記録します。

package example.checkout;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class CheckoutApplication {
    public static void main(String[] args) {
        SpringApplication.run(CheckoutApplication.class, args);
    }
}

@RestController
class CheckoutController {
    private final MeterRegistry registry;
    private final AtomicInteger inFlight = new AtomicInteger();
    private final Counter accepted;
    private final Timer duration;

    CheckoutController(MeterRegistry registry) {
        this.registry = registry;
        accepted = registry.counter("checkout.accepted", "channel", "web");
        Gauge.builder("checkout.in.flight", inFlight, AtomicInteger::get)
            .register(registry);
        duration = Timer.builder("checkout.duration")
            .publishPercentileHistogram()
            .serviceLevelObjectives(Duration.ofMillis(250))
            .register(registry);
    }

    @PostMapping("/checkout/{orderId}")
    ResponseEntity<Void> checkout(@PathVariable("orderId") String orderId) {
        Timer.Sample sample = Timer.start(registry);
        inFlight.incrementAndGet();
        try {
            if ("declined".equals(orderId)) {
                return ResponseEntity.unprocessableEntity().build();
            }
            accepted.increment();
            return ResponseEntity.noContent().build();
        } finally {
            inFlight.decrementAndGet();
            sample.stop(duration);
        }
    }
}

起動直後のインスタンスで curl -X POST http://127.0.0.1:8080/checkout/42 と curl -X POST http://127.0.0.1:8080/checkout/declined を一度ずつ実行し、管理エンドポイントをスクレイプします。

時系列 確認する値の変化 意味
checkout_accepted_total 1 増える 受理された注文は 1 件
checkout_duration_seconds_count 2 増える 受理と拒否の両方を計測した
checkout_in_flight 両方の処理が終わると 0 に戻る スクレイプ時点で処理中の件数

Gauge は既定で監視対象を弱参照するため、コントローラーのフィールドに AtomicInteger を保持します。短いピークはスクレイプの間に発生して観測できない場合があります。区間内に起きた件数を見たいときは、目的に応じて Counter または Timer のカウントを使います。注文 ID はタグに含めず、例では固定の channel 値と HTTP のルートテンプレートを使います。Micrometer の Gauge(英語)

バケットを収集して P95 を求める

Prometheus が同じネットワーク名前空間で動く場合は、次のジョブ設定を使います。

scrape_configs:
  - job_name: spring-app
    metrics_path: /actuator/prometheus
    static_configs:
      - targets: ["127.0.0.1:9091"]

独自 Timer はパーセンタイルヒストグラムを有効にし、250 ミリ秒の目標値をバケット境界に追加しています。出力に checkout_duration_seconds_bucket があることを確認します。件数と合計時間から平均は求められますが、分位数の推定には分布が必要です。累積バケットには先に rate を適用し、le を残して集計します。複数インスタンスで集約するときはバケット境界をそろえます。以下は処理時間の P95 を秒単位で推定する式です。

histogram_quantile(
  0.95,
  sum by (le) (rate(checkout_duration_seconds_bucket{job="spring-app"}[5m]))
)

既存のダッシュボードが http.server.requests を使っている場合、HTTP の分位数が必要ならそのメーターにもヒストグラムを個別に設定し、出力を確認します。クライアント側で求めた分位数を足し合わせても、全インスタンスの分位数は求められません。Micrometer のヒストグラムと分位数(英語) · Prometheus の分位数クエリ(英語)

Guance に取り込む場合は、DataKit の Prom コレクター(英語) に実際に到達できるエンドポイントを設定します。スクレイプ結果と取り込み後の名前、タグ、単位を見比べ、受理件数、HTTP ステータスの内訳、処理時間の P95 を組み合わせて見ます。注文の拒否が増えたのか、リクエスト処理全体が遅くなったのかを切り分けられます。RED と USE の方法論

最適なプランを相談する

お問い合わせ

コミュニティに参加

WeChatでスキャンして
コミュニティに参加

Guanceを試す

オンラインですぐに始めて、使った分だけお支払いください。

利用を開始

Guanceのプランを選択

コードリポジトリ