Spring Boot 애플리케이션을 Prometheus로 모니터링하기
Actuator와 Micrometer로 스크레이프 엔드포인트를 설정하고 승인된 주문 수, 처리 중인 요청 수, 처리 시간 P95를 측정합니다.
주문 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로 저장합니다. 두 리스너 모두 루프백 주소에 바인딩합니다. 관리 포트에서는 상태 확인과 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 레지스트리의 데이터를 스크레이프 형식으로 제공하고, 노출 목록이 HTTP로 접근할 수 있는 엔드포인트를 결정합니다. 관리 포트를 분리해도 인증이 적용되지는 않습니다. 원격 수집기가 필요하면 관리 주소에 접근할 경로를 마련하고 허용할 수집기를 제한합니다. 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 증가 | 주문 한 건을 승인함 |
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 방식
