Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

In this article, we’ll explore Micrometer metrics with a focus on tagging. We’ll use Micrometer in a Spring Boot application and apply various patterns to create simple metrics, such as counters and timers.

We’ll start by using Micrometer’s Builder API to create meters with variable tag values. Additionally, we’ll look at MeterProviders as an alternative that allows us to avoid potential performance issues. We’ll also use Spring AOP and Micrometer-specific annotations to record method invocations in a declarative manner.

Finally, we’ll cover best practices for naming conventions and selecting tag values, as well as common pitfalls to avoid.

2. Using the Builder API

We’ll use a simple Spring Boot service with a public function called foo() that takes the client device type as a String. For the code samples in this article, we’ll attempt to count and time each call to foo(), and tag the metrics with the device type passed as a parameter:

@Service
class DummyService {
    // logger, constructor

    public String foo(String deviceType) {
        log.info("foo({})", deviceType);
        String response = invokeSomeLogic();
        return response;
    }

    private void invokeSomeLogic() { /* ... */ }
}

Firstly, let’s add the Spring Boot Actuator dependency to our pom.xml, which will include the Micrometer dependencies:

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

A simple approach is to use the Micrometer fluent API to create different types of meters. When foo() is called, we create a Counter.builder with a meter name, then add the tag as a key-value pair.

Micrometer uses a MeterRegistry to manage and store all the meters we create. So we need to inject it into our service and use it in the final step of the builder chain – by calling register(). This actually builds and registers the meter.

Finally, we simply call the increment() method on the created Counter instance:

@Component
class DummyService {

    private final MeterRegistry meterRegistry;

    // logger, constructor

    public String foo(String deviceType) {
        log.info("foo({})", deviceType);

        Counter.builder("foo.count")
          .tag("device.type", deviceType)
          .register(meterRegistry)
          .increment();

        String response = Timer.builder("foo.time")
          .tag("device.type", deviceType)
          .register(meterRegistry)
          .record(this::invokeSomeLogic);

        return response;
    }

    private void invokeSomeLogic() { /* ... */ }
}

As we can see, registering a Timer is very similar to registering a Counter. The main difference is that instead of using increment() like a Counter, a Timer uses methods like record(). In our case, we use record() to pass in a function to execute. The Timer will wrap the function call, measure how long it takes, record the timing, and return the function’s result.

It’s important to know that a meter is uniquely identified by its name and its set of tags. For example, even if we use the builder pattern to create multiple Counters named “foo.count” with the same tag “device.type” set to “mobile“, they will actually refer to the same underlying metric. So, incrementing either one will update the same counter.

On the other hand, this approach has the downside of creating builder objects every time foo() is called. Depending on how often the method is invoked, this can increase garbage collection overhead and impact performance over time.

3. Exposing the Metrics

Now that we are monitoring the invocations of the foo() method, we can expose these metrics through Spring Boot Actuator. To do this, we update the management.endpoints.web.exposure.include property in the configuration and set it to metrics, or use ‘*’ to expose all endpoints:

management:
  endpoints.web.exposure.include: '*'

As a result, we can now view the metrics for foo() at /actuator/metrics/foo.count and /actuator/metrics/foo.time. For example, this is what is exposed for foo.time:

{
  "name": "foo.time",
  "baseUnit": "seconds",
  "measurements": [
    {
      "statistic": "COUNT",
      "value": 100
    },
    {
      "statistic": "TOTAL_TIME",
      "value": 5.5068953
    },
    {
      "statistic": "MAX",
      "value": 0
    }
  ],
  "availableTags": [
    {
      "tag": "device.type",
      "values": [ "mobile", "tablet", "smart_tv", "wearable", "desktop" ]
    }
  ]
}

As we can see, each metric also shows the list of available tags. We can use any of these tags to narrow the metric’s scope. For example, to inspect invocations for the desktop device type, we can use the endpoint /actuator/metrics/foo.time?tag=device.type:desktop.

4. Using Meter Providers

As discussed, using Micrometer’s Builder API has the drawback of creating builder objects on every function call. We can avoid this by leveraging the MeterProvider API. A MeterProvider follows a variation of the template design pattern, allowing us to reuse meters and reduce garbage collection overhead.

In the constructor, we’ll still use Counter.builder(), but instead of calling register(), we use the withRegistry(meterRegistry) variation. This returns a MeterProvider<Counter>, which we can store as a field in our service and reuse whenever needed.

The same approach works for other meter types like Timers, with the API returning a MeterProvider<Timer>:

@Service
class DummyService {

