<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafał Kosiński on Medium]]></title>
        <description><![CDATA[Stories by Rafał Kosiński on Medium]]></description>
        <link>https://medium.com/@rafalkosinski07?source=rss-da2825d8a186------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4-vI5OHDE8GANqrNzE4ekA.jpeg</url>
            <title>Stories by Rafał Kosiński on Medium</title>
            <link>https://medium.com/@rafalkosinski07?source=rss-da2825d8a186------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:13:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafalkosinski07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring @DirtiesContext — false friend]]></title>
            <link>https://medium.com/bitso-engineering/spring-dirtiescontext-false-friend-de0e5b8b41cb?source=rss-da2825d8a186------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0e5b8b41cb</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[good-practices]]></category>
            <dc:creator><![CDATA[Rafał Kosiński]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 14:55:11 GMT</pubDate>
            <atom:updated>2024-11-27T14:55:11.059Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring @DirtiesContext — false friend</h3><p>@DirtiesContext is an annotation that, at first glance, seems like a time-saver for developing integration tests. But what happens when there’s an issue with the Spring context while running tests, or when your test disrupts others by interfering with the Spring context? It’s tempting to simply apply @DirtiesContext and watch everything work like magic, with tests passing smoothly. But is it truly a solution?</p><h3>How Spring context works in tests</h3><p>When your application runs locally or on a Kubernetes cluster in production mode, there is typically just one Spring context per application instance. However, that’s not the case for integration tests. In tests, multiple application contexts can exist. Why is that?</p><p>You can define your own context using @ContextConfiguration, and there can be multiple such definitions. Additionally, using different Spring profiles in your tests can increase the number of contexts. Furthermore, annotations like @MockBean or @SpringBean—used to mock beans—can also trigger the creation of new contexts.</p><p>As a result, it’s common to have multiple Spring contexts in your tests. Keep in mind that creating these contexts can be time-consuming, often accounting for the majority of the execution time for integration tests.</p><p>The size of the Spring context cache is configurable. You can adjust it using the spring.test.context.cache.maxSize property, with a default value of 32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlHc7MH7djWbqfpFon81uA.png" /><figcaption>Spring context caching</figcaption></figure><h3>When @DirtiesContext is used</h3><p>@DirtiesContext is used to close and remove the Spring context before or after a test. By default, this annotation destroys the context after test execution, preventing it from being reused by other tests. You can apply this annotation at both the class and method levels.</p><p>@DirtiesContext is typically used when something goes wrong with the Spring context. This may happen if your test modifies the context in a way that causes other tests to fail or if other tests alter the context state, leading to failures in your tests. As mentioned earlier, the context is reused to speed up test execution, so one test can inadvertently affect another by modifying the shared context.</p><p>It may be tempting to use @DirtiesContext when tests behave unpredictably. For example, consider an in-memory cache bean managed by Spring. One test modifies the cache but fails to clean it up afterward. A subsequent test expecting an empty cache encounters leftover data and fails. What can you do in this scenario? You realize the Spring context is corrupted. Here are your options:</p><ol><li><strong>Identify and fix the test that corrupts the context.</strong><br>Result: The context is restored to a proper state and can be reused by other tests.</li><li><strong>Annotate the test that corrupts the context with </strong>@DirtiesContext<strong>.</strong><br>Result: The problematic test still corrupts the context, but it won’t affect others, as its context is destroyed afterward.</li><li><strong>Use </strong>@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)<strong> to get a fresh Spring context for your test.</strong><br>Result: The test that corrupts the context remains unchanged but your test runs successfully. However, other developers may follow suit, recreating the context for their tests, significantly slowing down test execution.</li></ol><p><strong>What is the easiest solution?</strong> The third option.<br><strong>What is the proper solution?</strong> The first option.</p><p>Here’s another example — this time, configuration-related. This scenario occurred in my team. In one of our Java services, we use Postgres to store order-related data. For integration tests, we rely on Testcontainers to provide Postgres containers. These containers have a connection limit of 100. At some point, tests began failing with the following exception:</p><p>Caused by: java.sql.SQLNonTransientConnectionException: Too many connections</p><p>The connection limit in the configuration was well below 100. Annotating tests that used database connections with @DirtiesContext allowed them to pass, but this significantly increased execution time. For each new context, execution time increased by 2-3 seconds. There were about 30 more contexts created. In general, the effect of using @DirtiesContext becomes more severe with the increase in the context size and the number of integration tests affected by the annotation.</p><p>The root issue was that the connection limit mentioned above was applied to a single application context. We had up to 32 cached contexts (the default value), and with the maximum number of connections configured at 10, this resulted in a theoretical total of 320 connections (32 contexts × 10 connections). Since @DirtiesContext destroyed the context after each test, connections were released immediately, which resolved the issue. However, it required recreating the contexts multiple times, causing a noticeable slowdown in test execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pAvJ3bux1lK_HKQHjVdkg.png" /><figcaption>DB configuration issue</figcaption></figure><p>We found a resolution for the issue. We reduced the maximum number of database connections to 3. With the default context cache size of 32, this configuration allowed tests to use up to 96 connections (3 connections × 32 cached contexts). This adjustment enabled us to reuse cached contexts while avoiding the “too many connections” error. As a result, tests started passing with improved execution times.</p><h3>Summary</h3><p>It’s a quick fix to resolve test issues by resetting the Spring context, but overusing it can slow down test execution dramatically. Instead of using @DirtiesContext, focus on identifying and fixing the tests or configurations that are breaking the Spring context. It’s the right way to handle it.</p><p>Spring reuses contexts to speed up integration tests, but creating too many or mismanaging them can waste time. Pay attention to how your tests impact the context and remember about cleanups.</p><p>The goal is to keep tests running smoothly and efficiently while addressing problems at their source instead of just papering over them.</p><h3>Sources</h3><ul><li><a href="https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/ctx-management/caching.html">Context Caching :: Spring Framework</a></li><li><a href="https://docs.spring.io/spring-framework/reference/testing/annotations/integration-spring/annotation-mockitobean.html">@MockitoBean and @MockitoSpyBean :: Spring Framework</a></li><li><a href="https://www.baeldung.com/spring-boot-testing-pitfalls">Pitfalls on Testing with Spring Boot | Baeldung</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0e5b8b41cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitso-engineering/spring-dirtiescontext-false-friend-de0e5b8b41cb">Spring @DirtiesContext — false friend</a> was originally published in <a href="https://medium.com/bitso-engineering">bitso.engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Proxy Mechanism in Spring and Micronaut]]></title>
            <link>https://medium.com/bitso-engineering/demystifying-proxy-mechanism-in-spring-and-micronaut-ffb9c6cec231?source=rss-da2825d8a186------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb9c6cec231</guid>
            <category><![CDATA[bitso]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[micronaut]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <dc:creator><![CDATA[Rafał Kosiński]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 12:34:59 GMT</pubDate>
            <atom:updated>2024-01-23T12:34:59.192Z</atom:updated>
            <content:encoded><![CDATA[<p>One crucial aspect of Bitso’s core operations is its Trading Engine, which primarily focuses on order matching and trade generation from a broad perspective. Order matching is the process of pairing buy and sell orders. It ensures efficient trade execution by finding matching orders at compatible prices. We recently had the opportunity to improve one of the Trade Engine’s components: the Orders Service. While enhancing order persistence functionality, we encountered an issue related to the<a href="https://github.com/micronaut-projects/micronaut-core/blob/4.3.x/src/main/docs/guide/aop/retry.adoc#simple-retry"> <strong><em>@Retryable</em></strong></a> annotation in Micronaut. After the investigation, I discovered that the method on which <strong><em>@Retryable</em></strong><em> </em>was used wasn’t proxied to add the retry feature.</p><p>My findings are quite interesting, as it would work just fine with the same configuration using the Spring framework. This inspired me to write this article expanding on the proxy mechanisms employed by Spring and Micronaut, revealing intriguing differences in their approaches.</p><h3>Understanding the Proxy Mechanism</h3><p>Proxies play a pivotal role in both Spring and Micronaut, facilitating features such as AOP (Aspect-Oriented Programming) and transaction management or retry mechanisms. Proxies act as intermediaries, allowing the frameworks to inject additional behavior or control over annotated components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*YKryevJR2RNQKgbc" /><figcaption>Interface-based proxy pattern example</figcaption></figure><h4>Spring’s Proxy Mechanism</h4><p>Spring supports two main types of proxies:<a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html"> JDK dynamic proxies and CGLIB proxies.</a></p><p>Those are the two most used proxy approaches in the Java ecosystem as you also might know. Here are some interesting points to observe:</p><p><strong>JDK Dynamic Proxies</strong></p><ul><li>Creation at runtime: JDK dynamic proxies are created dynamically at runtime based on the interfaces implemented by the target class.</li><li>Interface-based: This type of proxy is interface-based, meaning that the target class must implement one or more interfaces to generate dynamic proxies.</li><li>Limitations: The main limitation is that JDK dynamic proxies can only proxy methods defined in interfaces.</li></ul><p><strong>CGLIB Proxies</strong></p><ul><li>Creation by code generation: CGLIB proxies are created through code generation at runtime by extending the target class.</li><li>Class-based: Unlike dynamic proxies, CGLIB proxies work with classes directly, allowing for the proxying of classes and methods not on interfaces.</li><li>Enhanced features: CGLIB proxies provide more flexibility but come with the cost of increased memory consumption and potential method overriding issues.</li><li>Limitations: CGLIB won’t work with final classes or methods as it cannot extend them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*wDuPY4DjLHF388AA" /><figcaption>Simplified representation of the CGLIB proxy</figcaption></figure><p>Understanding which type of proxy is in use is crucial for troubleshooting. If you encounter issues related to method visibility or unexpected behavior, it’s worth checking whether JDK dynamic or CGLIB proxies are employed.</p><p>More details on Spring proxy: <br><a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html">https://docs.spring.io/spring-framework/reference/core/aop/proxying.html</a></p><h4>Micronaut’s Proxy Mechanism</h4><p>In Micronaut, the proxy mechanism differs significantly from Spring’s runtime-oriented approach. Micronaut adopts a custom <a href="https://docs.micronaut.io/latest/guide/index.html#how">compile-time processing model</a>, leveraging annotation processors during compilation to generate proxies. This approach provides certain advantages in terms of performance and enables Micronaut’s efficiency in resource utilization.</p><p><strong>Compile-Time Processing</strong></p><ul><li>Proxies generated during compilation: Micronaut proxies are generated during compilation, allowing for efficient and optimized code.</li><li>Annotation processors: Micronaut relies on annotation processors to analyze annotated classes and generate the necessary proxy code.</li><li>Performance benefits: Since proxies are created at compile time, there is no runtime overhead associated with proxy creation, contributing to improved application performance in some areas(e.g., startup time).</li></ul><p>More details on Micronaut proxy:<a href="https://docs.micronaut.io/latest/guide/index.html#how"> https://docs.micronaut.io/latest/guide/index.html#how</a></p><h3>Proxy difference example</h3><p>Let’s check how Spring and Micronaut behave with similar configurations of retry features created by frameworks proxy.</p><p>The source code of the Spring example: <a href="https://github.com/rafal-kosinski/proxy-spring-example">https://github.com/rafal-kosinski/proxy-spring-example</a></p><p>The source code of the Micronaut example: <a href="https://github.com/rafal-kosinski/proxy-micronaut-example">https://github.com/rafal-kosinski/proxy-micronaut-example</a></p><p>In both projects there are classes:</p><ul><li><em>RetrySingletonExample</em>: A bean class created by annotation with the <em>retryMe</em> method demonstrating the use of the retry feature</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a36f159903ba9a1edd0222326abb59de/href">https://medium.com/media/a36f159903ba9a1edd0222326abb59de/href</a></iframe><ul><li><em>RetryCreatedByFactoryExample</em>: A bean class created by the <em>RetryFactory</em> class with the <em>retryMe</em> method demonstrating the use of the retry feature</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe010dd2752766069e01437865d686c1/href">https://medium.com/media/fe010dd2752766069e01437865d686c1/href</a></iframe><ul><li><em>RetryExecutor</em>:<em> </em>Executes<em> retryMe </em>in<em> RetrySingletonExample </em>and<em> RetrySingletonExample </em>once the application context loads</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60642ec78ebe64c05ee5f3db3615c866/href">https://medium.com/media/60642ec78ebe64c05ee5f3db3615c866/href</a></iframe><ul><li><em>RetryFactory</em>: Creates the <em>RetryCreatedByFactoryExample </em>bean</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23df1fdc7a883e66df87465283f62380/href">https://medium.com/media/23df1fdc7a883e66df87465283f62380/href</a></iframe><p>Once you start the applications or run the test present in the linked project you will see the following output on the console:</p><p>Spring example:</p><pre>Executing retryMe in class created by factory<br>Executing retryMe<br>Executing retryMe<br>Executing retryMe<br>Done<br>Executing retryMe in a class created using @Component<br>Executing retryMe<br>Executing retryMe<br>Executing retryMe<br>Done</pre><p>Micronaut example:</p><pre>Executing retryMe in a class created using @Singletion<br>Executing retryMe<br>Executing retryMe<br>Executing retryMe<br>Executing retryMe<br>Done<br>Executing retryMe in class created by factory<br>Executing retryMe<br>Done</pre><p>You can see that the <em>retryMe </em>is retried for in both <em>RetrySingletonExample </em>and<em> RetryCreatedByFactoryExample </em>in the Spring example, which is not the case for the Micronaut example. In Micronaut, the retry works only for the bean created using an annotation. For the bean created in <em>RetryFactory</em>, <em>RetryCreatedByFactoryExample</em>, retry was not applied.</p><h4>A closer look at proxies created for RetrySingletonExample</h4><p>First, let’s see how <em>RetrySingletonExample </em>was proxied by frameworks to add the retry feature.</p><p><strong>Spring</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0x-qA7VBvGEbS4Mehbp7w.png" /><figcaption>CGLIB proxy in the stack trace</figcaption></figure><p>In the stack trace of the <em>retryMe</em> method originating from <em>RetrySingletonExample</em>, we can see that CGLIB is used to proxy the method call and add the retry feature.</p><p><strong>Micronaut</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uYvmTOCyK-VvRB8-_OG3A.png" /><figcaption>Micronaut proxy in the stack trace</figcaption></figure><p>The stack trace of calling the same method, that is <em>retryMe</em>, in the Micronaut example of the use of proxy generated during compilation that is adding the retry feature. Once the project is built, we can see this proxy class in the build artifacts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAnMK-AkdG8GzP9bncS3wg.png" /><figcaption>Project tree depicting the proxy classes generated by Micronaut</figcaption></figure><p>Both frameworks created proxies to add the retry feature in their way and it works fine.</p><h4>Why retries for RetryCreatedByFactoryExample does not work in Mcronaut but it works in Spring?</h4><p>In the image shown above, we can spot classes with the <em>$Intercepted </em>suffix these classes intercept the calls to real objects like <em>RetrySingletonExample </em>adding extra features like retries, but we cannot spot such a class for <em>RetryCreatedByFactoryExample</em>. <strong>It means that this bean is not proxied, therefore no retry feature was added</strong>. Why is that?</p><p>Micronaut will not add a proxy for the object constructed by ourselves in the <em>RetryFactory</em>, where we are calling the constructor of <em>RetryCreatedByFactoryExample </em>as presented here:</p><pre>@Factory<br>public class RetryFactory {<br>    @Bean<br>    RetryCreatedByFactoryExample retryCreatedByFactoryExample() {<br>        return new RetryCreatedByFactoryExample();<br>    }<br>}</pre><p>In the Spring framework, the analogic configuration works, and the proxy is added on runtime using CGLIB similarly as it is for a bean created by annotation. That’s the use case where those two frameworks work differently for the same configuration because of their different approach to proxy objects.</p><h3>Summary</h3><p>To address the issue in the Orders Service mentioned at the beginning, where <strong><em>@Retryable</em></strong> was ineffective for a factory-created bean, we opted to use the <strong><em>@Singleton</em></strong> annotation. This adjustment successfully applied the retry proxy in Micronaut.</p><p>In summary, both Spring and Micronaut excel as frameworks, sharing similarities but differing in how they implement proxy mechanisms. The choice between them depends on your specific needs. Spring seems to provide more flexibility but comes with the cost of increased memory consumption and potential method overriding issues. Micronaut on the other hand emphasizes reduced memory consumption and optimized resource utilization for the cost of slightly limited proxy capability.</p><p><em>I hope this article is helpful. Thank you for taking the time to read it. If you could share, and comment, it would motivate me to create more content like this. I appreciate your honest feedback!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb9c6cec231" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitso-engineering/demystifying-proxy-mechanism-in-spring-and-micronaut-ffb9c6cec231">Demystifying Proxy Mechanism in Spring and Micronaut</a> was originally published in <a href="https://medium.com/bitso-engineering">bitso.engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>