<?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 Prashant Pandey on Medium]]></title>
        <description><![CDATA[Stories by Prashant Pandey on Medium]]></description>
        <link>https://medium.com/@pandepra?source=rss-5a4ba3e91298------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IHMVafPIn3DCtuHW7dHZRw.jpeg</url>
            <title>Stories by Prashant Pandey on Medium</title>
            <link>https://medium.com/@pandepra?source=rss-5a4ba3e91298------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:17:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pandepra/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[A Tale of Scale: Virtual Threads in Java]]></title>
            <link>https://pandepra.medium.com/a-tale-of-scale-virtual-threads-in-java-aca5a8b95da0?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca5a8b95da0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 19:35:37 GMT</pubDate>
            <atom:updated>2025-07-25T16:31:33.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fm1ci91sg9I3fu2_5WXSDQ.png" /></figure><p>Java’s virtual threads represent a fundamental shift in how we build concurrent applications using Java. In addition to just making traditional Java threads lighter (as the name might suggest), they position Java as a serious contender for writing high-performance, cloud-native applications at internet scale, a space where languages like Go have traditionally excelled. Cloud-native applications share a few common traits:</p><ul><li>They are <em>massively</em> concurrent. A small container should be able to handle hundreds of thousands of connections at the same time (“internet scale applications”).</li><li>They are I/O bound — Most threads are waiting for a majority of their lifetimes, waiting for responses from the DB or downstream services.</li><li>Requests are short-lived — A typical request will typically be served in a few hundred milliseconds.</li></ul><h4><strong>Motivation for Virtual Threads</strong></h4><p>Java has had excellent multi-threading support from day 1. Then what was the need of virtual threads?</p><p>To understand this, let us take a quick look at the current multi-threading model in Java. Threads in Java are simply the underlying platform threads. When we create a thread:</p><pre>Thread t = new Thread(() -&gt; handleRequest())</pre><ul><li>The JVM makes a bunch of system calls to spawn a new OS thread.</li><li><strong>The lifecycle of the thread is then managed by the OS, till it terminates</strong>. The OS also takes care of scheduling the thread (preemptively).</li></ul><p>Simply put, Java’s threads are thin wrappers over platform threads. This threading model made perfect sense when Java added it. The nature of applications back then was a bit different than applications we have now:</p><ul><li>They were monolithic, unlike modern cloud-native applications that are often distributed and small. The latter kind of applications involve a lot of network calls, which means threads are mostly waiting for data to arrive on sockets.</li><li>Weren’t massively concurrent (tens of connections per JVM was the norm), so not expected to handle thousands of connections concurrently.</li><li>Connections were long lived, unlike today’s short-lived requests (so the application doesn’t need to create a large number of threads quickly).</li></ul><p>In this context, creating a limited number of platform threads and handing over their life-cycle management to the OS made sense.</p><p>But in the context of cloud-native applications, this makes Java’s current multi-threading model orthogonal to the requirements:</p><ul><li>A platform thread typically occupies around 1M of stack, this puts a significant limit on the number of threads you can create in a JVM. This ultimately limits our application’s throughput.</li><li>Creating threads on the fly is expensive, as it involves a bunch of system calls. In modern day web apps, we typically need to create hundreds of threads in seconds. Currently, this is solved with techniques like thread pooling and executor services, but it they have their own caveats and limitations.</li><li>Context switching across platform threads is expensive, and limits the application concurrency.</li></ul><p>Virtual threads solve these problems. And some more, which we will see further down.</p><h4><strong>What Exactly Are They?</strong></h4><ul><li>Virtual threads are lightweight, user-space threads, running in the JVM whose entire lifecycle is managed by the JVM, rather than the OS.</li><li>They are akin to Go’s Goroutines or Kotlin’s coroutines (with native JVM support, however).</li><li>A virtual thread is scheduled (mounted) on a platform thread, but when it blocks, instead of scheduling out the platform thread, the JVM swaps it with some other virtual thread.</li><li>This makes sure that the underlying platform thread is not blocked.</li><li>All scheduling is done by the JVM transparently to the user.</li></ul><h4>What Problems do they Solve?</h4><ul><li>Since they are lightweight (typical stack size 4K), launching them en-masse is cheap.</li><li>A single JVM can support hundreds thousands of them without running out of resources, so they enable our applications to be <em>massively</em> concurrent.</li><li>With cooperative scheduling, the JVM ensures that the underlying platform threads are not blocked — This increases the application throughput.</li><li><em>Codes like blocking, performs like non-blocking.</em> Barrier to entry to task parallelism in Java is reduced.</li></ul><h4><strong>Walk the Walk: Virtual Threads in Action!</strong></h4><p>Before we delve into the vagaries of virtual threads, I want to convince the reader that they are actually needed. In the following sections, we will go on a journey, one that will closely resemble Java’s own journey to virtual threads.</p><p>We will write a very simple TCP <em>echo</em> server - The server simply reverts back the string a client sends to it. We will bombard each version of the server with request and see how many each can handle.</p><p>We will use this client to bombard our servers with connections (this is basically a primitive DDoS client) to simulate high loads:</p><pre>public class CrazyClient {<br><br>  private static final int port = 8091;<br>  private static final int noConnections = 10_000;<br><br>  public static void main(String[] args) throws IOException, InterruptedException {<br>    IntStream.range(0, noConnections)<br>        .forEach(i -&gt; {<br>          try {<br>            Socket clientSocket = new Socket(&quot;localhost&quot;, port);<br>          } catch (IOException e) {<br>            e.printStackTrace();<br>          }<br>        });<br>    Thread.sleep(Integer.MAX_VALUE);<br>  }<br>}</pre><h4><strong>Version 1: 1 Thread-Per-Connection</strong></h4><p>In this version, we’ll create a single (platform) thread to handle each connection.</p><pre> package loom;<br><br>import java.io.*;<br>import java.net.ServerSocket;<br>import java.net.Socket;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class PlatformThreadedServer {<br><br>    private static final ExecutorService ES = Executors.newCachedThreadPool();<br><br>    public static void main(String[] args) throws IOException {<br>        ServerSocket ss = new ServerSocket(8091);<br>        int conns = 0;<br>        while (true) {<br>            //main thread -&gt; just listens<br>            Socket socket = ss.accept();//blocks<br>            System.out.println(&quot;Connected to client..., total: &quot; + (++conns));<br>            //workers threads 1:1 for each connection<br>            ES.submit(() -&gt; handleRequest(socket));<br>        }<br>    }<br><br>    private static void handleRequest(Socket socket) {<br>        try (<br>                PrintWriter out =<br>                        new PrintWriter(socket.getOutputStream(), true);<br>                BufferedReader in = new BufferedReader(<br>                        new InputStreamReader(socket.getInputStream()));<br>        ) {<br>            String inputLine;<br>            // blocks<br>            while ((inputLine = in.readLine()) != null) {<br>                // blocks if the socket is not ready for writes<br>                out.println(inputLine);<br>            }<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br><br>    }<br>}<br></pre><p>What goes on above is:</p><ol><li>The main thread opens a server socket on port 8091.</li><li>It then continuously listens to incoming connections on this port in a loop.</li><li>For every new connection, it creates a runnable and submits it to an cached executor service. This frees up the main thread to listen for incoming connections.</li><li>The ES will create platform threads on demand — For each connection, it create one platform thread.</li><li>Each worker thread in the ES, listen on the corresponding input stream for data. If there is nothing to read, the underlying OS suspends the thread and moves it to waiting.</li><li>The thread remains in the waiting state till some data appears on the socket. At some point in future, the OS moves the thread back to runnable.</li><li>The corresponding thread acquires the CPU and reads the incoming data and processes it.</li></ol><p>This is a classic example of task parallelism wherein we distribute workers among workers across task boundaries. In our case, the task is a request.</p><h4>Limitations</h4><ol><li>The server creates 1 platform thread for each connection. Assuming a platform thread occupies 1M of stack on most JVMs, we have a limit on the number of threads we can create.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*6r3Dw4zE-39yuQhP_4DV5A.png" /></figure><p>2. On my machine, I ran out of memory to to create more threads when the no of concurrent connections reached 4067.</p><pre>Connected to client..., total: 4067<br>[6.302s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 4k, detached.<br>Exception in thread &quot;main&quot; java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached<br>	at java.base/java.lang.Thread.start0(Native Method)<br>	at java.base/java.lang.Thread.start(Thread.java:802)<br>	at java.base/java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:945)<br>	at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1364)<br>	at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123)<br>	at loom.PlatformThreadedServer.main(PlatformThreadedServer.java:23)<br>[12.356s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 4k, detached.</pre><p>3. A good question to perhaps ask yourself at this point is — <strong>Since the thread is just lying idle, can I schedule some other task on it? </strong>We will soon find the answer to this question. For now, let us carry on.</p><h4><strong>Version 2: Java NIO + Event Loop</strong></h4><p>Non-blocking I/O is a good way to scale our applications. If you look at the previous server code, there are certain points where our threads get blocked:</p><pre>  // blocking call<br>  Socket socket = ss.accept();<br>  //blocking call<br>  in.readLine();</pre><p>These blocking calls are anathema to scalability. Thousands of your threads are just lying idle, occupying resources, waiting for the sockets to have some data. Java NIO (Non-blocking I/O) helps us around limitation.</p><p>So our next version of the server will use non-blocking calls using NIO everywhere:</p><pre>package loom;<br><br>import java.io.IOException;<br>import java.net.InetSocketAddress;<br>import java.nio.ByteBuffer;<br>import java.nio.channels.ServerSocketChannel;<br>import java.nio.channels.SocketChannel;<br>import java.util.Map;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class PlatformThreadedServerPoll {<br><br>  //contains a map of socket channels to their corresponding byte buffers so that we don&#39;t have to allocate them again and agian<br>  private static final Map&lt;SocketChannel, ByteBuffer&gt; FDS = new ConcurrentHashMap&lt;&gt;();<br>  private static final ExecutorService ES = Executors.newCachedThreadPool();<br><br>  public static void main(String[] args) throws IOException {<br>    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();<br>    serverSocketChannel.configureBlocking(false);<br>    serverSocketChannel.bind(new InetSocketAddress(8091));<br>    ES.submit(() -&gt; {<br>      //this runnable is executed on the event loop thread<br>      while (true) {<br>        FDS.forEach((fd, bb) -&gt; {<br>          bb.clear();<br>          try {<br>            int read = fd.read(bb); //event loop does not block here<br>            //if there is data on the socket, then serve it<br>            if (read &gt; 0) {<br>              //echo back<br>              bb.flip();<br>              fd.write(bb);<br>            }<br>          } catch (IOException e) {<br>            e.printStackTrace();<br>          }<br>        });<br>      }<br>    });<br>    int conns = 0;<br>    //main thread continuously listens to incoming connections in a loop<br>    while (true) {<br>      SocketChannel socketChannel = serverSocketChannel.accept(); // non-blocking<br>      if (socketChannel != null) {<br>        System.out.println(&quot;Connections: &quot; + (++conns));<br>        //the corresponding socket is configured to non-blocking mode.<br>        //non-blocking simply means reads from/writes to this socket doesn&#39;t block the thread<br>        socketChannel.configureBlocking(false);<br>        //NIO uses bytebuffers<br>        FDS.put(socketChannel, ByteBuffer.allocate(1024));<br>      }<br>    }<br>  }<br><br>}</pre><p>Here’s a quick run-down of how this works:</p><ol><li>A thread (main) continuously listens to incoming connections in a loop.</li><li>For every new connection, it configures the corresponding socket as non-blocking, creates a ByteBuffer for that socket and puts both into a Map&lt;SocketChannel,ByteBuffer&gt; .</li><li>Another thread (the event loop) continuously iterates through this map, checks if it is has some data in it (busy-waiting). Note that this check is non-blocking — The event loop is not blocked anywhere during this check.</li><li>For every socket that is ready, the event loop serves it (so make sure you do not have long running operations on this event loop, and advice you might carry over from the NodeJs world!).</li></ol><p>This server is quite scalable — I could establish 10k concurrent connections to it before my client threw this exception. This happens because I ran out of file descriptors on my machine. This can be handled by increasing this limit, but I did not bother:</p><pre>java.net.SocketException: Too many open files<br>	at java.base/java.net.Socket.createImpl(Socket.java:533)<br>	at java.base/java.net.Socket.&lt;init&gt;(Socket.java:504)</pre><h4><strong>Limitations</strong></h4><p>The main limitation of this model is the polling — It’s sub-optimal and spikes our application’s CPU usage. In this particular example, we have 1 connection polling thread and 1 event loop. Both of these threads are scheduled to 2 cores, leading to a 2/8 = 25% CPU usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*bxLprvNHCBPGF3qACwsdgg.png" /></figure><p>Polling isn’t a good idea and we need an event driven model. This is exactly what the next version solves.</p><h4><strong>Version 3: Java NIO + Selector</strong></h4><p>In Java NIO, selectors provide us a way to monitor multiple channels for events. Before this, we were doing this by polling. Whenever any of these events occur, the selector notifies the application which can then serve it. Here’s the code:</p><pre>package loom;<br><br>import java.io.IOException;<br>import java.net.InetSocketAddress;<br>import java.nio.ByteBuffer;<br>import java.nio.channels.SelectionKey;<br>import java.nio.channels.Selector;<br>import java.nio.channels.ServerSocketChannel;<br>import java.nio.channels.SocketChannel;<br>import java.util.Set;<br><br>public class PlatformThreadedServerSelector {<br>    public static void main(String[] args) throws IOException {<br>        Selector selector = Selector.open();<br>        ServerSocketChannel ssc = ServerSocketChannel.open();<br>        ssc.bind(new InetSocketAddress(&quot;localhost&quot;, 8091));<br>        ssc.configureBlocking(false);<br>        //will notify for any ACCEPT events (new connections)<br>        ssc.register(selector, SelectionKey.OP_ACCEPT);<br>        ByteBuffer bb = ByteBuffer.allocate(1024);<br>        int conns = 0;<br>        while (true) {<br>            selector.select();<br>            //get all selected events<br>            Set&lt;SelectionKey&gt; selectedKeys = selector.selectedKeys();<br>            for (var key : selectedKeys) {<br>                //if the event is OP_ACCEPT, i.e., new connection<br>                if (key.isAcceptable()) {<br>                    try {<br>                        SocketChannel client = ssc.accept();<br>                        if(client != null) {<br>                            System.out.println(&quot;Connected...conns: &quot; + (++ conns));<br>                            client.configureBlocking(false);<br>                            client.register(selector, SelectionKey.OP_READ);<br>                        }<br>                    } catch (IOException e) {<br>                        throw new RuntimeException(e);<br>                    }<br>                } else if (key.isReadable()) {<br>                    //if data is available on the socket to read<br>                    try {<br>                        echo(bb, key);<br>                    } catch (IOException e) {<br>                        throw new RuntimeException(e);<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    private static void echo(ByteBuffer bb, SelectionKey key) throws IOException {<br>        SocketChannel client = (SocketChannel) key.channel();<br>        int read = client.read(bb);<br>        if (read == -1) {<br>            client.close();<br>        } else {<br>            bb.flip();<br>            client.write(bb);<br>            bb.clear();<br>        }<br>    }<br>}<br></pre><p>Selectors use Linux’s underlying <em>epoll</em> mechanism to avoid polling. This server is more scalable than the previous server with polling, and it does so without mindlessly occupying the CPU. In the background, it uses Linux’s <em>epoll</em> facility for materializing this event driven model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*qgBFNYvl1CKAkmDErVpYOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*ER6ZAzD_kVc3nE7T-NRfJA.png" /></figure><h4>Limitations</h4><p>One of the main limitations of the Java NIO library is its complex and unintuitive API, which makes it difficult for most developers to use effectively. The programming model is not very idiomatic and often requires familiarity with low-level, niche constructs of the JDK, such as selectors, channels, and non-blocking I/O loops. Developers generally prefer writing straightforward, imperative code that still delivers high performance. This disconnect is a major reason why NIO never gained widespread adoption among Java developers.</p><h4><strong>Version 4: Reactive Java</strong></h4><p>Before the arrival of virtual threads, many teams adopted Reactive Java frameworks (Reactor, RxJava, Akka Streams) to solve I/O‑bound, high‑concurrency requirements without relying on large pools of OS threads. The core ideas are:</p><ol><li><strong>Non‑blocking I/O everywhere</strong>: Utilize Netty or NIO under the covers to avoid blocking system calls.</li><li><strong>Event-driven, callback‑style APIs</strong>: Developers compose data‑flows with operators (map, <a href="https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95">flatMap</a>, filter, etc.) to react to signals (data, errors, completion).</li><li><strong>Back-pressure support</strong>: The framework signals upstream producers when consumers cannot keep up (via Flux/Flowable semantics).</li></ol><pre>import reactor.netty.tcp.TcpServer;<br><br>public class ReactiveEchoServer {<br>  public static void main(String[] args) {<br>    TcpServer.create()<br>      .host(&quot;localhost&quot;)<br>      .port(8091)<br>      .handle((inbound, outbound) -&gt;<br>        outbound.sendString(<br>          inbound.receive()<br>                 .asString()<br>        )<br>      )<br>      .bindNow()<br>      .onDispose()<br>      .block();<br>  }<br>}</pre><h4>Benefits</h4><ol><li><strong>Scalability</strong>: The server can handle tens of thousands of concurrent connections on a single JVM, because it uses a small, fixed number of event‑loop threads.</li><li><strong>Memory footprint</strong>: A handful of long‑lived threads (not one per connection) keeps stack and GC pressure low.</li></ol><h4>Limitations</h4><ol><li><strong>High Barrier to Entry</strong>: Having worked with Reactive for over 3 years, this was my biggest gripe with it. In a team of 10, normally no more than 3 people will truly understand how to use it properly, and I don’t blame those who could not. The functional, declarative style API with complex concurrency primitives make it hard to learn and use effectively.</li><li><strong>Control flow inversion</strong>: Purely reactive code intermixes business logic with reactive operators, making imperative tasks less straightforward.</li><li><strong>Debugging &amp; tooling gaps</strong>: Breakpoints, thread dumps, and profiler outputs may show framework internals more than application logic. Debugging reactive code is a nightmare.</li></ol><h4><strong>Version 5: Virtual Threads</strong></h4><p>With virtual threads, this server is very similar to what we had in the <em>1 Platform Thread Per Connection</em> case. All we do is replace the executor service with</p><pre>Executors.newVirtualThreadPerTaskExecutor()</pre><p>As its name suggests, this ES service creates 1 virtual thread for each task, which in our case is a client connection (task parallelism). This executor will create an unbounded number of virtual threads — Which is very high given how cheap it is to create and maintain virtual threads. Here’s the code:</p><pre>package package loom;<br><br>import java.io.*;<br>import java.net.ServerSocket;<br>import java.net.Socket;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class VirtualThreadedServer {<br><br>    private static final ExecutorService ES = Executors.newVirtualThreadPerTaskExecutor();<br><br>    public static void main(String[] args) throws IOException {<br>        ServerSocket ss = new ServerSocket(8091);<br>        int conns = 0;<br>        while (true) {<br>            //main thread -&gt; just listens<br>            Socket socket = ss.accept();//blocks<br>            System.out.println(&quot;Connected to client..., total: &quot; + (++conns));<br>            //workers threads 1:1 for each connection<br>            ES.submit(() -&gt; handleRequest(socket));<br>        }<br>    }<br><br>    private static void handleRequest(Socket socket) {<br>        try (<br>                PrintWriter out =<br>                        new PrintWriter(socket.getOutputStream(), true);<br>                BufferedReader in = new BufferedReader(<br>                        new InputStreamReader(socket.getInputStream()));<br>        ) {<br>            String inputLine;<br>            while ((inputLine = in.readLine()) != null) {<br>                out.println(inputLine);<br>            }<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br><br>    }<br>}<br></pre><p>Here, we are creating a virtual thread for handling each connection. This server is able to handle 10k connections concurrently. But what is even more impressive is that we are writing blocking, imperative code and still getting NIO level performance. This is the beauty of virtual threads — Developers can now focus on the business logic rather than figuring our arcane APIs to write performant code, as it should always be.</p><ol><li><strong>Plain imperative code</strong>: Virtual threads let you write blocking, step‑by‑step logic without callbacks—easier to read and maintain. <em>Writes like blocking, performs like non-blocking!</em></li><li><strong>Back to 1:1 Model</strong>: With virtual threads, we are back to the easiest to understand and write 1:1 task parallelism model. Unlike reactive servers that multiplex many connections on a few threads (risking head‑of‑line blocking or complex back-pressure), each virtual thread enjoys its own call stack and execution context at ~4 KB.</li><li><strong>Simplified Observability</strong>: Thread dumps show your direct application threads, and standard profilers/instrumentation work without reactive adapters.</li></ol><h4>Deep-dive</h4><p>While this article doesn’t delve deeply into virtual threads, partly because they’re still evolving and any specifics risk becoming outdated or inaccurate, I’ve included a brief summary below to set the context.</p><ol><li>Virtual threads are cooperatively scheduled, not preemptively. This means they must explicitly yield control, typically at known “block points. For example, when performing a blocking read from a socket.</li><li>When a virtual thread yields, the scheduler picks another virtual thread from the runnable queue and schedules it on a platform (carrier) thread.</li><li>The default scheduler is the common ForkJoinPool , which maintains a pool of <em>n</em> platform threads, where <em>n</em> equals the number of CPU cores on your machine. This is configurable, but by default, it maps to the core count.</li><li>Virtual threads excel in I/O-bound applications, where threads spend most of their time waiting for data (e.g., from sockets). Here, they can efficiently yield and let other virtual threads use the platform thread.</li><li><strong>In compute-bound scenarios, however, virtual threads offer no real advantage over platform threads</strong>. Take examples like parallel array sum or merge sort. These are classic data-parallel tasks where threads are busy doing work and never block or yield. As such, virtual threads don’t get a chance to be rescheduled.</li><li>The ForkJoinPool is a work-stealing scheduler, which allows idle threads to pick up tasks from others. In data-parallel tasks, this keeps all platform threads busy, and adding virtual threads doesn’t help — the CPU is already saturated with work.</li><li>You might ask, “But aren’t virtual threads cheaper to create and more lightweight?” Yes, they are — but that’s irrelevant here. The ForkJoinPool already keeps a fixed number of platform threads (equal to core count), and creating more threads doesn’t help if they all want CPU time at once. Even if you had 1,000 cores, you’d only need 1,000 threads running in parallel — and that’s perfectly manageable.</li></ol><h3>Further Readings</h3><ul><li><a href="https://www.infoq.com/articles/java-virtual-threads/">Virtual Threads: New Foundations for High-Scale Java Applications</a></li><li><a href="https://openjdk.org/jeps/425">JEP 425: Virtual Threads (Preview)</a></li><li><a href="https://www.infoq.com/news/2023/04/virtual-threads-arrives-jdk21/">JEP 444: Virtual Threads Arrive in JDK 21, Ushering a New Era of Concurrency</a></li><li><a href="https://inside.java/tag/loom">Loom</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca5a8b95da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer to LLD Interviews]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://pandepra.medium.com/a-primer-to-lld-interviews-2b23f52ccea0?source=rss-5a4ba3e91298------2"><img src="https://cdn-images-1.medium.com/max/1920/1*oX03hU-1iQIMszzyhuQUug.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Most tech interviews these days across all levels have a Low Level Design (LLD) component.</p><p class="medium-feed-link"><a href="https://pandepra.medium.com/a-primer-to-lld-interviews-2b23f52ccea0?source=rss-5a4ba3e91298------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://pandepra.medium.com/a-primer-to-lld-interviews-2b23f52ccea0?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b23f52ccea0</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 14:46:09 GMT</pubDate>
            <atom:updated>2023-09-16T14:49:41.997Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Decorators in Java]]></title>
            <link>https://pandepra.medium.com/decorators-in-java-4fc5cd9417ae?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fc5cd9417ae</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 12:50:52 GMT</pubDate>
            <atom:updated>2023-07-07T15:49:07.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMymwkUHtPuys_XKyH5EHA.jpeg" /></figure><p>The <a href="https://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a> is one of my favourites in Java. Early in my career we used it heavily in Spring Reactor (reactive Java) to seamlessly transfer MDCs across threads and with Spring AoP to add runtime behaviour to my classes with annotations (an example, acquiring a distributed lock in redis on an <em>orderId</em> before the request gets into the controller).</p><p>Decorators allows us to add to the behaviour of an object at runtime. Let us see how it is done with an example. In the following example, we will implement a BoundedSet — A set in Java whose size can be limited. This example has been taken from <em>Java: Concurrency in Practice</em>, but the implementation is my own.</p><pre>public abstract class ForwardingSet&lt;T&gt; implements Set&lt;T&gt; {<br><br>    public abstract Set&lt;T&gt; delegate();<br><br>    @Override<br>    public int size() {<br>        return delegate().size();<br>    }<br><br>    @Override<br>    public boolean isEmpty() {<br>        return delegate().isEmpty();<br>    }<br><br>    @Override<br>    public boolean contains(Object o) {<br>        return delegate().contains(o);<br>    }<br><br>    @Override<br>    public Iterator&lt;T&gt; iterator() {<br>        return delegate().iterator();<br>    }<br><br>    @Override<br>    public Object[] toArray() {<br>        return delegate().toArray();<br>    }<br><br>    @Override<br>    public &lt;T1&gt; T1[] toArray(T1[] a) {<br>        return delegate().toArray(a);<br>    }<br><br>    @Override<br>    public boolean add(T t) {<br>        return delegate().add(t);<br>    }<br><br>    @Override<br>    public boolean remove(Object o) {<br>        return delegate().remove(o);<br>    }<br><br>    @Override<br>    public boolean containsAll(Collection&lt;?&gt; c) {<br>        return delegate().containsAll(c);<br>    }<br><br>    @Override<br>    public boolean addAll(Collection&lt;? extends T&gt; c) {<br>        return delegate().addAll(c);<br>    }<br><br>    @Override<br>    public boolean retainAll(Collection&lt;?&gt; c) {<br>        return delegate().retainAll(c);<br>    }<br><br>    @Override<br>    public boolean removeAll(Collection&lt;?&gt; c) {<br>        return delegate().removeAll(c);<br>    }<br><br>    @Override<br>    public void clear() {<br>        delegate().clear();<br>    }<br><br>}</pre><p>ForwardingSet is inspired from Guava’s ForwardingSet . This set simply delegates all of its method calls to the underlying delegate object (digression: This is composition). What is a delegrate? Well, it is the underlying object to which all our calls are delegated to (after we are done modifying the behaviour). We can now subclass this class and override any methods to modify their behaviour, as we have done in <em>BoundedSet</em>:</p><pre>@ThreadSafe<br>public class BoundedSet&lt;T&gt; extends ForwardingSet&lt;T&gt; {<br><br>    private Set&lt;T&gt; set;<br>    private Semaphore semaphore;<br><br>    public BoundedSet(int bound) {<br>        this.semaphore = new Semaphore(bound);<br>        this.set = Collections.synchronizedSet(new HashSet&lt;&gt;());<br>    }<br><br>    @Override<br>    public boolean add(T t) {<br>        try {<br>            semaphore.acquire();<br>            boolean wasAdded = super.add(t);<br>            if (!wasAdded) {<br>                semaphore.release();<br>            }<br>            return wasAdded;<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>    @Override<br>    public boolean remove(Object o) {<br>        boolean wasRemoved = super.remove(o);<br>        if (wasRemoved) {<br>            semaphore.release();<br>        }<br>        return wasRemoved;<br>    }<br><br>    @Override<br>    public boolean addAll(Collection&lt;? extends T&gt; c) {<br>        try {<br>            boolean setChanged = false;<br>            for(var e : c) {<br>                semaphore.acquire();<br>                boolean wasAdded = super.add(e);<br>                if(!wasAdded) {<br>                    semaphore.release();<br>                }<br>                setChanged |= wasAdded;<br>            }<br>            return setChanged;<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>    @Override<br>    public boolean removeAll(Collection&lt;?&gt; c) {<br>        boolean setChanged = false;<br>        for(var e : c) {<br>            boolean wasRemoved = super.remove(e);<br>            if(wasRemoved) {<br>                semaphore.release();<br>            }<br>            setChanged |= wasRemoved;<br>        }<br>        return setChanged;<br>    }<br><br>    @Override<br>    public Set&lt;T&gt; delegate() {<br>        return this.set;<br>    }<br><br>}</pre><p>Here, we have modified the behaviour of <em>add</em>, <em>remove</em>, <em>addAll</em>, <em>removeAll</em> methods. For each add, we acquire a permit from the semaphore. For each remove, we add a permit. The implementation is a bit terse as I am using a synchronised set here which does not scale well, but you get the idea. To use this class, do:</p><pre>Set&lt;Integer&gt; set = new BoundedSet&lt;&gt;(10);</pre><p>The delegate in this case is the underlying synchronised set.</p><p>Spring uses decorators heavily to intercept calls to your objects before they enter them. In our case, we had to solve the tricky problem of transferring MDCs b/w two threads whenever a thread switch happened in Java. We solved this by decorating the submit method of the corresponding executor service to get the calling thread’s MDC, copying it to the current thread’s MDC (inside the runnable), and then dispatching the call to the underlying delegate. Here’s the code:</p><p><em>ForwardedExecutorService.java</em></p><pre>public abstract class ForwardedExecutorService implements ExecutorService {<br><br>    public abstract ExecutorService delegate();<br><br>    @Override<br>    public void shutdown() {<br>        delegate().shutdown();<br>    }<br><br>    @Override<br>    public List&lt;Runnable&gt; shutdownNow() {<br>        return delegate().shutdownNow();<br>    }<br><br>    @Override<br>    public boolean isShutdown() {<br>        return delegate().isShutdown();<br>    }<br><br>    @Override<br>    public boolean isTerminated() {<br>        return delegate().isTerminated();<br>    }<br><br>    @Override<br>    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {<br>        return delegate().awaitTermination(timeout, unit);<br>    }<br><br>    @Override<br>    public &lt;T&gt; Future&lt;T&gt; submit(Callable&lt;T&gt; task) {<br>        return delegate().submit(task);<br>    }<br><br>    @Override<br>    public &lt;T&gt; Future&lt;T&gt; submit(Runnable task, T result) {<br>        return delegate().submit(task, result);<br>    }<br><br>    @Override<br>    public Future&lt;?&gt; submit(Runnable task) {<br>        return delegate().submit(task);<br>    }<br><br>    @Override<br>    public &lt;T&gt; List&lt;Future&lt;T&gt;&gt; invokeAll(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks) throws InterruptedException {<br>        return delegate().invokeAll(tasks);<br>    }<br><br>    @Override<br>    public &lt;T&gt; List&lt;Future&lt;T&gt;&gt; invokeAll(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks, long timeout, TimeUnit unit) throws InterruptedException {<br>        return delegate().invokeAll(tasks, timeout, unit);<br>    }<br><br>    @Override<br>    public &lt;T&gt; T invokeAny(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks) throws InterruptedException, ExecutionException {<br>        return delegate().invokeAny(tasks);<br>    }<br><br>    @Override<br>    public &lt;T&gt; T invokeAny(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {<br>        return delegate().invokeAny(tasks, timeout, unit);<br>    }<br><br>    @Override<br>    public void execute(Runnable command) {<br>        delegate().execute(command);<br>    }<br>}<br></pre><p><em>MDCAwareExecutorService</em>.<em>java</em></p><pre>public class MDCAwareExecutorService extends ForwardedExecutorService {<br><br>    private ExecutorService es;<br><br>    public MDCAwareExecutorService() {<br>        this.es = Executors.newCachedThreadPool();<br>    }<br><br>    @Override<br>    public ExecutorService delegate() {<br>        return this.es;<br>    }<br><br>    @Override<br>    public &lt;T&gt; Future&lt;T&gt; submit(Callable&lt;T&gt; task) {<br>        return super.submit(decorateTask(task));<br>    }<br><br>    @Override<br>    public &lt;T&gt; Future&lt;T&gt; submit(Runnable task, T result) {<br>        return super.submit(decorateTask(task), result);<br>    }<br><br>    @Override<br>    public Future&lt;?&gt; submit(Runnable task) {<br>        return super.submit(decorateTask(task));<br>    }<br><br>    @Override<br>    public void execute(Runnable command) {<br>        super.execute(decorateTask(command));<br>    }<br><br>    private &lt;V&gt; Callable&lt;V&gt; decorateTask(Callable&lt;V&gt; task) {<br>        //get current thread&#39;s MDC<br>        Map&lt;String, String&gt; mdc = MDC.METADATA.get();<br>        return () -&gt; {<br>            MDC.METADATA.set(mdc);<br>            return task.call();<br>        };<br>    }<br><br>    private Runnable decorateTask(Runnable task) {<br>        //get current thread&#39;s MDC<br>        Map&lt;String, String&gt; mdc = MDC.METADATA.get();<br>        return () -&gt; {<br>            MDC.METADATA.set(mdc);<br>            task.run();<br>        };<br>    }<br>}</pre><p><em>MDC.java</em></p><pre>public class MDC {<br>    public static ThreadLocal&lt;Map&lt;String, String&gt;&gt; METADATA = new ThreadLocal&lt;&gt;();<br>}</pre><p><em>Driver.java</em></p><pre>public class Driver {<br>    public static void main(String[] args) throws InterruptedException {<br>        MDC.METADATA.set(Map.of(&quot;k1&quot;,&quot;v1&quot;,&quot;k2&quot;,&quot;v2&quot;));<br>        var es = new MDCAwareExecutorService();<br>        es.submit(() -&gt; {<br>            System.out.println(&quot;Thread: &quot; + Thread.currentThread().getName() + &quot;, MDC: &quot; + MDC.METADATA.get());;<br>        });<br>        Thread.sleep(Integer.MAX_VALUE);<br>    }<br>}</pre><p>That is all folks, till next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fc5cd9417ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Tracing with Hypertrace]]></title>
            <link>https://engineering.razorpay.com/distributed-tracing-with-hypertrace-30b0334d0c0b?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b0334d0c0b</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Thu, 07 Apr 2022 12:59:52 GMT</pubDate>
            <atom:updated>2022-04-18T08:29:48.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRqK1pxi0dy7yBUvmgDD8A.png" /></figure><p>As a continuation to our <a href="https://engineering.razorpay.com/tracing-our-observability-journey-a3c72f52d77f">previous article on Razorpay’s distributed tracing journey</a>, this article covers <a href="https://www.hypertrace.org/">Hypertrace</a>, an OSS distributed tracing platform from <a href="https://traceable.ai/">traceable.ai</a> that forms the backbone of our current distributed tracing infrastructure.</p><h4><strong>Once Upon a Time, There was Jaeger</strong></h4><p>As stated in the previous blog, Razorpay’s distributed tracing journey started with <a href="https://www.jaegertracing.io/">Jaeger</a>. There were multiple reasons behind choosing it at that time:</p><ol><li>Jaeger was (and still is) one of the most popular tools for distributed tracing.</li><li>It is compatible with OpenTracing, OpenTelemetry and Zipkin. We were especially cautious about using open standards, as using any proprietary instrumentation would have meant a difficult migration down the line.</li><li>It uses a familiar tech stack and is easy to get up and running. We already had sufficient expertise in-house with Kafka and Cassandra.</li><li>It is OSS with active community support.</li></ol><p>At that time, when the platform’s adoption at Razorpay was sub-optimal and our developers were still warming up to the idea of distributed tracing (as a means of application debugging and performance monitoring), the focus was on the platform’s evangelisation and training developers on effective instrumentation, rather than finding the best tracing platform out there. So going with Jaeger was a no-brainer for us. However, as the platform’s adoption grew (both in complexity and scale), we quickly realized that Jaeger was going to be insufficient for our long-term needs.</p><h4><strong>From Jaeger </strong>to<strong> Hypertrace</strong></h4><p>The fundamental reason why we moved from Jaeger to Hypertrace was that our eventual (observability) platform was envisioned to be capable of more than just end-to-end trace debugging and service dependency analysis –the primary features of Jaeger.</p><p>While the fundamental building blocks would remain the same (traces), we wanted the system to derive much more juice from them than we could from Jaeger. To achieve this, some features were needed that Jaeger fell short on:</p><ol><li><strong>Derived Metrics</strong>: Jaeger does not provide metrics. You cannot use it to answer questions like:</li></ol><ul><li>What is the P99 duration and error rate of all calls to a particular DB?</li><li>How has my service’s P99 latency deviated from the normal in the last one hour?</li><li>What is the rate of failure b/w two services shown in the dependency graph?</li><li>What is the P95 response time b/w them?</li><li>What are the top 5 slowest endpoints of my service?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCfJSTdGBLd7sTem859IDg.png" /><figcaption>At the Time of Evaluation, Jaeger Didn’t Do Much for Metrics</figcaption></figure><p>Hypertrace, on the other hand, derives RED (rate, error, duration) metrics about your services out-of-the-box, as can be seen in the following dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FszWxLHq6ESk1vfEVa_89A.png" /></figure><p>Having these metrics right alongside their traces keeps developers from having to switch b/w metrics and tracing dashboards, saving time and reducing context-switch fatigue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KprtAA_LXakXab_yOKB_w.png" /></figure><p>The above screenshot shows the overview of <em>splitz-prod</em> in Hypertrace. Two things are of particular interest:</p><ul><li><strong>Radar Chart (under HEALTH): </strong>The radar chart illustrates how your service’s <em>RED</em> metrics have changed over time. In this example, it compares these metrics in the last 15m to their values in the last one hour. Such information can be handy for example after a new deployment, when you want to monitor if your service is deviating from the norm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*Wr4ZST6yqkditxLfIBcItQ.png" /></figure><ul><li><strong>Top Endpoints By…</strong>: You can sort your endpoints based on metrics like calls count, error rate, latency, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*3mPe9fOKH1IW8UnWiGgD0Q.png" /></figure><p>Hypertrace also derives metrics from custom tags. For example, if your traces have a <em>merchantId</em> tag, you can use Hypertrace to get metrics like duration, call count, error count, etc. for a particular merchant. The ability to do such analysis on high-cardinality tags like <em>merchantId</em> and <em>customerId</em> is a powerful feature of Hypertrace that we’ll explore in detail in later sections.</p><p>2. <strong>Custom Trace Enrichment</strong>: We often need to enrich our traces with custom tags that are derived from existing tags. For example, our traces can have an IP Address attribute, and we might want to add a confidence score to it. A low value of this score indicates that the IP might be of a malicious source. Such information can be very handy to do security analysis later. Hypertrace lets us add such custom attributes to our traces in the ingestion pipeline. There is no way to do this in Jaeger.</p><p>3. <strong>Entity-Based Drilldowns:</strong> Entities are a standard set of tags that have a bounded set of values. For example, databases, endpoints, HTTP methods, etc. Many production debugging scenarios start with the developer just knowing some entity name. For example, you may observe that calls to a particular DB are failing in high numbers. With Jaeger, there is no easy way to use this information and get a head start - We need to search on the tag <em>db.name = someDB</em>. With Hypertrace, however, we can search for this specific DB in the Backends view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L65kCB6p_8wiSTSiHNfRJg.png" /></figure><p>Now we can get both metrics and traces for this DB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZL2OZ8xiwhSwnI9cGb_uA.png" /></figure><p>Similarly, starting with the endpoint name, you can look for it in API Endpoints and drill down from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxCoybm691HIZzlU_oRcog.png" /></figure><p>4. <strong>Sevice Dependency Analysis</strong>: Service dependency diagrams generated by Jaeger are pretty basic, offering nothing more than information about application dataflow and call counts. The following two screenshots compare the service dependency diagrams generated by Jaeger and Hypertrace for the ever-famous HotRod app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty79D3yb-yWyGSLzRYrPBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tr3gqbUs1r4FA0jqnxLYfg.png" /></figure><p>Hypertrace not only shows dependencies among the system components but also derives the RED metrics corresponding to these interactions. Such metrics are very useful to quickly get an idea of how well the service is communicating with its dependencies. In the above example, the developer can quickly know what percentage of calls from the driver to Redis are failing by simply hovering on it. Why would he do so? Because Hypertrace color-codes Redis in red, indicating something is wrong with it. These service interaction diagrams are also generated on a per-service basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7jQJqYcAfq0fB6gOWaWRg.png" /><figcaption>Service Dependency Graph for splitz</figcaption></figure><p>In addition to the above advantages over Jaeger, Hypertrace is also:</p><ol><li>K8s native, simple, and easy to operate without a huge learning curve.</li><li>OSS and has an active Slack community.</li><li>A PAAS offering. This would be useful if we decide to move to a managed solution later down the line.</li></ol><p>Keeping these points in mind, using Hypertrace was the best choice under the prevalent circumstances. We transitioned from Jaeger to Hypertrace in Jan 2021.</p><h4>Traces</h4><p>Traces are the bread-and-butter of any distributed tracing platform, and Hypertrace is no exception. Users can see the traces associated with an entity (backend, endpoint, service) by going to that entity’s trace view. For example, traces in <em>beethoven-prod</em> in the past 1h can be seen as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dx99hnP43bNR1faDAbpj0g.png" /></figure><p>Trace View lets us do quite a bit of slicing and dicing on traces. It lets us filter them by specifying predicates on attributes like duration, status code, tags, etc. It also lets us sort on comparable attributes like Duration, Start Time, etc. Clicking on a trace generates its waterfall model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCYsXZKjM8hZFgF2t5muhw.png" /></figure><p>A waterfall model illustrates relationships among spans (of a trace) by using the causality information derived by Hypertrace in the backend (the <a href="https://opentracing.io/specification/#:~:text=The%20OpenTracing%20Data%20Model">OpenTracing data model</a> is a fantastic read to learn about these causal relationships in detail).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkgYI641DQGJhMF85f07BQ.png" /><figcaption>A Span’s Context</figcaption></figure><p>Clicking on any span brings up its context. This context comprises attributes added by the developer during instrumentation and any additional attributes added in the ingestion pipeline.</p><h4>Godmode with Explorer</h4><p>Hypertrace empowers developers to ask arbitrary questions about their services using Explorer, perhaps one of its most powerful features. If your applications are instrumented with the right business and operational context, Explorer can give you deep insights into it. Let us see this with some examples.</p><p>Say we are getting a usually high number of creating payment calls and want to find out which merchant(s) is making these calls first. We start by stating the following predicates on Explorer:</p><ol><li><em>Service Name = API</em></li><li><em>Tags.http.path = /v1/orders</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zifSSBV65gHVlNg4Wbdkpg.png" /></figure><p>To get the temporal distribution of call rate, we choose Calls as the metric and Rate(sec) as the aggregate under Select metrics. Hypertrace provides several other metrics and aggregates, such as Duration, Exception Count, Average, Pxx, etc. We finally group the results by the tag merchant. You can group by a whole lot of attributes like Endpoint Name, HTTP Method, Service Name, etc. From the final results, we can see that merchant <em>TtPtHDFd1d</em> has been calling this endpoint at a high rate.</p><p>Let us figure out the routes with the highest error rate in the last hour in <em>API</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwg7XHjPBIhMJCx7QT5_JQ.png" /></figure><p>Note that we’ve specified a regex in the tag’s value, as we want to look for any status code in the 5xx range. Hypertrace supports regex search on tags as well. Grouping the result by endpoint yields what we wanted. We can immediately see that <em>v1/settlements/{id}</em> has the highest error rate in the last hour.</p><p>With the right instrumentation in place, Explorer empowers developers to debug their services effectively without depending on experts. A huge win!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FY7kRinVZYW4Kt70vqNlzw.png" /></figure><h4><strong>Operating Hypertrace at Scale</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Epq7sTNpvnV9-qJsh9Wvdw.png" /></figure><h4>Ingestion</h4><p>The journey of a span in Hypertrace starts with the collector pushing spans to the ingestion pipeline. The collector receives spans from agents running as daemons on application nodes. The ingestion pipeline is a stream of spans/traces in Kafka, with various transformers acting on it:</p><ol><li><strong>Span Normalizer</strong>: It adds a <a href="https://github.com/hypertrace/data-model/tree/main/data-model/src/main/avro/eventfields">standard set of attributes</a> to spans as they pass through it. Span normalizer is compatible with different trace formats like OpenTracing, OpenTelemetry, Jaeger or Zipkin. This compatibility came in very handy for us, as no instrumentation changes were needed when we migrated from Jaeger to Hypertrace.</li><li><strong>Raw Spans Grouper</strong>: This is the only stateful transformation in the entire ingestion pipeline. It consumes “raw” spans emitted by Span Normalizer and groups them by <em>traceId</em>, to create a StructuredTrace. In addition to this, RSG can be used to implement tail sampling in the pipeline. Tail sampling looks at the attributes of a trace at the end of the workflow and decides whether it should be sampled or not. For example, we might want to drop all traces with status code = 200, and sample only those traces with status code = 5xx. Since RSG has access to the entire trace, this logic can be implemented here.</li><li><strong>Trace Enricher</strong>: As explained in the previous sections, Trace Enricher enriches your traces with custom attributes. For example, Trace Enricher will add a label <em>db.instance = db_name</em> for all calls to a particular database. It will also label a span as an ENTRY or EXIT span.</li><li><strong>All Views Generator</strong>: This component consumes from Trace Enricher and creates views that map 1:1 to Pinot tables.</li></ol><p>The following diagram illustrates these series of transformations in greater detail. Dotted arrows represent synchronous communication, while solid arrows represent asynchronous communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*M8dV4SenlLKI10j_Uv7OJQ.png" /></figure><p>All of these transformers are realtime streaming applications written in KStreams. With an average ingestion of ~100k spans/s, our P99 trace freshness remains under 1m.</p><h4>Querying</h4><p>Hypertrace exposes GraphQL endpoints to query data from Pinot. Requests to these endpoints are translated into PQL (Pinot Query Language) by the Query Service that interfaces with Pinot using a <em>PinotBasedRequestHandler</em>. Query Service can interface with other datastores using different implementations of RequestHandler (<em>PinotBasedRequestHandler</em> implements this interface).</p><h4>Query Patterns</h4><p>The following histogram shows the distribution of query intervals over a period of one week:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsPA8Wkpnrq3wG_IxK2V_Q.png" /></figure><p>96% of the queries lay within the last 24 hours. Just 1.6% of the total calls lay in the last 30 days. This skewed distribution gives us an opportunity to optimize our storage - Optimizing for the common case first, we can store the most frequently queried data in fast storage (like SSDs) and less frequently accessed data in slow storage (like HDDs). Trading off speed for latency will only affect a minuscule fraction of our queries (less than 5%). Doing this becomes even more important to us as our data ingestion rate increases as more services onboard the platform along with increases to the retention period.</p><p>Here’s an example of such storage separation currently in the works. A Spark job writes data coming in from Kafka to the data lake (S3). The data lake has much larger retention (currently 30d). Both Pinot and data lake are queried by Presto. Alluxio is used to bring the data lake closer to Presto (compute). This speeds up reads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*w1Bdu4Nea6ZbjMnMMcaJ8w.png" /></figure><p>The query service queries both sources based on a time boundary. For example, if the user requests for data older than 7 days, it’ll only query the data lake. If they request data within the last 7 days, it’ll only query Pinot. If the time period staggers this 7 day boundary, both the data sources are queried and the results are merged. The tables in the data lake are created 1:1 to Pinot’s, so very minimal changes are needed in the query generator to query.</p><p>Further, Pinot <a href="https://docs.pinot.apache.org/operators/operating-pinot/tiered-storage">identifies</a> this heterogeneity as well and automatically moves its segments (data partitions) b/w multiple storage tiers. More recent segments are stored in faster, more expensive tiers (with SSDs) while older segments are moved to slower, cheap tiers (with HDDs). Combined with the previous solution, this optimizes storage costs to a large extent.</p><h4>High Cardinality Tags</h4><p>One particular feature worth mentioning is how Hypertrace handles high cardinality tags. In systems like Prometheus, queries become very slow if data has many labels with high cardinality. This is because of the multiplicative growth in time series data that Prometheus needs to store and index as a label&#39;s cardinality increases. Due to this limitation, one cannot choose a label like <em>merchantId</em> that can have thousands of values. So if you would like to have separate dashboards for a particularly high-value merchant, Prometheus isn’t the right tool for it.</p><p>Hypertrace faces no such problems when dealing with such high cardinality tags. This lets developers add tags like <em>merchantId</em> and <em>customerId</em> that can have millions of unique values, which can later be used to do all sorts of slicing and dicing using Explorer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NOGBm3DslBjUQ_eEDfdBg.png" /></figure><p>In the above example, we use <em>Explorer</em> to get the count of calls per endpoint for a particular merchant in <em>API</em>.</p><p>The ability to handle such high-cardinality tags combined with its powerful analytic capabilities makes Hypertrace a very capable system for fine-grained monitoring and analysis.</p><h4>Challenges and Learnings</h4><p>Over the course of the last year, from the time the need for a distributed tracing platform was realized at Razorpay to now when Hypertrace has been adopted by ~35% of the services in the org, the journey has had its fair share of challenges, as explained below:</p><ol><li><strong>Sampling</strong>: We sample 100% of traces in production. While this may seem wasteful and expensive, it was done for the following reasons:</li></ol><ul><li>We do not have a very good heuristic for head-based sampling. For example, we cannot sample for a specific set of merchants for specific routes, as this number can explode quickly (For 500k merchants and 50 routes, we have around 25M combinations to decide on). However, we do skip <em>/health</em> and <em>/status</em> endpoints, in addition to any other endpoints that developers explicitly ask to omit.</li><li>We could have resorted to tail sampling using Raw Spans Grouper but that would have required us to add more compute resources, as each and every trace would need to be analyzed for certain predicates. With 100% sampling, the trade-off was more storage costs, which is still cheaper than the other option.</li><li>Hypertrace is a first-class debugging tool for us, and any missing data can lower developer confidence in the platform. Additionally, as Hypertrace derives its metrics from spans, missing spans can lead to incorrect metrics. This is again unacceptable as Hypertrace is a source of preliminary metrics for many teams.</li><li>Extending the previous point, developers also use Hypertrace to set up alerts for their services. Inaccurate metrics will make these alerts effectively useless.</li></ul><p>We will be covering sampling in detail in a future blog post.</p><p>2. <strong>Long Term Retention</strong>: 100% sampling at our scale leads to increased storage requirements. As described in the ‘Querying’ section, data received only in the last 24 hours is queried most frequently. Our current retention period is 7 days but we have had instances in which users want to debug older issues. To support such requirements, we need to increase the retention period to a higher value (30 days currently but should be configurable). However, the cost of storing a month&#39;s worth of data in Pinot’s servers can be prohibitive. Also, both the daily ingestion volume and the retention period can increase in the future. Therefore, our storage implementation has to be independent of these values. In addition to the solutions explained in the previous sections, we are looking at two more ways to solve this:</p><ul><li>Using the deep-store (S3 in our case) as a possible (and only) storage tier, besides Pinot servers. “Freezing” old segments into the deep-store and “thawing” them on-demand is a <a href="https://github.com/apache/pinot/issues/7229">WIP</a>. This solution has the drawback that “thawing” segments on-demand will have high response times. However, for our use case, it will affect only a minuscule number of queries (less than 5%).</li><li>Use <a href="https://www.startree.ai/blogs/introducing-tiered-storage">StarTree’s</a> distribution of Pinot that already has tiered storage productionized.</li></ul><p>3. <strong>Quality of Instrumentation</strong>: As we have seen in the section on <em>Explorer</em>, having the right metadata in your traces is essential for leveraging Hypertrace fully. The job of effective instrumentation lies with developers, who often are not aware of this “caveat” of Hypertrace. This leads to multiple rounds of instrumentation (and disappointment), with developers reinstrumenting their applications once they find out what they need is not actually present in Hypertrace. We have tried to address the problem in two ways:</p><ul><li>Creating a standard tracing package for Golang and PHP. This package adopts a “convention over configuration” approach, by adding important sets of tags for different types of applications. For example, for Kafka, it adds a type=consumer/producer tag by default.</li><li>Allocating additional bandwidth to help developers with any instrumentation issues they might be facing. This also includes taking ownership of any code reviews related to Hypertrace integration.</li></ul><p>Notwithstanding these measures, effective instrumentation is a constantly moving target.</p><h4><strong>Razorpay and Hypertrace</strong></h4><p>Hypertrace is a strategic platform for Razorpay, and we have committed to contributing to it in the long term. Most of our contributions are results of our own requirements. Some of them include <a href="https://github.com/hypertrace/hypertrace-ui/pull/1394">drill-downs in charts to help investigate anomalies</a>, <a href="https://github.com/hypertrace/hypertrace-ui/pull/1353">improving caching capabilities for Better UX</a>, <a href="https://github.com/hypertrace/hypertrace-ui/pull/1408">a widget for loading custom iFrame into the layout</a>, <a href="https://github.com/hypertrace/hypertrace-ui/pull/1454">multiple markers and tooltip correlation amongst multiple graphs to help narrow down on the root cause</a>, <a href="https://github.com/hypertrace/hypertrace-ui/pull/1486">amending the explorer behavior to retain certain filters on switching tabs, analytics telemetry support</a> (adds support for Rudderstack), <a href="https://github.com/hypertrace/hypertrace-ui/issues/1155">custom dashboards from saved queries</a> (WIP)<strong>, </strong><a href="https://github.com/hypertrace/hypertrace/issues/114">support for Postgres in document store</a><strong>, </strong><a href="https://github.com/hypertrace/hypertrace-ingester/pull/208">support for follows-from construct</a><strong>, </strong>etc.</p><p>The community can be found on <a href="http://hypertrace.slack.com/">Slack</a>.</p><p><strong>Edit</strong>: Jaeger now has support for <a href="https://github.com/jaegertracing/jaeger-ui/issues/736">metrics</a>. However, this capability was added after we had evaluated both the tools in December 2020.</p><p>We have written on our observability stack earlier in the following posts:</p><ol><li><a href="https://engineering.razorpay.com/scaling-to-trillions-of-metric-data-points-f569a5b654f2">Scaling to Trillions of Metric Data Points.</a></li><li><a href="https://engineering.razorpay.com/tracing-100k-spans-with-razorpay-opencensus-php-fork-d217aa9eca6">Tracing 100k Spans in a Single Request.</a></li><li><a href="https://engineering.razorpay.com/tracing-our-observability-journey-a3c72f52d77f">Tracing our Observability Journey</a>.</li></ol><p>A special thanks to <a href="https://www.linkedin.com/in/arjun-ravindhar-43670a77/">Arjun</a> for helping us with the design elements in this post.</p><h4>We are Hiring!</h4><p>If you love working on exciting challenges, we are actively hiring for our Engineering team. We are a bunch of ignited minds simplifying financial infrastructure for businesses, and we’re always looking out for great folks. We are looking for both Engineering Managers and Senior Engineers to break barriers and build for the future. <a href="https://razorpay.com/jobs/?utm_src=medium&amp;utm_medium=blog">Apply now.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b0334d0c0b" width="1" height="1" alt=""><hr><p><a href="https://engineering.razorpay.com/distributed-tracing-with-hypertrace-30b0334d0c0b">Distributed Tracing with Hypertrace</a> was originally published in <a href="https://engineering.razorpay.com/">Razorpay Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Reactor’s flatMap And Backpressure]]></title>
            <link>https://medium.com/swlh/project-reactors-flatmap-and-backpressure-fba97472d625?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba97472d625</guid>
            <category><![CDATA[reactor-project]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 15:03:52 GMT</pubDate>
            <atom:updated>2021-01-05T15:19:26.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acM6hMQPnr1JQ52j0yai6g.png" /><figcaption>flatMap’s Marble Diagram</figcaption></figure><p>In the <a href="https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95">previous</a> post, we looked at the basics of how <em>flatMap</em> works. This post can be considered an addendum to that post.</p><p><em>flatMap</em> has two other overloaded versions:</p><ol><li><em>flatMap(Function&lt;? super T, ? extends Publisher&lt;? extends V&gt;&gt; mapper, int concurrency)</em></li><li><em>flatMap(Function&lt;? super T, ? extends Publisher&lt;? extends V&gt;&gt; mapper, int concurrency, int prefetch)</em></li></ol><p>In this post, I’ll be covering the first variant (the 2nd one is easy to understand once you understand the first variant)<em>. Concurrency</em> is the number of inner streams <em>flatMap</em> subscribes to simultaneously. This is also the number of events that <em>flatMap</em> requests from the upstream, and defaults to 256. Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ad4d42eaa041b063f4edb9da1fda8c/href">https://medium.com/media/11ad4d42eaa041b063f4edb9da1fda8c/href</a></iframe><p>Here’s how console log:</p><pre>19:02:03.447 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework<br>19:02:03.472 [main] INFO reactor.Flux.Range.1 - | onSubscribe([Synchronous Fuseable] FluxRange.RangeSubscription)<br>19:02:03.474 [main] INFO reactor.Flux.FlatMap.2 - onSubscribe(FluxFlatMap.FlatMapMain)<br>19:02:03.476 [main] INFO reactor.Flux.FlatMap.2 - request(unbounded)<br>19:02:03.476 [main] INFO reactor.Flux.Range.1 - | request(256)<br>19:02:03.476 [main] INFO reactor.Flux.Range.1 - | onNext(1)<br>19:02:03.526 [main] INFO reactor.Flux.FlatMap.2 - onNext(1)<br>19:02:03.527 [main] INFO reactor.Flux.Range.1 - | onNext(2)<br>19:02:03.527 [main] INFO reactor.Flux.FlatMap.2 - onNext(2)<br>19:02:03.527 [main] INFO reactor.Flux.Range.1 - | onNext(3)<br>19:02:03.527 [main] INFO reactor.Flux.FlatMap.2 - onNext(3)</pre><p>The first request from downstream (the subscriber) is unbounded. But <em>flatMap</em> limits it to 256 (many reactive operators alter the downstream demand like this, for example, <em>buffer</em>).</p><p>Let us change this demand:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf4e5e51828667435b4642315bd4c436/href">https://medium.com/media/bf4e5e51828667435b4642315bd4c436/href</a></iframe><p>Here’s the console log:</p><pre>19:25:36.943 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework<br>19:25:36.972 [main] INFO reactor.Flux.Range.1 - | onSubscribe([Synchronous Fuseable] FluxRange.RangeSubscription)<br>19:25:36.975 [main] INFO reactor.Flux.FlatMap.2 - onSubscribe(FluxFlatMap.FlatMapMain)<br>19:25:36.976 [main] INFO reactor.Flux.FlatMap.2 - request(unbounded)<br>19:25:36.977 [main] INFO reactor.Flux.Range.1 - | request(10)<br>19:25:36.978 [main] INFO reactor.Flux.Range.1 - | onNext(1)<br>19:25:37.017 [main] INFO reactor.Flux.FlatMap.2 - onNext(1)<br>19:25:37.018 [main] INFO reactor.Flux.Range.1 - | onNext(2)<br>19:25:37.018 [main] INFO reactor.Flux.FlatMap.2 - onNext(2)<br>19:25:37.018 [main] INFO reactor.Flux.Range.1 - | onNext(3)<br>19:25:37.018 [main] INFO reactor.Flux.FlatMap.2 - onNext(3)</pre><p>As you can see, the demand changes to 10.</p><p><strong>A publisher can publish events only after a demand has been signalled from downstream.</strong> This fact along with the <em>concurrency</em> parameter can be used to implement a <em>stop-and-wait</em> protocol. Consider a use-case where the stream comprises batches, and we have to consume the next batch only after the current batch has been processed <em>successfully</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38bf513ad7ccf1b65518872de2693928/href">https://medium.com/media/38bf513ad7ccf1b65518872de2693928/href</a></iframe><p>Here’s the console log:</p><pre>19:46:59.699 [main] INFO reactor.Flux.Iterable.1 - | onSubscribe([Synchronous Fuseable] FluxIterable.IterableSubscription)<br>19:46:59.705 [main] INFO reactor.Flux.FlatMap.2 - onSubscribe(FluxFlatMap.FlatMapMain)<br>19:46:59.706 [main] INFO reactor.Flux.FlatMap.2 - request(unbounded)<br>19:46:59.706 [main] INFO reactor.Flux.Iterable.1 - | request(1)<br>19:46:59.707 [main] INFO reactor.Flux.Iterable.1 - | onNext([1, 2, 3])<br>19:47:00.293 [parallel-1] INFO reactor.Flux.FlatMap.2 - onNext(1)<br>19:47:00.798 [parallel-2] INFO reactor.Flux.FlatMap.2 - onNext(2)<br>19:47:01.300 [parallel-3] INFO reactor.Flux.FlatMap.2 - onNext(3)<br>19:47:01.301 [parallel-3] INFO reactor.Flux.Iterable.1 - | request(1)<br>19:47:01.301 [parallel-3] INFO reactor.Flux.Iterable.1 - | onNext([4, 5, 6])<br>19:47:01.805 [parallel-4] INFO reactor.Flux.FlatMap.2 - onNext(4)<br>19:47:02.310 [parallel-5] INFO reactor.Flux.FlatMap.2 - onNext(5)<br>19:47:02.813 [parallel-6] INFO reactor.Flux.FlatMap.2 - onNext(6)<br>19:47:02.813 [parallel-6] INFO reactor.Flux.Iterable.1 - | request(1)<br>19:47:02.813 [parallel-6] INFO reactor.Flux.Iterable.1 - | onNext([7, 8, 9])<br>19:47:02.815 [parallel-6] INFO reactor.Flux.Iterable.1 - | onComplete()<br>19:47:03.318 [parallel-7] INFO reactor.Flux.FlatMap.2 - onNext(7)<br>19:47:03.824 [parallel-8] INFO reactor.Flux.FlatMap.2 - onNext(8)<br>19:47:04.328 [parallel-1] INFO reactor.Flux.FlatMap.2 - onNext(9)<br>19:47:04.328 [parallel-1] INFO reactor.Flux.FlatMap.2 - onComplete()</pre><p>As you can see, a request is made for 1 batch. Only after that batch has been processed (by emitting <em>onComplete</em> in the inner stream) is when <em>flatMap</em> makes the next request and receives the next batch.</p><p><strong>This pattern can be used in cases for where publisher is, for example, a generator function that consumes from an event bus like Kafka, and you don’t want to interweave events from two consecutive batches because of strict ordering requirements.</strong></p><p>One final thing about <em>flatMap</em> is that it uses a <em>prefetch-and-replinish</em> strategy, requesting a new batch after 75% of the initial demand has been met. Consider the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d033d4a25d9b6104db4188bcb38bcb30/href">https://medium.com/media/d033d4a25d9b6104db4188bcb38bcb30/href</a></iframe><p>Here’s the console log (trimmed):</p><pre>19:55:41.317 [main] INFO reactor.Flux.Range.1 - | onSubscribe([Synchronous Fuseable] FluxRange.RangeSubscription)<br>19:55:41.321 [main] INFO reactor.Flux.Range.1 - | request(10)<br>19:55:41.322 [main] INFO reactor.Flux.Range.1 - | onNext(1)<br>19:55:41.374 [main] INFO reactor.Flux.Range.1 - | onNext(2)<br>19:55:41.374 [main] INFO reactor.Flux.Range.1 - | onNext(3)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(4)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(5)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(6)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(7)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(8)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | request(8)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(9)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(10)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(11)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(12)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(13)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(14)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(15)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(16)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | request(8)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(17)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(18)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(19)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(20)<br>19:55:41.375 [main] INFO reactor.Flux.Range.1 - | onNext(21)<br>19:55:41.376 [main] INFO reactor.Flux.Range.1 - | onNext(22)</pre><p>You see, after 8 (10 * 0.75) events have been published, the next batch is requested, with a demand of 8. Then again after 15, and so on. From Reactor’s docs, <em>“This is a heuristic optimization made so that these operators proactively anticipate the upcoming requests.”</em>.</p><p>Hopefully this article helped you understand the subtlities of <em>flatMap</em>. You can read the first part <a href="https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95">here</a>.</p><p>References:</p><ol><li><a href="https://projectreactor.io/docs/core/release/reference/">https://projectreactor.io/docs/core/release/reference/</a></li><li><a href="https://github.com/reactive-streams/reactive-streams-jvm">https://github.com/reactive-streams/reactive-streams-jvm</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba97472d625" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/project-reactors-flatmap-and-backpressure-fba97472d625">Project Reactor’s flatMap And Backpressure</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to the Java Memory Model]]></title>
            <link>https://medium.com/swlh/an-introduction-to-the-java-memory-model-8c306697acad?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c306697acad</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[synchronization]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 09:34:32 GMT</pubDate>
            <atom:updated>2021-08-10T07:59:19.257Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a short article to give you a taste of the Java Memory Model. Being unaware of its rules can lead to some pretty knotty bugs. Any serious Java developer who wishes to write thread-safe concurrent programs should be aware of the memory visibility issues that arise due to the JMM.</p><p><strong>What Is a Memory Model?</strong></p><p>Any modern computer architecture can do such things like cache global variables and reorder instructions to get a performance boost. It is not guaranteed that the instructions are run in the order as they were written in the high-level program. In a single threaded program, the execution follows the <em>as-if-serial</em> semantics. That is, while the instructions can be reordered, the result would be as if the program were executed serially. This does not hold true for concurrent programs.</p><p><strong>Why the Java Memory Model?</strong></p><p>Since each architecture can have its own memory model, the JMM abstracts all of them out by providing a common memory model on any architecture. The programmer does not have to worry himself about the underlying architecture, as long as he/she is following the rules of the JMM.</p><p><strong>Total Order vs. Partial Order</strong></p><p>Informally speaking, a total order is a binary relation that applies to any two elements of a set. For instance, for the set of integers, we have a total-order <strong><em>less-than</em></strong><em>. </em>Any you items in the set can be are related through this relation.</p><p>A partial-order however, applies to only some of the elements of the set. An example of this would be <strong><em>divisible-by</em></strong>. Take 2 and 3 for instance. Neither 2 is <strong><em>divisible-by</em></strong> 3 nor 3 is<em> </em><strong><em>divisible-by</em></strong> 2. This relation applies to only a subset of elements, and therefore, is a partial-order. In this case, we have 4 is <strong><em>divisible-by</em></strong> 2.</p><p>For a partial-order, the binary relation is <strong>transitive</strong> (this is the only property you will need to understand this article, so I skip the rest). That is, <strong>a <em>rel</em> b</strong> and <strong>b <em>rel</em> c</strong>, then <strong>a <em>rel</em> c.</strong></p><p><strong>Details</strong></p><p>The Java Memory Model (JMM) guarantees a <em>as-if-serial </em>guarantee to the execution of a program iff there is a <em>happens-before</em> relationship b/w the instructions. While the compiler can still reorder instructions that have a <em>happens-before </em>relationship, the final result will be as if the entire program were executed serially.</p><p>The JMM guarantees that instructions executing within a thread have a <em>happens-before</em> relationship b/w them. This guarantees that if the thread writes to a variable and then reads it, it <em>will</em> see the last written value. Another <em>happens-before</em> guarantee that the JMM gives is that a monitor lock can be acquired only after it has been relinquished (regardless of what thread relinquishes it and what thread acquires it).</p><p>What distinguishes a parallel program from a serial program is that the instructions in the latter are <em>totally-ordered</em> (governed by <em>happens-before</em>), while the former only has a <em>partial-order</em>. A parallel program can be given a total order with proper synchronisation. The more ordering we can ensure, the better we can reason about the behaviour of the program. Now consider the following implementation of lazy loading:</p><pre><strong>@NotThreadSafe<br>public class </strong>LazyObjectFactory {<br><br>    <strong>private </strong>LazyObject <strong>instance</strong>;<br><br>    <strong>public </strong>LazyObject getInstance() {<br>        <strong>if</strong>(<strong>null </strong>== <strong>instance</strong>) {    //read1<br>            <strong>instance </strong>= <strong>new </strong>LazyObject();<br>        }<br>        <strong>return instance</strong>;    //read2<br>    }<br>}</pre><p>The above program basically is a factory that maintains a singleton. This class is obviously not thread safe as there is a race-condition. It’s possible that the correct behaviour of the program is broken in case two threads call <em>getInstance()</em> in parallel, leading to the creation of two <em>LazyObject</em> instances.</p><p>But there is something much more sinister going on here. The above code can show some pretty absurd behaviour:</p><ol><li>Thread A initialises the object and assigns it to <em>instance</em>. However, thread B still see it as <em>null</em> and goes ahead with creating another instance.</li><li>Thread A initialised the object and assigns it to instance. Thread B sees a non-null value during <em>read1</em>, but returns an improperly constructed object.</li></ol><p>For the initialising thread, this relation satisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*YvRTqGpmlD-Zetrk7MxzAQ.png" /></figure><p>But observe that no such relationship exists b/w the assignment in thread A and the read in thread B, leading to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*TK3Xjkk8eKHaz8OSalAadg.png" /></figure><p>To see how 2 takes place, note that thread B can observe thread A’s actions in the opposite order. That is, the assignment takes place before the initialisation. So <em>read1</em> shows a non-null value, but an improperly constructed object is returned.</p><p>Now consider the thread-safe version of the above program:</p><pre><strong>@ThreasSafe<br>public class </strong>LazyObjectFactory {<br><br>    <strong>private </strong>LazyObject <strong>instance</strong>;<br><br>    <strong>public synchronised </strong>LazyObject getInstance() {<br>        <strong>if</strong>(<strong>null </strong>== <strong>instance</strong>) {    //read1<br>            <strong>instance </strong>= <strong>new </strong>LazyObject();<br>        }<br>        <strong>return instance</strong>;    //read2<br>    }<br>}</pre><p>How does synchronisation help us? The following diagram illustrates it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*GRf_VSQ9XFcRJn2-0-9W1Q.png" /></figure><p>We know that the JMM guarantees a <em>happens-before</em> relation b/w a lock’s release and its acquisition (release <em>happens-before</em> acquisition). The lock release happens-before lock acquire, we have a total ordering across events for these two threads (whatever thread A did before relinquishing the lock and whatever thread B did after acquiring the lock). This alleviates both of the problems above.</p><p>The diagram above illustrates an important concept. Since we have a total ordering, <em>any</em> memory writes that thread A did before relinquishing the lock will be visible to thread B, and not just the proper publishing of <em>instance</em>.</p><p>The JMM also guarantees a <em>happens-before</em> relationship b/w writing to a volatile variable and reading from it. That is, any subsequent reads from any thread will see the latest value written from any thread. Note that <em>volatile</em> variables are not a replacement for proper locking. For instance, declaring <em>count</em> as <em>volatile</em> does not guarantee that <em>count++</em> will be atomic. You <em>have</em> to encapsulate it in synchronised blocked as it is a compound action that needs to be executed atomically. All <em>volatile</em> ensures is proper memory visibility.</p><p><strong>Static Initialisers and Thread Safety</strong></p><p>An easy way to create thread-safe singleton factories is using static initialisers as:</p><pre><strong>@ThreadSafe<br>public class </strong>SingletonFactory {<br><br>    <strong>private static </strong>Singleton <strong>instance = new </strong>Singleton();<br><br>    <strong>public </strong>Singleton getInstance() {<br>        return instance;<br>    }<br>}</pre><p>Since this is a static initialiser, it will be called once the class is loaded (and before any thread can start using this class). The object will be properly constructed and the reference properly initialised before any other thread and use it. There is again a <em>happens-before</em> relationship that guarantees that no such issues as above arise.</p><p>The above implementation can be used to create objects lazily in a thread-safe manner as:</p><pre><strong>@ThreadSafe<br>public class </strong>SingletonFactory {<br><br>    <strong>public</strong> <strong>static</strong> <strong>Singleton</strong> getInstance() {<br>        return Creator.instance;<br>    }</pre><pre>    <strong>private</strong> <strong>static</strong> <strong>class</strong> Creator {<br>        <strong>private</strong> <strong>static</strong> <strong>Singleton</strong> instance = <strong>new</strong> Singleton();<br>    }</pre><pre>}</pre><p>Creator is loaded lazily when the first call to <em>getInstance()</em> takes place. This achieves lazy-initialisation in a thread safe manner.</p><p><strong>Double Checked Locking</strong></p><p>Now that you are a bit aware of the JMM, you should be able to tell why the code below is not thread safe:</p><pre><strong>@NotThreadSafe<br>public class </strong>SingletonFactory {<br><br>    <strong>private </strong>Singleton <strong>instance</strong>;<br><br>    <strong>public </strong>Singleton getInstance() {<br>        <strong>if</strong>(<strong>null </strong>== <strong>instance</strong>) {<br>            <strong>synchronized </strong>(<strong>this</strong>) {<br>                <strong>if</strong>(<strong>null </strong>== <strong>instance</strong>) {<br>                    <strong>instance </strong>= <strong>new </strong>Singleton();<br>                }<br>            }<br>        }<br>        <strong>return instance</strong>;<br>    }<br><br>}</pre><p>This technique is called <strong>Double Checked Locking</strong> and aims to optimise the lock contention by first checking if the instance is <em>null</em>. But there is a fatal flaw, can you see it?</p><p>This article is meant to be a gentle introduction to the JMM. It’s too vast a topic to be covered in a single article. You should at least be aware of these basic to avoid making any catastrophic mistakes writing parallel programs.</p><p><strong>References:</strong></p><p><a href="https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=sr_1_1?crid=OYK6NGGB5IKU&amp;dchild=1&amp;keywords=java+concurrency+in+practice&amp;qid=1593717713&amp;sprefix=java+concur%2Caps%2C452&amp;sr=8-1"><strong>Java: Concurrency in Practice by Brian Goetz</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c306697acad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/an-introduction-to-the-java-memory-model-8c306697acad">An Introduction to the Java Memory Model</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of Floating-Point: Part 1]]></title>
            <link>https://pandepra.medium.com/basics-of-floating-point-part-1-956ba5f99213?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/956ba5f99213</guid>
            <category><![CDATA[numerical-analysis]]></category>
            <category><![CDATA[floating-points]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 21:30:39 GMT</pubDate>
            <atom:updated>2020-04-13T21:30:39.080Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been trying to understand David’s Goldberg’s seminal article <em>What Every Computer Scientist Should Know About Floating-Point Arithmetic </em>for some time now. As a programmer with no formal background in numerical analysis, floating-point was always (and still is) intimidating to me. And rightly so — floating-point is difficult and arcane, and if a programmer wants to write correct FP programs, he needs to understand how it works. In this article, I have tried to cover some of the basics of floating-point.</p><p>First, why floating-point? As we all know, the computer is a finite-state machine. It was assume only so many states as it has limited memory. Real numbers, on the other hand, are unlimited. Between 1.0 and 1.1, you can fit an infinite amount of numbers. Computers, therefore, have to make a compromise by approximating real numbers. A real-number that cannot be exactly represented in a given floating-point format would be rounded off so to be represented by a floating-point number. The set is a countable set, just like the set of all integers. A number as simple as 0.1 cannot be represented exactly on modern computers.</p><p>A floating-point format is specified by the following three parameters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*NI_UX0vuTl8Qi9Ks.png" /></figure><p>A floating-point number would then be represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/0*xEqbkY79rt3ncSi6.png" /></figure><p>Note that the total precision includes the digit before the dot. For the IEEE 754 Single-Precision, it’s 24. For Double-Precision, it’s 53. The specifics of the format will be covered later.</p><p>Let us construct a toy floating-point system with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*im7jhl371P32rRhR.png" /></figure><p>Here’s a list of all the possible numbers in this system. Not great, we have just 33 floating-point numbers that will approximate all the real numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*OewukvPFMlhyVwtT.png" /><figcaption>All Possible Positive Floating-Point Numbers In Our Toy System. Each Number Has A Negative Counterpart</figcaption></figure><figure><img alt="Floating-Point Numbers" src="https://cdn-images-1.medium.com/max/1024/1*iUcpCjJ4WuJhutSOfvwBOA.png" /><figcaption>The Above Numbers Represented On A Number Line</figcaption></figure><p>A few quick observations:</p><ol><li>All the numbers have been normalised (the first bit is 1). This is because this gives us a unique representation of these numbers. Otherwise the same number can have multiple representations that we can get by shifting the decimal point and changing the exponent.</li><li>The spacing b/w two floating-point numbers increases as we go left or right.</li><li>Including 0, we have a total of 33 floating-point numbers (16 positive and 16 negative) in this system.</li><li>Adjacent floating-point numbers are separated by a distance of 1 ULP. ULP stands for “Units In The Last Place”. It is the position value of the last digit in a number. So, for 1.01 x 10²³, the value of the ULP is 0.01 x 10²³.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/0*uM6v55nE5xGCKEeE.png" /><figcaption>1 ULP = 0.01 x 2¹</figcaption></figure><p>Relative error is another way to measure the error that results from an approximation. It’s defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*7o4O8wiXxF0xe7O-.png" /></figure><p>If you observed closely, the above formula tells us how many “actuals” fit in the absolute error. So if the above formula returns 1, it means you can fit one “actual” in the absolute error (implying a 100% error).</p><h3><strong>Rounding</strong></h3><p>As state before, a real-number that cannot be represented exactly as a floating-point number will be rounded off to one. A number needs to be rounded when:</p><ol><li>It lies outside the range of the floating-point system (say, 7.2) in our toy system.</li><li>The number lies within the range, but requires more precision to be represented than available.</li></ol><p>Here’re some examples of numbers that need to be rounded for the Single-Precision FP system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/0*b-iWC-Y9v3ifgIRe.png" /><figcaption>The first number is larger than the largest SP FP number. The second is smaller than the smallest, and the last one requires 31 bits of precision. All of these numbers need to be approximated.</figcaption></figure><p>The second number is an interesting one, because it is a sub-normal number and can be represented exactly. Subnormal numbers help in gradual underflow, so that any number smaller than the smallest floating-point number does not round off to 0 immediately (for negative numbers, the same rule applies).</p><p>Consider the following definition for a real-number <em>x</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*yyblzv03jrxCZ68y.png" /></figure><h3>Rounding Modes</h3><p>The IEEE standard defines four rounding modes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*NdC78Vro5Gtff-rx.png" /></figure><p>You can refer to Theorem 5 in Goldberg’s paper to see for yourself why round-to-even is the preferred method. With round up, calculations can drift upwards. We’ll be using round-to-even in the rest of the article.</p><p>Let us approximate real-numbers on the above system by rounding-off to the nearest value (there’s an exception to this rounding mode, which I’ll cover later in this section). Note that in this rounding system, the error can be no larger than 0.5 ULPs. Why? Take 4.2 for instance. In our toy system, we’ll round it off to 4. So the error here is 0.2 ULPs. As soon as we cross 4.5, we’ll approximate it to 5. So the max error is when we’re approximating 4.5, which is 0.5 ULPs. (In binary, it’s like approximating 1.11 x 2² with 1.111 x 2²).</p><p>Generally speaking, this happens when</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*_2L-bpi-729SBAIH.png" /></figure><p>Is approximated by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/0*ewnc-eDKSEAv3Vu0.png" /></figure><p>The error in this case becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*qccH3X1L6DUEdgcl.png" /></figure><p>Note that it above value has p units of 0s. Generally speaking, this error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/0*Fjmjgi-sXWksEaiu.png" /></figure><p>This is the maximum absolute error that can occur while approximating a real-number using the round-to-nearest rounding system. Note that this value is the same for any number for a given exponent in the FP system. The actual value satisfied the relation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/0*lhNDD6fOGQM7D2pr.png" /></figure><p>Dividing the absolute value with the min. and the max. values, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*GnuF4TtZfEFF837l.png" /></figure><p>The upper-bound of the relative error is called the machine-epsilon.</p><p>Note that if we don’t round to nearest, the error can be can approach 1 ULP, and in this case, the upper bound of the relative error becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*tSnX9q2NobWGY31L.png" /></figure><p>It is useful to remember that adjacent floating-point numbers differ by 1 ULP in a given exponent range. Take the IEEE 754 Single Precision system. We have 24 bits of precision. So if we want to know what’s the floating-point number next to 1.0000…..00000 x 2⁰, we just have to add 1 ULP = 0.0000….00001 x 2⁰, and we get 1.00000.00001 x 2⁰.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*b3FSjx21eeXo965X.png" /><figcaption>Calculating the next floating-point number</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*e20hPyXJnmUBMmqT.png" /></figure><p>So the above sum is actually the value of the floating-point number next to 1 in IEEE 754 Single-Precision. Let us have a look at the following calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*vMKuTcXjFnTfDyps.png" /></figure><p>In the above calculation, we try to add 1/2 ULP to 1. It ends up exactly in b/w 1 and the next floating point number (1 + 1/2²³). Therefore, it has to be rounded. Using round-to-even, we round it to the nearest number. But since this is a tie, we’ll round it off to whatever number is even. Therefore, we round it down to 1.</p><p>Now you should be able to answer the below question with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/53/0*dfhv32qgfMpbB8AC.png" /></figure><p>Here’s a C program that demonstrates the above:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;math.h&gt;<br><br><strong>int </strong>main(<strong>int </strong>argc, <strong>char </strong>*argv[]) {<br>    <strong>float </strong>a = 1;<br>    <strong>float </strong>b = powf(2,-23);<br>    <strong>float </strong>c = (<strong>float</strong>)(a + b);<br>    printf(<strong>&quot;%.16f\n&quot;</strong>,c); <em>//will not be rounded<br>    <br>    </em><strong>float </strong>d = powf(2,-24);<br>    c = (<strong>float</strong>)(a + d);<br>    printf(<strong>&quot;%.16f\n&quot;</strong>,c);   <em>//will be rounded to 1<br>    <br>    </em><strong>float </strong>e = powf(2,-25);<br>    c = (<strong>float</strong>)(a + e);<br>    printf(<strong>&quot;%.16f\n&quot;</strong>,c);   <em>//will be rounded to 1<br>    <br>    </em><strong>float </strong>f = 1.1 * powf(2,-24);<br>    c = (<strong>float</strong>)(a + f);<br>    printf(<strong>&quot;%.16f\n&quot;</strong>,c);   <em>//will be rounded to the next floating point number, 1 + 2^-23</em></pre><pre>    return 0;<br>}</pre><p>The output is:</p><pre>1.0000001192092896<br>1.0000000000000000<br>1.0000000000000000<br>1.0000001192092896</pre><p>As you can see, the result is exactly what we expected. Here’s a pictorial representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*jxMb6wNjsEPUgKGKjSX3gg.png" /></figure><p>Now we discuss some subtleties of rounding. If x &gt; Nmax, then ideally, we should always be rounding it to Nmax. The reason is that theoretically speaking, x is always closed to Nmax than it is to positive infinity. However, always rounding to Nmax can give rise to misleading results. Imagine if you added the largest possible floating-point number to itself and got the number back. That would be…..wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*IjsOtZPatNx0bBn1.png" /><figcaption>-x to be handled similarly</figcaption></figure><p>We have already derived the upper bound on the relative error when round-to-even mode is being used. If you re-write that formula, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*Zw_0X3PFTMhBqaNE.png" /></figure><p>Note that the relative error is independent on the exponent. It depends just on the base and the precision. Also, as you can clearly see, for round-to-even, the error bounds are half of what they are when we use round-to-up.</p><p>I’ll end this section by demonstrating how weird floating-point arithmetic can be. Consider the program below:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;math.h&gt;<br><br><strong>int </strong>main(<strong>int </strong>argc, <strong>char </strong>*argp[]) {<br>  <em>//demonstrates that floating-point addition is not associative;<br>  </em><strong>float </strong>x = 1;<br>  <strong>float </strong>y = powf(2,-25);<br>  <strong>float </strong>z = powf(2,-24);<br><br>  <em>//(x + y) + z<br>  </em><strong>float </strong>s1 = (<strong>float</strong>) (x + y);<br>  <strong>float </strong>res1 = (<strong>float</strong>) (s1 + z);<br>  printf(<strong>&quot;%.16f\n&quot;</strong>,res1);<br><br>  <em>//x + (y + z)<br>  </em><strong>float </strong>s2 = (<strong>float</strong>) (y + z);<br>  <strong>float </strong>res2 = (<strong>float</strong>) (s2 + x);<br>  printf(<strong>&quot;%.16f\n&quot;</strong>, res2);<br><br>  printf(<strong>&quot;%d\n&quot;</strong>, res1 == res2);<br>}</pre><p>What do you think the result will be? Addition, as we know is associative. That is, a + (b + c) = (a + b) + c. But if you run this program, you’ll know that this does not hold true for floating-point arithmetic.</p><p>Here’s a follow-up question. Is floating-point addition commutative?</p><h3>Correctly Rounded Operations</h3><p>The IEEE 754 mandates that operations be correctly rounded. That is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*mftE4QeZu1jE1jbe.png" /></figure><p>…and for other operations defined in the standard.</p><p>Correctly rounded operations are nothing but operations where you represent both the operands with infinite precision and then round the final result to fit the given floating-point system. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*n5zIYjorpFMwotMJ.png" /></figure><p>We always shift right to match the smaller exponent with the larger exponent. Note that as mentioned before, we don’t really care about precision at this point because every number will be written in infinite precision (you might notice the 24th bit in the smaller number after shifting). Adding, both, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/0*6nj6py1EQTz6bIv_.png" /><figcaption>Addition With Infinite Precision</figcaption></figure><p>We’ll now use the round-to-even rule to round this value off, as mandated in the standard. Note that this number is exactly 1/2 ULP away from 1.100….00001²³ x 2⁰. So, we’ll round to even. Thus, the final result will be 1.100….00001²³ x 2⁰ + 1 ULP = 1.100….00010²³ x 2⁰. This is the final value after rounding off.</p><p>Now since computers work in a finite number of bits (sentence taken from the paper), using infinite precision is not possible practically. Can we simply drop whatever we have after the 23rd bit blindly? No, as it can lead to some very inaccurate results. Floating-point hardware designers realised this and the problem was solved by preserving some limited number of bits beyond the permitted precision. I’ll be covering guard bits in the next part of the article.</p><p>References:</p><ol><li>What Every Computer Scientist Should Know About Floating-Point Arithmetic (<a href="https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html">https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html</a>)</li></ol><p>2. Michael L. Overton, Numerical Computing With IEEE Floating Point Arithmetic, 2001.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956ba5f99213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Dependency Injection?]]></title>
            <link>https://medium.com/swlh/why-dependency-injection-415bd7a3a828?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/415bd7a3a828</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 19:39:04 GMT</pubDate>
            <atom:updated>2019-08-21T07:38:04.056Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a class like this:</p><pre><strong>public class </strong>Engine {<br>  <strong>private </strong>Gasoline <strong>gas </strong>= <strong>new </strong>Gasoline();<br><br>  <strong>public </strong>Double getRemainingGas() {<br>    <strong>return this</strong>.<strong>gas</strong>.getRemaining();<br>  }<br>}</pre><p>We basically have a class called <strong>Engine</strong>. An instance of this class is dependent on an instance of the class <strong>Gasoline </strong>(tight coupling, bad). Now suppose we want to write a unit test for this class. Remember, unit tests are to test the class in isolation — we try to mock its dependencies and use them to write assertions.</p><p>Note that it is not possible to write a unit test for this class. It is because when you create an instance of this class, you implicitly create an actual instance of the <strong>Gasoline</strong> class as well — this is wrong (as we’re trying to test this class in isolation). This happened because we have intertwined the business logic of our application with the object instantiation logic — a practice that is advised against.</p><p>This is where DI kicks in. Consider the following class:</p><pre><strong>public class </strong>Engine {<br>  <strong>private </strong>Gasoline <strong>gas</strong>;<br><br>  <strong>public </strong>Engine(Gasoline gas) {<br>    <strong>this</strong>.<strong>gas </strong>= gas;<br>  }<br><br>  <strong>public </strong>Double getRemainingGas() {<br>    <strong>return this</strong>.<strong>gas</strong>.getRemaining();<br>  }<br>}</pre><p>This time, the Engine class declares that it needs an instance of the <strong>Gasoline</strong> class to instantiate an object of itself. What a DI framework will do is inject an instance of the <strong>Gasoline</strong> class at runtime (we’ll write this framework in a while). The benefits are immense — The class is now testable. You can create a mock of the <strong>Gasoline</strong> class and pass it to the constructor instead. You no longer have to create an actual instance of it. If <strong>Gasoline</strong> is an interface, you can pass any mock implementation for testing, say, <strong>LeadGasoline</strong>. An instance of <strong>Engine</strong> is no longer tightly couple to an instance of <strong>Gasoline</strong>.</p><p>Let us create the task of object creation to a Factory class:</p><pre><strong>public class </strong>ApplicationFactory {<br><br>  <strong>private </strong>Engine <strong>engine</strong>;<br>  <strong>private </strong>Gasoline <strong>gas</strong>;<br><br>  <strong>public void </strong>create() {<br>    instantiateGas();<br>    instantiateEngine();<br>  }<br><br>  <strong>public </strong>Engine engine() {<br>    <strong>return this</strong>.<strong>engine</strong>;<br>  }<br><br>  <strong>public </strong>Gasoline gas() {<br>    <strong>return this</strong>.<strong>gas</strong>;<br>  }<br><br>  <strong>private void </strong>instantiateEngine() {<br>    <strong>this</strong>.<strong>engine </strong>= <strong>new </strong>Engine(gas());<br>  }<br><br>  <strong>private void </strong>instantiateGas() {<br>    <strong>this</strong>.<strong>gas </strong>= <strong>new </strong>Gasoline();<br>  }<br>}</pre><p>Now, we can write our main method as:</p><pre><strong>public class </strong>Driver {<br>  <strong>public static void </strong>main(String[] args) {<br>    ApplicationFactory af = <strong>new </strong>ApplicationFactory();<br>    <em>// called once, therefore all the objects are created only once<br>    </em>af.create();<br>    Engine engine = af.engine();<br>    System.<strong><em>out</em></strong>.println(engine.getRemainingGas());<br>  }<br>}</pre><p>We instantiate the <strong>ApplicationFactory</strong> class, and call the <strong>create</strong>() method (once). This ensures that it creates all the methods inside it only once (so we’re effectively creating singleton objects here). After this is done, you can ask the factory object for whatever object you want and it will supply it to you.</p><p>Remember to always separate your instantiation logic from the business logic. Specify your dependencies in the constructor — and ask for them during runtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=415bd7a3a828" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-dependency-injection-415bd7a3a828">Why Dependency Injection?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Kafka Poller and Awaitility]]></title>
            <link>https://pandepra.medium.com/reactive-kafka-poller-and-awaitility-4306bc03fee7?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/4306bc03fee7</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[reactor-library]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Sun, 14 Jul 2019 06:34:15 GMT</pubDate>
            <atom:updated>2019-07-16T15:36:14.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HW1ON_YExp-gx7wP9KgY0A.png" /></figure><p>I have been working with Kafka for the past few months. Recently, I programmed a critical part of our system — a Kafka poller that polls the Fulfilment Service (FS). Writing a robust poller while ensuring that records are processed as per the business needs (and parallelising wherever possible) and testing such an asynchronous system is I would say, a bit complex and requires a thorough understanding of how Kafka works (at least its API, if not its architecture). Through this post, I have tried to summarise what I learnt, what worked for me, and what didn’t. It has been a very rewarding experience.</p><p>The FS sends us three kinds of events — Order Suspended, Order Concluded and Order Released. A fulfilment is suspended when there is a fraud that is detected in the order. It is released when the fulfilment starts, and concluded when the order reaches the customer. Let S = {Order Released, Order Concluded, Order Suspended}. Let us define a binary relation ≤ over S such that and for any a, b in this set, a ≤ b iff a is released before or when b is released. This is a POSET with the following relationships:</p><p>Order Released ≤ Order Concluded</p><p>What this means is that a Order Released event comes before a Order Concluded event, and thus, has to be processed first. There are some critical business flows that get executed while processing the Order Released events, including moving the money to our company’s account. This sanity check is done while processing a Order Concluded event, so if we process it before the corresponding Released event, it would fail.</p><p>Since Kafka guarantees intra-partition ordering, it was decided that the FS would send all events for a particular order in a single partition, in-order (the orderId would be used as the record key). Due to these reasons, it became imperative that we process each record in a partition in-order.</p><p>Here’re some important points to consider when you are consuming from Kafka:</p><p>1. Apache’s Kafka Java client is not thread-safe. So if you thinking of processing the events in parallel, make sure you synchronise access to the consumer. Ideally, all accesses should be synchronised. The easiest way to do this is to use Java’s synchronisation primitive (keyword ‘synchronised’). Make sure all accesses to the consumer are guarded by the same lock.</p><p>2. Most of the time, make sure you do not commit as soon as you consume: if the consumer dies in b/w and the record was not processed totally, you won’t be able to get that record again since you had already committed.</p><p>3. Kafka has two versions on commit: commitSync and commitAsync. If your use-case demands high throughput (and if you can afford reprocessing records), then use commitAsync. The reason is simple: The async version does not wait for the commit to be successful, and won&#39;t retry (it does accept a callback though, if you want to retry). Retrying this is dangerous - what is you fail to commit, but the next commit for that partition was successful. Now if you retry the previous commit, you&#39;ll move the offset back. When a new consumer is assigned that partition, he&#39;ll reprocess some messages. The sync version on the other had retries until the commit is successful - this will block your thread, leading to reducing your processing throughput but will ensure that the chances of you reprocessing a message are low.</p><p>4. Important Kafka configurations (especially used for testing): session.timeout.ms and max.poll.interval.ms. Kafka has a heartbeat thread and a processing thread. Using the heartbeat thread, a consumer can send a heartbeat to the broker b/w two consecutive polls. So if the whole consumer dies, it takes just session.timeout.ms to detect is. If just the processing thread dies, then it takes max.poll.interval.ms to detect it. maxBlockTime is the time a producer waits for a message to publish successfully (update metadata) before it throws an exception. If it is too high, your processing thread may get stuck and a partition rebalancing could take place. I faced this issue during test, where I had to fine tune these variables for my tests to behave as I expected.</p><p>5. Please check if you can parallelise processing across partitions. Kafka gives no guarantee of inter-partition ordering anyway — better process each on a separate thread. But keep in mind that you might have to process records in a a partition in order. So you can’t process them in parallel. This was exactly our requirement while writing the FS Kafka poller.</p><p>5. For FS’ Kafka listener, here’s what we wrote in the polling loop:</p><pre>private void consume(FsKafkaConsumerProperties properties) {<br>    while (true) {<br>      ConsumerRecords&lt;String, String&gt; records;<br>      records = fsKafkaConsumer.poll(Duration.ofMillis(properties.getPollTimeout()));<br>      Flux.fromIterable(records.partitions())<br>          .flatMap(<br>              topicPartition -&gt;              Mono.just(records.records(topicPartition)).subscribeOn(Schedulers.parallel())) //1<br>          .flatMap(this::processPartitionInSequence)<br>          .publishOn(Schedulers.parallel())<br>          .collectList()<br>          .doOnNext(a -&gt; logBatchProcessingFinish(records))<br>          .block(); // don&#39;t consume the next batch until you process this one<br>    }<br>  }<br><br>    private Flux&lt;ConsumerRecord&lt;String, String&gt;&gt; processPartitionInSequence(<br>      List&lt;ConsumerRecord&lt;String, String&gt;&gt; partitionRecords) {<br>    // concatMap ensures the list is processed in sequence<br>    return Flux.fromIterable(partitionRecords).concatMap(this::process);<br>  }</pre><p>We wanted to process a partition in order, but different partition can be processed in parallel. So, we emit each partition on a separate thread (1), and then each record on that thread is processed in order (by using concatMap instead of flatMap). Note that we don’t consume the next batch unless we process each record of the current batch (that’s why we used a .block()). Using .block() also allows us to call fsKafkaConsumer.poll(..) without guarding any access - we are sure that when the consumer is being used for polling, no other thread would be using it.</p><p>6. What happens to those messages that failed processing for some reason? This depends upon the business requirement — if you cannot afford losing that, then push it to a DLQ (Dead Letter Queue) and commit and move ahead. Resolving the DLQ generally requires manual intervention. Here’s Uber’s excellent article on such an architecture: <a href="https://eng.uber.com/reliable-reprocessing/">https://eng.uber.com/reliable-reprocessing/</a>. A more mature architecture would be to have separate DLQs based on what service failed: Identity, Payment, Price, Fulfilment, etc. Each queue can have a processor. In the end, there can be a DLQ that is resolved manually. Records can be pushed into it when the previous DLQ processors fail again.</p><p>7. Make sure that the retention period of the DLQ is high enough. If you lose messages here, they’re gone.</p><p>8. Here’s our processing chain:</p><pre>Mono.just(model)<br>        .flatMap(this::processRecord)<br>        .onErrorResume(<br>            err -&gt; {<br>              logProcessingError(err);<br>              model.err(err);<br>              return Mono.just(model);<br>            })<br>        .flatMap(this::publishEventToDLQ)<br>        .onErrorResume(err -&gt; Mono.just(record))<br>        .doOnNext(this::commit)<br>        .onErrorResume(<br>            err -&gt; {<br>              logCommitFailure(err);<br>              return Mono.just(record);<br>            })<br>        .subscriberContext(context);</pre><p>We try to process the record. In case some error happens, log it and publish the record to the DLQ. If publishing fails, then still move ahead and try to commit. If commit fails, log and move ahead. Perhaps we can raise an alert whenever more than 10 messages are pushed into the DLQ in a short duration. This depends upon the business.</p><p>9. Create an identifier (for example, a random UUID)to make a distinction b/w each record that you consume, even if they are duplicates, and put it into the subscriber context and the MDC. Do not depend upon the event to send a unique identifier (for example, ‘eventId’). In our case, the FS was sending different events with the same ‘traceId’ and the same ‘eventId. It was leading to very messy logging. I can’t emphasize on how important it is — a God-send while debugging.</p><p>10. We can maintain metadata of all the events that have been processed in a persistent file storage. In our case, each order document contains a metadata section. When we process a message successfully, we update the metdata with the ‘eventId’. As soon as we start processing the event, we do a sanity check if the metadata already contains the ‘eventId’. If yes, then the event has already been processed. We don’t process it.</p><p>10. A very clean way to handle all the mess that comes with deserialising events (in case you are consuming a large variety of events) — write a custom deserialiser. GSON lets us write your own deserialiser and register with it. Do whatever sphagetti code you want in there.</p><h3>Testing</h3><p>Testing asynchronous systems can be difficult. Let us see how we tested the Order Released events flows (L1 integration). Here’s a brief summary of the flow:</p><p>1. An Order Released event is consumed.</p><p>2. A sanity check if done to see if the event has been processed already. If yes, then don’t process it.</p><p>3. A ‘getPayment’ call is made and a sanity check is done to verify that the payment has been charged.</p><p>4. The payment is finalised (moved in the company’s account)</p><p>5. The corresponding invoice is marked as ‘Paid’.</p><p>6. The order document is updated with the ‘eventId’ in its metadata section. This means that the event has been processed.</p><p>7. The updated order is persisted in the database.</p><p>8. If any of the above steps fail, the event is pushed into the DLQ.</p><p>This is how we tested the happyPath:</p><pre>// send the event<br>    // Wait till the document metadata is updated<br>    Awaitility.await()<br>        .atMost(30, TimeUnit.SECONDS)<br>        .until(<br>            () -&gt;<br>                isMetadataUpdated(<br>                    &quot;orderId&quot;,<br>                    &quot;eventId&quot;));<br><br>    assertPaymentFinalised(&quot;e8756088-7959-46c8-8f14-eef5e6c74cae&quot;);<br>    assertInvoicePaid(&quot;93042a7c-28a3-4195-8523-b45104d7ad8b&quot;);<br><br>    // assert that the message is not published to the DLQ<br>    assertFalse(failedEventIds.contains(eventId));</pre><p>We have a Kafka poller running on a separate thread that listens to the DLQ and populates the events into a a list (failedEventIds). The last step in the happy path is the persist, so we wait for at most 30 seconds and check if the metadata section of the order document has been updated. For this, we use a library called &#39;Awaitality&#39;. But for this library, we would have done a Thread.sleep(30000). The downside to this approach is would make the thread sleep for 30 seconds every time - even if the metadata section was updated in 5 seconds. On the other hand, Awaitality continually polls the given boolean condition and breaks out as soon as it is satisfied.</p><p>Now since it has been asserted that the document metadata section was updated, we can assert that the payment was finalised and the invoice was marked paid and the event was not pushed into the DLQ. Note that metadata is updated in the last step, so all the other steps are guaranteed to have been executed before it.</p><p>Let us take a negative scenario, when the order is in an invalid state (the order needs to be ‘Checkedout’ for the processor for process this event).</p><pre>// Wait till the dead letter is published<br>    Awaitility.await()<br>        .atMost(new org.awaitility.Duration(5, TimeUnit.MINUTES))<br>        .until(() -&gt; failedEventIds.contains(eventId));<br><br>    /* verify that the order is not processed by asserting that document metadata does not contain<br>    the event id*/<br>    assertTrue(isMetadataNotUpdated(orderId, eventId));</pre><p>Here, since the processing failed, we wait for the event to be pushed into the DLQ. Then we assert that the document metadata should not be updated, since the event processing failed.</p><p>Let us test our actual Kafka poller. Here’s what happens in it:</p><p>1. The event is consumed.</p><p>2. The event is deserialised into one of the known event types.</p><p>3. It is processed.</p><p>4. If the processing fails, it is pushed into the DLQ, and a commit is done.</p><p>5. The publish to the DLQ fails, still the event is committed.</p><p>Here’s how we test the scenario corresponding to step 5 (DLQ publish itself fails).</p><pre>// FS uses the orderId as the partition key to Kafka<br>    ListenableFuture&lt;SendResult&lt;String, String&gt;&gt; sendResultListenableFuture =<br>        kafkaTemplate.sendDefault(<br>            &quot;orderId&quot;, eventToSend);<br><br>    SendResult&lt;String, String&gt; sendResult = sendResultListenableFuture.get();<br>    int recordPartition = sendResult.getRecordMetadata().partition();<br>    long offset = sendResult.getRecordMetadata().offset();<br><br>    // consumer.committed(....) returns null if there was no prior commit to a partition. So wait<br>    // till there is a commit<br>    Awaitility.await()<br>        .atMost(new Duration(30, TimeUnit.SECONDS))<br>        .until(<br>            () -&gt;<br>                null<br>                    != testConsumer.committed(<br>                        new TopicPartition(&quot;FULFILMENT_ORDER&quot;, recordPartition)));<br><br>    OffsetAndMetadata offsetAndMetadata =<br>        testConsumer.committed(new TopicPartition(&quot;FULFILMENT_ORDER&quot;, recordPartition));<br><br>    // assert that the last committed offset was equal to the offset of the consumed message<br>    assertEquals(offset, offsetAndMetadata.offset());</pre><p>Our Kafka poller commits a message even when it could not be processed. So, wait till it is committed (for at most 30 seconds). Then assert that the last committed offset for that partition was equal to the offset of the message that was consumed. Note that we’ll have to simulate a DLQ publish error. This can be done by giving the wrong server location in the configuration file.</p><p>That’s all folks, for this post. Let me know if you have any suggestions to improve upon the poller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4306bc03fee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reactor’s .flatMap() Operator]]></title>
            <link>https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95?source=rss-5a4ba3e91298------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a7e62d3e95</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Prashant Pandey]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 17:42:54 GMT</pubDate>
            <atom:updated>2021-01-09T06:31:41.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Reactive’s .flatMap() Operator</h3><p><em>.flatMap()</em> is one of the most arcane of Reactive’s operators. While it is difficult to understand, once we understand exactly how it works, it becomes an extremely powerful operator in our toolkit. In this article, we’ll try to dissect it and understand what it does and why it does what it does. Note: I am using Project Reactor for demonstration but RxJava’s <em>.flatMap()</em> also works in the same way. All you need to know about Reactor for this post is that a <em>Mono</em> represents a stream containing a single event, whereas a <em>Flux</em> represents a stream with more than one event.</p><p>Before we go any further into understanding <em>.flatMap()</em>, we need to understand another operator, <em>.merge()</em>. Here’s its ‘marble’ diagram (please don’t get intimidated by these diagrams. Once you get the hang of them, they are very useful in understanding the more difficult operators):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khWxzh9dpm3NVoCjI5RPgA.png" /><figcaption>.merge()</figcaption></figure><p>What <em>.merge()</em> does is it takes the two streams, subscribes to both of them eagerly, and emits out a sequence of interweaved events. ‘Eagerly’ here means that the operator subscribes to both the streams at once (simultaneously) and does not wait for one of the streams to finish before subscribing to the other. The important thing to note here is that <em>.merge()</em> does not give any ordering guarantees.</p><p>Let us study <em>.flatMap() </em>now. Here’s its marble diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Y63YvBMyq8gnTkO_g3etQ.png" /></figure><p>What we have here is a stream. Now we all know that <em>.flatMap()</em> creates a new stream out of every upstream event (one-to-many mapping, you take one upstream stream, and create a stream from it that can have multiple events). So, what happens is that <em>.flatMap()</em> creates a stream out of the two upstream events (represented by the green and the yellow circles). It then eagerly subscribes to each of the newly created streams and dynamically merges them both of them. Again, what eagerly means here is that it won’t wait for any inner streams to complete before subscribing to the next one. The inner stream may emit immediately, or it may be an asynchronous HTTP call that takes a bit of time. <em>.flatMap()</em> doesn’t care. It will simply merge the resulting promise into the resulting (new) stream when the former becomes available. Since <em>.flatMap()</em> is doing a dynamic merge, it won’t guarantee any ordering among the resulting events. So please refrain from using it in case you want any ordering.</p><p><em>.flatMap()</em>, like any other Reactive’s operators, could not care less about what threads the upstream events or the newly created promises come in. Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/277e0dd3e9009d8614b89e3ca8155f54/href">https://medium.com/media/277e0dd3e9009d8614b89e3ca8155f54/href</a></iframe><p>Here’s the output I got:</p><p><em>Received: 1 on thread: parallel-1<br>Received in flatMap: 1 on thread: parallel-1<br>Received: 2 on thread: parallel-1<br>Received in flatMap: 2 on thread: parallel-1<br>Received (in the subscriber): 2 on thread: elastic-2<br>Received: 3 on thread: parallel-1<br>Received in flatMap: 3 on thread: parallel-1<br>Received (in the subscriber): 3 on thread: elastic-3<br>Received: 4 on thread: parallel-1<br>Received in flatMap: 4 on thread: parallel-1<br>Received (in the subscriber): 4 on thread: elastic-4<br>Received: 5 on thread: parallel-1<br>Received in flatMap: 5 on thread: parallel-1<br>Received (in the subscriber): 5 on thread: elastic-5<br>Received (in the subscriber): 6 on thread: elastic-6</em></p><p>The first <em>.flatMap()</em> creates a new stream (<em>Mono</em>) out of every element in the original stream and then merges all of these sub-streams (wrong term, but just for illustration). There are a total of 6 sub-streams created. As <em>.flatMap() </em>keeps creating a promise (by doing <em>Mono.just(a)</em>), it keeps subscribing to it. Since this is a trivial example, when subscribed to, these sub-streams emit their respective events immediately.</p><p>Note that the return type of <em>.flatMap()</em> here is a <em>Flux&lt;Integer&gt;</em>. Why’s that? Because again, the <em>.flatMap()</em> would merge all these sub-streams into a single stream to give you a stream that looks like: <em>Flux&lt;1,2,3,4,5&gt;</em>. Note that any operator in Rx (or Reactor) creates a new stream altogether, without touching the stream from the operator above. Each item of this stream comes on a separate thread, but hey, <em>.flatMap()</em> doesn’t care.</p><p>Note that the <em>.doOnNext()</em> prints all the elements on the ‘parallel-1’ thread. Here’s what is happening:</p><ol><li>1 is emitted on the ‘main’ thread.</li><li>The first <em>.flatMap()</em> receives this event on the same (main) thread and creates a stream from it (let us call this SS1), which will be emitted on a parallel thread. Reactor choose the ‘parallel-1’ thread (can be any thread, it’s a pool).</li><li>Before 2 could be emitted on the main thread and enter the first <em>.flatMap()</em>, SS1 enters the second <em>.flatMap()</em>, which will create a new stream (let us call it SS2), on a thread from the elastic thread pool. As soon as the second <em>.flatMap()</em> subscribes to SS2, ‘parallel-1’ becomes free.</li><li>Reactor uses ‘parallel-1’ to emit 2 as well, as it was free.</li><li>Similarly for the other events in the original stream.</li></ol><p>You can just specify the thread pool. It is Reactor’s job to choose which thread to pick for the job from the specified pool.</p><p>Long story short, here’s what <em>.flatMap()</em> does:</p><ol><li>Create a new stream out of every upstream event.</li><li>Subscribe to each newly created stream eagerly. We call these streams promises. A promise is simply an object that says, “I cannot guarantee you when I’ll return, but what I can guarantee you is that I’ll return for sure, at some point in future”. Remember Java’s <em>Future&lt;V&gt;</em>? They are promises as well.</li><li>Dynamically merge all the newly created streams as they emit. This is the ‘flat’ in <em>.flatMap()</em>.</li></ol><p>Now that you understand <em>.flatMap()</em>, try reading <em>.concatMap()</em>’s documentation. It should not take you more than a few minutes to understand it. Part 2 of this article (which I finally managed to write after more than an year), that you can catch <a href="https://pandepra.medium.com/project-reactors-flatmap-and-backpressure-fba97472d625">here,</a> covers the back-pressure effects of this operator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a7e62d3e95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-reactors-flatmap-operator-a6a7e62d3e95">Understanding Reactor’s .flatMap() Operator</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>