Skip to content

About

A reusable Spring Boot observability framework automatic REST API monitoring, P95/P99 latency analytics, alerting, and a live dashboard. Zero code changes required.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

API Monitor

A reusable Spring Boot observability framework. Add one Maven dependency and one property to any Spring Boot application, and every REST endpoint is automatically timed, aggregated into P50/P95/P99 latency and error-rate metrics, evaluated against configurable alert thresholds, and rendered on a live dashboard — with zero changes to the monitored application's code.

monitor.enabled=true

That line, plus a dependency in pom.xml, is the entire integration. See demo-user-service for proof: its controllers contain no reference to this framework whatsoever.


Why this exists

Every API-first company (Stripe, Datadog, Adobe, Atlassian) needs to answer three questions continuously: Is the API healthy right now? Which endpoints are slow or failing? Did we just regress? This project is a small, complete, self-hosted answer to those questions, built to demonstrate the engineering that production APM tools (Datadog APM, New Relic, Elastic APM) actually do under the hood — async instrumentation, percentile math, threshold-based alerting, and a real ingestion pipeline — at a scale one engineer can build, run, and fully explain in a single project.


Module structure

api-monitor/
├── pom.xml                          parent POM: reactor build, shared dependency versions
├── docker-compose.yml               Postgres + dashboard + demo service, one command
├── docs/                            diagrams, design-decision notes
│
├── api-monitor-core/                 pure Java, zero Spring dependency
│   └── src/main/java/com/apimonitor/core/
│       ├── model/        RequestMetric.java              immutable fact: one HTTP request
│       ├── metrics/       PercentileCalculator.java        P50/P95/P99, nearest-rank
│       │                  EndpointMetricsAggregator.java    groups facts into per-endpoint snapshots
│       │                  EndpointMetricsSnapshot.java
│       ├── alert/          AlertEngine.java                 stateless threshold evaluation
│       │                  AlertThresholds.java
│       │                  Alert.java
│       └── collector/      MetricCollector.java              async batching: BlockingQueue + bg thread
│                          MetricSink.java                   interface: what happens to a flushed batch
│
├── api-monitor-starter/              Spring Boot auto-configuration
│   └── src/main/java/com/apimonitor/starter/
│       ├── autoconfig/     ApiMonitorAutoConfiguration.java the @AutoConfiguration entry point
│       ├── interceptor/    ApiMonitorInterceptor.java       HandlerInterceptor: the instrumentation point
│       ├── config/         ApiMonitorProperties.java        monitor.* property binding
│       └── sink/           HttpMetricSink.java              default sink: POSTs batches to the dashboard
│                          RequestMetricPayload.java
│
├── api-monitor-dashboard/            the deployable observability backend + UI
│   └── src/main/java/com/apimonitor/dashboard/
│       ├── entity/          RequestMetricEntity.java, AlertEntity.java
│       ├── repository/      RequestMetricRepository.java, AlertRepository.java
│       ├── service/         AnalyticsService.java           percentiles over real persisted data
│       │                  AlertEvaluationService.java      @Scheduled threshold re-evaluation
│       │                  AlertQueryService.java
│       │                  JpaMetricSink.java                this app's own MetricSink: direct JPA
│       │                  RequestMetricEntityMapper.java
│       ├── controller/      AnalyticsController.java        /api/analytics/**
│       │                  AlertController.java             /api/alerts
│       │                  IngestionController.java         /api/ingest/metrics
│       │                  DashboardPageController.java     /monitor — serves the Thymeleaf shell
│       └── resources/
│           ├── templates/dashboard.html
│           ├── static/css,js/dashboard.css,.js              Chart.js, vanilla JS, polling
│           └── db/migration/V1__initial_schema.sql           Flyway
│
└── demo-user-service/                 sample app proving "zero code changes"
    └── src/main/java/com/apimonitor/demo/
        ├── controller/      UserController.java   GET /users, POST /users, GET /slow-users, GET /error
        ├── service/         UserService.java
        └── model/           User.java, CreateUserRequest.java
        (nothing here imports com.apimonitor.* — see application.properties instead)

Architecture

Two architectural decisions define this system; both are explained in depth in docs/DESIGN_DECISIONS.md, but the short version:

  1. Async, batched metric capture. The interceptor never blocks the request thread on I/O. It hands a fact to an in-memory BlockingQueue; a single background thread batches and flushes. Under sustained overflow, metrics are dropped (counted, logged) rather than applying backpressure to the monitored application.
  2. HTTP shipping, not a shared database. A monitored application (like demo-user-service) and the dashboard are separate deployable services. The starter's default MetricSink ships batches over HTTP to the dashboard's /api/ingest/metrics endpoint, mirroring how real APM agents work. The dashboard application, monitoring itself, swaps in a direct JPA sink instead, skipping the network hop for its own traffic.
flowchart TB
    subgraph MonitoredApp["Monitored Application e.g. demo-user-service"]
        direction TB
        Controller["Rest Controller<br/>zero awareness of monitoring"]
        Interceptor["ApiMonitorInterceptor"]
        Queue["BlockingQueue of RequestMetric<br/>bounded, drops on overflow"]
        BgThread["Background Thread<br/>MetricCollector"]
        HttpSink["HttpMetricSink<br/>default MetricSink"]

        Controller -- "1 request arrives" --> Interceptor
        Interceptor -- "2 record metric<br/>non-blocking" --> Queue
        Queue -- "3 poll" --> BgThread
        BgThread -- "4 flush batch" --> HttpSink
    end

    HttpSink -- "5 POST /api/ingest/metrics" --> IngestController

    subgraph DashboardApp["Dashboard Application"]
        direction TB
        IngestController["IngestionController"]
        JpaSink["JpaMetricSink"]
        DB[("Postgres")]
        AlertJob["AlertEvaluationService<br/>scheduled every 60s"]
        AlertEngine["AlertEngine core module"]
        AnalyticsSvc["AnalyticsService"]
        API["Analytics + Alert Controllers"]
        UI["Thymeleaf + Chart.js<br/>polls every 5s"]

        IngestController -- "6 saveAll" --> JpaSink
        JpaSink --> DB
        AlertJob -- "7 read recent window" --> DB
        AlertJob --> AlertEngine
        AlertEngine -- "8 breach found" --> AlertJob
        AlertJob -- "9 save alert deduplicated" --> DB
        AnalyticsSvc -- "10 query and aggregate" --> DB
        API --> AnalyticsSvc
        UI -- "11 fetch polling" --> API
    end

    style MonitoredApp fill:#0f1419,stroke:#58a6ff,color:#e6edf3
    style DashboardApp fill:#0f1419,stroke:#3fb950,color:#e6edf3
Loading

Sequence: one request, end to end

sequenceDiagram
    participant Client
    participant Ctrl as UserController
    participant Interceptor as ApiMonitorInterceptor
    participant Collector as MetricCollector (bg thread)
    participant Sink as HttpMetricSink
    participant Ingest as IngestionController
    participant DB as Postgres
    participant AlertJob as AlertEvaluationService
    participant Analytics as AnalyticsController
    participant UI as Dashboard UI

    Client->>Ctrl: GET /users/slow-users
    Ctrl->>Interceptor: preHandle - stash start time
    Note over Ctrl: business logic executes<br/>interceptor is NOT in this path
    Ctrl->>Interceptor: afterCompletion - compute duration
    Interceptor->>Collector: record metric - non-blocking offer
    Interceptor-->>Client: HTTP response returns immediately

    Note over Collector: batchSize reached OR<br/>flushIntervalMillis elapsed
    Collector->>Sink: flush batch
    Sink->>Ingest: POST /api/ingest/metrics JSON
    Ingest->>DB: saveAll entities

    loop every 60s
        AlertJob->>DB: findByTimestampBetween last 5 min
        AlertJob->>AlertJob: aggregate then AlertEngine.evaluateAll
        alt threshold breached and not duplicate within cooldown
            AlertJob->>DB: save alert
        end
    end

    loop every 5s
        UI->>Analytics: GET /api/analytics/summary
        Analytics->>DB: query and aggregate
        DB-->>UI: P50 P95 P99, error rate, charts, alerts
    end
Loading

Quick start (Docker — recommended)

Requires Docker and Docker Compose. From the repo root:

docker compose up --build

This starts, in order: Postgres → dashboard (waits for Postgres healthcheck) → demo-user-service (waits for dashboard healthcheck). First build takes a few minutes (Maven downloads dependencies inside the build container); after that, Docker layer caching makes rebuilds fast.

Once it's up:

What URL
Live dashboard http://localhost:8080/monitor
Demo service API http://localhost:8081/users
Dashboard's own health http://localhost:8080/actuator/health

Generate traffic to see the dashboard populate:

# normal traffic
for i in $(seq 1 20); do curl -s http://localhost:8081/users > /dev/null; done

# create a few users
curl -s -X POST http://localhost:8081/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Test User","email":"test@example.com"}'

# slow traffic — populates the "Top Slow Endpoints" table and latency charts
for i in $(seq 1 10); do curl -s http://localhost:8081/users/slow-users > /dev/null & done

# error traffic — populates "Highest Error Endpoints" and triggers alerts
for i in $(seq 1 20); do curl -s http://localhost:8081/users/error > /dev/null; done

Refresh http://localhost:8080/monitor — cards, charts, and tables update automatically every 5 seconds without a manual reload.

To stop and remove containers (keeping the Postgres volume):

docker compose down

To also wipe all stored metrics/alerts:

docker compose down -v

Quick start (without Docker)

Requires JDK 21, Maven 3.9+, and a running Postgres instance.

# 1. Create the database
createdb apimonitor   # or: psql -c "CREATE DATABASE apimonitor;"

# 2. Build the whole reactor (core → starter → dashboard → demo)
mvn clean install

# 3. Run the dashboard (separate terminal)
cd api-monitor-dashboard
mvn spring-boot:run
# Flyway runs V1__initial_schema.sql automatically on startup

# 4. Run the demo service (separate terminal)
cd demo-user-service
mvn spring-boot:run

Dashboard: http://localhost:8080/monitor · Demo API: http://localhost:8081/users


Integrating the starter into YOUR OWN application

This is the part that matters most — the actual "framework" usage, not just this project's own demo.

1. Add the dependency (after mvn install-ing this repo, or once published, from a Maven repository):

<dependency>
    <groupId>com.apimonitor</groupId>
    <artifactId>api-monitor-starter</artifactId>
    <version>1.0.0</version>
</dependency>

2. Add two properties:

monitor.enabled=true
monitor.dashboard-url=http://localhost:8080

3. That's it. Every endpoint in your application is now instrumented. Nothing else changes. See docs/INTEGRATION_GUIDE.md for the full property reference (custom thresholds, include/exclude patterns, batch tuning) and for instructions on supplying your own MetricSink if you'd rather persist directly instead of shipping over HTTP.


API reference

Method Path Purpose
GET /api/analytics/summary?from=&to= Four dashboard cards: total requests, avg/P95 latency, error rate
GET /api/analytics/endpoints/slowest?limit=10 Top N slowest endpoints by P95
GET /api/analytics/endpoints/highest-errors?limit=10 Top N endpoints by error rate
GET /api/analytics/trends/request-volume?bucket=minute|hour|day Time-series: request count
GET /api/analytics/trends/latency?bucket=... Time-series: average latency
GET /api/analytics/trends/error-rate?bucket=... Time-series: error rate %
GET /api/alerts?page=0&size=20 Paginated alert history, newest first
POST /api/ingest/metrics Receives batches from remote HttpMetricSink instances
GET /monitor The Thymeleaf dashboard page itself

Full request/response shapes are in docs/API_REFERENCE.md.


Testing

mvn clean verify

Runs unit tests in every module plus the Testcontainers-backed integration test for the Postgres-specific date_trunc queries (requires Docker to be running locally; CI environments with Docker-in-Docker work the same way). verify also enforces an 80% line-coverage gate via JaCoCo (configured in the parent POM) — the build fails if coverage regresses below that bar.

Test breakdown by module:

Module What's tested How
api-monitor-core Percentile math, alert thresholds, async collector concurrency (batching, backpressure, graceful shutdown) Plain JUnit 5, no Spring context
api-monitor-starter Interceptor behavior, auto-configuration conditional wiring Mockito + Spring's ApplicationContextRunner
api-monitor-dashboard Repositories (H2 for derived queries, Testcontainers/Postgres for native bucketing queries), services (Mockito), controllers (@WebMvcTest), full context load JUnit 5 + Spring Boot Test
demo-user-service Controller behavior, including an explicitly non-flaky test for the randomized /error endpoint @WebMvcTest + MockMvc

Configuration reference

All properties live under the monitor.* prefix. Full descriptions are in api-monitor-starter's additional-spring-configuration-metadata.json, which also gives IDE autocomplete for every property below.

Property Default Purpose
monitor.enabled false Master switch — opt-in by design
monitor.dashboard-url http://localhost:8080 Where HttpMetricSink ships batches
monitor.include-patterns /** Ant-style paths to monitor
monitor.exclude-patterns dashboard/actuator/static paths Paths to never monitor
monitor.collector.queue-capacity 10000 Max in-flight metrics before drop-under-backpressure
monitor.collector.batch-size 100 Flush trigger: batch size
monitor.collector.flush-interval-millis 5000 Flush trigger: max time between flushes
monitor.thresholds.latency-warning-ms 500 P95 latency → WARNING alert
monitor.thresholds.latency-critical-ms 2000 P95 latency → CRITICAL alert
monitor.thresholds.error-rate-warning 0.05 Error rate → WARNING alert
monitor.thresholds.error-rate-critical 0.20 Error rate → CRITICAL alert

Project documents

License

MIT — see LICENSE.

About

A reusable Spring Boot observability framework automatic REST API monitoring, P95/P99 latency analytics, alerting, and a live dashboard. Zero code changes required.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages