1. Introduction

Spring Boot applications can have complex component graphs, startup phases, and resource initialization steps.

In this article, we’ll take a look at how to track and monitor this startup information via a Spring Boot Actuator endpoint.

2. Application Startup Tracking

Tracking the various steps during application startup can provide useful information that can help us to understand the time spent during various phases of application startup. Such instrumentation can also improve our understanding of the context lifecycle and the application startup sequence.

The Spring Framework provides the functionality to record the application startup and graph initialization. In addition, Spring Boot Actuator provides several production-grade monitoring and management capabilities via HTTP or JMX.

As of Spring Boot 2.4, application startup tracking metrics are now available through the /actuator/startup endpoint.

3. Setup

To enable Spring Boot Actuator, let’s add the spring-boot-starter-actuator dependency to our POM:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

We’ll also add the spring-boot-starter-web dependency as this is required to access endpoints over HTTP:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.1.2</version>
</dependency>

In addition, we’ll also expose the required endpoint over HTTP by setting the configuration property in our application.properties file:

management.endpoints.web.exposure.include=startup

Finally, we’ll use curl and jq to query the actuator HTTP endpoint and parse the JSON response, respectively.

4. Actuator Endpoint

In order to capture startup events, we need to configure our application with an implementation of the @ApplicationStartup interface. By default, the ApplicationContext for managing the application lifecycle uses a no-op implementation. This obviously performs no startup instrumentation and tracking, for minimal overhead.

Therefore, unlike other actuator endpoints, we need some additional setup.

4.1. Using BufferingApplicationStartup

We need to set the application’s startup configuration to an instance of BufferingApplicationStartup. This is an in-memory implementation of the ApplicationStartup interface provided by Spring Boot. It captures the events during Spring’s startup process and stores them in an internal buffer.

Let’s start by creating a simple application with this implementation for our application:

@SpringBootApplication
public class StartupTrackingApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(StartupTrackingApplication.class);
        app.setApplicationStartup(new BufferingApplicationStartup(2048));
        app.run(args);
    }
}

Here, we’ve also specified a capacity of 2048 for the internal buffer. Once the buffer reaches this capacity for events, no further data will be recorded. Therefore, it’s important that we use an appropriate value to allow storage of events based on the application complexity and the various steps executed during startup.

Crucially, the actuator endpoint is only available once this implementation is configured.

4.2. startup Endpoint

Now, we can start our application and query the startup actuator endpoint.

Let’s use curl to invoke this POST endpoint and format the JSON output using jq:

> curl 'http://localhost:8080/actuator/startup' -X POST | jq
{
  "springBootVersion": "2.5.4",
  "timeline": {
    "startTime": "2021-10-17T21:08:00.931660Z",
    "events": [
      {
        "endTime": "2021-10-17T21:08:00.989076Z",
        "duration": "PT0.038859S",
        "startTime": "2021-10-17T21:08:00.950217Z",
        "startupStep": {
          "name": "spring.boot.application.starting",
          "id": 0,
          "tags": [
            {
              "key": "mainApplicationClass",
              "value": "com.baeldung.startup.StartupTrackingApplication"
            }
          ],
          "parentId": null
        }
      },
      {
        "endTime": "2021-10-17T21:08:01.454239Z",
        "duration": "PT0.344867S",
        "startTime": "2021-10-17T21:08:01.109372Z",
        "startupStep": {
          "name": "spring.boot.application.environment-prepared",
          "id": 1,
          "tags": [],
          "parentId": null
        }
      },
      ... other steps not shown
      {
        "endTime": "2021-10-17T21:08:12.199369Z",
        "duration": "PT0.00055S",
        "startTime": "2021-10-17T21:08:12.198819Z",
        "startupStep": {
          "name": "spring.boot.application.running",
          "id": 358,
          "tags": [],
          "parentId": null
        }
      }
    ]
  }
}

As we can see, the detailed JSON response contains a list of instrumented startup events. It contains various details about each step such as the step name, start time, end time, as well as the step timing details. Detailed information about the response structure is available in the Spring Boot Actuator Web API documentation.

Additionally, the complete list of steps defined in the core container and further details about each step are available in Spring reference documentation.

An important detail to note here is that subsequent invocations of the endpoint do not provide a detailed JSON response. This is because the startup endpoint invocation clears the internal buffer. Therefore, we’ll need to restart the application to invoke the same endpoint and receive the full response again.

We should save the payload for further analysis if required.

4.3. Filtering Startup Events

As we’ve seen, the buffering implementation has a fixed capacity for storing events in memory. Therefore, it might not be desirable to store a large number of events in the buffer.

We can filter the instrumented events and only store those that may be of interest to us:

BufferingApplicationStartup startup = new BufferingApplicationStartup(2048);
startup.addFilter(startupStep -> startupStep.getName().matches("spring.beans.instantiate");

Here, we’ve used the addFilter method to only instrument steps with the specified name.

4.4. Custom Instrumentation

We can also extend BufferingApplicationStartup to provide custom startup tracking behavior to meet our specific instrumentation needs.

As this instrumentation is particularly valuable in testing environments rather than production, it’s a simple exercise to use a system property and switch between the no-op and buffering or custom implementations.

5. Analyzing Startup Times

As a practical example, let’s try to identify any bean instantiation during startup that might be taking a relatively long time to initialize. For example, this could be cache loading, database connection pooling, or some other expensive initialization during application startup.

We can invoke the endpoint as previously, but this time, we’ll process the output using jq.

As the response is quite verbose, let’s filter on steps that match the name spring.beans.instantiate and sort them by duration:

> curl 'http://localhost:8080/actuator/startup' -X POST \
| jq '[.timeline.events
 | sort_by(.duration) | reverse[]
 | select(.startupStep.name | match("spring.beans.instantiate"))
 | {beanName: .startupStep.tags[0].value, duration: .duration}]'

The above expression processes the response JSON to extract timing information:

  • Sort the timeline.events array in descending order.
  • Select all steps matching the name spring.beans.instantiate from the sorted array.
  • Create a new JSON object with beanName and the duration from each matching step.

As a result, the output shows a concise, ordered, and filtered view of the various beans instantiated during application startup:

[
  {
    "beanName": "resourceInitializer",
    "duration": "PT6.003171S"
  },
  {
    "beanName": "tomcatServletWebServerFactory",
    "duration": "PT0.143958S"
  },
  {
    "beanName": "requestMappingHandlerAdapter",
    "duration": "PT0.14302S"
  },
  ...
]

Here, we can see that the resourceInitializer bean is taking around six seconds during startup. This may be considered as contributing a significant duration to the overall application startup time. Using this approach, we can effectively identify this issue and focus on further investigation and possible solutions.

It’s important to note that ApplicationStartup is intended for use only during application startup. In other words, it does not replace Java profilers and metrics collection frameworks for application instrumentation.

6. Conclusion

In this article, we looked at how to obtain and analyze detailed startup metrics in a Spring Boot application.

First, we saw how to enable and configure the Spring Boot Actuator endpoint. Then, we looked at the useful information obtained from this endpoint.

Finally, we looked at an example to analyze this information in order to gain a better understanding of various steps during application startup.

As always, the code for this article is available over on GitHub.