spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Execution order of @Timed and @Transactional

Open dkroehan opened this issue 1 year ago • 2 comments

I use micrometer in a Spring Boot application to measure the execution time of a method. Given the following (Kotlin) method:

class MyClass(...) {

  @Timed(value = "my_timer")
  @Transactional
  fun doSomething() {
    // Some code that performs changes on the database
  }
}

I would expect that the @Timed annotation measures the total time that the method execution takes including the @Transactional handling. I compared it to measuring the time outside, as in the following example:

val start = System.nanoTime()
myClass.doSomething()
timer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS)

Since the time measuring is different I did some debugging and found out that the underlying io.micrometer.core.aop.TimedAspect runs after the @Transactional processing, which means the order is as follows:

  1. Transaction start
  2. Time measurement starts
  3. Method body execution
  4. Time measurement stops
  5. Transaction commits

What I would like to achieve is the following order:

  1. Time measurement starts
  2. Transaction start
  3. Method body execution
  4. Transaction commits
  5. Time measurement stops

I already opened an issue at micrometer: https://github.com/micrometer-metrics/micrometer/issues/5235, but they pointed me to the spring-framework issue tracker.

I already tried to use @DeclarePrecedence like this + @EnableAspectJAutoProxy on the @SpringBootApplication class, but it had no effect.

@Aspect
@DeclarePrecedence("TimedAspect, *")
public class TimedAspectPrecedence {

}

dkroehan avatar Sep 25 '24 19:09 dkroehan