<?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 Mahesh Senniappan on Medium]]></title>
        <description><![CDATA[Stories by Mahesh Senniappan on Medium]]></description>
        <link>https://medium.com/@maheshsenniappan?source=rss-e97ef4f345d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8VwRB6HXOdeA0gy6sW6IxQ.jpeg</url>
            <title>Stories by Mahesh Senniappan on Medium</title>
            <link>https://medium.com/@maheshsenniappan?source=rss-e97ef4f345d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:59:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maheshsenniappan/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[Host name resolution in Java]]></title>
            <link>https://maheshsenniappan.medium.com/host-name-resolution-in-java-80301fea465a?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/80301fea465a</guid>
            <category><![CDATA[jdk]]></category>
            <category><![CDATA[cname]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 16:47:22 GMT</pubDate>
            <atom:updated>2019-04-17T14:58:55.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47ts4VbiPHSY9x36nSq_0Q.png" /></figure><p>It is very rare nowadays to find code that uses IP address to connect to servers — especially with the popularity of cloud based infrastructure and microservices. It is convenient to have human-friendly host names than a few random numbers put together. “<em>mydatabase.company.com</em>” is much easier to comprehend than “<em>10.202.17.5</em>”. It wouldn’t be an understatement if I said, host name resolution is one of the most overlooked and taken for granted functionality in software applications.</p><p>Most often than not if you are thinking about DNS resolution, it is highly possible that you are facing connectivity issues and your application is not working as expected. Well, I was in the exact situation recently — we migrated our database to a new server and the <a href="https://en.wikipedia.org/wiki/CNAME_record">CNAME</a> was updated to point to the new IP address. One of our Spring Boot applications was still writing to the old server even after the CNAME was switched to the new server. Although resolving the problem was straightforward, it got me thinking about DNS resolution and how it is done inside the JDK.</p><p>For the impatient, here is a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*QXqRtVJtTPE7E7hc-_UiFQ.png" /></figure><p>If you want to know more, read on.</p><h4>Socket and InetAddress</h4><p>As users of JDBC and other connection management libraries, we are abstracted from the low-level transport layer and communication protocol details as the libraries provide a convenient and rich API for us to work with. Most servers use TCP for communication and also have their own protocol to enable executing various commands sent from the client to the server. For example, these are the protocols for <a href="https://redis.io/topics/protocol"><strong>Redis</strong></a>, <a href="https://www.postgresql.org/docs/9.3/protocol.html"><strong>Postgres</strong></a> and <a href="https://dev.mysql.com/doc/internals/en/client-server-protocol.html"><strong>MySQL</strong></a> which define the contents of the messages or commands, format and order.</p><p><a href="https://docs.oracle.com/javase/8/docs/api/java/net/package-frame.html"><strong><em>java.net</em></strong></a><em> </em>is where most of the network related classes are available in the JDK and when it comes to handling low-level communication between machines, it boils down to these two classes - <a href="https://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html"><strong><em>InetAddress</em></strong></a><strong><em> </em></strong>and <a href="https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html"><strong><em>Socket</em></strong></a>. <em>InetAddress</em> is used to represent an IP address, be it IPv4 or IPv6. Socket defines an endpoint using an IP address and port number for communication between two machines. One of the constructors in the <em>Socket</em> class does exactly this — takes an <em>InetAddress</em> and port number to create a socket.</p><pre>public Socket(<a href="https://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html">InetAddress</a> address,<br>              int port)<br>       throws <a href="https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html">IOException</a></pre><h4>Anatomy of host name resolution</h4><p>To find the IP address of a host name, the code would be something like this:</p><pre>InetAddress address = InetAddress.getByName(&quot;<a href="http://www.example.com/">www.somedomain.com</a>&quot;); <br>System.out.println(address.getHostAddress());</pre><p>getByName is where the resolution magic happens. I have learned to love reading OpenJDK source code and that is the right place to look to know more about this.</p><p>When this code is executed, there is a series of private method calls and this is what happens.</p><ul><li>The provided host value is checked if it is a null value. If it is, the <a href="https://en.wikipedia.org/wiki/Loopback">loopback</a> address is returned — 127.0.0.1</li><li>If the input host is already an IP address, then there is no further lookup to do — input is returned</li><li>Check if the hostname had been resolved earlier and stored in the cache. If it is available in the cache, the value is returned. The property <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/net/properties.html"><strong>networkaddress.cache.ttl</strong></a> is used to control how long cached entries are valid. There is also a negative cache, which stores unsuccessful lookup so that the no time is spent on doing that again. <strong>networkaddress.cache.negative.ttl</strong> is used to set TTL for the negative cache.</li><li>If the cache look up fails, all the registered <a href="https://docs.oracle.com/cd/E19455-01/806-1387/6jam6926f/index.html"><strong>name services</strong></a> are called one by one until the IP address is found.</li><li>Unless custom name services are registered, there is a default name service provider registered which will be used for the look up.</li><li>After these steps, from the name service it finally reaches a native method called <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><strong><em>getaddrinfo</em></strong></a> in Linux based systems. For Windows, you can imagine something similar is happening.</li></ul><h4>getaddrinfo</h4><p><a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html">getaddrinfo</a> function is shipped as part of all operating systems conforming to the <a href="https://en.wikipedia.org/wiki/POSIX">POSIX</a> standard. It is used for translating a host name into an IPv4 or IPv6 address. It is defined in the <a href="http://pubs.opengroup.org/onlinepubs/9699919799.2018edition/">specification</a> as:</p><pre>The <em>getaddrinfo</em>() function shall translate the name of a service location (for example, a host name) and/or a service name and shall return a set of socket addresses and associated information to be used in creating a socket with which to address the specified service.</pre><p>In essence, it takes a host name and returns a list of IP addresses — yes, a list. I emphasize that here because, in the sample code earlier java.net.InetAddress#getByName returns a single address. When the native call to getaddrinfo is completed, the code in the JDK receives a list of addresses. All but one of the addresses are dropped and returned to the user’s code — as simple as addresses[0].</p><p>Older versions of the JDK used a different function called <a href="http://man7.org/linux/man-pages/man3/gethostbyname.3.html"><strong><em>gethostbyname</em></strong></a> which is now obsolete. There are some excellent references about how <strong><em>getaddrinfo</em></strong> function works <a href="https://jameshfisher.com/2018/02/03/what-does-getaddrinfo-do/">here</a>, <a href="https://github.com/angrave/SystemProgramming/wiki/Networking,-Part-2:-Using-getaddrinfo">here</a> and <a href="https://beej.us/guide/bgnet/html/multi/syscalls.html#getaddrinfo">here</a> if you are interested in knowing more about the internals.</p><h4>Conclusion</h4><p>Host name resolution is a complex topic and if you start following the clues, it takes you to interesting places. This was an opportunity for me to peek into OpenJDK code and some native functions. Hope you find this useful and don’t forget to set networkaddress.cache.ttl and networkaddress.cache.negative.ttl properties for your application<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80301fea465a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java performance profiling using flame graphs]]></title>
            <link>https://maheshsenniappan.medium.com/java-performance-profiling-using-flame-graphs-e29238130375?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e29238130375</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cpu]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 23:21:56 GMT</pubDate>
            <atom:updated>2019-04-15T23:21:56.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5c27xq5vCBvf7THW5hO7JQ.png" /><figcaption>MySQL flame graph from Brendan Gregg’s article</figcaption></figure><p>One of the great advantages of microservices is that, when there is an issue, you already have a pretty good idea of where it is happening and which microservice is responsible for it. And if it is a performance issue, you have a manageable amount of code or libraries to investigate, rather than dealing with the monolith as a whole.</p><p>There are a lot of performance measurement tools that come as part of JDK itself — <a href="http://openjdk.java.net/tools/svc/jconsole/">JConsole</a>, <a href="https://visualvm.github.io/">VisualVM</a>, <a href="https://docs.oracle.com/javase/7/docs/technotes/samples/hprof.html">HPROF</a>, etc. Most of them profile the application as a whole and it would take some effort to get to class or method level hot spots. While I was trying to evaluate the performance of one of our microservices, I came across a method using flame graphs which I found very effective in finding out CPU usage of the code. This post is more of a how-to and all credits go to <a href="http://www.brendangregg.com/blog/2014-06-12/java-flame-graphs.html">Brendan Gregg</a>.</p><h3>Requirements</h3><ul><li>A Linux machine with <a href="https://perf.wiki.kernel.org/index.php/Main_Page">perf</a></li><li>JDK — JDK8u60 and above</li><li><a href="https://github.com/brendangregg/FlameGraph">FlameGraph visualizer</a></li><li><a href="https://github.com/jvm-profiling-tools/perf-map-agent">jvm-profiling-tools/perf-map-agent</a></li><li>An application to profile :)</li></ul><p>I used an EC2 machine running RHEL 7 for this exercise — although I never tried, I expect Vagrant or VirtualBox should also work. If the application is an API, you need a load testing tool like <a href="https://jmeter.apache.org/">JMeter</a> or <a href="https://github.com/wg/wrk">wrk</a> to generate traffic for the API.</p><h3>Steps</h3><p>At a very high level, this is what needs to be done.</p><ol><li>Install perf_events</li><li>Build perf-map-agent from source</li><li>Run the Java application in the machine with -XX:+PreserveFramePointer JVM option</li><li>Generate load for the application using a load testing tool</li><li>Run perf-record command to capture performance counter profile</li><li>Run perf-map-agent to generate a map for JIT-compiled methods</li><li>Generate stack trace output from the previously recorded data by running perf-script</li><li>Generate flame graph</li></ol><p>I am using a RHEL machine, the commands in this post are based on it, but it should be easy to find equivalent commands for your OS. Let’s look at each of these steps in detail now.</p><h4>Install perf_events</h4><p>As the flame graphs are generated from the output of Linux perf_events, the first steps is to install it which provides the perf CLI command. Command to install perf_events:</p><pre>yum install perf</pre><h4>Build perf-map-agent</h4><p>When an application is running, JVM performs just-in-time (JIT) compilation of the byte code at runtime to optimize frequently used “hot” code. The byte code is converted to native code to improve performance and this native code is stored in memory. When perf runs, only this memory address is accessible and not the actual Java class or method. A tool like perf-map-agent connects to a running a JVM process and exports a map file which can be used by perf to generate the stack trace with the actual Java method names.</p><p>To build perf-map-agent follow the instructions in the <a href="https://github.com/jvm-profiling-tools/perf-map-agent">source repo</a>. It should be something like this:</p><pre>git clone <a href="https://github.com/jvm-profiling-tools/perf-map-agent.git">https://github.com/jvm-profiling-tools/perf-map-agent.git</a><br>export JAVA_HOME=&lt;JDK_DIR&gt;<br>cd perf-map-agent<br>yum install cmake<br>cmake .<br>make</pre><h4>Run the application</h4><p>The next step is to run the application with the JVM option -XX:+PreserveFramePointer. Frame pointers are commonly used to provide information to the debuggers about the call stack. With this option set, perf can construct more accurate stack traces by using information in the frame pointer about the currently executing method. Using this feature requires, JDK8u60 and above.</p><pre>java -XX:+PreserveFramePointer -jar app.jar</pre><p>Keep the application running to until performance profile (perf record) and symbol table (perf-map-agent) are captured.</p><h4>Generate load</h4><p>Generate load for your application using any of the load testing tools or a different approach depending on the application.</p><h4>Capture performance profile</h4><p>When the application is running, start capturing the CPU profile using perf_events with the following command:</p><pre>perf record -F 99 -p `pgrep java` -g -- sleep 10</pre><ul><li>-F 99 — Run profile at this frequency</li><li>-p — Profile an existing process with this PID</li><li>-g — Generate call graph</li><li>sleep 10 — Profile for ten seconds</li></ul><p>Once the profiling is completed after ten seconds, this command will generate a file called perf.data.</p><h4>Export symbols</h4><p>Assuming you have already built perf-map-agent, run the following command while the application is running to generate a map file of JVM symbols:</p><pre>bin/create-java-perf-map.sh `pgrep java`</pre><p>This command will create the file /tmp/&lt;PID&gt;.map. The application can be stopped at this point and is not needed for the subsequent steps.</p><h4>Generate trace output</h4><p>Now that we have the profile data and the symbols map, we can generate a details trace output of the profiled information. Run this command in the same directory as the perf.data file generated earlier:</p><pre>perf script &gt; out.perf</pre><p>This command will look for the map file in \tmp and use it to generate the output. It will fail if the .map file is not present in /tmp.</p><h4>Flame graph 🔥</h4><p>Get the scripts to generate the flame graph from the <a href="https://github.com/brendangregg/FlameGraph">source repo</a>. Run the scripts by passing the trace output generated earlier.</p><pre>git clone --depth 1 <a href="https://github.com/brendangregg/FlameGraph.git">https://github.com/brendangregg/FlameGraph.git</a><br>./FlameGraph/stackcollapse-perf.pl out.perf &gt; out.folded<br>./FlameGraph/flamegraph.pl out.folded &gt; graph.svg</pre><p>graph.svg is the flame graph and it can be opened in your favorite browser to explore.</p><h4>Conclusion</h4><p>Check out the reference articles and video linked below to get more information about flame graphs. Hope you found this useful.</p><h4>References</h4><ul><li><a href="http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html">CPU Flame Graphs</a></li><li><a href="https://medium.com/netflix-techblog/java-in-flames-e763b3d32166">Java in Flames</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnZfNehCzGdw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnZfNehCzGdw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnZfNehCzGdw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b455a3849b3db3b839e440bb19da65/href">https://medium.com/media/09b455a3849b3db3b839e440bb19da65/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e29238130375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disk based key-value stores]]></title>
            <link>https://maheshsenniappan.medium.com/disk-based-key-value-stores-5e0da4c9bdea?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e0da4c9bdea</guid>
            <category><![CDATA[rocksdb]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[key-value-database]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 03:13:31 GMT</pubDate>
            <atom:updated>2019-02-04T16:07:38.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rV_Y1MEyp5X13PY9Htj0eA.jpeg" /></figure><p>When it comes to key-value stores that provide low-latency, high-throughput access to data, <a href="https://redis.io/">Redis</a> is the first thing that comes to mind. It is widely used in an amplitude of use cases — session store, application cache and even as a key-value database. Redis ticks a lot of these boxes as it is memory based and is able to provide crazy fast access to data and perform operations on the data in a fraction of time taken by disk-based data stores. See <a href="https://redis.io/topics/benchmarks">this page</a> in Redis’s website to understand what I mean by crazy fast.</p><p>Once you move past session stores and application caches, there are a lot of uses for key-value stores even in big data and web-scale applications. For example, a Spark job can use a key-value store for fast lookups as part of a larger data pipeline or a social network can use it as a front for a relational database to store profiles of millions of users for fast access. In both these examples, it is paramount for the key-value store to provide low-latency, high-throughput access to data.</p><p>There is only one caveat — if there is one thing we have learnt from cloud services, it is that memory is not cheap. For example, at the time of writing (Jan 2019), this is how two machines with similar CPUs but different memory capacities are priced (on-demand)in AWS east region. As you can see, there is a price difference of 30%.</p><pre>+----------+------+-------------+----------------+<br>| Instance | vCPU | Memory(GiB) | Price/hour ($) |<br>+----------+------+-------------+----------------+<br>| m5.large |    2 |           8 |          0.096 |<br>| r5.large |    2 |          16 |          0.126 |<br>+----------+------+-------------+----------------+</pre><p>Let say we have a dataset that has 50 million keys each with string values of size 1kB. At least 47GB of memory is required to store just the values (over simplified estimate). This would require three r5.large instances with a total cost of 0.378/hour or $63/week. A fault tolerant setup would incur double the cost if not more. The purpose of this blog post is to find out if SSD based key-value stores (open-source), can be an alternative for the costlier memory-based solutions. There is no question that memory lookups will always be faster than SSD lookups. But how much of a performance compromise are we talking about?</p><h3>SSD based key-value stores</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*xYdNsnwFnu8vl9MdoJGSdw.png" /></figure><p>Gone are the days of magnetic tapes and spinning disks. SSDs are the next best thing to store data after main memory when it comes to low latency access. Look at this list of <a href="https://gist.github.com/hellerbarde/2843375">latency numbers every programmer should know</a> to understand how fast SSDs can be (150μs for random reads). They are also widely supported by cloud providers and are getting cheaper every day. For comparison, the 50 million values mentioned earlier can be stored in a single node having sufficient SSD storage for just 1/3 of the total cost. So, can they be a viable alternative for memory-based key-value stores? Read on.</p><p>There has been a lot of research and development in the area of disk-based key-value data stores in the past few years producing projects like <a href="https://github.com/google/leveldb">LevelDB</a>, <a href="https://rocksdb.org/">RocksDB</a>, <a href="https://symas.com/lmdb/">LMDB</a>, <a href="https://github.com/dgraph-io/badger">BadgerDB</a>, etc. In fact, they have become so popular that Redis and memcached — the two most popular key-value stores are offering disk-based solutions — <a href="https://redislabs.com/redis-enterprise/technology/redis-on-flash/">Redis on Flash</a> and <a href="https://github.com/memcached/memcached/wiki/Extstore">Extstore</a>. I am going to take RocksDB as an example here as it is very popular lately, it is open source and is <a href="https://github.com/facebook/rocksdb/blob/master/USERS.md">used in a lot of projects</a> as a storage backend.</p><h4>RocksDB Performance</h4><p>Performance benchmarks are <a href="https://github.com/facebook/rocksdb/wiki/Performance-Benchmarks">provided</a> by the RocksDB team which was done in an <a href="https://aws.amazon.com/ec2/instance-types/i3/">AWS i3 instance</a> with NVMe SSD storage and is optimized for low latency access. Random writes clock at around 56 micros/op which translates (1/(56 * 1e-6)) to 17k ops/sec and random reads are close at around 64 micros/op and 15k ops/sec. Note that if regular SSD backed instances were used instead of NVMe storage, latency numbers would be a bit higher. So theoretically if you run RocksDB and your application in two different availability zones, you can expect latencies of around 1ms to 3ms for key lookups from application code. Is it reasonable to expect these numbers?</p><p><a href="https://github.com/yinqiwen/ardb">Ardb</a> (with RocksDB storage) running in an <a href="https://aws.amazon.com/ec2/instance-types/m5/">m5.large instance</a> was used for the benchmarks to write and read 1 million keys. The instance has 2 cores and 8GiB memory and was configured with General Purpose SSD (gp2). Ardb was configured to use 2 threads to match the cpu cores in the instance. Benchmarks were run from a different instance (r5.large) in the same availability zone.</p><p><strong>Benchmark command:</strong></p><pre>redis-benchmark -h &lt;IP_ADDRESS&gt; -t set,get -r 1000000 -n 1000000 -d 1024</pre><p><strong>Benchmark Results:</strong></p><p><em>(few lines were truncated for brevity)</em></p><pre>====== SET ======<br>  1000000 requests completed in 25.53 seconds<br>  50 parallel clients<br>  1024 bytes payload<br>  keep alive: 1</pre><pre>19.34% &lt;= 1 milliseconds<br>99.83% &lt;= 5 milliseconds<br>99.96% &lt;= 10 milliseconds<br>99.99% &lt;= 26 milliseconds<br>100.00% &lt;= 203 milliseconds<br><strong>39171.14 requests per second</strong></pre><pre>====== GET ======<br>  1000000 requests completed in 19.80 seconds<br>  50 parallel clients<br>  1024 bytes payload<br>  keep alive: 1</pre><pre>51.08% &lt;= 1 milliseconds<br>99.93% &lt;= 2 milliseconds<br>99.99% &lt;= 7 milliseconds<br>100.00% &lt;= 203 milliseconds<br><strong>50507.60 requests per second</strong></pre><p>For comparison, Redis running in the same instance produced the following results.</p><pre>====== SET ======<br>  1000000 requests completed in 19.50 seconds<br>  50 parallel clients<br>  1024 bytes payload<br>  keep alive: 1</pre><pre>61.89% &lt;= 1 milliseconds<br>99.82% &lt;= 2 milliseconds<br>99.93% &lt;= 3 milliseconds<br>99.99% &lt;= 8 milliseconds<br>100.00% &lt;= 203 milliseconds<br><strong>51284.68 requests per second</strong></pre><pre>====== GET ======<br>  1000000 requests completed in 19.31 seconds<br>  50 parallel clients<br>  1024 bytes payload<br>  keep alive: 1</pre><pre>67.99% &lt;= 1 milliseconds<br>99.97% &lt;= 2 milliseconds<br>99.99% &lt;= 3 milliseconds<br>100.00% &lt;= 203 milliseconds<br><strong>51783.96 requests per second</strong></pre><p>Here is how the results look side-by-side.</p><pre>+-----------------+----------+----------------+<br>|    <strong>Datastore</strong>    |  <strong>Redis</strong>   | <strong>Ardb + RocksDB</strong> |<br>+-----------------+----------+----------------+<br>| SET (req/sec)   | 51284.68 |       39171.14 |<br>| GET (req/sec)   | 51783.96 |       50507.60 |<br>| P99 SET (ms)    |        2 |              5 |<br>| P99.9 SET (ms)  |        3 |             10 |<br>| P99.99 SET (ms) |        8 |             26 |<br>| P99.9 GET (ms)  |        2 |              2 |<br>| P99.99 GET (ms) |        3 |              7 |<br>+-----------------+----------+----------------+</pre><p>The performance numbers shown above can either be encouraging or discouraging depending on the use case and requirements but it is important to remember the trade off between performance and cost.</p><p>As you can see, Ardb with RocksDB storage engine is performing with millisecond latencies for most operations except for write throughput and P99.99 latency. While RocksDB provides lot of configurations to tune performance, <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html#EBSVolumeTypes_piops">Provisioned IOPS SSD</a> can be used to improve performance. There is also the possibility of running multiple instances of Ardb to effectively use all the cores in the machine. While you can do the same with Redis, it will soon run out of memory which is not the case with disk space.</p><h4>Storage libraries and Embedded databases</h4><p>If you look at the descriptions of RocksDB, LevelDB or BadgerDB, they are either called storage engines or embedded databases. Practically, what this means is that, these can’t run like a typical database server. They are meant to be used as a library from your application code - there, I said it. So you would bundle these “libraries” as part of an application’s code and deploy them in an environment with access to SSD storage. This is a radically different type of application architecture and comes with advantages and disadvantages of it’s own. But what if you are using Redis and would like to try or switch to one of these storage libraries?</p><h4>Redis protocol to the rescue</h4><p>Redis used a protocol called <a href="https://redis.io/topics/protocol">RESP</a> (REdis Serialization Protocol) for client-server communication. While it is meant to be used by Redis, it is flexible enough to be used in other projects where client-server communication is required, especially in a key-value store. The added advantage is that the existing tool set around Redis can be reused — redis-cli and other language specific clients.</p><p>So the solution is to use one of the storage engine libraries mentioned above for storage and add a TCP communication layer which communicates using Redis protocol to create a key-value store. Luckily, there are a few projects that have already done it and <a href="https://github.com/yinqiwen/ardb">ardb</a> is one such project. It is as simple as building the project with the storage engine of your choice and it can be deployed on a server as a key-value store. If there is existing code that uses Redis, it just needs to be pointed to the new server.</p><h4>High availability and Replication</h4><p>Although it is simple enough to get started with these storage engines using projects like <strong>Ardb</strong>, they can’t help if your goal is to have a highly available (HA) system. Replication and sharding are required to make this a highly available system and there is no built-in feature either in the storage engine libraries or in the Redis protocol wrappers (ardb) to setup a HA system.</p><p>This is exactly the problem Netflix was trying to solve and <a href="https://github.com/Netflix/dynomite">Dynomite</a> was created as a result of it. To quote Dynomite documentation, it’s design goal is:</p><blockquote>Dynomite’s design goal is to turn those single-server datastore solutions into peer-to-peer, linearly scalable, clustered systems while still preserving the native client/server protocols of the datastores, e.g., Redis protocol.</blockquote><p>Default implementation of Dynomite supports both Redis and Memcached protocols and it can also be extended to support other protocols if needed. Note that I said protocols instead of the actual data stores. This means that, any data store can be plugged into Dynomite as long as they speak one of these two protocols. Here is how the architecture will look like, straight from Dynomite documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ERzha6ivarzuga75yoZZJw.png" /><figcaption>Image source: <a href="https://github.com/Netflix/dynomite/wiki/Architecture">https://github.com/Netflix/dynomite/wiki/Architecture</a></figcaption></figure><p>Dynomite will sit in front of the data store and will replicate the data across multiple nodes in multiple data centers. While Dynomite itself is standalone, it can be used along with other tools in the <a href="https://github.com/Netflix/dynomite/wiki/Dynomite-Ecosystem">ecosystem</a> like <a href="https://github.com/Netflix/dyno">Dyno</a> client and <a href="https://github.com/Netflix/dynomite-manager">Dynomite-manager</a> for additional benefits.</p><h3>Conclusion</h3><p>There will always be an implicit trade-off between performance and cost and I have to acknowledge the fact that memory based data stores will always be faster than disk-based solutions. Having said that, it is not always possible to depend on memory based solutions because of the cost and their ephemeral characteristics. Disk based key-value stores are a viable alternative as they can provide acceptable performance characteristics for a fraction of the cost. Especially, if the values stored in the KV-store are larger and stored for longer periods. We also looked at how solutions (RocksDB, Ardb and Dynomite), that each address a specific concern, can be combined to produce a highly available storage solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e0da4c9bdea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Raspberry Pi without keyboard and mouse (headless)]]></title>
            <link>https://maheshsenniappan.medium.com/setting-up-a-raspberry-pi-without-keyboard-and-mouse-headless-9359e0926807?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9359e0926807</guid>
            <category><![CDATA[headless]]></category>
            <category><![CDATA[raspberry-pi-3]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[raspbian]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Sun, 11 Feb 2018 01:09:40 GMT</pubDate>
            <atom:updated>2021-03-22T02:02:59.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeRHIdDUgzk7FSyWjiI8GQ.png" /></figure><p><strong><em>Update 21-Mar-2021</em></strong><em> — A lot has changed since I wrote this article and while the method described here still works, there appears to be an easier way. Raspberry Pi team has released </em><a href="https://www.raspberrypi.org/software/"><em>Raspberry Pi Imager</em></a><em> which can be used to burn OS images to SD cards and it </em><a href="https://www.raspberrypi.org/blog/raspberry-pi-imager-update-to-v1-6/"><em>provides options to enable SSH and setup WiFi</em></a><em> using a simple interface. Since the imager can do all of what this article describes, there is no reason why you should be following the method described here, but read on if you must. Thank you!</em></p><p>If you are someone like me without a USB keyboard, mouse or a LAN cable, it is not straight forward to install <a href="https://www.raspbian.org/"><strong>Raspbian</strong></a> on a <a href="https://www.raspberrypi.org/"><strong>Raspberry Pi 3</strong></a>. As the latest releases of Raspbian come with <a href="https://www.raspberrypi.org/blog/a-security-update-for-raspbian-pixel/">SSH disabled</a> by default for security reasons, it took me a while to figure out a way to set it up with SSH enabled so that I can install and configure other tools on the Pi.</p><p>Here are two methods that have worked for me.</p><ol><li>Burn Raspbian image to SD card (I prefer this)</li><li>Using <strong>NOOBS</strong> to install Raspbian</li></ol><p>If you have a USB keyboard and mouse, using NOOBS gives you an interactive interface to easily install Raspbian (or any other OS). But it is challenging to use NOOBS if you don’t have the USB devices. I find method 2 to be the most straight forward to setup Raspbian with SSH and Wi-Fi connectivity preconfigured. Once you are able to SSH into the Raspberry Pi, you should be able to accomplish most of the other configurations.</p><h4>Required Tools</h4><ol><li>Raspberry Pi 3 model B</li><li>A computer that you can use to prepare the SD card and SSH into the Pi</li><li>SD Card Reader</li><li>Wi-Fi network</li></ol><p>Wi-Fi network is not required if you have a LAN cable that you can use to connect the Raspberry Pi and router.</p><h4>Method 1</h4><p>This method installs an image of Raspbian directly in the SD card using an image writing tool like <a href="https://etcher.io/">Etcher</a>.</p><p>1. Download the latest image of Raspbian from here — <a href="https://www.raspberrypi.org/downloads/raspbian/">https://www.raspberrypi.org/downloads/raspbian/</a></p><p>2. Format the SD using a tool like <a href="https://www.sdcard.org/downloads/formatter_4/index.html">SD Memory Card Formatter</a> if it is not done already.</p><p>3. I am using <strong>Etcher</strong> for writing the image to the SD card. Download the latest version of Etcher from here — <a href="https://etcher.io/">https://etcher.io/</a></p><p>4. Open Etcher and select the image downloaded earlier. Ensure that you have selected the correct SD card and flash it.</p><p>5. Once the flash is complete, you should see a <strong>boot</strong> volume created in your SD card.</p><p>6. For enabling SSH in the Pi, create a file named SSH in the root of the boot volume.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ed9f922f0d13a441141bbb54cbdedaf/href">https://medium.com/media/1ed9f922f0d13a441141bbb54cbdedaf/href</a></iframe><p>7. To preconfigure the Pi to connect to a WiFi network, create a file called <em>wpa_supplicant.conf</em> in the root of the <strong>boot</strong> volume with the following contents. This is not required if you have a LAN cable to connect the Pi to your router. You can skip this step if you have a LAN cable to connect your Pi and router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850d7c824e73e0a99bd58f2485a87f5d/href">https://medium.com/media/850d7c824e73e0a99bd58f2485a87f5d/href</a></iframe><p>8. Eject the SD card and insert it into the Raspberry Pi</p><p>9. If you have got an HDMI cable, connect the Pi to a display as it helps to find out any problems when the Pi boots for the first time.</p><p>10. Power up the Pi and give it a minute to boot</p><p>11. From your laptop, use a tool like <a href="https://nmap.org/">Nmap</a> to scan your local network. If you don’t have Nmap, look at the steps <a href="https://superuser.com/a/1009536">here</a> to install it. I have used 192.168.0.1/24 for the CIDR range to scan but this depends on your local network. Find out your machine’s IP adress in the local network and use that in the CIDR range.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01a20ca4eab95f73c8598910a9112aa4/href">https://medium.com/media/01a20ca4eab95f73c8598910a9112aa4/href</a></iframe><p>12. Nmap scan should provide a list of IP addresses corresponding to the devices connected to your network. Usually, the last IP address in the scan will be Pi’s as it is the latest device to join the network.</p><p>13. Once you know the Pi’s IP address, SSH into it as pi user with the default password raspberry. It is best to change to change the default password once you login for security.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/972d7fff98a34b7aac395135a95424b5/href">https://medium.com/media/972d7fff98a34b7aac395135a95424b5/href</a></iframe><p>You are good to go! Read on if for some reason if you want to use NOOBS.</p><h4>Method 2</h4><ol><li>Download NOOBS from here — <a href="https://www.raspberrypi.org/downloads/noobs/">https://www.raspberrypi.org/downloads/noobs/</a></li><li>Format the SD using a tool like <a href="https://www.sdcard.org/downloads/formatter_4/index.html">SD Memory Card Formatter</a> if it is not done already.</li><li>Extract and copy contents to SD card</li><li>Assuming that you want to install Raspbian, delete every other operating system directory from os directory except for Raspbian</li><li>Append silentinstall to <em>recovery.cmdline</em> file the in root directory</li><li>Edit <em>/os/Raspbian/partition_setup.sh</em> in the SD card and add the following lines after the three sed commands after replacing the <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">two letter ISO code</a> for your country, Wi-Fi network name and password. If you have a LAN cable to connect your Pi and router, you can remove the lines after and including #Configure WiFi.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c74c06703f6133e6bfc39ee81cffb070/href">https://medium.com/media/c74c06703f6133e6bfc39ee81cffb070/href</a></iframe><p>7. Eject the SD card and insert it into the Raspberry Pi</p><p>8. If you have got an HDMI cable, connect the Pi to a display as it really helps to monitor the progress of the installation.</p><p>9. Power up the Pi and wait for the installation to complete</p><p>10. From your laptop, use a tool like <a href="https://nmap.org/">Nmap</a> to scan your local network. If you don’t have <strong>Nmap</strong>, look at the steps <a href="https://superuser.com/a/1009536">here</a> to install it. I have used 192.168.0.1/24 for the CIDR range to scan but this depends on your local network. Find out your machine’s IP address in the local network and use that in the CIDR range.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01a20ca4eab95f73c8598910a9112aa4/href">https://medium.com/media/01a20ca4eab95f73c8598910a9112aa4/href</a></iframe><p>11. <strong>Nmap</strong> scan should provide a list of IP addresses corresponding to the devices connected to your network. Usually, the last IP address in the scan will be Pi’s as it is the latest device to join the network.</p><p>12. Once you know the Pi’s IP address, SSH into it as the default pi user with the password raspberry. It is best to change to change the default password once you login for security.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/972d7fff98a34b7aac395135a95424b5/href">https://medium.com/media/972d7fff98a34b7aac395135a95424b5/href</a></iframe><p>If you have come this far, you should be able to make changes to your Raspberry Pi using SSH. Have a ☕️ and enjoy your Pi.</p><p><strong>References</strong></p><p><a href="https://raspberrypi.stackexchange.com/a/31594">https://raspberrypi.stackexchange.com/a/31594</a></p><p><a href="https://github.com/raspberrypi/noobs/blob/master/README.md">https://github.com/raspberrypi/noobs/blob/master/README.md</a></p><p><a href="https://www.raspberrypi.org/forums/viewtopic.php?f=63&amp;t=141559">https://www.raspberrypi.org/forums/viewtopic.php?f=63&amp;t=141559</a></p><p><a href="https://github.com/raspberrypi/noobs/issues/365">https://github.com/raspberrypi/noobs/issues/365</a></p><p><a href="https://raspberrypi.stackexchange.com/questions/15192/installing-raspbian-from-noobs-without-display">https://raspberrypi.stackexchange.com/questions/15192/installing-raspbian-from-noobs-without-display</a></p><p><a href="http://blog.smalleycreative.com/linux/setup-a-headless-raspberry-pi-with-raspbian-jessie-on-os-x/">http://blog.smalleycreative.com/linux/setup-a-headless-raspberry-pi-with-raspbian-jessie-on-os-x/</a></p><p>Image source: <a href="https://www.pexels.com/photo/usb-technology-green-microchip-57007/">https://www.pexels.com/photo/usb-technology-green-microchip-57007/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9359e0926807" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive SVG charts — viewBox may not be the answer]]></title>
            <link>https://maheshsenniappan.medium.com/responsive-svg-charts-viewbox-may-not-be-the-answer-aaf9c9bc4ca2?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaf9c9bc4ca2</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[responsive-design]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Thu, 01 Dec 2016 21:33:04 GMT</pubDate>
            <atom:updated>2016-12-02T15:18:15.402Z</atom:updated>
            <content:encoded><![CDATA[<p>I was working on a visualization library last year where I had the opportunity to work on some interesting charts created using <a href="https://d3js.org/">D3.js</a>. The library had around 30+ charts and supported a plethora of configurations and features. One of our challenges was to make the widgets responsive and make them available for our clients on desktops, tablets and mobile devices.</p><p>We considered these two approaches for making the charts responsive.</p><ol><li>Use SVG <a href="https://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute">viewBox</a> attribute</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements">Determine the dimensions</a> of the container element and draw the chart inside it using the available space</li></ol><p>I will not get into the details of how <em>viewBox </em>attribute works (you can read <a href="https://sarasoueidan.com/blog/svg-coordinate-systems/">this</a>) but instead will be focusing on my experiences with the <em>viewBox </em>attribute and <strong><em>why I didn’t use it</em></strong> for making our charts responsive. I am not saying that the attribute is not useful at all, because it is a life saver when you are dealing with drawings, images and icons. But when it comes to charts, <em>viewBox </em>may not produce the results you expect.</p><h3><em>viewBox </em>attribute in a nutshell</h3><p>To give a gist of how <em>viewBox </em>works, let’s take a SVG circle for example. We define a SVG element with fixed dimensions <em>(100 x 100)</em> and define a circle in its center <em>(50, 50)</em> like so.</p><pre>&lt;svg width=”100&quot; height=”100&quot; xmlns=”<a href="http://www.w3.org/2000/svg">http://www.w3.org/2000/svg</a>&quot;&gt;<br>    &lt;circle cx=”50&quot; cy=”50&quot; r=”40&quot;/&gt;<br>&lt;/svg&gt;</pre><p>What if you want to display a larger circle for desktop browsers and smaller one in mobiles? <em>viewBox </em>attribute on the SVG element lets you define a co-ordinate system that is agnostic of the viewport. Depending on the element where this SVG is placed inside, it will automatically occupy the available space. The same circle when defined using <em>viewBox </em>will look like this.</p><pre>&lt;svg viewBox=”0 0 100 100&quot; xmlns=”<a href="http://www.w3.org/2000/svg">http://www.w3.org/2000/svg</a>&quot;&gt;<br>    &lt;circle cx=”50&quot; cy=”50&quot; r=”50&quot;/&gt;<br>&lt;/svg&gt;</pre><p>Notice the value of the <em>viewBox </em>attribute, it is a list of four numbers — <em>min-x</em>, <em>min-y</em>, <em>width</em> and <em>height</em>. The circle now resizes automatically without us writing even a single line of code - try resizing the browser.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fmaheshsenni%2Fembed%2Fpreview%2FrWpygY%3Fheight%3D600%26amp%3Bslug-hash%3DrWpygY%26amp%3Bdefault-tabs%3Dhtml%2Cresult%26amp%3Bhost%3Dhttp%253A%252F%252Fcodepen.io%26amp%3Bembed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fmaheshsenni%2Ffull%2FrWpygY%2F&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F239184.rWpygY.small.fb3937d4-90a3-4957-9fcb-5e10683daffe.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5d9d6e5bde1a29ae49621269b8d1740/href">https://medium.com/media/e5d9d6e5bde1a29ae49621269b8d1740/href</a></iframe><h3>The problem</h3><p><em>viewBox </em>works perfectly when it comes to charts that have a width to height ratio (<a href="https://en.wikipedia.org/wiki/Aspect_ratio_(image)">aspect ratio</a><a href="https://en.wikipedia.org/wiki/Aspect_ratio_(image))">)</a> of 1. So if you are creating charts like pie charts, <em>viewBox </em>greatly simplifies the process of making them responsive.</p><p>The problem is with charts that do not have an aspect ratio of 1 — charts like bar charts and histogram. To demonstrate this, let’s compare a bar chart created with <em>viewBox </em>used in two containers of different dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*kjYT9T7bIb8JELiW8Hi3Aw.png" /><figcaption>Bar chart with viewBox. Red border indicates the SVG element. Left — Bar chart is inside grey container. Right — Bar chart leaves empty spaces on each side.</figcaption></figure><p>The bar graph on the right leaves out empty spaces on each side because, SVGs by default try to satisfy the aspect ratio defined in the <em>viewBox </em>attribute. For example, if the value of the <em>viewBox</em> attribute is “<em>0 0 160 100</em>”, aspect ratio is 1.6. When the bar chart is placed inside containers that match this aspect ratio (<em>160 x 100</em>, <em>320 x 200, etc.</em>), the chart will fit exactly. In our case, bar chart on the right has a different aspect ratio than it’s container. So the SVG element leaves out empty space on each side to satisfy the aspect ratio defined by the <em>viewBox</em> attribute — in other words, <em>aspect ratio is preserved</em>.</p><h4>preserveAspectRatio is the answer — or is it?</h4><p>The only way to make the bar chart to occupy the whole space is to use another attribute <a href="https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute">preserveAspectRatio</a>.</p><pre>&lt;svg viewBox=”0 0 100 100&quot; preserveAspectRatio=&quot;none&quot; xmlns=”<a href="http://www.w3.org/2000/svg">http://www.w3.org/2000/svg</a>&quot;&gt;<br>    ...bar chart<br>&lt;/svg&gt;</pre><p>There is a huge list of possible values for this attribute but the only value that will make the SVG fill it’s container is “<em>none</em>”.</p><p>When <em>preserveAspectRatio=</em>“<em>none</em>”, the SVG element will fill it’s container without worrying about aspect ratio. This is how the bar chart looks with <em>preserveAspectRatio </em>as “<em>none</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*SiFcN0pT4oPthcHisycMLQ.png" /><figcaption>When preserveAspectRatio=none, SVG is stretched because of non-uniform scaling.</figcaption></figure><p>In case you haven’t noticed the text on the top-right corner of the chart, you can see that it is stretched. <strong>This is not good, especially in charts because axis labels and any other text inside the SVG will be stretched. This is a deal breaker because it solves one problem i.e. being responsive, but produces a chart that is unpleasant for the users.</strong></p><h3>Responsive charts without viewBox</h3><p>The other approach to do responsive charts is by <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements">determining the dimensions of the container element</a> and draw the chart according to these dimensions. This approach involves writing more code to draw or redraw the chart when viewport size changes (portrait to landscape?), but it produces a good looking chart. Here is the same bar chart drawn using this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*uoAEfJO-tgM6tNu1CfLiIA.png" /><figcaption>Chart without viewBox</figcaption></figure><p>There is another advantage when you take this approach. When a user switches from portrait to landscape mode in a tablet or mobile, you have the flexibility to use the extra space any way you choose. In the case of bar charts, you can simply increase the bar width or show more bars.</p><h3>Finally</h3><p>I decided not to use <em>viewBox </em>for creating responsive charts because the results it produced weren’t what I expected and I learnt it the hard way. <em>viewBox </em>is very useful when you are dealing with drawings, images and icons but when it comes to charts, the results it produces may not be what you want.</p><p><em>Let me know your experience with viewBox in the comments and if you liked this, don’t forget to click the💚 below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaf9c9bc4ca2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a module bundler with Hot Module Replacement]]></title>
            <link>https://maheshsenniappan.medium.com/creating-a-module-bundler-with-hot-module-replacement-b439f0cc660f?source=rss-e97ef4f345d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b439f0cc660f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mahesh Senniappan]]></dc:creator>
            <pubDate>Tue, 17 May 2016 03:34:18 GMT</pubDate>
            <atom:updated>2016-05-17T03:34:18.989Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer, I use a lot of libraries and tools developed by the community in my day to day work. Most of the time, I am not interested in how they actually work as long as they get the job done. There are a lot of tools like these — code linters, module bundlers and sourcemaps to name a few. I sure do understand them at a high-level, but I don’t know their internals. If I were to write my own version of a module bundler I wouldn’t know where to start. This post is my attempt at understanding one such tool and implementing a (over) simplified version of it from scratch.</p><p>One of those things that has always intrigued me is live reloading. It was amazing to see what LiveReload could do a few years back. I mean editor on one display and browser refreshing on the other display whenever you save files — it was magical. Then there was BrowserSync with its synchronised browsers idea. And now it is HMR — why refresh the browser when you can “hot replace” the code.</p><h4>How it works</h4><p>I started looking for hot module replacement related posts and came across this <a href="http://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack">Stack Overflow answer</a> (which is now <a href="http://webpack.github.io/docs/hot-module-replacement-with-webpack.html">added to webpack docs</a>) which explains the various things in play to get it to work. App code, webpack compiler, modules implementing HMR API and HMR runtime — all work in tandem to achieve hot module replacement.</p><p>Here is what happens every time you make changes to your code if you have HMR configured in webpack:</p><ol><li>webpack rebuilds the changed modules</li><li>Sends a signal via a websocket connection to HMR runtime running in the browser. <em>HMR runtime is added to your app bundle when you enable HMR via webpack configuration</em>.</li><li>Upon receiving this signal, HMR runtime makes a request to webpack server to get a list of updated modules. Response to this request is a JSON containing a list of changed modules called an “<strong>update manifest</strong>”.</li><li>HMR runtime then downloads the updated modules (update chunks) via JSONP and applies the updates</li></ol><p>The downloaded update chunk is a call to “<strong><em>webpackHotUpdate</em></strong>” function with the updated modules passed in as arguments. This function is immediately called when the update chunk is downloaded and the modules in the browser are updated with the latest updates. Here is how the update chunk looks if you make changes to a stylesheet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ff058fc68552fbc073d3e8ce24e5e11/href">https://medium.com/media/7ff058fc68552fbc073d3e8ce24e5e11/href</a></iframe><p>All that was said till now in this post holds good theoretically, but I wanted to see how challenging it will be to apply this knowledge in creating a module bundler of my own which is capable of doing hot module replacement.</p><h4>Writing a Module Bundler</h4><p>We will be creating a module bundler which will bundle our app code written as CommonJS modules to make them run in the browser (something like browserify). The sample app code is split across two files — <strong><em>app.js </em></strong>is the entry file which updates an element’s (<em>#message</em>) text in the page, <strong><em>message.js</em></strong> provides the text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6996d68aed804f22387d83ba9212928/href">https://medium.com/media/a6996d68aed804f22387d83ba9212928/href</a></iframe><p>So how do we takes these files and create a bundle which runs in the browser? We are going to rely on a few packages to do the heavy lifting for us.</p><p>A good way to understand how a tool works is to look at it’s dependencies. I found these two interesting packages in the dependencies of <strong>browserify</strong>.</p><ul><li><a href="https://github.com/substack/module-deps"><strong>module-deps </strong></a>— It takes an entry point file as input, recursively traverses through all of it’s dependencies and outputs a JSON. The JSON contains all the files and their dependencies starting from the specified entry point file.</li><li><a href="https://github.com/substack/browser-pack"><strong>browser-pack</strong></a> — Takes the JSON output from module-deps as input and creates a bundle capable of running in the browser.</li></ul><p>Let’s start with an <strong>index.js file </strong>to create our module bundler. Here is how the implementation of our module bundler looks so far. It does the following:</p><ol><li>Accepts the entry file path via command line</li><li>Provides the entry file path to module-deps and gets the JSON output</li><li>Feeds the JSON output from <strong>module-deps</strong> to <strong>browser-pack</strong> to generate the browser bundle</li><li>Writes the final bundle to <em>dist/bundle.js</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f54887a880353b68855ab7a24211199/href">https://medium.com/media/3f54887a880353b68855ab7a24211199/href</a></iframe><p>I have also added a small http server backed by <a href="http://expressjs.com/"><strong>express</strong></a> to serve our app. At this point, if you open <a href="http://localhost:3001/"><em>http://localhost:3001</em></a> in a browser, you should see the text from <em>message.js </em>displayed in the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*ur3TBokfLxL2NkYNumaTGA.png" /><figcaption>Browser running the app</figcaption></figure><p>We need to customise the bundle a bit to add a function which will update modules whenever updates are detected — think of the “<strong><em>webpackHotUpdate</em></strong>”<strong><em> </em></strong>function I mentioned earlier. We will get to that shortly.</p><h4>Watching for changes and notifying the browser</h4><p>Now that we have a functional module bundler, the next step is to watch for changes to any of the files and notify the browser about them. We will be doing the following things to achieve this:</p><ol><li>Listen for file system changes</li><li>Recreate the bundle with the latest changes</li><li>Notify the browser of the changes using a websocket connection (<a href="http://socket.io/"><strong>socket.io</strong></a>)</li><li>Listen for messages through the websocket connection from the browser</li></ol><p>Here are the changes to <em>index.js</em><strong> </strong>which does items 1, 2 and 3 above. I have modified the <em>processFiles </em>function to invoke a callback, added <a href="https://nodejs.org/docs/latest/api/fs.html#fs_fs_watch_filename_options_listener"><strong><em>fs.watch</em></strong></a><em> </em>to watch for file changes inside <em>“app”</em> directory and send a message using websocket connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/babeb8823e0b5b393bfee37fa628152f/href">https://medium.com/media/babeb8823e0b5b393bfee37fa628152f/href</a></iframe><p>For the next step, we need to add a couple of scripts to the page running the application to listen for these websocket messages. Here are the contents of <em>index.html</em> which runs the app and <strong><em>hmr.js</em> </strong>which contains code to listen for websocket messages. Notice that <em>Socket.IO</em> library and <em>hmr.js</em> are added to <em>index.html</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425e9f7ea2b505dcabbe4b8c483b7b9d/href">https://medium.com/media/425e9f7ea2b505dcabbe4b8c483b7b9d/href</a></iframe><p>At this point if you open <a href="http://localhost:3001/"><em>http://localhost:3001/</em></a><em> </em>in the browser and make any changes to files in the <em>“app” </em>directory, the browser will reload and run the app with the latest changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*KUUjSGiV6MciQyFfWRcSUg.png" /><figcaption>Browser reloads on file changes</figcaption></figure><h4>Hot update changed modules</h4><p>Now that we have the infrastructure in place, we can look at hot replacing modules. Here is a list of things that need to be done:</p><ol><li>Create an <strong><em>express</em></strong> server end point, <em>/hot-update,</em> that will accept the file or module name as a request parameter and respond with the latest code for the module wrapped around a <em>JSONP </em>callback function (let’s call the function <strong><em>hotUpdate</em></strong>)</li><li>Modify bundle output from <strong><em>browser-pack</em></strong><em> </em>to include the <em>JSONP </em>callback function, <strong><em>hotUpdate</em></strong>,<strong><em> </em></strong>mentioned in step 1 above</li><li>Send a request to <em>/hot-udpate </em>whenever a file change message is received via the websocket connection</li></ol><p>Let’s start by defining the <em>/hot-update </em>endpoint. If you remember, we start the bundling process by feeding the entry point file to <a href="https://github.com/substack/module-deps"><strong>module-deps</strong></a><strong> </strong>which returned all the modules and their source code in a JSON format. We can store this JSON in-memory and use it to retrieve the module’s source code while responding to the endpoint request. If you are curious, <a href="https://webpack.github.io/"><strong>webpack</strong></a><strong> </strong>does something similar with the help of an in-memory file system, <a href="https://github.com/webpack/memory-fs"><strong>memory-fs</strong></a>. I have added the following code to <em>index.js</em> which implements the endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223b20f6ae01c479d230cf629fa8c680/href">https://medium.com/media/223b20f6ae01c479d230cf629fa8c680/href</a></iframe><p>We can move on to adding the <strong><em>hotUpdate</em> </strong>function to the bundle output. This function will replace an existing module running in the browser with the latest changes supplied by <em>/hot-update</em>. Once the module is replaced, it will bootstrap the application by invoking it’s entry point module. Here is the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41832ade7629a385274bbdb53eea8d43/href">https://medium.com/media/41832ade7629a385274bbdb53eea8d43/href</a></iframe><p>The <a href="http://benclinkinbeard.com/posts/how-browserify-works/">final bundle is nothing but an IIFE</a> which accepts all the modules passed in as a map. When an update is received, the <em>hotUpdate </em>function just replaces the updated module in the module map with its new defintion. Once the module is updated, it calls the app’s entry point so that the app bootstraps again.</p><p>Now that we have the function, this needs to be added to the bundle output so that it can be called whenever we receive updates. As we use <a href="https://github.com/substack/browser-pack"><strong>browser-pack</strong></a><strong> </strong>to create the bundle, we can accomplish this easily supplying an option called “<em>prelude</em>” to it. <em>prelude </em>is nothing but a “prefix” like code which will be added before the app code when creating the bundle. You can find the default prelude provided by browser-pack <a href="https://github.com/substack/browser-pack/blob/master/prelude.js">here</a>. I have added the <strong><em>hotUpdate </em></strong>function<strong><em> </em></strong>defined above to the default prelude.</p><p>The module bundler is now close to completion, we just have to kick start hot module replacement whenever changes are made. To do this, we make a JSONP request to the <em>/hot-update </em>endpoint defined above, once we receive a “<em>file-change” </em>message via websocket (remember, we were listening to this message before to reload the browser). To make the request, we add a new <em>&lt;script&gt; </em>tag with it’s <em>src</em> attribute set to “<em>/hot-update?moduleId=&lt;id&gt;</em>”. I have modified the websocket message handler function, which was reloading the browser on file changes to make this request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26485d39920390eec4cffb0a287de936/href">https://medium.com/media/26485d39920390eec4cffb0a287de936/href</a></iframe><p>We have everything we need to test our module bundler (finally!). You can see the text in the page updating when I changed the text in <em>message.js</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*P7cUumCqgzh1i6bnegmQqg.png" /></figure><h4>HMR API in webpack</h4><p>Updating modules has a lot of side effects, which I have conveniently chosen not to worry about in this blogpost for the sake of brevity. This is where the <a href="https://webpack.github.io/docs/hot-module-replacement.html#api">HMR API methods defined in <strong><em>webpack</em></strong></a><strong><em> </em></strong>come in. These methods can be implemented by modules to handle various side effects when performing an hot update. For example, <a href="https://webpack.github.io/docs/hot-module-replacement.html#dispose-adddisposehandler"><strong><em>dispose</em></strong></a><strong><em> </em></strong>function can be implemented to perform clean up operations in a module before it is updated. The API also allows the developers to choose whether modules can accept updates with the help of <a href="https://webpack.github.io/docs/hot-module-replacement.html#accept"><strong><em>accept</em></strong></a><strong><em> </em></strong>and <a href="https://webpack.github.io/docs/hot-module-replacement.html#decline"><strong><em>decline</em></strong></a><strong><em> </em></strong>functions.</p><h4>Conclusion</h4><p>This was my attempt at understanding how module bundling and hot module replacement work and I learnt quite a few things while doing this exercise. I can also better appreciate the need for webpack’s various hot module replacement related API methods. While the idea looks simple, there is a lot of brilliance in play to get something this intricate to work in the scale of webpack.</p><p><em>If you have come this far, thanks for reading. You can find the source code for the sample app </em><a href="https://github.com/maheshsenni/how-hmr-works"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b439f0cc660f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>