    private final MeterRegistry meterRegistry;
    private final Meter.MeterProvider<Counter> counterProvider;
    private final Meter.MeterProvider<Timer> timerProvider;

    // logger

    public DummyService(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;

        this.counterProvider = Counter.builder("bar.count")
          .withRegistry(meterRegistry);
        this.timerProvider = Timer.builder("bar.time")
          .withRegistry(meterRegistry);
    }

    // ...
}

Now, we can use the counterProvider and meterProvider fields to record metrics while intercepting calls to a new method, which we’ll call bar():

public String bar(String device) {
    log.info("bar({})", device);

    counterProvider.withTag("device.type", device)
        .increment();
    String response = timerProvider.withTag("device.type", device)
        .record(this::invokeSomeLogic);

    return response;
}

As we can see, we can use a MeterProvider to add tags dynamically and then call the meter-specific methods, such as increment() for a Counter or record() for a Timer.

5. Using AOP

In addition to the Builder and MeterProvider APIs, we can also define meters declaratively using Aspect-Oriented Programming (AOP).

Our component is a Spring-managed bean annotated with @Service; therefore, we can use Spring’s AOP support to automatically record metrics for method invocations and avoid managing the meters manually. To do this, we only annotate the method we want to observe with the appropriate Micrometer annotations.

For example, we can create a new method, buzz(), and annotate it with Micrometer’s @Counted and @Timed:

@Timed("buzz.time")
@Counted("buzz.time")
public String buzz(String device) {
    log.info("buzz({})", device);
    return invokeSomeLogic();
}

By doing this, we’ll automatically record the method’s invocations and expose the metrics through Actuator. However, since this relies on AOP, it’s important that calls to buzz() go through the Spring proxy; direct internal calls within the same class won’t be intercepted.

The dynamic tagging is supported for the @Timed and @Counted annotations, but it needs additional configuration. First, we need to enable the annotations observation from our config:

management:
  observations.annotations.enabled: true
  # ...

Additionally, we need to define a MeterTagAnnotationHandler bean to help the meter evaluate annotated parameters. While it can be configured to parse SpEL expressions, we’ll keep it simple and have it always return the annotated object’s toString() method:

@Bean
MeterTagAnnotationHandler meterTagAnnotationHandler() {
    return new MeterTagAnnotationHandler(
      aClass -> Object::toString,
      aClass -> (exp, param) -> pram.toString()
    );
}

Lastly, we’ll annotate the parameter of the buzz() method with @MeterTag. 

@Timed(value = "buzz.time")
@Counted(value = "buzz.count")
public String buzz(@MeterTag("device.type") String device) {
    log.info("buzz({})", device);
    return invokeSomeLogic();
}

As a result, the Timer that intercepts calls to buzz() will dynamically attach the “device.type” tag.

On the other hand, if we want to configure @Counted to work in the same way, we’ll need to register the CountedAspect bean and manually set a CountedMeterTagAnnotationHandler implementation:

@Bean
public CountedAspect countedAspect() {
    CountedAspect aspect = new CountedAspect();
    CountedMeterTagAnnotationHandler tagAnnotationHandler = new CountedMeterTagAnnotationHandler(
      aClass -> Object::toString,
      aClass -> (exp, param) -> "");
    aspect.setMeterTagAnnotationHandler(tagAnnotationHandler);
    return aspect;
}

6. Best Practices and Conventions

Micrometer encourages descriptive, lowercase names separated by dots for metrics and tags – such as “foo.time” and “device.type”. The metric name should provide meaningful context on its own, while tags add additional dimensions for filtering or grouping. 

We should avoid overly generic tags like “service” that aggregate unrelated metrics. Generic names can make it difficult to understand what the metric represents and reduce the usefulness of the collected data.

We should be cautious with dynamic tag values. Highly variable values can create many unique metric combinations, increasing cardinality and putting pressure on the monitoring system. In our demo, using “device.type” is safe because it has a limited set of values, keeping cardinality low.

7. Conclusion

In this tutorial, we explored different ways to create Micrometer metrics with variable tag values. We started by learning that a metric is uniquely identified by its name and tags, and manually created Counter and Timer meters using the Builder API.

Next, we saw that this approach can lead to creating builder instances on each method call, which can put pressure on the garbage collector. To address this, we explored using a MeterProvider to reuse meters and reduce overhead.

Finally, we leveraged Spring AOP and Micrometer-specific annotations like @Timed and @Counted to record method invocations declaratively. We also discussed best practices for using dynamic tags and following consistent naming conventions.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI – (cat=Spring)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)