Micronaut - Introduction to the Modern, JVM-Based, Full-Stack Framework
Table of Contents

Micronaut - Introduction to the Modern, JVM-Based, Full-Stack Framework

If you're in the JVM (Java Virtual Machine) world and curious about alternatives to Spring or Grails for developing modern web applications, you should check out Micronaut. It is a modern, lightweight, reactive framework for building high-performance, scalable, and cloud-native applications. The framework has a dedicated and official website at https://micronaut.io/.

Micronaut was first released as an open-source project in 2018 and has gained popularity among Java, Kotlin, and Groovy developers for its innovative features and developer-friendly approach. It was co-founded by Graeme Rocher, known for his work on the Grails framework, and Jeff Scott Brown, a prominent figure in the Groovy and Grails community. The new framework has been developed under the umbrella of Object Computing, Inc. (USA).

Furthermore, Micronaut can offer as rich a component set as one would expect from its more mature competitor, Spring framework. Indeed, there are useful similarities between them such as an online project generator with a display of available ecosystem of auto-configured libraries via https://micronaut.io/launch resembling https://start.spring.io/ or a command line tooling (Micronaut CLI). These and many other similarities may help to flatten the learning curve for developers who are familiar with other mature frameworks. However, despite these similarities, Micronaut has been built on different design principles and outperforms other frameworks in certain areas.  

One of Micronaut's novel features is the ability for ahead-of-time (AOT) compilation in Graal VM. This reduces startup time by compiling code at build time rather than runtime, which is the typical technique in Java. Compile-time Dependency Injection (CDI) is another significant feature that resolves injected dependencies during the compilation step rather than at runtime. This eliminates the need for standard runtime DI (Dependency Injection) frameworks' usage of runtime reflection and dynamic proxy generation. This results in shorter startup times and higher runtime performance because dependency resolution is done during compilation and adds no overhead during runtime.  

Micronaut also includes a slew of other essential components for developing Message-Driven Applications, Command Line Applications, HTTP Servers, and other applications. Micronaut Framework, in particular, enables Distributed Configuration, Service Discovery, HTTP Routing, and Client-Side Load Balancing for Microservices. Notable features include a non-blocking Netty-based HTTP server (but also Jetty, Tomcat, and others) and built-in support for unit and integration testing in its own test framework, which includes a mock server. Other features, such as multi-sourced configuration management, cloud-native deployment, observability, and security, make Micronaut ideal for developing microservices, serverless applications, and other cloud-native applications that require fast response times, scalability, and efficiency.

Reference Code

This is a sample of Java code, a simple REST controller in Micronaut outlining a validated endpoint and its test. This code has been used for benchmarking Micronaut performance in comparison to an analogous endpoint implemented in Spring and Quarkus (another competitive framework). Entire code can be found in this Gihub repository https://github.com/graemerocher/framework-comparison-2020.  

However the benchmarking has been carried out on the previous version of Micronaut 2.0 M2 and JDK 14 in April 2020 by Greame Rocher himself it still can illustrate the benefits of the design principles Micronaut has been built on. The benchmarking has been video recorded and can be watched on Youtube. Further down in the article the results of this comparison will illustrate the strengths and features of Micronaut.

@Controller("/")
public class MessageController {
   private final MessageService messageService;
   public MessageController(MessageService messageService) {
       this.messageService = messageService;
   }
   @Get(value = "/hello/{name}", produces = MediaType.TEXT_PLAIN)
   String hello(@NotBlank String name) {
       return messageService.sayHello(name);
   }
}

@MicronautTest
public class MessageControllerTest {
   @Inject
   @Client("/")
   RxHttpClient client;
   @Test
   void testMessage() {
       HttpResponse<String> response = client.toBlocking().exchange(
               "/hello/John",
               String.class
       );
       Assertions.assertEquals(
               HttpStatus.OK,
               response.status()
       );
       Assertions.assertEquals(
               "Hello John",
               response.body()
       );
   }
}

Boosting Developer Productivity with Micronaut

