<?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 Lucas Borsatto on Medium]]></title>
        <description><![CDATA[Stories by Lucas Borsatto on Medium]]></description>
        <link>https://medium.com/@lucas01?source=rss-37a4826a85ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bSL6yjMVyrogjMz7.</url>
            <title>Stories by Lucas Borsatto on Medium</title>
            <link>https://medium.com/@lucas01?source=rss-37a4826a85ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:45:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucas01/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[Understanding Consistency in Databases: Beyond basic ACID]]></title>
            <link>https://medium.com/@lucas01/understanding-consistency-in-databases-beyond-the-basics-293013a50481?source=rss-37a4826a85ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/293013a50481</guid>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[isolation-level]]></category>
            <dc:creator><![CDATA[Lucas Borsatto]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 02:55:17 GMT</pubDate>
            <atom:updated>2025-06-02T12:09:14.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*qOzx2SZAkoJSZHqWRWJPiw.png" /><figcaption>What to do when dealing with N multiple transactions at the same time?</figcaption></figure><p>Most of the time we perform CRUD operations under the pragmatic standard transactional scope, thinking it will suffice under all circumstances. After all, what could go wrong when we always apply a standard ACID tool provided by our frameworks, right? But it feels “good enough” only until we face corner cases of the real world production traffic: missing rows after pagination, duplicated updates, or metrics that refuse to add up.</p><p>Going deeper in the reasons of why to use more than the traditional transactional, scope can be hard without some real world examples of when or how should we use something different from what we use to. In this article I revisit those issues through a tiny Spring Boot/Java code base. The example we will use run through the following steps:</p><ol><li><strong>Paginate</strong> 5 000 Sale rows whose status starts as NOT_INITIALIZED.</li><li><strong>Publish </strong>each id to a Kafka topic.</li><li><strong>Consume </strong>each message, updating its status to PROCESSING.</li><li>Demonstrate how plain idempotency checks and pagination fail under load.</li><li>Apply <strong>REPEATABLE READ</strong> isolation level and <strong>optimistic locking</strong> to restore consistency with much better performance.</li></ol><h4>Experiment set up</h4><p>The article code can be found on <a href="https://github.com/lucasbsimao/db-consistency-article">github here</a>. We will use a controller with three endpoints running different implementations of the proposed example:</p><pre>// ExperimentController<br>@PostMapping(&quot;/pagination-zero&quot;)<br>public ResponseEntity&lt;Void&gt; pagination() {<br>    Thread.ofVirtual().start(() -&gt; paginationZeroService.process(false));<br>    return ResponseEntity.accepted().build();<br>}<br><br>@PostMapping(&quot;/pagination-zero-fixed&quot;)<br>public ResponseEntity&lt;Void&gt; paginationFixed() {<br>    Thread.ofVirtual().start(() -&gt; paginationZeroService.process(true));<br>    return ResponseEntity.accepted().build();<br>}<br><br>@PostMapping(&quot;/repeatable-read&quot;)<br>public ResponseEntity&lt;Void&gt; repeatable() {<br>    Thread.ofVirtual().start(() -&gt; repeatableReadService.process());<br>    return ResponseEntity.accepted().build();<br>}</pre><p>We will use <em>/pagination-zero</em> to demonstrate the problem when we run on a default pagination implementation. After that we show why fixing pagination at 0 is necessary when no isolation level is applied, running the experiment on /<em>pagination-zero-fixed</em> endpoint. And on conclusion we show our final solution for the corner cases presented, running the <em>/repeatable-read</em> endpoint.</p><h3>What is an Isolation Level?</h3><p>We can think of isolation level to be the degree of <strong>visibility </strong>that CRUD operations have when two or more transactions are running concurrently. Taking our sales example in consideration, it would be translated to how much a transaction running the status update from NOT_INITIALIZED to PROCESSING can affect and be affected by other concurrent transactions.</p><p>By default, SQL databases support four types of isolation levels:</p><ul><li><strong>READ UNCOMMITED</strong> : No guarantees, rarely used. Transactions are not independent, and even in flight operations which were not yet commited are seen by other transactions, what is know as dirty reads.</li><li><strong>READ COMMITED</strong> : Applied by default. Guarantees that in flight CRUD operations are not seem by other running transactions. Only commited changes performed before operation starts are seen, preventing dirty reads. But the same query performed in two diffent places of the transaction can read two different values, what is known as non-repeatable read.</li><li><strong>REPEATABLE READ</strong> : All operations inside the transaction see a stable snapshot of the data related to that query, preventing dirty and non-repeatable reads. But fails when business rules depend on seing if another transaction updated its rows values to evaluate if it can proceed. This event is known as write-skew.</li><li><strong>SERIALIZABLE</strong> : Performs each CRUD operation in sequence, making database execute only one operation per time through locks or by abort-and-retry. Prevent all cited anomalies.</li></ul><p>So why not apply SERIALIZABLE directly? Cause the stronger the isolation level is, more you compromise your application performance. Under high workload, it may be impractical to apply such level depending on the circunstances. And that’s where <em>locking</em> strategies step in.</p><h3>Locking strategies</h3><p>Before we dive into the experiment itself, let’s refresh the two classic locking approaches:</p><ul><li>Pessimistic locking : Usually applied implementing FOR UPDATE for row-level or LOCK TABLEfor table-level directly on a query. It guarantees that no other transaction will alter the rows affected by this query by waiting locks to be released. It usually presents better performance when application shows significant more write workload than reads, because retries consume more resource under such circunstances.</li><li>Optimistic locking : Applies locking through adding a new column on desired table, which indicates the row version number or timestamp of the last update. When a transaction is about to affect a row, it has to check if its version of the row matches the one that is present on database. It can be done by simply putting something like UPDATE … WHERE id = ? AND version = ?in the SQL statement. If not, an retry can be done later. It usually presents better performance when application shows significant more read workload than writes, because retries are done more rarely.</li></ul><h3>The experiment — Pagination problems</h3><p>Lets consider our first implementation through <em>/pagination-zero </em>endpoint. The process of sending each row to kafka topic can be done as following:</p><pre>public void process() {<br>    Pageable pagination = PageRequest.of(0, 50);<br>    Page&lt;Sale&gt; pageSale;<br><br>    saleService.updateAllCreatedAt();<br><br>    do {<br>        pageSale = saleService.findAllByStatus(SaleStatus.NOT_INITIALIZED, pagination);<br><br>        pageSale.forEach(<br>            sale -&gt; {<br>                var event = new SaleEvent(sale.getId(), EventType.PAGINATION_ZERO);<br>                saleEventProducer.sendMessage(&quot;my-topic&quot;, &quot;key&quot;, event.toString());<br>            }<br>        );<br><br>        pagination = pageSale.getPageable().next();<br>    } while (pageSale.hasNext());<br>}</pre><p>And as we consume such events, we have to make sure that each sale set the proper status:</p><pre>public void processSaleEvent(Long id) {<br>    var sale = this.findById(id);<br>    if (sale.get().getStatus().equals(SaleStatus.PROCESSING))<br>        return;<br><br>    Sale sale = saleRepository.findById(id).orElseThrow();<br>    saleRepository.updateStatusById(id, SaleStatus.PROCESSING);<br><br>    var salePersisted = saleRepository.findById(id);<br>    var saleAudit = SaleAudit.fromSale(salePersisted.get());<br>    saleAuditRepository.save(saleAudit);<br>}</pre><p>Running such implementation, we can see the final result throuhg GET /status-count endpoint:</p><pre>[<br> {<br>  &quot;status&quot;: &quot;NOT_INITIALIZED&quot;,<br>  &quot;count&quot;: 3949<br> },<br> {<br>  &quot;status&quot;: &quot;PROCESSING&quot;,<br>  &quot;count&quot;: 1051<br> }<br>]</pre><p>So, what happened? Aren’t all sales supposed to be in PROCESSINGstatus?</p><p>Imagine that, after first pagination, the consumer could only update 8 sale rows to PROCESSINGbefore the loop on producer get the next page. Then, in the 2nd page the read is made just after the consumer commited its 8 sale updates, so its start point will be 8 rows after first page started. It will then skip 50 rows and initiate the page on position 58, simply not processing rows from 50 to 57.</p><p>The first approach one could try to solve it would be repeating pagination to be always at 0 on while loop, like on code below:</p><pre>public void process() {<br>    Pageable pagination = PageRequest.of(0, 50);<br>    Page&lt;Sale&gt; pageSale;<br><br>    saleService.updateAllCreatedAt();<br><br>    do {<br>        pageSale = saleService.findAllByStatus(SaleStatus.NOT_INITIALIZED, pagination);<br><br>        pageSale.forEach(<br>            sale -&gt; {<br>                var event = new SaleEvent(sale.getId(), EventType.PAGINATION_ZERO);<br>                saleEventProducer.sendMessage(&quot;my-topic&quot;, &quot;key&quot;, event.toString());<br>            }<br>        );<br><br>        //Since we are running locally, we have put it to sleep a bit to let consumer process messages<br>        try {<br>            Thread.sleep(40);<br>        } catch (InterruptedException ex) {<br>            System.out.println(&quot;Erro no thread sleep&quot;);<br>        }<br>         <br>        //Commenting paging number evaluation so it cant skip rows<br>        //pagination = pageSale.getPageable().next();<br>    } while (pageSale.hasNext());<br>}</pre><p>The code above is implemented when requesting endpoint /<em>pagination-zero-fixed.</em> This will make the loop repeat itself sometimes, and would produce the same message more than once since the findAll is faster than the update on our consumer.</p><p>But with this approach we find a couple of issues. The main one is that we are wasting resources simply looping and sending the same records again. That’s far from efficient and can take significally long if you dont have a proper settled cluster. For this experiment, which is running locally for example, it could take almost 10 times more than using proper pagination. We can verify it by requesting endpoint /<em>elapsed-time</em>:</p><pre>Total time elapsed in seconds: 151</pre><p>Besides, another issue comes with the duplication of messages, not only made by the producer but also due to default <a href="https://docs.confluent.io/kafka/design/delivery-semantics.html#exactly-once-support">Kafka guarantees</a> for the consumer. With that, Kafka could deliver more than one message for the consumer with at-least-one settled.</p><h3>The experiment — Solving pagination and duplicated messages</h3><p>With all those issues in mind, we can implement what we first proposed about isolation levels and locking strategies to solve the problem. In such case, the pagination issue we described in the last session is known as non-repeatable read, as we mentioned earlier. The minimum isolation level to solve it is REPEATABLE READ, and to achieve that on Spring is kind of simple:</p><pre>//Annotation guraranteeing REPEATABLE_READ isolation<br>@Transactional(isolation = Isolation.REPEATABLE_READ)<br>public void process() {<br>    Pageable pagination = PageRequest.of(0, 50);<br>    Page&lt;Sale&gt; pageSale;<br><br>    saleService.updateAllCreatedAt();<br><br>    do {<br>        pageSale = saleService.findAllByStatus(SaleStatus.NOT_INITIALIZED, pagination);<br><br>        pageSale.forEach(<br>            sale -&gt; {<br>                var event = new SaleEvent(sale.getId(), EventType.PAGINATION_ZERO);<br>                saleEventProducer.sendMessage(&quot;my-topic&quot;, &quot;key&quot;, event.toString());<br>            }<br>        );<br><br>        pagination = pageSale.getPageable().next();<br>    } while (pageSale.hasNext());<br>}</pre><p>And, with that we have the proper process concluded. Verifying again through endpoint <em>/status-count</em>:</p><pre>[<br> {<br>  &quot;status&quot;: &quot;PROCESSING&quot;,<br>  &quot;count&quot;: 5000<br> }<br>]</pre><p>And the amount of time taken by the operation according to <em>/elapsed-time </em>endpoint was:</p><pre>Total time elapsed in seconds: 24</pre><p>So, problem solved right? Not quite.</p><p>Remember that kafka, by default, guarantees at-least-once delivery. It means that the broker can, and will, deliver some messages more than once. The figure below shows what could happen if the interval between duplicated consumptions is low enough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dITzyakLm6UMqezHrAW28A.png" /><figcaption>When if idempotency does not suffice</figcaption></figure><p>So, in this image we can see that, if a second consumption is made while the first one didn’t update the sale to PROCESSING status, the second one will pass the idempotency we implemented on the snippet earlier:</p><pre>public void processSaleEvent(Long id) {<br>    var sale = this.findById(id);<br>    if (sale.get().getStatus().equals(SaleStatus.PROCESSING))<br>        return;<br><br>    // ...<br>}</pre><p>And now we have two sales registered on sale_audittable. We can easily simulate such scenario through a simple test:</p><pre>@Test<br>void simulateConcurrentUpdatesWithOCC() throws Exception {<br>    long saleId = 1L;<br><br>    ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>    executor.submit(() -&gt; {<br>        saleService.processSaleEvent(saleId, true);<br>        return &quot;Job1 succeeded&quot;;<br>    });<br><br>     executor.submit(() -&gt; {<br>        Thread.sleep(10);<br>        saleService.processSaleEvent(saleId, true);<br>        return &quot;Job2 succeeded&quot;;<br>    });<br><br>    executor.shutdown();<br><br>    assertThat(saleAuditService.findAll()).hasSize(1);<br>}</pre><p>The test will fail because, of course, there are two rows on sale_audit, not one as it was supposed to be.</p><p>And here is how locking strategies can help us. In our case, as the duplicate consumption is supposed to be rare, following the reasoning defined earlier we can apply optimistic locking. Let’s implement it as a version number in our Sale entity:</p><pre>@Entity<br>@Table(name = &quot;sale&quot;)<br>public class Sale {<br><br>    // The version of the row<br>    @Version<br>    private Long version;<br><br>    // ...<br>}</pre><p>And we also should check this version on every update, like on the following code snippet:</p><pre>@Modifying<br>@Transactional<br>@Query(&quot;&quot;&quot;<br>UPDATE Sale s<br>   SET s.status    = :status,<br>       s.updatedAt = CURRENT_TIMESTAMP,<br>       s.version   = s.version + 1<br> WHERE s.id       = :id<br>   AND s.version  = :expectedVersion<br>&quot;&quot;&quot;)<br>int updateStatusById(@Param(&quot;id&quot;) Long id, @Param(&quot;status&quot;) SaleStatus status, Long expectedVersion);</pre><p>And after calling the update, we check the number of rows updated to decide if to proceed or not:</p><pre>public void processSaleEvent(Long id, Boolean idempotency) {<br>  // This check is not needed anymore<br>  // var sale = this.findById(id);<br>  // if (sale.get().getStatus().equals(SaleStatus.PROCESSING))<br>  //    return;<br><br>  Sale sale = saleRepository.findById(id).orElseThrow();<br>  var rows = saleRepository.updateStatusById(id, SaleStatus.PROCESSING, sale.getVersion());<br><br>  if (rows == 0) return;<br><br>  // ...<br>}</pre><p>Now, returning to our diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olqBDbM7z7eIN8Xv7Gj4Hg.png" /><figcaption>Optimistic locking alone is sufficient to discart the duplicated event</figcaption></figure><p>Of course we could for example check if status was already in PROCESSINGdirectly in the update, but for didactic reasons I decided to show how it is usually implemented.</p><p>And now we finally can say that our implementation is safe, consistent and performant.</p><h3>Closing Thoughts</h3><p>Isolation levels and locking strategies are not for DBA experts only — they are very useful on day‑to‑day for every backend developer. And by switching one annotation and adding one column we recovered correctness <em>and</em> shaved more than 120 seconds off the job.</p><p>Happy consistent coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293013a50481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insights and Optimizations from Benchmarking Frameworks]]></title>
            <link>https://medium.com/@lucas01/insights-and-optimizations-from-benchmarking-frameworks-a089bf44320?source=rss-37a4826a85ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a089bf44320</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Lucas Borsatto]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 16:59:16 GMT</pubDate>
            <atom:updated>2025-04-26T19:25:30.937Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cutting up to 50% of Instances Costs with Go: A benchmark between Go, NextJS, Java and GraalVM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vB9Lv3lB0o5XUNlD.png" /><figcaption>Soiurce Image: <a href="https://crl2020.imgix.net/img/cloud-report-footer.png?auto=format,compress&amp;q=60&amp;w=1185">https://crl2020.imgix.net/img/cloud-report-footer.png</a></figcaption></figure><p><strong>TLDR:</strong> The results are on the charts at the bottom of this article, and source code for this article can be found on this <a href="https://github.com/lucasbsimao/benchmark-apis">repository here</a>;</p><p>In the microsservices architecture, applying observability with metrics like saturation and latency is a key component to understand and improve application performance. While the choice of algorithms and code optimizations often have the most significant impact in these metrics — you can check algorithms comparison across languages on sites like <a href="https://programming-language-benchmarks.vercel.app/">Vercel</a> — there are few references that explore efficiency of the language frameworks themselves.</p><p>This article aims to provide a broader benchmark perspective by evaluating a basic REST Api implemented in Java, Go, Kotlin and Node. To this end we will use <a href="https://github.com/lucasbsimao/benchmark-apis">Benchmark API</a>, which I developed to measure saturation and latency metrics and to explore possible performance optimizations in scenarios we will discuss here.</p><h4>Benchmark Setup</h4><p>The benchmark was runned on top of Docker compose and you can see more instructions about it on the project’s <a href="https://github.com/lucasbsimao/benchmark-apis/blob/main/README.md">README file</a>. The PC setup is:</p><ul><li>AMD Ryzen 7 5800H with Radeon Graphics 3.20 GHz</li><li>16,0 GB DDR4 3200 MHz</li><li>Runned in WSL2, Windows 11</li><li><a href="https://www.artillery.io/docs">Artillery</a> used to collect latency metrics</li></ul><p>All benchmarks runned with following docker compose configuration:</p><pre>deploy:<br>    resources:<br>      limits:<br>        cpus: &#39;6&#39;<br>        memory: 8g</pre><h4>Bechmark languages and frameworks</h4><ul><li>Java with GraalVM/Spring Boot</li><li>Java/Spring Boot</li><li>Java/Micronauts</li><li>Java/Quarkus</li><li>Kotlin/SpringBoot</li><li>Node/Nestjs</li><li>Go/Gin</li><li>Go/Chi</li></ul><h4>Benchmark API definition</h4><p>As the goal here is to collect requests latency, CPU and RAM usage, all APIs were developed following the definition below:</p><ul><li>Endpoint GET /benchmark with query parameter N</li><li>Declaration of an array with N positions</li><li>A for loop interacting N times, computing an arbitrary math function and attaching to an array position, to test Garbage Collectors</li></ul><p>Example request for the Api is:</p><pre>curl localhost:8080/benchmark?n=100</pre><h4>Artillery Configurations</h4><p>The benchmark was runned with the following Artillery configurations:</p><p>— Case 1</p><p>Warm up: Arrival rate of 150 users per sec for 60 seconds with N=800<br>Spike: Arrival rate of 300 users per sec for 60 seconds with N=800</p><p>— Case 2</p><p>Warm up: Arrival rate of 400 users per sec for 60 seconds with N=1<br>Spike: Arrival rate of 550 users per sec for 60 seconds with N=1</p><h3>RESULTS</h3><p>Now that we placed the the definitions around the benchmark, we will start discussing some results per language/frameworks. At the end we will make a comparative review of the top performers among them.</p><h4>Node results</h4><p>First, I chose NestJS as framework because it is widely used and offers some advantages like Convention over Configuration, Invertion of Control and built-in modularization. Here, we will compare two scenarios: one using NestJS with Express, without optimizations, and another NestJS using Fastify incorporating the <a href="https://www.npmjs.com/package/cluster">cluster</a> library.</p><p>Let’s begin with the results from Artillery Case 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ow0X-PliMg6EjN7orq4STg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Jq5zxLhenTg3--DeCheIOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FDJokeoE1TJNmKdcnGv4Bw.png" /><figcaption>NestJS with Express</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pJA28w6Fvvm9rMROVh5d3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mmJekuNZE6scGb4-pjuQ1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pvkgKDek4itFzdfjqXpXag.png" /><figcaption>NestJS with clustered Fastify</figcaption></figure><p>Considering that we blocked the event loop adopting N=800, it is expected that an application utilizing multi cluster would handle it better than one with single CPU core, although the CPU and RAM graphs indicate some concerning spikes with Fastify. But what if we shift the scenario to Artillery Case 2, which involves more concurrency and less CPU usage. Even then, we would expect that the optimized app to outperform, right? Well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FCKIigbh7ZyNFl1AyfBFSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vP--PMLZfO0c9fVDlcfjDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gywZnW-Wp5hN-OrWJBmQ6w.png" /><figcaption>NestJS with Express</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vDqYphAlY97tTxGIwOJMXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pvkBEAAHVMM6uJzI_ZCwSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iGJ_DSy0TnZRzTIfVL_UAw.png" /><figcaption>NestJS with clustered Fastify</figcaption></figure><p>And here we arrive at our first lesson. Due to the multiple spawned proccesses and the simple nature of our requests, the communication overhead between primary and worker proccesses leads to more CPU usage, which outweights the advantage of using multiples cores with cluster library.</p><p>The winner is then NestJS with clustered Express. Although the performance is very similar, Fastify is presenting a concerning increase on RAM usage. And with that, we have our second lesson: a technology or framework will not be a solution if we don’t pay attention to its limitations and to the potential performance bottlenecks it may introduce.</p><p>And of course, Node gives us some optimization options through parameters like <em>— max-old-space-size</em> to define how much RAM long term objects can occupy.</p><h4>Java/Kotlin results</h4><p>For Java, I selected some of most used frameworks: Spring Boot, Micronauts and Quarkus.</p><p>The results for Artillery Case 1 are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*H8t4JwiAWuQwJg0pHFZTUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WF0otRXeKaUaagPvEV1xqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CnFS_8_FwbvpP6SkGnQQDw.png" /><figcaption>Micronauts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TRblbisjcoag7Jp0e5cbOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9wknWFKKh1nduniVQxYT_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0MI9Bz4mqky7IaQmsImplw.png" /><figcaption>Quarkus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*1ePou-t1h2iCcCy8e6zdsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*kMH7VGvXWLGU6boX2VtTXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CmPy6ZevW12ggcGuAebXrQ.png" /><figcaption>Spring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iSawbbWVraZ5RuiPnY1usA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*viFZBS5uHxD3wUHk_fzI-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*a4dcZhJe1Xc0ymayn2YUNw.png" /><figcaption>Spring Native</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*p4Mr4vG8BRb6Zo7y1fNdXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6s8EU7WATTLy5p0OzWMp5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CnFS_8_FwbvpP6SkGnQQDw.png" /><figcaption>Kotlin with Spring</figcaption></figure><p>As the results seem to differ only slightly from one another, let’s examine the results for Artillery Case 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jFOSgl7FkfuByxpSkbB2AA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Fa1Pd86Vjga1FCc6KZevqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZftsYojPVqzZkWVc6a-7ow.png" /><figcaption>Micronauts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-Fqugm-y4agDABYnRACMYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*X0FMlB_uxIoACb5DiZG5nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6qFgwzQmss7Ju4a6gEGSog.png" /><figcaption>Quarkus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sauCqKYjFfMZkA_Gww49Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*16pjWkEe_EDfEOsea6Iueg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*L2Lvk2ehLe2p63mNR8bYoQ.png" /><figcaption>Spring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rj-X9lxjz5rLofG13gntyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-zfxTThSr0RxwIY0RvjV_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xIWlXqC22ehljaL_v30MHg.png" /><figcaption>Spring Native</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*R6BKlngDPn1PzgTdR6PS2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MCa8h3oFwk0-T6l4pVbNJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*h6nybkBhBjeHqYfpuJM1eQ.png" /><figcaption>Kotlin with Spring</figcaption></figure><p>And Quarkus is the winner here by a small margin. It’s important to note that Kotlin, even with coroutines, didn’t outperform others. This is likely because there’s no operation that actually suspends our coroutine during the request. As was mentioned earlier, the benefits of certain language features tends to be more perceptible in more complex applications where performatic algorithms would be applied. This applies for coroutines and other features that give Kotlin some advantage over Java.</p><p>Another point to consider is that, although Quarkus outperformed Spring Native, the last tends to use considerably less CPU resources, which favours a swarm up of the instance.</p><p>Finally, one always can improve RAM performance through parameters <em>-Xms</em> and <em>-Xmx</em>, or <em>-XX:+UseZGC</em> to change the application GC to a more performatic one. Although, it is not a requirement in such a simple API as ours.</p><h4>Go results</h4><p>Go is recognized as one of the most performatic languages on the market. This might lead us to assume that it would outperform other languages in any scenario. Is it? In this section we will review the benchmark results of both Go using Chi and Gin, which are two of the most popular Go frameworks. Here are the graphs for Artillery Case 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*W0S5cOsCvos7HOKq5-r8Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*n3vZTlb4TU0WgEEKjWeaBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*afX4nWrkTtHm7VZqq87vjg.png" /><figcaption>Go with Chi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BB_MpDiT0qGFu33qFuDTdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*soD15wqg-c9d6dBFdVKAmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*45XxPHh61d6fK29LdYctfw.png" /><figcaption>Go with Gin</figcaption></figure><p>Both have pretty similar performances, and that’s due to the fact that both use net/http under the hood. But despite the results from the first case, the results from Artillery Case 2 appear to be somewhat better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qsB-GSJNNBzmUmn0fbKlLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*umWM1fXUOp8GYVNre8iaxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b7YtM9GV9Kszy7TzPsTePw.png" /><figcaption>Go with Chi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2A-ZOq0GBXpVH7HzGo9vRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WKFxG9qy4wSnHjbxBOtrtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wc9vxwhoepafEmgY0WW7GQ.png" /><figcaption>Go with Gin</figcaption></figure><p>Both keep with pretty similar results, so we can in fact consider it a draw.</p><p>For further improvements in application performance, one can try changing the environment variable <em>GOMAXPROCS</em>, which has a default value that depends on the server settings.</p><p>Besides that, we can also improve the performance migrating from gin.Default instead of gin.New to initiate our server. Further more, we should also configure it with gin.SetMode(gin.ReleaseMode).</p><h3>SUMMARY OF RESULTS</h3><p>And here are the final results summarized. With Artillery Case 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ow0X-PliMg6EjN7orq4STg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Jq5zxLhenTg3--DeCheIOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FDJokeoE1TJNmKdcnGv4Bw.png" /><figcaption>NestJS with Express</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TRblbisjcoag7Jp0e5cbOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9wknWFKKh1nduniVQxYT_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0MI9Bz4mqky7IaQmsImplw.png" /><figcaption>Quarkus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*W0S5cOsCvos7HOKq5-r8Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*n3vZTlb4TU0WgEEKjWeaBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*afX4nWrkTtHm7VZqq87vjg.png" /><figcaption>Go with Chi</figcaption></figure><p>And with Artillery Case 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FCKIigbh7ZyNFl1AyfBFSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vP--PMLZfO0c9fVDlcfjDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gywZnW-Wp5hN-OrWJBmQ6w.png" /><figcaption>NestJS with Express</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-Fqugm-y4agDABYnRACMYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*X0FMlB_uxIoACb5DiZG5nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6qFgwzQmss7Ju4a6gEGSog.png" /><figcaption>Quarkus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qsB-GSJNNBzmUmn0fbKlLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*umWM1fXUOp8GYVNre8iaxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b7YtM9GV9Kszy7TzPsTePw.png" /><figcaption>Go with Chi</figcaption></figure><h3>CONCLUSION</h3><p>In summary, Go is clearly the most performatic framework on this benchmark. As you can see on the previous graphs, it uses 2 times less RAM and CPU. With that in mind, even though the latency percentiles we saw are pretty similar between frameworks, we could save up to 50% of instance costs, leading to significantly cost reduction. There are some reasons for this:</p><ul><li>Ahead of time compilation (AOT): Go is pre-compiled and optimized for machine code. But it’s important to notice that AOT implementation doesn’t guarantee superior performance over JIT. This can be observed by running this benchmark with Spring Native and comparing the results with those from Quarkus or Spring using JIT.</li><li>Goroutines: coroutines have the same purpose to threads, but they are more lightweight and can be suspended and resumed with greater ease. Coroutines can be created more frequently than threads, and they operate on top of Go’s thread pool.</li><li>Garbage Collection: GC in Go is designed to be as low latency as possible. Although Java has made significant improvements in garbage collection with the G1 and ZGC, Go’s GC is generally considered faster than its competitors.</li></ul><p>But of course, the choice of language and framework for your projects should be based on your team’s proficiency, functional and performance requirements, and in how much community support does that language and framework have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a089bf44320" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>