Email Alerts with Spring Events and @TransactionalEventListener (Uptime Monitor Part 6)
Send DOWN and RECOVERED emails from Spring Boot with incidents, Spring events, @Async and @TransactionalEventListener, without alert spam. Part 6 of the UpCheck series.
Part 6 of the UpCheck series emails you when a site goes DOWN and again when it RECOVERS, and records every outage as an incident.
- 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 (you are here)
- Part 7: Uptime stats, pagination and retention
- Part 8: Testing, Docker and deployment
Incidents and email alerts with Spring events#
Today UpCheck emails you when a site goes DOWN and again when it RECOVERS, with the downtime. Each outage is saved as an incident so users can see their history.
The status rules#
| From | To | When | What happens |
|---|---|---|---|
| UNKNOWN | UP | first successful check | nothing (no alert for a new monitor) |
| UP | DOWN | 2 failures in a row (failure-threshold) |
open incident, send DOWN email |
| DOWN | DOWN | more failures | nothing (no spam) |
| DOWN | UP | one successful check | close incident, send RECOVERED email with downtime |
Every email comes from a transition into a new state, never from a single check, which is what keeps alerts quiet and trustworthy.
Why an event instead of calling the mail sender directly?#
Three real production bugs are avoided this way:
- Email for a change that never happened.
@TransactionalEventListener(AFTER_COMMIT)sends only after the database commit succeeds. - A slow SMTP server blocking checks.
@Asyncsends on another (virtual) thread. - A broken mail server breaking monitoring. Mail errors are caught and logged; checks keep running.
Step 1: Incident repository and service#
package com.upcheck.incident;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface IncidentRepository extends JpaRepository<Incident, Long> {
Optional<Incident> findFirstByMonitorIdAndResolvedAtIsNullOrderByStartedAtDesc(Long monitorId);
Page<Incident> findByMonitorIdOrderByStartedAtDesc(Long monitorId, Pageable pageable);
}
Propagation.MANDATORY makes these methods fail loudly if someone calls them outside a transaction, because opening an incident without saving the status change would leave the data inconsistent.
package com.upcheck.incident;
import com.upcheck.monitor.Monitor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Optional;
@Service
public class IncidentService {
private final IncidentRepository incidentRepository;
public IncidentService(IncidentRepository incidentRepository) {
this.incidentRepository = incidentRepository;
}
/** Opens a new incident unless one is already open (idempotent). */
@Transactional(propagation = Propagation.MANDATORY)
public Incident open(Monitor monitor, Instant at, String cause) {
return incidentRepository.findFirstByMonitorIdAndResolvedAtIsNullOrderByStartedAtDesc(monitor.getId())
.orElseGet(() -> incidentRepository.save(new Incident(monitor, at, cause)));
}
/** Closes the open incident, if any, and returns it. */
@Transactional(propagation = Propagation.MANDATORY)
public Optional<Incident> resolve(Monitor monitor, Instant at) {
Optional<Incident> open =
incidentRepository.findFirstByMonitorIdAndResolvedAtIsNullOrderByStartedAtDesc(monitor.getId());
open.ifPresent(incident -> incident.resolve(at));
return open;
}
}
Step 2: The event and the alert listener#
The event carries plain values, not entities. By the time the async listener runs, the transaction is closed and a lazy monitor.getOwner() would throw LazyInitializationException.
package com.upcheck.alert;
import com.upcheck.monitor.MonitorStatus;
import java.time.Duration;
import java.time.Instant;
public record MonitorStatusChangedEvent(
Long monitorId,
String monitorName,
String url,
String ownerEmail,
String ownerName,
MonitorStatus newStatus,
String cause,
Duration downtime,
Instant at
) {}
package com.upcheck.alert;
import com.upcheck.config.AppProperties;
import com.upcheck.monitor.MonitorStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
import java.time.Duration;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Service
public class AlertService {
private static final Logger log = LoggerFactory.getLogger(AlertService.class);
private static final DateTimeFormatter TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC);
private final JavaMailSender mailSender;
private final String from;
public AlertService(JavaMailSender mailSender, AppProperties props) {
this.mailSender = mailSender;
this.from = props.mail().from();
}
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onStatusChanged(MonitorStatusChangedEvent event) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(from);
mail.setTo(event.ownerEmail());
if (event.newStatus() == MonitorStatus.DOWN) {
mail.setSubject("[DOWN] " + event.monitorName() + " is not responding");
mail.setText("""
Hi %s,
UpCheck detected that your monitor is DOWN.
Monitor: %s
URL: %s
Reason: %s
Since: %s
We will email you again when it recovers.
— UpCheck
""".formatted(event.ownerName(), event.monitorName(), event.url(),
event.cause(), TIME.format(event.at())));
} else {
mail.setSubject("[RECOVERED] " + event.monitorName() + " is back up");
mail.setText("""
Hi %s,
Good news: your monitor is UP again.
Monitor: %s
URL: %s
Downtime: %s
Back at: %s
— UpCheck
""".formatted(event.ownerName(), event.monitorName(), event.url(),
humanize(event.downtime()), TIME.format(event.at())));
}
try {
mailSender.send(mail);
log.info("Sent {} alert for monitor {}", event.newStatus(), event.monitorId());
} catch (MailException e) {
// an email failure must never break monitoring; log and move on
log.error("Could not send {} alert for monitor {}", event.newStatus(), event.monitorId(), e);
}
}
static String humanize(Duration d) {
if (d == null) return "unknown";
long h = d.toHours(), m = d.toMinutesPart(), s = d.toSecondsPart();
if (h > 0) return h + "h " + m + "m";
if (m > 0) return m + "m " + s + "s";
return s + "s";
}
}
Step 3: Final version of CheckService#
Replace the Part 5 CheckService with this one. It opens and closes incidents and publishes the event. The history() method is used by the API in Part 7.
package com.upcheck.check;
import com.upcheck.alert.MonitorStatusChangedEvent;
import com.upcheck.common.PageResponse;
import com.upcheck.config.AppProperties;
import com.upcheck.incident.IncidentService;
import com.upcheck.monitor.Monitor;
import com.upcheck.monitor.MonitorRepository;
import com.upcheck.monitor.MonitorService;
import com.upcheck.monitor.MonitorStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.time.Instant;
@Service
public class CheckService {
private static final Logger log = LoggerFactory.getLogger(CheckService.class);
private final MonitorRepository monitorRepository;
private final CheckResultRepository checkResultRepository;
private final IncidentService incidentService;
private final MonitorService monitorService;
private final ApplicationEventPublisher events;
private final int failureThreshold;
public CheckService(MonitorRepository monitorRepository, CheckResultRepository checkResultRepository,
IncidentService incidentService, MonitorService monitorService,
ApplicationEventPublisher events, AppProperties props) {
this.monitorRepository = monitorRepository;
this.checkResultRepository = checkResultRepository;
this.incidentService = incidentService;
this.monitorService = monitorService;
this.events = events;
this.failureThreshold = props.checker().failureThreshold();
}
@Transactional
public void record(Long monitorId, CheckOutcome outcome) {
Monitor monitor = monitorRepository.findById(monitorId).orElse(null);
if (monitor == null || !monitor.isActive()) {
return;
}
checkResultRepository.save(new CheckResult(monitor, outcome));
MonitorStatus previous = monitor.getStatus();
MonitorStatus changedTo = monitor.recordCheck(outcome.up(), outcome.checkedAt(), failureThreshold);
if (changedTo == MonitorStatus.DOWN) {
incidentService.open(monitor, outcome.checkedAt(), outcome.errorMessage());
log.warn("Monitor {} is DOWN: {}", monitorId, outcome.errorMessage());
publish(monitor, MonitorStatus.DOWN, outcome.errorMessage(), null, outcome.checkedAt());
} else if (changedTo == MonitorStatus.UP && previous == MonitorStatus.DOWN) {
Duration downtime = incidentService.resolve(monitor, outcome.checkedAt())
.map(i -> i.duration(outcome.checkedAt()))
.orElse(null);
log.info("Monitor {} RECOVERED after {}", monitorId, downtime);
publish(monitor, MonitorStatus.UP, null, downtime, outcome.checkedAt());
}
// UNKNOWN -> UP is the first successful check: nothing to alert
}
@Transactional(readOnly = true)
public PageResponse<CheckResponse> history(Long userId, Long monitorId, Pageable pageable) {
monitorService.findOwned(userId, monitorId);
return PageResponse.from(checkResultRepository
.findByMonitorIdOrderByCheckedAtDesc(monitorId, pageable)
.map(CheckResponse::from));
}
private void publish(Monitor m, MonitorStatus status, String cause, Duration downtime, Instant at) {
events.publishEvent(new MonitorStatusChangedEvent(
m.getId(), m.getName(), m.getUrl(),
m.getOwner().getEmail(), m.getOwner().getName(),
status, cause, downtime, at));
}
public record CheckResponse(Instant checkedAt, boolean up, Integer statusCode,
Long responseTimeMs, String errorMessage) {
static CheckResponse from(CheckResult r) {
return new CheckResponse(r.getCheckedAt(), r.isUp(), r.getStatusCode(),
r.getResponseTimeMs(), r.getErrorMessage());
}
}
}
Add a monitor for https://httpstat.us/503 with a 1-minute interval. After two checks, open Mailpit at http://localhost:8025: the [DOWN] email is there, and the incidents table has an open row. Change the URL to a working site and wait for the [RECOVERED] email.
Key takeaways#
- Alert on status transitions, not on single checks, so users never get spammed.
- Send email AFTER_COMMIT so a rolled-back change never triggers an alert.
- Run listeners with @Async and catch mail errors so SMTP problems never stop monitoring.