Micronaut provides built-in support for generating API documentation, making it easy to document API and share it with others through the OpenAPI (formerly Swagger) specification, a widely used standard for describing RESTful APIs.

The framework provides modular feature sets that can be selectively included or excluded in the application, depending on the requirements. It is easy to experiment with this modularity via https://micronaut.io/launch. For example, you can include only the required modules to cater for the specific application needs and thus reduce unnecessary overhead to keep the application lightweight and efficient. Each module comes with a sensible default configuration which automatically fits in default application setup for example caching, logging, security or the configuration can work out of the box but can be further customised either through the configuration files or programmatically.

Micronaut's built-in testing support speeds the feedback loop for tests and fosters the development of a full test pyramid from unit tests at the bottom to end-to-end testing at the top. Micronaut tests run around 60% quicker than Spring tests. In compared to the 7.2 seconds it takes the Spring Framework to execute the aforementioned sample test, Micronaut only took 4.3 seconds. Fast test execution aids in the creation of maintainable code and promotes TDD (Test Driven Development).  

Another advantage of Micronaut is its small memory footprint. Micronaut's memory use was found to be 60% less than that of its Spring equivalent when the code sample was run with a memory limitation specified via the command-line option -Xmx128m, which determines the top limit of heap size allocated to the Java Virtual Machine (JVM). This result carries the prospect of cost savings in infrastructure expenses for cloud-based applications because memory consumption directly influences operating costs.  

Furthermore, Micronaut's easy integration with common IDEs and build tools enhances the developer experience, for example. To interface with the project generator, Intellij Ultimate includes extra plugins.  

Additionally, Micronaut's comprehensive documentation, community support, and integrations with popular development tools and frameworks make it easy for developers to adopt and use effectively.

Performance and Scalability with Micronaut

Micronaut's built-in testing support speeds the feedback loop for tests and fosters the development of a full test pyramid from unit tests at the bottom to end-to-end testing at the top. Micronaut tests run around 60% quicker than Spring tests. In compared to the 7.2 seconds it takes the Spring Framework to execute the aforementioned sample test, Micronaut only took 4.3 seconds. Fast test execution aids in the creation of maintainable code and promotes TDD (Test Driven Development).  

Another advantage of Micronaut is its small memory footprint. Micronaut's memory use was found to be 60% less than that of its Spring equivalent when the code sample was run with a memory limitation specified via the command-line option -Xmx128m, which determines the top limit of heap size allocated to the Java Virtual Machine (JVM). This result carries the prospect of cost savings in infrastructure expenses for cloud-based applications because memory consumption directly influences operating costs.  

Furthermore, Micronaut's easy integration with common IDEs and build tools enhances the developer experience, for example. To interface with the project generator, Intellij Ultimate includes extra plugins.  

micronaut:
  caching:
    default:
      enabled: true
      maximumSize: 1000
      expireAfterAccess: 5m
    caches:
      cache2:
        enabled: true
        maximumSize: 500
        expireAfterWrite: 10m

import io.micronaut.cache.annotation.Cacheable

@Cacheable("cache2")
String getCachedData(String key) {
    // Logic to retrieve data based on key
    // ...
}

Security and Resilience with Micronaut

Micronaut allows developers to configure and implement various authentication mechanisms, such as OAuth 2.0, JWT (JSON Web Token), LDAP (Lightweight Directory Access Protocol), and more.

The framework provides also mechanisms for authentication and authorization, allowing to define fine-grained access controls based on roles, permissions, or custom logic. Developers can configure authorization rules using annotations, interceptors, or other mechanisms, to restrict access to certain parts of your application based on the user's role or other criteria.

Micronaut supports encryption of sensitive data, such as passwords, configuration properties, and other sensitive information, using various encryption algorithms and protocols. This helps protect against data breaches or unauthorised access to sensitive information. Micronaut includes built-in protection against common web security vulnerabilities, such as XSS and CSRF attacks. It provides security mechanisms to prevent malicious scripts from being injected into web pages and protects against CSRF attacks by generating and validating anti-CSRF tokens. Framework also supports integration with third-party security libraries and frameworks, such as Spring Security, Apache Shiro, and Keycloak, allowing you to leverage existing security solutions and customise security features based on the application's specific requirements.

