How to Write a Timing Aspect for Slow Methods in Spring
Write a timing aspect for Spring that flags slow methods: a custom annotation, threshold logging, Micrometer timers and the limits of proxy timing.

A method that is sometimes slow is hard to catch with profilers that run for a few minutes. An aspect that logs calls over a threshold and records timings makes the slow cases visible all the time. Examples use Spring Boot 4.
The annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SlowCheck {
long thresholdMs() default 200;
}Opt-in annotations keep the cost to chosen methods and let each one set its own threshold.
The aspect
@Aspect
@Component
public class SlowMethodAspect {
private static final Logger log = LoggerFactory.getLogger(SlowMethodAspect.class);
private final MeterRegistry registry;
public SlowMethodAspect(MeterRegistry registry) { this.registry = registry; }
@Around("@annotation(slow)")
public Object time(ProceedingJoinPoint pjp, SlowCheck slow) throws Throwable {
long start = System.nanoTime();
String outcome = "ok";
try {
return pjp.proceed();
} catch (Throwable t) {
outcome = "error";
throw t;
} finally {
long nanos = System.nanoTime() - start;
Timer.builder("app.method.time")
.tag("method", pjp.getSignature().toShortString())
.tag("outcome", outcome)
.register(registry)
.record(nanos, TimeUnit.NANOSECONDS);
long ms = nanos / 1_000_000;
if (ms >= slow.thresholdMs()) {
log.warn("slow call {} took {} ms (threshold {} ms)",
pjp.getSignature().toShortString(), ms, slow.thresholdMs());
}
}
}
}The finally block runs for success and failure, so exceptions are timed too. System.nanoTime is the right clock for durations, because it is monotonic and not affected by wall clock changes. The timer is tagged with the method and outcome. Keep the tag values from user input out, to avoid unbounded cardinality in the metrics system.
Use it
@Service
class ReportService {
@SlowCheck(thresholdMs = 500)
public Report build(long customerId) { ... }
}The aspect needs spring-boot-starter-aop and the Actuator with a registry such as Prometheus. Then app_method_time_seconds appears in /actuator/prometheus with percentiles if you enable the histogram, as in finding slow endpoints.
The built-in alternatives
Before writing your own, check Micrometer's annotations:
@Timed(value = "report.build", percentiles = {0.5, 0.95, 0.99})
public Report build(long customerId) { ... }@Timed needs a TimedAspect bean:
@Bean
TimedAspect timedAspect(MeterRegistry registry) { return new TimedAspect(registry); }@Observed goes further and creates a span and a timer from one annotation with the Observation API. The custom aspect is useful when you also want to log slow calls or add business logic to the check.
Be careful with accuracy
- The measurement includes the aspect's own overhead and proxy dispatch, small but nonzero.
- Timing a transactional method from outside the transaction advice includes commit time; the order of aspects matters. Use
@Orderto place the timing aspect outside or inside the transaction advice depending on what you want to measure. - Asynchronous methods return before the work finishes, so a timer around an
@Asyncmethod measures only the submit.
Limits
Proxy AOP times only calls that enter through the proxy:
public void generate() {
build(1L); // not timed: self-invocation
}Move the timed method to another bean, or use AspectJ weaving. The explanation is in self-invocation and the choice in Spring AOP versus AspectJ.
Combine with logging
A timing aspect and a logging aspect share structure; keep them as separate aspects with distinct concerns.
Measuring honestly
A timing aspect gives numbers, and numbers from a cold JVM mislead. The first calls of any method run in the interpreter, and class loading and JIT compilation add their own cost, so a method that takes 40 ms the first time may take 2 ms once it is warm. Ignore the first few hundred calls when you judge a method, and read percentiles instead of averages: the 50th, 95th and 99th percentile tell you how the typical call and the worst calls behave, while a mean hides the tail that users actually complain about. Use System.nanoTime() for intervals, never System.currentTimeMillis(), because the wall clock can jump when the system synchronizes time.
Remember what the aspect measures. Around a service method it includes everything that method waits on: the database, a remote call, a lock. A slow number says the method is slow and not why. Use the timer to find which method to look at and a profiler to find out what inside it is slow.
Micrometer instead of log lines
For anything that stays in production, record a metric and do not write a log line per call. Micrometer's @Timed annotation does it, once you register the aspect:
@Bean
TimedAspect timedAspect(MeterRegistry registry) {
return new TimedAspect(registry);
}The annotation then records a timer named after the metric you give it, visible at /actuator/metrics/<name> and in any backend your registry exports to. Enable percentile histograms for the timers you care about with management.metrics.distribution.percentiles-histogram, and keep tag values low in cardinality: tag by method name or outcome, never by user id or order id, because every distinct value creates a new time series and a metrics backend can run out of memory on a runaway tag.
Proxy limits and ordering
The aspect works through a proxy, so it shares the proxy's limits. A call from one method to another inside the same class bypasses it, as with @Transactional, and private and final methods cannot be advised. The relative order of aspects also changes what you measure. If the timing aspect runs outside the transaction aspect, the time includes the commit, which is often where the slowness is. If it runs inside, you measure only the method body. Set @Order on the aspect deliberately, and say in a comment which one you meant, since the two readings differ by the cost of the commit.
Keeping it safe in production
Log only when a call crosses a threshold, such as 500 ms, so a healthy system produces no noise. Never log the arguments by default: arguments carry personal data, tokens and payloads, and a timing aspect that dumps them into the logs has created a privacy incident. Log the method name, the duration and, if you need it, a correlation id. Wrap the timing in try/finally, so a method that throws is still measured, and rethrow the original exception without changing it.
Testing the aspect itself
An aspect is code, and it can be wrong in ways that are invisible in normal runs. Write a test with a Spring context that contains the aspect and a small bean annotated with your timing annotation, call the method, and assert that the timer or log recorded one call with a plausible duration. A second test should have the method throw and assert that the exception reaches the caller unchanged and that the timing was still recorded. A third should call the method from another method of the same bean and assert that nothing was recorded, which documents the self-invocation limit in a way that no comment can.
When not to write your own
Before writing an aspect, check whether the tools you already have report the same thing. The Spring Data repositories, the web layer and the RestClient are all instrumented by Micrometer through the Actuator, with timers per route and per client, so a slow endpoint is visible in a dashboard without any code of yours. A custom aspect earns its place for a business operation that crosses layers, such as "price an order", where the interesting number is the total, and for temporary investigations, where you attach it for a day and remove it after.
When this does not apply
For finding hot spots in unknown code, a profiler beats instrumentation. See reading thread dumps for the stack view. References: Micrometer timers and Spring Boot observability.


