Uptime Percentage with SQL Aggregate Queries in Spring Data JPA (Uptime Monitor Part 7)
Compute uptime % and average response time with JPQL aggregate queries, add pagination and a batched data-retention job in Spring Boot. Part 7 of the UpCheck series.
Part 7 of the UpCheck series adds the numbers users care about: uptime % and average response time, paged history, incident history and a nightly cleanup job.
- Part 1: Project setup with MySQL and Docker
- Part 2: Database design with Flyway and JPA
- Part 3: REST API, validation and error handling
- Part 4: Spring Security with JWT
- Part 5: Scheduler with virtual threads
- Part 6: Incidents and email alerts
- Part 7: Uptime stats, pagination and retention (you are here)
- Part 8: Testing, Docker and deployment
Uptime percentage with SQL aggregate queries, pagination and data retention#
Today you add the numbers users actually care about: uptime % and average response time for the last 24 hours and 7 days, plus paged check history, incident history, and a nightly job that keeps the database small.
New endpoints#
| Method | Path | Returns |
|---|---|---|
| GET | /api/monitors/{id}/stats | uptime % and avg response time, 24 h and 7 days |
| GET | /api/monitors/{id}/checks?page=0&size=50 | check history, newest first |
| GET | /api/monitors/{id}/incidents | downtime history with durations |
Step 1: Let MySQL do the math#
Never load 10,080 check rows into Java just to count them. One aggregate query returns three numbers, and the (monitor_id, checked_at) index from Part 2 makes it fast. The JPQL SELECT new ... maps the result straight into a record.
package com.upcheck.stats;
/** Result row of the aggregate query. */
public record CheckAggregate(Long totalChecks, Long upChecks, Double avgResponseTimeMs) {
/** Uptime in percent with 2 decimals, or null when there is no data yet. */
public Double uptimePercent() {
if (totalChecks == null || totalChecks == 0) {
return null;
}
double pct = upChecks * 100.0 / totalChecks;
return Math.round(pct * 100.0) / 100.0;
}
public Long avgResponseTimeRounded() {
return avgResponseTimeMs == null ? null : Math.round(avgResponseTimeMs);
}
}
The final CheckResultRepository:
package com.upcheck.check;
import com.upcheck.stats.CheckAggregate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
public interface CheckResultRepository extends JpaRepository<CheckResult, Long> {
Page<CheckResult> findByMonitorIdOrderByCheckedAtDesc(Long monitorId, Pageable pageable);
/** Total checks, successful checks and average response time since a point in time. */
@Query("""
SELECT new com.upcheck.stats.CheckAggregate(
COUNT(c),
COALESCE(SUM(CASE WHEN c.up = true THEN 1 ELSE 0 END), 0),
AVG(c.responseTimeMs))
FROM CheckResult c
WHERE c.monitor.id = :monitorId AND c.checkedAt >= :since
""")
CheckAggregate aggregateSince(@Param("monitorId") Long monitorId, @Param("since") Instant since);
/** Bulk delete in batches: one huge DELETE would lock the table for a long time. */
@Modifying
@Query(value = "DELETE FROM check_results WHERE checked_at < :cutoff LIMIT :batchSize", nativeQuery = true)
int deleteOlderThan(@Param("cutoff") Instant cutoff, @Param("batchSize") int batchSize);
}
The same query in plain SQL, if you want to try it in MySQL Workbench:
SELECT COUNT(*) AS total_checks,
SUM(CASE WHEN up THEN 1 ELSE 0 END) AS up_checks,
ROUND(SUM(up) * 100.0 / COUNT(*), 2) AS uptime_percent,
ROUND(AVG(response_time_ms)) AS avg_response_ms
FROM check_results
WHERE monitor_id = 1
AND checked_at >= NOW() - INTERVAL 24 HOUR;
Step 2: StatsService#
package com.upcheck.stats;
import com.upcheck.check.CheckResultRepository;
import com.upcheck.common.PageResponse;
import com.upcheck.incident.Incident;
import com.upcheck.incident.IncidentRepository;
import com.upcheck.monitor.Monitor;
import com.upcheck.monitor.MonitorService;
import com.upcheck.monitor.MonitorStatus;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@Service
public class StatsService {
private final MonitorService monitorService;
private final CheckResultRepository checkResultRepository;
private final IncidentRepository incidentRepository;
private final Clock clock;
public StatsService(MonitorService monitorService, CheckResultRepository checkResultRepository,
IncidentRepository incidentRepository, Clock clock) {
this.monitorService = monitorService;
this.checkResultRepository = checkResultRepository;
this.incidentRepository = incidentRepository;
this.clock = clock;
}
@Transactional(readOnly = true)
public MonitorStats stats(Long userId, Long monitorId) {
Monitor monitor = monitorService.findOwned(userId, monitorId);
Instant now = clock.instant();
CheckAggregate last24h = checkResultRepository.aggregateSince(monitorId, now.minus(Duration.ofHours(24)));
CheckAggregate last7d = checkResultRepository.aggregateSince(monitorId, now.minus(Duration.ofDays(7)));
return new MonitorStats(monitorId, monitor.getStatus(), monitor.getLastCheckedAt(),
Window.from(last24h), Window.from(last7d));
}
@Transactional(readOnly = true)
public PageResponse<IncidentResponse> incidents(Long userId, Long monitorId, Pageable pageable) {
monitorService.findOwned(userId, monitorId);
Instant now = clock.instant();
return PageResponse.from(incidentRepository
.findByMonitorIdOrderByStartedAtDesc(monitorId, pageable)
.map(i -> IncidentResponse.from(i, now)));
}
public record MonitorStats(Long monitorId, MonitorStatus status, Instant lastCheckedAt,
Window last24Hours, Window last7Days) {}
public record Window(long totalChecks, Double uptimePercent, Long avgResponseTimeMs) {
static Window from(CheckAggregate a) {
return new Window(a.totalChecks(), a.uptimePercent(), a.avgResponseTimeRounded());
}
}
public record IncidentResponse(Long id, Instant startedAt, Instant resolvedAt,
boolean open, long durationSeconds, String cause) {
static IncidentResponse from(Incident i, Instant now) {
return new IncidentResponse(i.getId(), i.getStartedAt(), i.getResolvedAt(),
i.isOpen(), i.duration(now).toSeconds(), i.getCause());
}
}
}
Step 3: Controller for stats, checks and incidents#
package com.upcheck.stats;
import com.upcheck.check.CheckService;
import com.upcheck.check.CheckService.CheckResponse;
import com.upcheck.common.PageResponse;
import com.upcheck.security.CurrentUser;
import com.upcheck.security.UserPrincipal;
import com.upcheck.stats.StatsService.IncidentResponse;
import com.upcheck.stats.StatsService.MonitorStats;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
@Tag(name = "Monitor insights")
@RestController
@RequestMapping("/api/monitors/{id}")
public class MonitorInsightsController {
private final StatsService statsService;
private final CheckService checkService;
public MonitorInsightsController(StatsService statsService, CheckService checkService) {
this.statsService = statsService;
this.checkService = checkService;
}
@GetMapping("/stats")
public MonitorStats stats(@CurrentUser UserPrincipal user, @PathVariable Long id) {
return statsService.stats(user.id(), id);
}
@GetMapping("/checks")
public PageResponse<CheckResponse> checks(@CurrentUser UserPrincipal user, @PathVariable Long id,
@PageableDefault(size = 50) Pageable pageable) {
return checkService.history(user.id(), id, pageable);
}
@GetMapping("/incidents")
public PageResponse<IncidentResponse> incidents(@CurrentUser UserPrincipal user, @PathVariable Long id,
@PageableDefault(size = 20) Pageable pageable) {
return statsService.incidents(user.id(), id, pageable);
}
}
Example response from GET /api/monitors/1/stats:
{
"monitorId": 1,
"status": "UP",
"lastCheckedAt": "2026-10-13T10:41:02.318Z",
"last24Hours": { "totalChecks": 1440, "uptimePercent": 99.86, "avgResponseTimeMs": 212 },
"last7Days": { "totalChecks": 10080, "uptimePercent": 99.91, "avgResponseTimeMs": 205 }
}
Step 4: Nightly retention job#
One monitor checked every minute creates 43,200 rows a month. With 1,000 monitors that is 43 million rows. The job deletes rows older than 30 days in batches of 5,000, each in its own short transaction, so the table is never locked for long.
package com.upcheck.check;
import com.upcheck.config.AppProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@Component
public class RetentionJob {
private static final Logger log = LoggerFactory.getLogger(RetentionJob.class);
private static final int BATCH_SIZE = 5_000;
private final CheckResultRepository checkResultRepository;
private final TransactionTemplate tx;
private final Clock clock;
private final int retentionDays;
public RetentionJob(CheckResultRepository checkResultRepository, TransactionTemplate tx,
Clock clock, AppProperties props) {
this.checkResultRepository = checkResultRepository;
this.tx = tx;
this.clock = clock;
this.retentionDays = props.retention().days();
}
@Scheduled(cron = "${upcheck.retention.cron}", zone = "UTC")
public void purgeOldChecks() {
Instant cutoff = clock.instant().minus(Duration.ofDays(retentionDays));
long total = 0;
int deleted;
do {
Integer n = tx.execute(status -> checkResultRepository.deleteOlderThan(cutoff, BATCH_SIZE));
deleted = n == null ? 0 : n;
total += deleted;
} while (deleted == BATCH_SIZE);
log.info("Retention job removed {} check results older than {}", total, cutoff);
}
}
Call /stats for a monitor that has been running for a while. Try ?sort=foo on the list endpoint: you get a clean 400 "Invalid sort field" instead of a 500.
Key takeaways#
- Let MySQL count and average; never load thousands of rows into Java to do math.
- A JPQL constructor expression maps aggregate results straight into a record.
- Delete old rows in small batches, each in its own transaction, to avoid long locks.