Micronaut provides built-in support for various industry-standard security protocols, including OAuth, JWT (JSON Web Tokens), and others. This support simplifies the integration of modern authentication and authorization systems into Micronaut applications.  

What’s interesting, Micronaut provides built-in fault tolerance features, such as circuit breakers and retries, that enhance application resilience in distributed environments. These features help applications to gracefully handle failures and errors, improving overall system resilience and reliability. Micronaut circuit breaker feature monitors the success and failure rates of external service calls and can automatically open the circuit (i.e., trip the breaker) when the failure rate exceeds a certain threshold. This prevents further requests to the failing service, allowing the system to gracefully degrade and recover from failures. Circuit breakers can be easily configured using Micronaut annotations or configuration properties, and they provide options for customising circuit breaker behaviour, such as retrying failed requests, fallback actions, and more.

Sample of a resiliency configuration in application.yaml

micronaut:
  circuit-breaker:
    default:
      failureThreshold: 5
      delay: 1000
      timeout: 5000
      successThreshold: 3
      rollingWindow: 10000

And a call to external service:

import io.micronaut.circuitbreaker.annotation.CircuitBreaker

@Controller("/example")
class ExampleController {

    @Get("/callExternalService")
    @CircuitBreaker(reset = "30s") // specify reset interval
    String callExternalService() {
        // Make an external service call here
        
        // Simulate a failure condition for demonstration purposes
        if (Math.random() < 0.5) {
            throw new RuntimeException("External service call failed");
        }
        
        return "Success";
    }
}

Micronaut provides built-in observability features, such as distributed tracing and metrics, that can greatly aid in monitoring and troubleshooting applications. These features including logging and error handling enable developers to gain insights into the behaviour and performance of their applications, helping them to identify and resolve issues efficiently.

Conclusion

Many companies, like Alibaba, Target, Microsoft, Boeing, and others, are putting Micronaut to use in production because they anticipate numerous gains in speed, scalability, and developer efficiency. Low-memory footprint design, rapid cold-start, well-integrated reactive model, and cloud-native deployment are some of the important advantages. All of this facilitates microservice architecture and its benefits such as demand-driven horizontal dynamic scalability.  

Micronaut's Cloud-Native Capabilities, which are well-suited for building applications deployable in cloud environments with built-in support for common cloud technologies such as Docker, Kubernetes, and AWS Lambda, and it also includes features such as distributed tracing, service discovery, and configuration management that are essential for building modern cloud applications, are also worth considering. All of these makes Micronaut a viable alternative to other frameworks.

If you want us to analyse whether Micronaut is good for your business, contact us here.

Resources and references

Liked the article? subscribe to updates!
360° IT Check is a weekly publication where we bring you the latest and greatest in the world of tech. We cover topics like emerging technologies & frameworks, news about innovative startups, and other topics which affect the world of tech directly or indirectly.

Like what you’re reading? Make sure to subscribe to our weekly newsletter!
Categories:
Share

Join 17,850 tech enthusiasts for your weekly dose of tech news

By filling in the above fields and clicking “Subscribe”, you agree to the processing by ITMAGINATION of your personal data contained in the above form for the purposes of sending you messages in the form of newsletter subscription, in accordance with our Privacy Policy.
Thank you! Your submission has been received!
We will send you at most one email per week with our latest tech news and insights.

In the meantime, feel free to explore this page or our Resources page for eBooks, technical guides, GitHub Demos, and more!
Oops! Something went wrong while submitting the form.

Related articles

Our Partners & Certifications
Microsoft Gold Partner Certification 2021 for ITMAGINATION
ITMAGINATION Google Cloud Partner
AWS Partner Network ITMAGINATION
ISO 9001 ITMAGINATIONISO-IEC 27001:2013 ITMAGINATION
© 2024 ITMAGINATION. All Rights Reserved. Privacy Policy