<?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 Oitihjya Sen on Medium]]></title>
        <description><![CDATA[Stories by Oitihjya Sen on Medium]]></description>
        <link>https://medium.com/@otee.dev?source=rss-c5f10dffc42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZurnVb8Kj6vrwjyL3zwdsQ.jpeg</url>
            <title>Stories by Oitihjya Sen on Medium</title>
            <link>https://medium.com/@otee.dev?source=rss-c5f10dffc42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:25:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@otee.dev/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[Protocols: Clojure’s Polymorphic Magic]]></title>
            <link>https://medium.com/helpshift-engineering/protocols-clojures-polymorphic-magic-d291eab91d1b?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/d291eab91d1b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[helpshift]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 09:19:28 GMT</pubDate>
            <atom:updated>2024-02-28T10:29:51.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Ey3R8_iTn2Jqm-fv" /></figure><p>In this post, we will try to understand how protocols work in Clojure. As an example, we will see how clojure/core.cache, a well-known Clojure library, implements caching algorithms using protocols.</p><h3>Polymorphism In Clojure</h3><p>Polymorphism is a design principle which proposes using a single interface for multiple (more specific) methods. In other words, it refers to the practice of using a common interface for a general class of actions, where the entity-specific implementations can differ based on the type of the entity. The advantage of using this practice is that a lay user can use the interface for any given entity, without having to worry about the specific implementation for that entity. More significantly, one need not evaluate each available implementation to determine the one that fits the entity at hand.</p><p>In Clojure, polymorphism is implemented using protocols. Because protocols work with records, let’s understand what records are.</p><h3>Understanding records</h3><p>Using defrecord we can create a map-like data type namely record, which is a key-value data structure. They work much like a Clojure map: we can destructure them, look-up values by using keyword, i.e., (:keyword m), use assoc to add new key-value pairs, etc.</p><p>But there are important differences between a simple Clojure map and a record. For example, when we create a record using defrecord, we are creating a Java class with a constructor, where the different key-value pairs represent the different members of the class. The constructor is generated by Clojure automatically. Because every Java Class inherits the methods of the Object class, methods of Object class such as hashCode and equals are available for records as well. Note that the default implementation of these two methods is overridden by defrecord’s constructor, such that two instances of the same type will have the same hashcode and be considered equal if their constituents (key-value pairs) are the same.</p><pre>(defrecord Cube [width length height])<br><br>(def my-cube (Cube. 11 11 11))<br>(def another-cube (Cube. 11 11 11))<br><br>(.hashCode my-cube)<br>;;=&gt; -1060357495<br><br>(.hashCode another-cube)<br>;;=&gt; -1060357495<br><br>(.equals my-cube another-cube)<br>;;=&gt; true</pre><p>There are other differences between a Clojure map and a record: records are more performant, take less memory, they cannot act as functions etc.</p><h3>Understanding Protocols</h3><p>The most crucial difference between a record and a map is that a record can be used to implement a protocol in Clojure (because it is a Java class).</p><p>Protocols are a set of function signatures — grouped under a common name. They are like interfaces in Java — the implementation of each function is left to the specific classes themselves. This means that we can define a protocol with its constituent methods, and leave the implementations to each specific classes that wish to extend those methods to themselves.</p><pre>(defprotocol SimpleProtocol<br>  &quot;A simple protocol for showing how to declare protocols&quot;<br>  (foo [x y] &quot;A foo method for this simple protocol&quot;)<br>  (bar [a] &quot;A bar method for this simple protocol&quot;))</pre><p>In the above example, we created a protocol (SimpleProtocol) which has two methods (foo and bar). Note how we declare the signature of the methods along with a helpful doc-string but do not specify their exact implementations.</p><p>It’s important here to note that the first argument of a protocol method should always be an instance of a Java Class (which includes a record). This is because the type of the first argument is used to dispatch the type-specific implementation of that function.</p><h3>Using extend-type to implement a protocol</h3><p>We can use extend-type to <strong><em>extend</em></strong> a protocol to an existing data-type (such as a record).</p><p>Let’s first create a protocol called Log which can be used to implement different forms of logging for different data-types. To keep things simple, this protocol has only two methods log-only - for simply logging a given payload and log-level - for logging the given payload along with some additional data.</p><pre>(defprotocol Log<br>  (log-only [m] &quot;Log the object&quot;)<br>  (log-level [m severity] &quot;Log the object with severity information&quot;))</pre><p>Let’s implement this for String class first:</p><pre>(extend-type String<br>  Log<br>  (log-only [m] (println m))<br>  (log-level [m severity] (println (format &quot;[%s]\n%s&quot; severity m))))<br>  <br>(log-only &quot;Server started...&quot;)<br>;;=&gt; Server started...<br>(log-level &quot;Server failed to start!&quot; &quot;ERROR&quot;)<br>;;=&gt; [ERROR]<br>;;=&gt; Server failed to start!</pre><p>Now, let’s create a new record:</p><pre>(defrecord ExampleMessage [ts msg severity])<br><br>(ExampleMessage. (System/currentTimeMillis) &quot;System working&quot; &quot;Info&quot;)<br>;;=&gt; {:ts 1707877144399, :msg &quot;System working&quot;, :severity &quot;Info&quot;}</pre><p>We can now implement the Log protocol for this new record:</p><pre>(extend-type ExampleMessage<br>  Log<br>  (log-only [m] (clojure.pprint/pprint m))<br>  (log-level [m severity] (println (format &quot;%s:\n&quot; (clojure.string/upper-case severity))<br>                                   (select-keys m [:msg :ts]))))<br>                                   <br>(def sample-message (ExampleMessage. (System/currentTimeMillis) &quot;Exception XYZ at ABC ...&quot; &quot;CRITICAL&quot;))<br><br>(log-only sample-message)<br>;;=&gt; {:ts 1707877683229,<br>;;=&gt;  :msg &quot;Exception XYZ at ABC ...&quot;,<br>;;=&gt;  :severity &quot;CRITICAL&quot;}<br><br>(log-level sample-message (:severity sample-message))<br>;;=&gt; CRITICAL:<br>;;=&gt; {:msg Exception XYZ at ABC ..., :ts 1707877683229}</pre><p>Important to note here is that with extend-type we can extend any protocol to an existing object. As shown above, the String class was not written to implement our custom protocol Log but we could still do it using extend-type. This means protocols defined by third-party libraries can be implemented for our application-specific object, without a sweat! And the converse is also possible, that is, we can extend application-specific protocols to third-party or built-in classes.</p><h3>Implementing a protocol within defrecord</h3><p>There is another way to implement a protocol for a record type: we can implement a protocol while declaring the record itself:</p><pre>(defrecord ExampleMessage [ts msg severity]<br>  Log<br>  (log-only [m] (clojure.pprint/pprint m))<br>  (log-level [m severity] (println (format &quot;%s:\n&quot; (clojure.string/upper-case severity))<br>                                   (select-keys m [:msg :ts]))))<br><br>(def another-message (ExampleMessage. (System/currentTimeMillis) &quot;System working...&quot; &quot;INFO&quot;))<br>(log-only another-message)<br>;;=&gt; {:ts 1707877985573, :msg &quot;System working...&quot;, :severity &quot;INFO&quot;}<br><br>(log-level another-message (:severity another-message))<br>;;=&gt; INFO:<br>;;=&gt;  {:msg System working..., :ts 1707877985573}</pre><p>Applying protocols within the defrecord form has its advantages: methods implemented this way are several times more performant than those extended to a record type using extend-type. Also, this allows functions to refer to the fields of the record type directly, i.e., using ts directly in a form rather than (:ts m)</p><h3>Beauty of clojure.core/cache</h3><p>While thinking about caching, choosing the most optimum cache replacement policy becomes crucial. There are many commonly used cache replacement algorithms, including Least-Recently Used (LRU), First-In-First-Out (FIFO), Least-Frequently-Used(LFU), etc<strong>.</strong></p><p>One way to write a caching library would be to write a separate and independent set of methods for each type of caching policy. The downside of doing this is that the end-user cannot assume any commonality in the API of the corresponding functions of the different types of caches. Thus, one would have to go through the implementation of each operation to be sure of the respective context.</p><p>Another — more idiomatic — way of doing this would be to use a protocol: we define the common operations related to any form of cache and then leave the implementations to the specific caching types. This is exactly how clojure/core.cache does it.</p><pre>(defprotocol CacheProtocol<br>  &quot;This is the protocol describing the basic cache capability.&quot;<br>  (lookup [cache e]<br>          [cache e not-found]<br>   &quot;Retrieve the value associated with `e` if it exists, else `nil` in<br>   the 2-arg case.  Retrieve the value associated with `e` if it exists,<br>   else `not-found` in the 3-arg case.&quot;)<br>  (has?    [cache e]<br>   &quot;Checks if the cache contains a value associated with `e`&quot;)<br>  (hit     [cache e]<br>   &quot;Is meant to be called if the cache is determined to contain a value<br>   associated with `e`&quot;)<br>  (miss    [cache e ret]<br>   &quot;Is meant to be called if the cache is determined to **not** contain a<br>   value associated with `e`&quot;)<br>  (evict  [cache e]<br>   &quot;Removes an entry from the cache&quot;)<br>  (seed    [cache base]<br>   &quot;Is used to signal that the cache should be created with a seed.<br>   The contract is that said cache should return an instance of its<br>   own type.&quot;))</pre><p>Thus, irrespective of the specific implementation of the cache you use, you know the function signature will remain the same for the respective method, and so will its context. Only the underlying implementation will differ — something the end-user need not be concerned about while interacting with the library.</p><p>clojure/cache.core uses defcache for creating a new type of cache and implementing the CacheProtocol . defcache is a convenience macro, that apart from implementing the CacheProtocol, also implements “<em>Clojure&#39;s associative </em><a href="https://cljdoc.org/d/org.clojure/core.cache/0.8.1/doc/extending#the-defcache-convenience-macro"><em>data structure protocols</em></a><em> as well</em>” as per the CacheProtocol implementation. That is to say, it ensures that when we use assoc, on a cache object, the corresponding implementation of miss will be triggered, and when we use contains?, the respective has implementation will be triggered, and so on.</p><h3>Creating a custom cache using CacheProtocol</h3><p>Now, let’s create a new type of cache which implements the <strong>Random Replacement (RR)</strong> Policy. As per this algorithm, when the cache reaches its capacity, a key would be randomly selected for eviction.</p><p>To create this cache, we must pass the following parameters:</p><ul><li>cache: a map</li><li>threshold: the capacity for the cache</li></ul><pre>(:require [clojure.core.cache :as ccc])<br><br>(ccc/defcache RRCache [cache threshold]<br>...<br>)</pre><p>Let’s start with implementing the trivial methods: lookup has? hit</p><pre>(:require [clojure.core.cache :as ccc])<br><br>(ccc/defcache RRCache [cache ks threshold]<br>  ccc/CacheProtocol<br>  (ccc/lookup [_ k]<br>          (get cache k))<br>  (ccc/lookup [_ k not-found]<br>          (get cache k not-found))<br>  (ccc/has? [_ k]<br>        (contains? cache k)) <br>  (ccc/hit [this k]<br>           this))</pre><p>Let’s implement miss now. If the cache size does not reach the specified threshold, we can simply return a new cache object, with the new key-value pair. If, however, the cache is at full capacity, we will have to first select a random key and then return a new cache object without this randomly selected key.</p><pre>(:require [clojure.core.cache :as ccc])<br><br>(ccc/defcache RRCache [cache ks threshold]<br>  ccc/CacheProtocol<br>  ...<br>  (ccc/miss [_ k v]<br>            (if (&gt;= (count cache) threshold)<br>              (let [ks (keys cache)<br>                    evicting-k (rand-nth ks)<br>                    new-cache (dissoc cache evicting-k)]<br>                (RRCache. (assoc new-cache k v)<br>                          threshold))<br>              (RRCache. (assoc cache k v)<br>                        threshold))))</pre><p>Let’s implement the remaining methods., evict and seed. Note that seed is used for populating the cache with a set of key-value pairs.</p><pre>(:require [clojure.core.cache :as ccc])<br><br>(ccc/defcache RRCache [cache ks threshold]<br>  ccc/CacheProtocol<br>  ...<br>  (ccc/evict [_ k]<br>         (RRCache. (dissoc cache k)<br>                   threshold))<br>  (ccc/seed [_ base]<br>        (RRCache. base<br>                  threshold)))</pre><p>This completes our own implementation of RRCache. Now, to create an instance of this cache, we need to create a cache-factory</p><pre>(:require [clojure.core.cache :as ccc])<br><br>(defn rr-cache-factory<br>  [base &amp; {threshold :threshold :or {threshold 32}}]<br>  (ccc/seed (RRCache. {} threshold) base))</pre><p>Let’s try this out:</p><pre>(def my-cache (atom (rr-cache-factory {:a 11 :b 22 :c 33 :d 44} :threshold 5)))<br>;;=&gt; #&#39;user.core/my-cache<br><br>(swap! my-cache ccc/miss :e 555)<br>;;=&gt; {:a 11, :b 22, :c 33, :d 44, :e 555}<br><br>(swap! my-cache ccc/miss :f 666)<br>;;=&gt; {:b 22, :c 33, :d 44, :e 555, :f 666}<br><br>(swap! my-cache ccc/miss :g 777)<br>;;=&gt; {:c 33, :d 44, :e 555, :f 666, :g 777}<br><br>(swap! my-cache ccc/hit :f)<br>;;=&gt; {:c 33, :d 44, :e 555, :f 666, :g 777}<br><br>(swap! my-cache ccc/hit :a)<br>;;=&gt; {:c 33, :d 44, :e 555, :f 666, :g 777}<br><br>(ccc/has? @my-cache :a)<br>;;=&gt; false<br><br>(ccc/has? @my-cache :f)<br>;;=&gt;true<br><br>(ccc/lookup @my-cache :f)<br>;;=&gt; 666</pre><h3>Conclusion</h3><p>In this post, we explored how the concept of polymorphism is available in Clojure: using protocols and records, we can make our code extensible and re-usable in new and different contexts, by allowing a set of given operations (or methods) to be custom-implemented for a wide variety of different data-types.</p><p>This lets Clojure make the best of both the worlds of functional programming and object-oriented programming. In an object-oriented programming language, like Java, objects are first-class entities and, therefore, methods, can reside only inside objects. Thus, only the respective class can decide whether to extend a protocol or not. However, in Clojure, being a functional programming language, functions are first-class entities. This means that ccc/has? has an independent existence (like any other function) and different types can choose to implement this function. As a consequence of this, we can extend any protocol to a built-in class (such as Exception or String) or a third-party class, even though that class did not implement this protocol in the first place. This is not possible in an object-oriented programming language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d291eab91d1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/protocols-clojures-polymorphic-magic-d291eab91d1b">Protocols: Clojure’s Polymorphic Magic</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding: Log-Structured Merge Trees]]></title>
            <link>https://medium.com/@otee.dev/understanding-log-structured-merge-trees-7fc0863ff02b?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc0863ff02b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 00:00:59 GMT</pubDate>
            <atom:updated>2023-04-19T14:19:14.216Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I am listing down my understanding of Log-Structured Merge Trees (LSM Trees, in short), based on my reading of the first part of Chapter 3 of ‘Designing Data-Intensive Applications’ by Martin Kleppmann.</p><h3>TLDR</h3><ul><li>An LSM tree-backed storage engine comprises of an in-memory data-structure, called a <strong>mem-table</strong>. Every write operation is done on this mem-table. This data-structure ensures that keys are stored in a sorted manner, irrespective of the write pattern.</li><li>Once the size of this data-structure reaches a given threshold, its contents are written to a file on disk (called a log). As the mem-table stores data in a sorted manner, the log file also contains keys in a sorted manner. Note that log files are <strong>immutable</strong> — each time you write to a file you either append or write to a new log file.</li><li>In the background, multiple log files are <strong>merged and compacted</strong> (i.e. removal of duplicate keys) from time to time.</li><li><strong>Read path</strong>: Reads are done in the following manner: search for a key in the mem-table, then on the latest log file, all the way up to the oldest log-file.</li><li><strong>Write path</strong>: Directly update the mem-table. This is one of the reasons LSM trees are <strong>so fast</strong>.</li><li>In addition to the memtable, we also keep an in-memory hash-index of keys, for each log, where each key maps to the on-disk location of the key. Because keys are always sorted, we keep a sparse index.</li></ul><h3>Detailed Notes</h3><h4>Simple k-v store: The Log</h4><ul><li>The simplest form of a key-value datastore would involve a text file (often called a ‘log’), where each line consists of a key-value pair (separated by a comma)</li><li>For writing to this data store, i.e., creating a new pair or updating an existing pair, we simply append the key-value pair at the end of that log</li><li>For reading, we need to scan the entire log, by looking for the given key. If two keys are found, the latest key-value pair will be considered. This is because we never overwrite an existing entry in the log: we simply append at the end of the log.</li><li>This kind of data-store has <strong>very fast writes — O(1)</strong> as appending to a file is a very cheap operation. Conversely, <strong>look-ups are very painful — O(n)</strong>, where n is the number of records in the log.</li><li>Important: we never write existing data present in the log file.</li></ul><h4>Using an in-memory hash-map to improve performance</h4><ul><li>To improve the look-up operations, we can make use of <strong>indexes</strong>, which store additional meta-data about the records and act as a “signpost”.</li><li>Essentially, while doing writes, we store this additional metadata in addition to the appending operation. Thus, adding any kind of index will slow down write operations, but will also speed up read operations. Because the effectiveness of an index is dependent on the patterns of read queries, an application developer needs to manually add indices — they don’t come set by default.</li><li>One common index is to use an in-memory hash-map, which contains all the keys of the actual data-store, and these keys map to the on-disk location of that key in the data store. This makes look-ups far more efficient: given a key, we can use the in-memory data-structure to find the location of the key on the disk (as opposed to scanning the whole log file).</li><li>One limitation of this in-memory hashmap approach is that the total number of keys is limited by the finite size of RAM — since all keys of the data-store needs to be stored in the in-memory data-structure. Given this limitation, this kind of data-store is very useful in cases where the number of keys are finite but the values are updated frequently.</li><li>We also need to consider the situation where the log file becomes so large that its size becomes comparable to that of the disk. To overcome this, we can break the log file into <strong>segments</strong>, such that, the moment the log reaches a given size, we make subsequent writes on a new segment file.</li></ul><h4>Merger and compaction of logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*LdAWs8T0KzI2aV6f.png" /></figure><p><em>Source: Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems</em></p><ul><li>Since <strong>compaction can make segments smaller</strong>, we can merge two or more segments into one new segment.</li><li>This compaction and merging of frozen segments can happen asynchronously (in the background), while new writes take place on a new segment and reads use existing segments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*TgpmmJXtGH5VEI_p.png" /></figure><p><em>Source: Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems</em></p><ul><li>We keep separate in-memory hash-map indices for each segment. When we need to look up a given key, we start with the hash-map of the latest segment and go all the way back to the oldest segment, stopping the moment we find the key we are looking for. <strong>Deleting operations need to be dealt with separately</strong> for this kind of data-store: when a key is deleted, a special value should be stored against it on the log file.</li><li>If the database crashes, we will need to re-construct the in-memory hash-maps of each segment from scratch. This limitation can be overcome, if we keep a copy of the in-memory data-stores on a separate log of operations on the disk.</li><li>Another limitation of this append-only data-store is that it is not efficient for making range queries.</li></ul><h3>SSTables and LSM-Tree</h3><ul><li>In an append-only data-store, writes are not made in any particular order: they are made sequentially.</li><li>But we can also store the key-value pairs in a sorted manner (i.e. sorted by keys), while storing in the segment logs. This format is called <strong>Sorted String Tables</strong>.</li><li>For a given segment log, a single key appears only once (this can be easily achieved by compaction, as seen above).</li><li>SSTables have several advantages over simple append-only databases.</li><li>First, merging segments is possible, even when the size of the segment files exceed the available memory. While merging multiple segments, we start with the first key of each segment file, and write the key with the lowest value, and so on (similar to mergesort algorithm). If two or more segments contain the same file, we pick from the segment which is more recent (as that’s how segments are created).</li><li>Second, we no longer need to maintain the file location of each key of the data-store. If we know the location of “handbag” and “hardwork”, we will know that the location of “handsome” will be in between these two locations. So we can jump to the offset of “handbag” and scan till we come across “handsome”. Thus, we no longer need to keep an in-memory map of <strong><em>all the keys of the data-store</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*fXWlmCJyuJkP3HX9.png" /></figure><p><em>Source: Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems</em></p><ul><li>How to store keys in a sorted manner, in the first place? We can use an appropriate in-memory tree data-structure (such as a <strong>red-black tree</strong>) which allows us to write data in any order, but which stores them in a sorted manner. Thus, when a write operation is made, the key-value pair is stored in an in-memory data-structure which ensures this sorting property.</li><li><strong>Once this data-structure passes a given threshold, we write the key-value pairs to a segment file in a sorted manner, thereby creating SSTables.</strong></li><li>For a read operation, we first search for the key in the memtable, then to the most recent SSTable segment file, and so on.</li><li>One downside: <strong>in case of a crash, the most recent keys in the memtable will be lost.</strong> To fix this, we take a backup of the memtable in a separate file — which can simply be <strong>an append-only log file</strong>. In effect, each write operation makes two operations, it writes to the memtable and to the back-up append-only log file. The latter is used only for re-constructing the mem-table in case of a server crash. Storage engines which are based on this principle of merging and compacting sorted files are often called LSM storage engines, or, Log-structured Merge-Tree storage engines.</li><li>In LSM storage engines, look-up operations for non-existent keys are slow: to confirm a key is absent, we need to traverse from the memtable all the way to the oldest segment file. We can use <strong><em>bloom filters</em></strong>, to optimise this, as it can help us in knowing if a key is absent or not.</li><li>Like the append-only storage engine, we keep in-memory hash maps for each segment file, which stores keys sparsely (ie not every key, but every n keys).</li></ul><h3>References</h3><ul><li>Martin Kleppmann, Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems (O’Reilly Media. 1st Edn.), Chapter 3</li><li>‘How do LSM Trees work?’,<a href="https://yetanotherdevblog.com/lsm/">https://yetanotherdevblog.com/lsm/</a></li></ul><p><em>Originally published at </em><a href="https://otee.dev/2023/04/17/log-structured-merge-tree.html"><em>https://otee.dev</em></a><em> on April 17, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc0863ff02b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transitioning from Heroku Free Tier to GCP + YugabyteDB]]></title>
            <link>https://medium.com/@otee.dev/transitioning-from-heroku-free-tier-to-gcp-yugabytedb-4d38bb285f5f?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d38bb285f5f</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[yugabyte]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 00:00:15 GMT</pubDate>
            <atom:updated>2023-01-08T16:43:10.498Z</atom:updated>
            <content:encoded><![CDATA[<p>This post captures the list of steps I followed to migrate a HTTP service from a Heroku dyno to a Google Cloud Platform instance powered by YugabyteDB cluster as the database.</p><h3>Introduction</h3><p>To deploy <a href="https://twirl.otee.dev/">Twirl</a>, my URL shortening service, I was using Heroku’s free tier plans ( <em>more on how I built this app </em><a href="https://otee.dev/2021/11/14/twirl-user-management.html"><em>here</em></a><em>, </em><a href="https://otee.dev/2021/11/14/twirl-user-management.html"><em>here</em></a><em>, and </em><a href="https://otee.dev/2021/11/14/twirl-user-management.html"><em>here</em></a><em>)</em>. But now that it is <a href="https://techcrunch.com/2022/08/25/heroku-announces-plans-to-eliminate-free-plans-blaming-fraud-and-abuse/">no longer free</a> and ( <em>more importantly</em>) there is no plausible way to pay for their premium plans from India (whether via Indian cards or any other payment methods), I was forced to shift my app to a more traditional cloud provider.</p><p>Since I have an <a href="https://otee.dev/2021/12/31/deploying-to-google-cloud-compute.html">existing setup</a> on Google Cloud Platform (GCP), I decided to migrate my setup to my GCP instance. Additionally, I chose to use YugabyteDB instead of PostgreSQL as my database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IrWTkMXY5JBmzizb.png" /></figure><p>Here are the steps I followed to migrate out of Heroku, for my URL shortening service: <a href="https://twirl.otee.dev/">twirl.otee.dev</a></p><h3>Current Architecture</h3><p>The following diagram largely displays the current architecture. For more details, read: <a href="https://otee.dev/2022/01/13/making-short-links-shorter.html">https://otee.dev/2022/01/13/making-short-links-shorter.html</a></p><p>Major components:</p><ul><li><strong>nginx</strong>: this is running on GCP and is used for custom domain mapping to a free Heroku tier dyno, without having the default herokuapp domain in the URL.</li><li><strong>HTTP server</strong>: this is NodeJs app that uses PostgreSQL for storing state. Here’s the repo: <a href="https://github.com/oitee/twirl">https://github.com/oitee/twirl</a></li><li><strong>PostgreSQL</strong>: the database that stores the users, short links and other associated data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*yQvnB89CRpB3XCMP.png" /></figure><h3>New Architecture</h3><p>In the <strong>first phase</strong>, we want to independently run the system on GCP. In this lift-and-shift phase, each of the components of the system will be running outside of Heroku:</p><p>In the <strong>second phase</strong>, we want to move the data that is already present in the PostgreSQL database on Heroku, to the new YugabyteDB Managed instance. The reason for choosing <a href="https://www.yugabyte.com/">YugabyteDB</a> was not lightly made. Most importantly, it supports PostgreSQL operations so it fits our use-case. There are many other advantages as well which I will illustrate in another post.</p><p>In the <strong>last phase</strong>, we will decommission Heroku dyno.</p><h3>Phase 1: Setting up a parallel service on GCP</h3><h4>Step 1.1: Create YugabyteDB cluster</h4><p>Setting up a YugabyteDB Managed instance is quite straight-forward. After completing the sign-up process on <a href="https://cloud.yugabyte.com/signup">https://cloud.yugabyte.com/signup</a>, the cluster looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zLVLdGyR2eiv6Fk0.png" /></figure><p>Once set up, we need to connect to this database to set up our schema for the URL shortening app, as per the <a href="https://github.com/oitee/twirl#readme">ReadMe</a> of the project. To do this, we have to use the connection string as per the <a href="https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-connect/connect-applications/#connection-parameters">documentation</a> on YugabyteDB:</p><pre>postgresql://&lt;DB USER&gt;:&lt;DB PASSWORD&gt;@us-west-2.....aws.ybdb.io:5433/yugabyte?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=&lt;ROOT_CERT_PATH&gt;</pre><p>Note that to connect to the YugabyteDB cluster, we need to download a digital certificate — this can be done from the dashboard itself, by clicking on the connect button on the top left corner, and choosing the Connect to your Application option. We need to add the path to this certificate to the connection string. This certificate is used for verify the identity of clusters, as YugabyteDB uses TLS protocol for communicating with its clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*aYXmaK5RaLElGBLH.png" /></figure><p>Also, to connect to the YugabyteDB cluster, we need to white-list the client IP address. This also can be done from the dashboard itself ( <em>which provides a convenient option to add your current IP address to the IP Allow list</em>). At this point, we must add the IP address of our local machine. Ultimately, the IP Allow list should contain the public IP address of our GCP instance only.</p><h4>Step 1.2: Set up the Database</h4><p>To connect to the YugabyteDB, we can use the command line utility psql which is compatible with PostgreSQL and like databases.</p><p>We will use the connection string mentioned above to connect:</p><pre>psql &quot;postgresql://&lt;DB USER&gt;:&lt;DB PWD&gt;@us-west-2....aws.ybdb.io:5433/yugabyte?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=/home/otee/Downloads/root.crt&quot;</pre><p>At this point, psql should connect to the default yugabyte database. We can now create a new database for our app, twirl</p><pre>yugabyte=&gt; DROP DATABASE IF EXISTS twirl;<br>NOTICE: database &quot;twirl&quot; does not exist, skipping<br>DROP DATABASE<br>yugabyte=&gt; CREATE DATABASE twirl;<br><br>CREATE DATABASE<br>yugabyte=&gt;<br>yugabyte=&gt; \connect twirl;<br><br>psql (12.12 (Ubuntu 12.12-0ubuntu0.20.04.1), server 11.2-YB-2.15.3.2-b0)<br>SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)<br>You are now connected to database &quot;twirl&quot; as user &quot;admin&quot;.<br>twirl=&gt;</pre><p>After this, the requisite schema for this app can be set up, following the queries mentioned ont the <a href="https://github.com/oitee/twirl#running-the-system">ReadMe</a>.</p><h4>Step 1.3: Local sanity testing</h4><p>Now that the schema has been set up correctly, we need to make sure our app can use this. For this, we can run our app locally and use this connection string as the db endpoint. This is for local sanity testing that the app functions normally before we try anything infrastructure specific.</p><p>To run the app locally, the following command needs to be run. This command is specific to the app at hand, which expects a few environment variables, like the db connection string:</p><pre># Note that we need to use the new database `twirl`<br># and not the default `yugabyte` in the connection string<br>PG_SSL_CONNECTION=true CUSTOM_DOMAIN_NAME=localhost:4001 RECAPTCHA_SECRET=EXEMPTED PORT=4001 COOKIE_SECRET=&lt;eiffeltower...&gt; PG_CONNECTION_STRING=&quot;postgresql://&lt;DB USER&gt;:&lt;DB PWD&gt;@us-west-2....aws.ybdb.io:5433/twirl?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=/home/otee/Downloads/root.crt&quot; node app.js<br>Twirl listenning on 4001...</pre><p>At this point, the app works locally! 🎇</p><h4>Step 1.4: Deploy HTTP server on GCP</h4><p>Now, we need to setup the app on our GCP instance. For this, the following steps need to be followed:</p><ol><li>After ssh-ing to GCP instance, clone the repo:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*oPrYjyOu6DCp4RXa.png" /></figure><p>2. Copy the root certificate file (downloaded from YugabyteDB dashboard) to the GCP instance (ssh alias already set up as calculus locally).</p><pre>scp /home/otee/Downloads/root.crt calculus:/home/oitee.codes</pre><p>3. Run the command we ran locally earlier:</p><pre> PG_SSL_CONNECTION=true CUSTOM_DOMAIN_NAME=localhost:4001 RECAPTCHA_SECRET=EXEMPTED PORT=4001 COOKIE_SECRET=&lt;eiffeltower...&gt; PG_CONNECTION_STRING=&quot;postgresql://&lt;DB USER&gt;:&lt;DB PWD&gt;@us-west-2....aws.ybdb.io:5433/twirl?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=/home/oitee.codes/root.crt&quot; node app.js<br> Twirl listenning on 4122...</pre><p>Once we see the system startup, we have no way of connecting to this port from the browser because this port is not exposed. We will do this in the next step.</p><p>Note: When we run a service on an instance like this, one of the housekeeping items to ensure is that if the instance reboots (which it will eventually), we have to make sure that our HTTP server is automatically started. This was already being taken care of by Heroku, but here we need to do this ourselves ( <em>this will be done later</em>). But even when we do this, it is not guaranteed that the instance would not be irrevocably lost; in which case we will need to set it up manually again.</p><h4>Step 1.5: Setting up nginx config</h4><p>For our parallel (trial) service, we need to create a simple nginx config that maps requests to a test sub-domain <a href="http://twirl-test.otee.dev/">twirl-test.otee.dev</a> to this new HTTP service.</p><pre>server {<br>        listen 80;<br>        listen [::]:80;<br>        server_name twirl-test.otee.dev;<br>        location / {<br>         proxy_pass http://127.0.0.1:4122;<br>        }<br>}</pre><p>Next, we need to add a new DNS entry pointing the trial sub-domain twirl-test.otee.dev to the GCP instance.</p><p>Unfortunately, .dev domains only support https connections. So, we have to install a certificate for this sub-domain. We can do this with certbot, (following the <a href="https://certbot.eff.org/instructions?ws=nginx&amp;os=ubuntufocal">official documentation</a>)</p><pre>sudo certbot --nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*lljeQDFxPAnPzM1r.png" /></figure><p>After cerbot finishes adding the certificate, the earlier nginx configuration will be updated with the new certificate enforcing HTTPS:</p><pre>server {<br>        server_name twirl-test.otee.dev;<br>        location / {<br>         proxy_pass http://127.0.0.1:4122;<br>        }<br><br>    listen [::]:443 ssl; # managed by Certbot<br>    listen 443 ssl; # managed by Certbot<br>    ssl_certificate /etc/letsencrypt/live/twirl-test.otee.dev/fullchain.pem; # managed by Certbot<br>    ssl_certificate_key /etc/letsencrypt/live/twirl-test.otee.dev/privkey.pem; # managed by Certbot<br>    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot<br>    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot<br><br>}<br>server {<br>    if ($host = twirl-test.otee.dev) {<br>        return 301 https://$host$request_uri;<br>    } # managed by Certbot<br><br>        listen 80;<br>        listen [::]:80;<br>        server_name twirl-test.otee.dev;<br>    return 404; # managed by Certbot<br><br>}</pre><h4>Step 1.6: Add GCP instance IP address to Yugabyte allow-list</h4><p>The GCP IP address needs to be white-listed on the YugabyteDB dashboard, because random connections to the database are not allowed. Note that we need to add the <strong>permanent public IP address</strong> (and not the internal ephemeral IP address) of the GCP instance.</p><p>Now, the system should work with the YugabyteDB as the database!</p><p>Note: we have thus far set-up a parallel service using a temporary sub-domain; we will still need to point <a href="http://twirl.otee.dev/">twirl.otee.dev</a> (the original sub-domain) to this GCP instance. This will be done at a later step.</p><h3>Phase 2: Bring the GCP service upto speed</h3><h4>Step 2.1: Migrate existing data from Heroku PosgreSQL to YugabyteDB Managed</h4><p>Now that the HTTP server is working, we need to migrate the existing data from the postgreSQL database on Heroku to the newly set-up YugabyteDB database.</p><p>For this, we can use pg_dump which comes installed with psql. pg_dump is a back-up utility for a PostgreSQL database. It spits out SQL commands which can be used to reconstruct the database with all its the data present at the time of the backup.</p><p>For this, we need to use the same PostgreSQL connection string that the Heroku app uses.</p><p>Note: We could not use pg_dump from the terminal of our local machine directly, because the Heroku instance was using postgres version 13 and the corresponding postgres-client version was not readily available. So, we used this <a href="https://github.com/oitee/twirl/blob/main/docker-compose.yml">docker file</a> and used pg_dump inside that docker container:</p><pre># Going into the container<br>sudo docker exec -it twirl_postgres_1 bash<br><br>root@3012d2b15617:/# pg_dump -d &quot;&lt;psql connection string&gt;&quot; -f sql_queries.txt<br><br>##Leave the Docker container and copy the file<br>sudo docker cp twirl_postgres_1:/sql_queries.txt /tmp/sql_queries.txt</pre><p>Now that the backup is ready, we need to recreate the twirl database on YugabyteDB. For this, we need to connect to the default database on YugabyteDB called yugabyte and create the twirl database afresh.</p><pre>yugabyte=&gt; DROP DATABASE IF EXISTS twirl;<br>DROP DATABASE<br>yugabyte=&gt; CREATE DATABASE twirl;<br><br>CREATE DATABASE<br>yugabyte=&gt;</pre><p>Next, we need to restore the data from the file created by pg_dump. Since this file contains just SQL commands, we can just run psql on the new database taking the SQL commands from the file instead of the prompt:</p><pre># Connection string to yugabyte<br>psql &quot;postgresql://....ybdb.io:5433/twirl?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=/home/otee/Downloads/root.crt&quot; -f /tmp/sql_queries.txt</pre><p>Note that some of the statements may fail — this can be due to commands related to ownership access and other settings but the data should not be missing. Once the back-up is complete, we can do a simple sanity test by checking the number of rows in each table in both the databases.</p><p>At this point, our parallel service is upto speed with the existing service. In other words, <a href="http://twirl-test.otee.dev/">twirl-test.otee.dev</a> and <a href="http://twirl.otee.dev/">twirl.otee.dev</a> should have the same data, i.e., user credentials, short-links, access counts etc. So, we have successfully migrated the data from Heroku to YugabyteDB and therefore most of the work is now done. 🥂</p><h4>Step 2.2: Install Twirl as a service on GCP</h4><p>The node process running in the background can crash due to unforeseen exceptions, out-of-memory errors or some other reason like restarting of the VM itself. When this happens (as it inevitably will), our node process will terminate and our app will be unavailable. To solve this, we can use systemd. It is a &quot;system and service manager&quot; for Linux Operating Systems.</p><p>On the GCP instance, we need to create a new systemd service:</p><pre>sudo nano /lib/systemd/system/twirl.service</pre><p>This file should contain the following:</p><pre>[Unit]<br>Description=twirl<br>Documentation=https://github.com/oitee/twirl#readme<br>After=network.target<br><br>[Service]<br>Environment=COOKIE_SECRET=XXX<br>Environment=CUSTOM_DOMAIN_NAME=twirl.otee.dev<br>Environment=PG_CONNECTION_STRING=postgresql://XXX.aws.ybdb.io:5433/twirl?ssl=true&amp;sslmode=verify-full&amp;sslrootcert=/home/oitee.codes/root.crt<br>Environment=PG_SSL_CONNECTION=true<br>Environment=RECAPTCHA_SECRET=XXX<br>Environment=PORT=4122<br>Type=simple<br>User=oitee.codes<br>ExecStart=/usr/bin/node /home/oitee.codes/projects/twirl/app.js<br>Restart=on-failure<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Note that we added the PORT environment variable which was not required on Heroku because it was setup by the setup of Heroku.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TXb3DrCieNPIFgni.png" /></figure><h4>Step 2.3: Divert traffic from Heroku service to the GCP service</h4><p>So far we have been making changes on a new sub-domain <a href="http://twirl-test.otee.dev/">twirl-test.otee.dev</a>. Now that we are confident that the GCP service is working as expected, we can stop the traffic to the Heroku server via <a href="http://twirl.otee.dev/">twirl.otee.dev</a> and instead serve it from the GCP instance through twirl.otee.dev. Once we achieve this, twirl-test.otee.dev will no longer be required.</p><p>We have to change the nginx configuration for twirl.otee.dev to point to the local port instead of Heroku. Current configuration looks like:</p><pre>server {<br>    listen 443 ssl;<br>    server_name twirl.otee.dev;<br>    return 301 $scheme://oteetwirl.herokuapp.com$request_uri;<br><br>    ssl_certificate /etc/letsencrypt/live/twirl.otee.dev/fullchain.pem; # managed by Certbot<br>    ssl_certificate_key /etc/letsencrypt/live/twirl.otee.dev/privkey.pem; # managed by Certbot<br>}<br>server {<br>    if ($host = twirl.otee.dev) {<br>        return 301 https://$host$request_uri;<br>    } # managed by Certbot<br><br>    listen 80;<br>    server_name twirl.otee.dev;<br>    return 404; # managed by Certbot<br><br>}</pre><p>Note the 301 redirect to oteetwirl.herokuapp.com. We need to replace this line mainly, by moving away from the return directive to the location directive using a proxy_pass:</p><pre>server {<br>    listen 443 ssl;<br>    server_name twirl.otee.dev;<br>  location / {<br>         proxy_pass http://127.0.0.1:4122;<br>    }<br><br>    ssl_certificate /etc/letsencrypt/live/twirl.otee.dev/fullchain.pem; # managed by Certbot<br>    ssl_certificate_key /etc/letsencrypt/live/twirl.otee.dev/privkey.pem; # managed by Certbot<br>}<br>server {<br>    if ($host = twirl.otee.dev) {<br>        return 301 https://$host$request_uri;<br>    } # managed by Certbot<br><br>    listen 80;<br>    server_name twirl.otee.dev;<br>    return 404; # managed by Certbot<br><br>}</pre><h3>Phase 3: Shut down Heroku server</h3><p>We can now stop the Heroku dyno.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYWMMhLA9JHarND5.png" /></figure><p>Now <a href="http://twirl.otee.dev/">twirl.otee.dev</a> should still work and be served from GCP instance powered by the YugabyteDB Managed cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2wnvIGSSi9Z5HBVd.png" /></figure><h3>Future Improvements</h3><h4>Permanent Redirections</h4><p>Note that because we used permanent redirection via HTTP status 301 browsers which previously got redirected to Heroku domain might see the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFG1K6_XH8SEkErc.png" /></figure><p>A simple solution to this is to disable cache on the browser and reload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rnxV6DoLTDfnTVq_.png" /></figure><p>Alternatively, we can write a simple Heroku app that just redirects back to GCP in order to undo the permanent caching without having our users’ browsers. We are going to leave this aside for now.</p><h4>Backups</h4><p>Our free Yugabyte instance does not have data-backups. This means that we are at a risk of losing all our data if the Yugabyte cluster goes down. A simple solution to this would be to run the pg_dump command above periodically (crontab) and uploading it to a cloud storage (like s3).</p><p>For now, we will run this command manually and store it.</p><p><em>Originally published at </em><a href="https://otee.dev/2023/01/08/migrating-heroku-to-gcp-and-yugabyte.html"><em>https://otee.dev</em></a><em> on January 8, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d38bb285f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Ring Middlewares and Compojure Routes]]></title>
            <link>https://medium.com/helpshift-engineering/understanding-ring-middlewares-and-compojure-routes-1c4e66d63cf?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c4e66d63cf</guid>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 11:24:47 GMT</pubDate>
            <atom:updated>2022-11-02T11:24:47.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ring Framework</h3><p>Ring is a Clojure library that provides an easy-to-use interface for developing web applications in Clojure. Quoting from the official <a href="https://github.com/ring-clojure/ring">documentation</a>:</p><blockquote><em>By abstracting the details of HTTP into a simple, unified API, Ring allows web applications to be constructed of modular components that can be shared among a variety of applications, web servers, and web frameworks.</em></blockquote><p>The Ring framework works on the HTTP layer and parses incoming HTTP messages into Clojure hash-maps. This enables us to work on HTTP messages seamlessly using Clojure. Handler functions can work on these request hash-maps and send a response back to Ring, which too should be a Clojure hash-map. Ring does the work of converting the response from a hash-map to a HTTP response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRb6dQMNUExkqy-OhitN1w.png" /></figure><h3>What is a handler?</h3><p>A handler is a function that takes a request map and returns a response. In other words:</p><pre>(defn handler-fn [request]<br>  (...)<br>  response)</pre><p>Here’s a trivial example:</p><pre>(defn hello-world-handler<br>  [_]<br>  {:status 200<br>   :headers {}<br>   :body &quot;Hello World&quot;})</pre><p>Naturally, we must pass the handler function to the server</p><pre>(use &#39;ring.adapter.jetty)</pre><pre>(run-jetty hello-world-handler {:port 8080})</pre><h3>What is a middleware?</h3><p>Conceptually, a middleware function sits between the server and the handler function. It can modify the request before it reaches the handler. Alternatively (or even additionally), it can modify the response that the handler returned before handing it over to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqIADIzZ9OpDHiyteHASwg.png" /></figure><p>How a middleware works in practice is quite interesting. Essentially, A middleware is a higher-order function that takes one handler and returns a new handler function. In other words:</p><pre>(defn middleware-fn<br>  [handler-fn]<br>  (fn [req]<br>    (...)<br>    response))</pre><p>Quoting from the official <a href="https://github.com/ring-clojure/ring/wiki/Concepts">documentation</a>:</p><blockquote><em>Middleware are higher-level functions that add additional functionality to handlers. The first argument of a middleware function should be a handler, and its return value should be a new handler function that will call the original handler.</em></blockquote><p>Typically, a middleware function would call the handler-fn that was passed to it as an argument. In addition to this, it would either (or both):</p><ul><li>Do some operations on the request map, before calling the handler function</li><li>Do some operations on the response map returned by the handler function, before returning it back.</li></ul><p>Thus, the skeleton of a middleware function would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e982c9349ffbec858114e31fac8eaf66/href">https://medium.com/media/e982c9349ffbec858114e31fac8eaf66/href</a></iframe><p>Importantly, a middleware takes a handler function and returns a new (and modified) handler function.</p><pre>(def final-handler<br>  (let [handler (fn [r] ...)<br>        handler* (middleware-1 handler)<br>        handler** (middleware-2 handler*)<br>        ...]<br>    handler**...*))<br>(final-handler request)</pre><pre>;;This can be re-written using threading macro:<br>(def final-handler (-&gt; (fn [request] ...)<br>                       middleware-1<br>                       middleware-2<br>                       ...))<br>(final-handler request)</pre><h3>Simple example of a middleware + (Ring) handler</h3><p>Let’s take an example. We want to write a handler function that can easily access the query and URL encoded parameters from an incoming request map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a3ec7a6917cae9df5f0d8742a68007a/href">https://medium.com/media/2a3ec7a6917cae9df5f0d8742a68007a/href</a></iframe><p>Ring does not provide this functionality out of the box, i.e., the request map does not, by default, contain the keyword :params.</p><p>Thankfully, Ring provides a useful middleware, ring.middleware.params/wrap-params, that converts query and URL encoded form parameters from the request map and adds the following keys to the request body: :query-params, :form-params and :params (containing a map of both query and form parameters).</p><pre>{<br>...<br>:query-string &quot;name=otee&quot;<br>:query-params {&quot;name&quot; &quot;otee&quot;}<br>:form-params {&quot;id&quot; &quot;1234&quot;}<br>:params {&quot;id&quot; &quot;1234&quot;, &quot;name&quot; &quot;otee&quot;}<br>...<br>}</pre><p>So, if we want this functionality, we can simply use this middleware, like so:</p><pre>(require &#39;[ring.middleware.params :as rmp])</pre><pre>(rmp/wrap-params handler-fn)<br>;;=&gt; new handler function that provides us the params keys</pre><p>But this alone will not work. This middleware does not add keywords into the :params hash-map.</p><p>There is another Ring middleware, ring.middleware.keyword-params/wrap-keyword-paramsthat does this. Once wrap-keyword-params is applied on the handler, the request map looks like this:</p><pre>{<br>...<br>:query-string &quot;name=otee&quot;<br>:query-params {&quot;name&quot; &quot;otee&quot;}<br>:form-params {&quot;id&quot; &quot;1234&quot;}<br>:params {:id &quot;1234&quot;, :name &quot;otee&quot;}<br>...<br>}</pre><p>So if we want this functionality, we can do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/047f85bee7998e37999848ac3fabf584/href">https://medium.com/media/047f85bee7998e37999848ac3fabf584/href</a></iframe><p>The threading macro (-&gt;) can be used to represent the chaining of middlewares better:</p><pre>(-&gt; handler-that-needs-keyword-params<br>    rmkp/wrap-keyword-params<br>    rmp/wrap-params)</pre><p>Note that the <em>order of chaining middlewares</em> is crucial. In this example, the handler function (handler-that-needs-keyword-params) is dependent on the two middlewares that appropriately prepares the request map. Similarly, the wrap-keyword-params looks for the keyword :params in the request map; hence it needs to be called <em>after </em>the wrap-params middleware has been called on the handler function.</p><p>More broadly, if middlewares are inter-dependent (i.e., the output of one is consumed by the other), we must ensure that the less dependent one (here, wrap-params)is called first.</p><p>In a threading macro, the least dependent one floats to the bottom:</p><pre>(-&gt; handler<br>    most-dependent-middleware<br>    less-dependent-middleware<br>    least-dependent-middleware)</pre><h3>What is a compojure route?</h3><p>There are some down-sides of using handlers, in the manner shown above. Handlers cannot differentiate between different routes. Thus, irrespective the URL path or the HTTP method, the same handler will be triggered. This can make things messy, as we need to tailor make our responses vis-a-vis the nature of the request (the route and the HTTP method, for example), as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/532af31f7e3abcb396e87521620ad963/href">https://medium.com/media/532af31f7e3abcb396e87521620ad963/href</a></iframe><p>This is where compojure comes into the scene. It is a routing library that works on top of Ring. Here’s how a single compojure route looks like:</p><pre>(require &#39;[compojure.core :refer [GET]])</pre><pre>(GET &quot;/&quot; request (str &quot;Hello World! This is your uri: &quot; (:uri<br>                                                         request)))</pre><p>In the above example, GET is a route macro. It gets triggered only when the URL path matches /, i.e., the first argument to that macro. The second argument is the request itself (which we can destructure in a <a href="https://github.com/weavejester/compojure/wiki/Destructuring-Syntax">number of ways</a>) and the third argument is a function that returns a response and it can access the second argument, namely the request map.</p><p>We can pass a compojure macro to a server and it will work just fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d101df776c9d5e3dd9aadb34db14d77c/href">https://medium.com/media/d101df776c9d5e3dd9aadb34db14d77c/href</a></iframe><p>We can even club multiple routes together using defroutes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc115a12dc8a0a95ea38de4aa4265fa3/href">https://medium.com/media/cc115a12dc8a0a95ea38de4aa4265fa3/href</a></iframe><h3>So how does a compojure route fit in the handler &lt;&gt; middleware dynamic?</h3><p>Earlier we defined a handler as a function that takes a request map and returns a response map. We also proposed that any function that meets this function signature can be passed as an argument to run-jetty.</p><p>Now, we are saying that we can replace a handler with a compojure route. Clearly, a compojure route does not meet the function signature of a handler. (<em>Where even is the handler, when we use a compojure route?</em>)</p><p>And, what about middlewares? As we know, a middleware is a function that expects a handler function as its argument. Can we, then, not use middlewares when we use routes?</p><p><strong>Good news</strong> is that <strong>whatever we can do with a handler, we can do with a compojure route</strong>. This is because, a compojure route is a macro. It always expands to a handler function. To quote from the official <a href="https://github.com/weavejester/compojure/wiki/Routes-In-Detail">documentation</a>:</p><blockquote><em>Routes return </em><a href="https://github.com/ring-clojure/ring/wiki/Concepts#handlers"><em>Ring handler</em></a><em> functions. Despite their syntax, there’s nothing magical about them. They just provide a concise way of defining functions to handle HTTP requests.</em></blockquote><p>Thus, we can use the middlewares discussed above, on compojure routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26ae014785122f93b6bdce0896a2f405/href">https://medium.com/media/26ae014785122f93b6bdce0896a2f405/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c4e66d63cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/understanding-ring-middlewares-and-compojure-routes-1c4e66d63cf">Understanding Ring Middlewares and Compojure Routes</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing Phantom Meetings Using Transactions and Serializable Isolation]]></title>
            <link>https://medium.com/@otee.dev/preventing-phantom-meetings-using-transactions-and-serializable-isolation-7c2209a50902?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2209a50902</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[isolation]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-02-11T18:54:12.152Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I discuss how time-slot collisions in a meeting scheduling application can be resolved. First, I discuss the business logic of determining a ‘time-slot conflict’. Second, I explain why we need transactions to prevent scheduling of concurrent conflicting meetings. Finally, I do a deep-dive on the different levels of isolation provided by database systems, to better understand why simply using transactions (with their default set-up) does not guarantee against conflicting meetings.</p><h3>Project Scope and Design Goals</h3><p>This project supports the following features:</p><ul><li><strong>Add new users and rooms:</strong> The system allows for the addition of new users and rooms (they are treated as ‘entities’ in the data model). Once added, users and rooms can be included in future meetings.</li><li><strong>Scheduling of meetings</strong>: The system allows for scheduling of new meetings involving one or more users at a given room.</li><li><strong>Detect conflicts</strong>: While setting up a meeting, the system will check if there are any time-slot conflicts (explained below) involving any of the proposed participants or the proposed room.</li></ul><p>The system interacts with the user on the Command Line.</p><p>Here’s the GitHub Repository hosting the project: <a href="https://github.com/oitee/meetings">https://github.com/oitee/meetings</a></p><p>The system guarantees that a meeting should be permitted to be scheduled <strong>only if</strong> every participating user and the respective room have no time-slot conflict. Even if one entity has a conflict, the system will reject the request for setting up the meeting and prompt the user to try again.</p><p>For the purposes of time-slot conflict-resolution, the system treats users and rooms alike.</p><h3>Resolving Time-Slot Conflicts</h3><p>What constitutes a time-slot conflict? Simply put, it refers to a situation where a single user or room is assigned to more than one meeting at any given point of time.</p><p>With respect to a meeting for a given time-slot A (with a start-point ‘s’ and an end-point ‘e’), there can be five types of time-slot conflicts, as shown below.</p><ul><li>Case 1: A meeting which started before ‘s’, but is scheduled to complete after the ‘s’ (but before ‘e’).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*wIhXk1GuY7zug-tc.png" /></figure><ul><li>Case 2: A meeting which started before ‘s’, and is scheduled to complete after ‘e’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qlt3A3G0eaPSyBtn.png" /></figure><ul><li>Case 3: A meeting which has the same start and end points as time-slot A.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*tiWsG8SaRn9rwch_.png" /></figure><ul><li>Case 4: A meeting which started and ended between points ‘s’ and ‘e’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*xQgtOexJvJgMB1BE.png" /></figure><ul><li>Case 5: A meeting which started after ‘s’ but before ‘e’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*gJw9zBAlEjguKysm.png" /></figure><p>In each of these cases, there is a time-slot conflict, i.e., at least one point where there are two simultaneous meetings.</p><h3>How to Resolve Time-Slot Conflicts?</h3><p>Obviously, if the parties involved in two meetings with conflicting time-slots are distinct and separate, there is no issue. The system will allow both the meetings to continue.( <em>Note here that when we use ‘participants’, we include both users and rooms</em>).</p><p>Thus, only if there is at least one common participant between the two conflicting time-slots, do we need to be careful. Thus, at the time of scheduling each meeting, we need to check if there is any potential conflict with respect to any of the participants of the meeting. This can be done using the following SQL query:</p><pre>SELECT entity FROM bookings WHERE <br>    entity IN (entity1, entity2... entityN) <br>    AND (<br>            (from_ts &lt;= to_timestamp(start_point) AND to_ts &gt;= to_timestamp(start_point))<br>            OR<br>            (from_ts &gt;= to_timestamp(start_point) AND from_ts &lt;= to_timestamp(end_point))<br>        )</pre><p>In the above example, (entity1, entity2... entityN) represents the list of all the participating entities of a proposed meeting and start_point and end_point represent the two end-points of the time-slot of the proposed meeting.</p><p>At the time of creating a new meeting, we run this query on our database. If this returns a non-empty response, it will signify a conflict and the system will prevent the creation of the meeting</p><h3>Need for Transactions</h3><p>In an ideal world, we follow a two-step process while creating a new meeting:</p><ul><li>First, check for conflicts</li><li>Next, insert the new meeting.</li></ul><p>This approach has one downside: if there is more than one system trying to write to the database simultaneously, the database may change its state between step one and step two above. For example, let’s say there are two systems attempting to simultaneously schedule the same meeting with the same time-slot and entities. It is possible, that read-write sequence interleaves in the following manner:</p><pre>System 1 reads the database ... (realizes that there is no conflict)<br>System 2 reads the database ... (realizes that there is no conflict)<br>System 1 writes the database ...(creates the meeting)<br>System 2 writes the database ... (creates the same conflicting meeting)</pre><p>Thus, we need to take an all-or-nothing approach while reading and writing. This can be achieved by using transactions.</p><h3>What is a Transaction?</h3><p>Simply put, a transaction represents a single or <em>atomic</em> unit of work performed by a database management system. A transaction is typically used to group multiple reads and writes into one logical unit. Because of their atomic nature, transactions cannot be broken down into its constituent actions: if, in the middle of a transaction, an error or failure takes place which prevents the transaction from being successfully completed, the database will rollback all the intermediate operations of that transaction.</p><p>This is very useful for our use-case, as we can use transactions to ensure an all-or-nothing approach while scheduling meetings: if our reading and writing operations form part of a single transaction, we can potentially prevent partial failures, like the one discussed above.</p><h3>ACID Properties</h3><p>Every database transaction has four key properties: atomicity, consistency, isolation and durability (commonly referred to as ‘ACID’). These ACID properties guarantee data validity even in the events of failures, errors and other mishaps.</p><p><strong>Atomicity</strong>: Every operation in the transaction should either all succeed (also called ‘committed’) or all fail. Partial failure or partial success is disallowed. Without the atomicity guarantee, if an error or a failure takes place during a transaction, it can get very difficult to reason about which operations were successful and which need to be tried again.</p><p><strong>Consistency</strong>: If the database is consistent before execution of a transaction, it should remain consistent after the transaction has been committed. In other words, a transaction should take the database from one valid state to another. If there are any rules or <em>invariants</em> enforced on the data, they should continue to be respected after a transaction is completed. (In fact, consistency is a property of the application layer instead of the database system itself, as the latter cannot prevent the violation of invariants if the application feeds improper or erroneous data. For this reason, it is said that “ <em>the letter C doesn’t really belong in ACID</em> “ [1]).</p><p><strong>Isolation</strong>: Often, a database needs to execute multiple transactions concurrently. This property provides a guarantee that concurrent transactions will be executed <em>as if</em> they were sequentially or serially executed. In other words, the goal of isolation is to ensure that simultaneous transactions making writes on the same set of objects (rows) of a database should not step onto each other’s toes.</p><p><strong>Durability</strong>: Once a transaction is committed, it should persist on the database, even in the wake of a system failure. In the case of single-node databases, this is usually achieved by storing results of transactions on non-volatile memory(disk). In the case of replicated databases, this is achieved by copying the data written during a transaction to a certain number of nodes of that database.</p><h3>Writing Transactions in PostgreSQL</h3><p>To fold multiple queries into one transaction, we should place them between BEGIN and COMMIT commands. During the middle of a transaction, if our application layer needs to withdraw a transaction,we should use ROLLBACK instead of COMMIT.</p><p>Here’s how the SQL expressions for scheduling a meeting can be written as a part of one transaction:</p><pre>BEGIN<br>SELECT entity FROM bookings WHERE<br>    entity IN (entity1, entity2... entityN)<br>    AND (<br>            (from_ts &lt;= to_timestamp(start_point) AND to_ts &gt;= to_timestamp(start_point))<br>            OR<br>            (from_ts &gt;= to_timestamp(start_point) AND from_ts &lt;= to_timestamp(end_point))<br>        )<br><br>-- application layer logic: if rows.length &gt; 0 <br>ROLLBACK;<br><br>-- application layer logic: else<br>INSERT INTO bookings (meeting_id, entity, from_ts, to_ts, created_at, updated_at) <br>        VALUES (...);<br>COMMIT;</pre><h3>Testing with Concurrent Queries</h3><p>Given the guarantees provided by transactions, we should expect that our application does not schedule conflicting meetings. To test this hypothesis, we can set up a test that makes concurrent and identical queries on the database. To implement this test, I’ve used the <a href="https://nodejs.org/api/worker_threads.html">worker threads</a> module, to create n number of worker threads that make the same query on the database. See the test here: <a href="https://github.com/oitee/meetings/blob/33aab6b/test/concurrent_requests.js">https://github.com/oitee/meetings/blob/33aab6b/test/concurrent_requests.js</a></p><p>When I ran this test for the first time, it passed. But when I ran the same test sequentially for ten times (using for i in `seq 1 10`; do npm test; done), it failed twice out of the ten times. For the next ten tests, it failed three times out of ten</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXp3qLWtQ4H8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXp3qLWtQ4H8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXp3qLWtQ4H8%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/adf50dd151d2164c8168de3176578319/href">https://medium.com/media/adf50dd151d2164c8168de3176578319/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uz6XzcAcDv9toErKFfLq4Q.png" /></figure><p>When a test fails, the same meeting (as shown in the above schema) with the same time-slot (between 2021-12-15 05:30:00+00 and 2021-12-15 07:30:00+00) gets inserted multiple times. So, why did my tests fail <em>some of the times</em>? What happened to the ACID properties of transactions?</p><h3>Different Levels of Isolation</h3><p>To better understand why my tests were failing sporadically, it is important to understand that databases enforce different degrees of isolation among concurrent transactions. Note that, ‘isolation’ was described above as a guarantee that the database system will execute concurrent transactions in such a manner that it will <em>appear as if</em> they were executed serially, i.e., one after the other. In fact, serial isolation (i.e., converting multiple concurrent transactions into a set of sequential transactions) is rarely used in practice. This is because serializable isolation has substantial performance costs which can slow down the response time of a database system. For this reason, most databases provide weaker levels of isolation:</p><blockquote><em>“ </em>Even on a single-node database, the penalties associated with providing serializability can be severe, including decreased concurrency, reduced performance, and the possibility of deadlock. Accordingly, since the earliest database systems such as System R in 1976, databases have provided a range of user configurable “weak isolation” properties. These properties do not guarantee serializability but offer benefits such as increased concurrency and ease of implementation.<em>” [</em><a href="http://www.bailis.org/papers/hat-hotos2013.pdf"><em>1</em></a><em>].</em></blockquote><p>When two or more concurrent transactions try to write on the same object of a database or one transaction reads an object that is being concurrently modified by another concurrent transaction, we can have concurrency issues, which are also called ‘race conditions’. Each level of isolation provides guarantees against some or all race conditions.</p><h3>Read Committed</h3><p>When a change made by a transaction has been committed, that change becomes permanent on the database and the transaction loses its right to ‘undo’ that change. However, uncommitted changes are always revocable. Working with uncommitted changes should ideally be avoided. Reading some other transaction’s uncommitted changes is called ‘dirty reads’. Writing on another transaction’s uncommitted changes is called ‘dirty writes’</p><p>‘Read committed’-the first (or weakest) level of isolation-provides guarantees against dirty reads and dirty writes. This is the default isolation level in PostgreSQL.</p><p>Dirty writes are prevented by locking relevant rows where writes take place. When a transaction needs to write a specific row, the database will lock that row. Only once the transaction is completed (aborted or committed) will this lock be opened. At a time, only one transaction can lock a row. So if there is a second transaction that needs to write on the same row, it needs to wait for the first transaction to be completed.</p><p>As for prevention of dirty reads, when a write lock is applied on a row, the database maintains two values for that row: the original value and the uncommitted value. Thus, read-only transactions can access the original value till the time the write lock is lifted.</p><p><strong>Read committed will not be adequate for our use-case, as our application does not rely on dirty reads or writes.</strong></p><h3>Snapshot Isolation and Repeatable Read</h3><p>In a snapshot isolation, each transaction works on a <em>consistent snapshot</em> of the database, i.e., the database as it stood at the beginning of the transaction.</p><p>Snapshot isolation is implemented by a technique called multi-version concurrency control (MVCC). The core principle of snapshot isolation is that for each transaction, they will read a consistent snapshot of the database, as it stood, when that transaction began. As a corollary, if the database progressed further (i.e., some uncommitted changes were committed during the course of a transaction), the transaction will not see those future changes. This ensures that writes do not block reads, and reads do not block writes. This can be especially useful for taking backups of a large database: the transaction making a copy of the database at a particular point in time (a read-only transaction) will not be impeded by other transactions that are writing on some of the rows of that database. However, note that snapshot isolation implements write locks as well, i.e., when a transaction is writing on a row, no other transaction can write it.</p><p>When we implement MVCC, the database may potentially need to maintain several versions of the database, each representing the ‘snapshot’ of the database when each ongoing transaction was initiated.</p><p>Snapshot isolation level is typically referred to as ‘repeatable read’ in SQL. However, these two terms are not exactly identical.</p><blockquote><em>“ </em>…it defines repeatable read, which looks superficially similar to snapshot isolation. PostgreSQL and MySQL call their snapshot isolation level repeatable read because it meets the requirements of the standard, and so they can claim standards compliance.</blockquote><blockquote>Unfortunately, the SQL standard’s definition of isolation levels is flawed-it is ambiguous, imprecise, and not as implementation-independent as a standard should be. Even though several databases implement repeatable read, there are big differences in the guarantees they actually provide, despite being ostensibly standardized. There has been a formal definition of repeatable read in the research literature, but most implementations don’t satisfy that formal definition. And to top it off, IBM DB2 uses “repeatable read” to refer to serializability. As a result, nobody really knows what repeatable read means<em> “[1]</em></blockquote><p>In addition to preventing dirty reads and writes, snapshot isolation also prevents non-repeatable reads: re-reading the same set of rows will not yield a different result.</p><p>Also, PostgreSQL’s implementation of repeatable read automatically detects <em>lost update</em>. A lost update happens when two concurrent transactions read the same row(s), modify the data and write that modified data on that row(s) ( <em>read-modify-write</em> cycle). When two such transactions are executed concurrently, one of the writes will be lost. Take the example of a database that maintains counters. Each transaction is required to read the data of the counter, and increment it by one and write the new data onto the database. Now if two transactions are fired at the same time, they will both read the same value, and they will both update the counter by one. So, while we made two queries for incrementing the value of the same counter, the value actually got increased once. (The other increment was ‘lost’). ( <em>I had encountered this particular problem while generating counters for my URL shortening application. </em><a href="https://otee.dev/2021/12/20/twirl-link-shortening.html"><em>Read here</em></a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HQnwxjJjLrxic4pZ.png" /><figcaption><em>Source: Designing Data Intensive Applications [1]</em></figcaption></figure><p>There are two explicit ways to prevent lost updates. First, we can use atomic operations, i.e., we read, modify and write the data in one single query. Second, we use explicit locking. When we use explicit locking, we tell the database to prevent any other transaction from reading or writing on the rows on which our transaction is working on, till the present transaction is completed. This can be done by using FOR UPDATE at the end of the SELECT query.</p><p>Other than these explicit ways, PostgreSQL also automatically detects if there is a lost update during a repeatable read transaction.</p><p><strong>Snapshot isolation will not be adequate for our use-case, as working with consistent snapshots cannot prevent parallel (and concurrent) transactions from making the same writes.</strong> Lost update seems close enough to our use case. However, as our writing operation is akin to creating a new row (as opposed to updating an existing row), Postgres cannot automatically prevent concurrent insertions of the same meeting.</p><h3>Serializable Isolation</h3><p>Serializable isolation offers the highest degree of protection.</p><blockquote><em>“ </em>Serializable isolation is usually regarded as the strongest isolation level. It guarantees that even though transactions may execute in parallel, the end result is the same as if they had executed one at a time, serially, without any concurrency. Thus, the database guarantees that if the transactions behave correctly when run individually, they con‐ tinue to be correct when run concurrently-in other words, the database prevents all possible race conditions.<em> “ [1]</em></blockquote><p>There are three alternative implementations of serializability:</p><ul><li>Serial Execution: Literally executing transactions serially, by using a single thread always.</li><li>Two phase locking: Concurrent reads are permitted on rows where no write operation is underway. If any transaction is making a write operation, it will lock the relevant row and every other transaction that wants to either read or write on that row will need to wait till the first transaction is completed. This approach is also called a <em>pessimistic concurrency control</em> mechanism, because the database system assumes the worst, i.e., every concurrent write operation on a transaction will fail, and guards against that eventuality. (Of course, this is more optimistic than single-threaded serial execution)</li><li>Serializable Snapshot Isolation: Unlike two-phase locking, in this approach, the database system allows for writes and reads to take place concurrently. At the time of committing a transaction, the database checks if there is any violation of isolation properties, in which case it will abort that transaction. This approach is referred to as the ‘optimistic concurrency’ approach.</li></ul><p>In the case of lost updates (involving a read-modify-write cycle), an easy fix is to use explicit locks on the relevant rows. However, what happens when the first read operation looks for the <em>absence</em> of rows (meeting a certain criteria)? If this criterion is met, i.e., if no rows exist meeting a certain condition, we write the database by inserting a new row. In this case, there is no row we can explicitly lock to prevent a write skew or a lost update. <strong>These kinds of concurrency issues are called ‘phantom reads’ and this is exactly the reason why our tests often fail.</strong> Because of its nature and the guarantees it provides, serializable isolation can consistently prevent phantom reads.</p><h3>Using Serializable Isolation to Prevent Time Collisions</h3><p>Let’s summarize the different levels of isolation and the respective guarantees they provide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knbCgompMdjIXaIzU-jBeQ.png" /></figure><p>We need to use serializable isolation for our meeting scheduling application, as we know that phantom reads are possible when concurrent transactions try to schedule meetings on the database. So, here’s the modified SQL query for inserting a new meeting on the database:</p><pre>BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;<br>SELECT entity FROM bookings WHERE <br>    entity IN (entity1, entity2... entityN) <br>    AND (<br>            (from_ts &lt;= to_timestamp(start_point) AND to_ts &gt;= to_timestamp(start_point))<br>            OR<br>            (from_ts &gt;= to_timestamp(start_point) AND from_ts &lt;= to_timestamp(end_point))<br>        );<br>-- if rows.length &gt; 0 <br>ROLLBACK;<br>-- else<br>INSERT INTO bookings (meeting_id, entity, from_ts, to_ts, created_at, updated_at) <br>        VALUES (...);<br>COMMIT;</pre><p>When we use the above query, our tests pass, consistently.</p><h3>References</h3><p>[1] Martin Kleppmann, Designing Data-Intensive Applications (2017), Ch. 7.</p><p>[2] Peter Bailis et al, HAT, not CAP: Towards Highly Available Transactions, <a href="http://www.bailis.org/papers/hat-hotos2013.pdf">http://www.bailis.org/papers/hat-hotos2013.pdf</a>.</p><p>[3] Michael Melanson, Transactions: the limits of isolation, <a href="https://www.michaelmelanson.net/posts/transactions-the-limits-of-isolation/">https://www.michaelmelanson.net/posts/transactions-the-limits-of-isolation/</a></p><p><em>Originally published at </em><a href="https://otee.dev/2022/02/10/transactions-and-phantom-reads.html"><em>https://otee.dev</em></a><em> on February 10, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2209a50902" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kicking Around Packets: Understanding How the Internet Works]]></title>
            <link>https://medium.com/@otee.dev/kicking-around-packets-understanding-how-the-internet-works-7f083673959c?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f083673959c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[network-protocols]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-02-03T07:45:19.559Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I try to answer the question “What is the internet and how does it really work?”</p><h3>Key terms</h3><p>Before going into further details, here is a useful list of some of the key terms used in this article.</p><ul><li><strong>End-system or host</strong>: This is a device (e.g., a computer) that actually wants to use the internet. It is the ultimate consumer of the communication services offered by the internet. It typically executes a network application on behalf of the user and uses the internet to that end. This article uses the terms ‘host’ and ‘end-system’ interchangeably.</li><li><strong>Packet switches or routers</strong>: Different networks are interconnected to each other through a series of packet-switches. They are mainly responsible for forwarding packets of information from one node to another. Packet switches are of two kinds: link-layer switches and routers (discussed below). For the most part, this article uses the term ‘routers’ to refer to packet-switches in general.</li><li><strong>Communication links</strong>: These are the physical media that connect routers to one another. Packets travel from one router to the next via a communication link.</li></ul><h3>Understanding the Internet</h3><p>The internet is a <strong>network of networks</strong>.</p><p>Each end-system accesses the internet through an <strong>Internet Service Provider</strong> (ISP). An ISP is typically a telecom company providing internet service to end-users.</p><p>The starting point of the internet is an access ISP. The access ISP is the network which connects a host with the rest of the internet.</p><p>Each ISP has its own network. The overarching goal of the internet is to enable any two end-systems to communicate with each other, irrespective of where they are situated. Thus, it is not practically feasible for one ISP to provide a direct line of communication between every pair of end-points. Instead, networks have inter-connections with each other. In other words, each network interacts with one or more networks to deliver a message. Here’s how <a href="https://en.wikipedia.org/wiki/Internetworking">Wikipedia</a> defines ‘inter-networking’</p><blockquote><em>“</em>Internetworking is the practice of interconnecting multiple computer networks, such that any pair of hosts in the connected networks can exchange messages irrespective of their hardware-level networking technology. The resulting system of interconnected networks are called an internetwork, or simply an internet.<em>”</em></blockquote><p>These interconnections can be direct, i.e., between two networks directly. This kind of interconnection is called <strong>peering</strong>, where two ISPs, at the same level of hierarchy, choose to mutually allow each other access to their respective networks. Most often, though, interconnections take place indirectly, i.e., to reach your destination end-system’s access ISP, you will have to go via one or more intermediary networks (which are typically larger networks with larger coverage). These kinds of indirect interconnections are called <strong>transit</strong>. Thus, typically, to pass on a message from one end-user to another the “ <em>the traffic will often be transferred through several indirect interconnections to reach the end-user</em>” ( <a href="https://arstechnica.com/features/2008/09/peering-and-transit/">source</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*6zsZrwE-K0kbV66z.png" /><figcaption><em>Source: </em><a href="https://eclass.teicrete.gr/modules/document/file.php/TP326/%CE%98%CE%B5%CF%89%CF%81%CE%AF%CE%B1%20(Lectures)/Computer_Networking_A_Top-Down_Approach.pdf"><em>Computer Programming: A Top-Down Approach</em></a></figcaption></figure><h3>How the Internet Works: Kicking Around Packets</h3><p>Largely, this is how the internet works: when a piece of information needs to be sent from one end-system to another, the information is divided into several segments, called <strong>packets.</strong> These packets are then sent to the destination end-system through the internet, which comprises several <strong>communication links</strong> and <strong>packet switches</strong>.</p><p>Communication links are the physical media through which packets are transmitted. Examples include optical fibers and twisted copper wires.</p><p>Each packet switch has multiple communication links attached to it. Packet switches take each packet it receives on any one of its attached communication links and forwards them to another one of its attached communication links. There are two main types of packet switches: routers and link-layer switches. While both forward packets towards the destination host, link-layer switches are used for connecting devices within a network. They are mostly used at the access network (for connecting a device to an access ISP). On the other hand, routers are used in the network core, i.e., for sending packets across networks. As both link-layers and routers do the fundamental task of forwarding packets towards the destination end-point, the rest of this article will refer to packet-switches as <strong>routers.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKPyxeeuOARi9Ts0yCrH7A.png" /><figcaption>Source: <a href="https://www.cloudflare.com/en-in/learning/network-layer/what-is-a-network-switch/"><em>Cloudflare</em></a></figcaption></figure><p>How does a router know which communication link to forward a given packet to? Every message transmitted by a source host will contain the IP address of the destination host. An IP address is hierarchical in nature and by looking at a specific part of the packet’s IP address and consulting its own <strong>forwarding table</strong> (which maps IP addresses to outbound communication links), it determines the correct communication link to forward the packet to.</p><p>On the destination end-system, the original message is re-composed by re-assembling all the packets. <strong>This is similar to how cargo gets delivered over roads.</strong> First, you divide the delivery goods into small packets and load them onto trucks. Then each of these trucks travel on high-ways (communication links) and at each intersection (packet switches) they are redirected to the next highway, which will eventually take them to their destination.</p><p>To ensure consistency, each actor involved in the exchange of information over the internet, are governed by a set of <strong>protocols</strong>. Two of the most fundamental protocols are the <strong>Internet Protocol (IP) and Transfer Control Protocol (TCP).</strong></p><p>Here’s a brief description of how a bit gets “kicked around” between two end-systems:</p><blockquote><em>“</em>Consider a bit traveling from one end system, through a series of links and routers, to another end system. This poor bit gets kicked around and transmitted many, many times! The source end system first transmits the bit, and shortly thereafter the first router in the series receives the bit; the first router then transmits the bit, and shortly thereafter the second router receives the bit; and so on. Thus our bit, when traveling from source to destination, passes through a series of transmitter-receiver pairs<em>” ( </em><a href="https://eclass.teicrete.gr/modules/document/file.php/TP326/%CE%98%CE%B5%CF%89%CF%81%CE%AF%CE%B1%20(Lectures)/Computer_Networking_A_Top-Down_Approach.pdf"><em>Source</em></a><em>)</em></blockquote><h3>A layered approach to Understanding the Internet</h3><p>Given the complexity and the numerous moving parts involved in the working of the internet, it is more elegant to organise the many happenings between two hosts, as a series of top-down layers of protocols.</p><blockquote><em>“</em>To provide structure to the design of network protocols, network designers organize protocols-and the network hardware and software that implement the protocols- in layers.<em>”( </em><a href="https://eclass.teicrete.gr/modules/document/file.php/TP326/%CE%98%CE%B5%CF%89%CF%81%CE%AF%CE%B1%20(Lectures)/Computer_Networking_A_Top-Down_Approach.pdf"><em>Source</em></a><em>)</em></blockquote><p>To understand this layered architecture, it is important to note that at each layer, the protocol provides some service to the layer above, by performing certain actions and by utilising the services provided by the layer immediately below it</p><p>A layered architecture provides the advantage of simplifying the architecture of the internet by breaking it down into specific, well-defined parts, each of which performs a specific task by depending on the service provided by the layer beneath it. More importantly, it adds modularity to the entire system, thereby allowing one to modify the implementation of the service provided by a specific layer, without affecting the rest of the system (so long as the modified implementation provides the same service and depends on the same layer to provide that service).</p><p>A protocol layer can be composed solely of software (application and transport layer), hardware (physical layer and data link layer) or a mixture of both (network link)</p><p>When taken together, the protocols of the various layers are called the <strong>protocol stack</strong>. According to the the TCP/IP architecture, the Internet protocol stack consists of five layers: the application layer, the transport layer, the network layer, the link layer and the physical layer.</p><p>Here’s a brief summary of what each of the protocol layers do:</p><ul><li><strong>Application layer:</strong> This layer provides services to the end-user, by executing an application that uses the internet. It does this by sending and receiving a series of messages from and to another host(s). It hides the complexities of how the network is laid out.</li><li><strong>Transport layer:</strong> This layer provides services to the application layer, by ensuring that the application layer messages are transported to and from the correct destination. It hides how the underlying network is managed (e.g., how packets of information is actually delivered to the correct destination).</li><li><strong>Network layer:</strong> This layer provides services to the transport layer by finding a “best effort” path via multiple routers, to deliver packets of information from the source host to the destination host. It hides how each router forwards packets to the successive router.</li><li><strong>Link layer:</strong> It provides services to the network layer by actually determining how to deliver packets of information between two given routers.</li><li><strong>Physical layer:</strong> It provides the service of physically transmitting “bits” of information to the next router, in a way that the receiver can understand and reconstruct the same.</li></ul><h3>Here’s an Analogy involving a King and a Queen</h3><p>Before moving forward and delving into the details of each protocol layer, it would be convenient to take an analogy to better understand the services provided by each layer. Let’s go back to a time before the advent of modern communication technologies: a world where one relied on postal services to send messages over a large distance. Now let’s imagine the King of a distant kingdom-presently at the battlefield-wishes to send a letter to his beloved Queen-presently residing at the Royal Palace. Let’s follow how the letter gets delivered to the Queen, from the prism of the five network protocol layers.</p><ol><li><strong>Application Layer:</strong> The King at the battlefield dictates the letter to his personal assistant, who writes its out and sends it to the Royal Secretary to deliver the letter he has written. Here, the King represents the <strong>user</strong>, the battlefield is the <strong>end-system,</strong> the King’s personal assistant represents the <strong>application layer</strong> and the Royal Secretary represents the <strong>transport layer</strong>.</li><li><strong>Transport Layer:</strong> The Royal Secretary puts the Royal Seal, adds the address of the Royal Palace and hands it over to the local post office.Here, the local post office represents the <strong>first router</strong> in the network layer and the Royal Palace is the destination end-system.</li><li><strong>Network Layer:</strong> The postal officer realizes that the destination is far-off and that there is no direct route to the Royal Palace. But, looking at the address, the postal officer understands that the Royal Palace is due East. So, they deliver the letter to the next postal caravan moving East.</li><li><strong>Link Layer:</strong> The caravan carries a load of postal traffic from this postal office to the next postal office in the East. The caravan leader draws out the route to the next postal office in the eastward direction. Here, the caravan leader is the link layer, connecting the first postal office (a router) to the next postal office (another router).</li><li><strong>Physical Layer:</strong> The caravan leader employs their trusted nephew to carry the King’s letter. The nephew, along with their camel-driven carriage, carries the King’s letter, following the route drawn by the caravan leader. The nephew and their carriage, is the physical layer, physically carrying the postal traffic from one postal office (router) to the next.</li><li><strong>Physical Layer:</strong> Once the carriage reaches the next postal office, the nephew off-loads its load from their carriage.</li><li><strong>Link Layer:</strong> The guard at the next postal office unpacks the postal load and hands over all its contents to the postal officer of that postal office. The guard is the link layer, passing on the load received from the carriage driven by the nephew (physical layer). The postal officer is the second router.</li><li><strong>Network Layer:</strong> The postal officer at the next postal office, receives the postal load delivered by the caravan leader and examines it. They find the King’s letter, and realize that the Royal Post Office is in the next town (it is only natural that the Royal Family has a post office of their own!). However, they have to find a way to physically transport the letter to the Royal Post Office. Luckily, they have a local pigeon sender who regularly delivers mail locally. The postal officer delivers the King’s letter to the local pigeon sender. Here, the local pigeon sender is the link layer and the pigeon is the physical layer.</li><li><strong>Link Layer:</strong> The pigeon sender knows the way to the Royal Post Office. They instruct the pigeon to fly to the Royal Post Office.</li><li><strong>Physical Layer:</strong> The pigeon flies away towards the Royal Post Office.</li><li><strong>Physical Layer:</strong> The pigeon successfully lands at the entrance of the Royal Pigeon Receiver at the Royal Post Office.</li><li><strong>Link Layer:</strong> The Royal Pigeon Receiver at the Royal Post Office receives the pigeon’s parcel, cleans it up and hands it over to the postal officer at the Royal Post Office. Here, the Royal Guard represents the link layer, which hands over the information received from the pigeon (physical layer) to the postal office (network layer).</li><li><strong>Network Layer:</strong> The postal officer at the Royal Post Office accepts the mail from the Royal Pigeon Receiver. They pass on the King’s letter to the Queen’s Secretary. The postal officer represents the network layer, while the Queen’s Secretary is the transport layer.</li><li><strong>Transport Layer:</strong> The Queen’s Secretary receives the King’s letter from the Royal Post Office, verifies the Royal Seal, ensures that it is complete and hands it over to the Queen’s personal assistant. Here, the Queen’s personal assistant represents the application layer, accepting the message delivered by the Queen’s Secretary (transport layer)</li><li><strong>Application Layer:</strong> The Queen’s personal assistant knock’s on the Queen’s room and reads out loud what the King had to say. The Queen is delighted to hear from the King!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aVL_32lQO70GCCQU.png" /></figure><p>Now, let’s try to understand how each of these layers actually work.</p><h3>Application layer</h3><p>First, it is important to understand what a ‘network application’ is. It is a program that runs on one host and communicates with another host, using the internet. In fact, programs running on different hosts, communicating over the internet are called <strong>processes:</strong></p><blockquote><em>“</em>In the jargon of operating systems, it is not actually programs but processes that communicate. A process can be thought of as a program that is running within an end system<em>” ( </em><a href="https://eclass.teicrete.gr/modules/document/file.php/TP326/%CE%98%CE%B5%CF%89%CF%81%CE%AF%CE%B1%20(Lectures)/Computer_Networking_A_Top-Down_Approach.pdf"><em>Source</em></a><em>)</em></blockquote><p>Processes on different hosts communicate with each other via <strong>messages</strong>. Typically, a network application consists of two different processes running on two different hosts, that send messages to each other (eg., server and client process on the web).</p><p>Now each process sends and receives messages over the internet by using a programming interface called the <strong>socket</strong>. Sockets act like doors- when the network application needs to send a message across the internet, it simply delivers it across the door, with the expectation that the rest will be taken care of by the network. Sockets in an end-system are identified by port numbers</p><p>In fact, sockets are the interface between the application layer and the transport layer.</p><p>Now, coming back to the application layer itself, it is defined as the “ <em>communications protocols and interface methods used in process-to-process communications across an Internet Protocol (IP) computer network</em>”( <a href="https://en.wikipedia.org/wiki/Application_layer">source</a>). Mainly, the application layer protocol standardized the manner in which data should be exchanged between two hosts. It does not deal with how this data will, in fact, be transferred.</p><p>Examples of application layer protocol include: HTTP(Hyper Text Transfer Protocol), FTP (File Transfer Protocol), SMTP (Simple Mail Transfer Protocol).</p><h3>Transport layer</h3><p>The transport layer transports the application-layer messages (received over the socket) between two application end-points (or hosts). The main objective of this layer is to provide <strong>logical communication</strong> between two application processes. This means that this layer will abstract out the details of the internet before the application layer, giving the impression to the application that it is directly connected to the other end-system’s application.</p><p>It is important to note that the transport layer protocols are implemented in the end-systems (or hosts). They are not implemented by intermediate routers or communication links.</p><p>In the internet, there are two transport layer protocols both of which can transport application layer messages:</p><ul><li>Transmission Control Protocol (TCP): TCP provides <strong>reliable data transfer</strong>. It guarantees delivery of messages and manages flow control. The latter ensures that messages are delivered in the correct order. It also provides congestion control, by preventing over-congestion of traffic on routers and links between two hosts. This is done by dividing messages into smaller segments, and reducing the transmission rate when the network is congested.</li><li>User Datagram Protocol (UDP): UDP provides a <strong>connectionless service</strong>. It provides no guarantees towards reliability, flow control, or congestion control.</li></ul><p>The transport layer protocols convert each application layer message into several transport layer packets called <strong>segments</strong> each of which is then sent across the network layer, via the routers and links.</p><h3>Network layer</h3><p>The network layer receives a transport layer segment and a destination address from the transport layer protocol of the source host. The network layer provides the service of delivering this segment to the correct destination host’s transport layer.</p><p>The <strong>Internet Protocol (IP)</strong> is the only network layer protocol of the internet. The IP implements a <strong>best effort</strong> service, meaning that while it makes a “best effort” to deliver segments between hosts, it does not make any guarantees regarding their delivery, i.e., the IP cannot guarantee the eventual delivery of a packet. Neither can it assure that the packets will be delivered in an orderly fashion nor that there will not be any tampering of the packets in the process of transmission.</p><p>The network layer protocol converts the transport layer segments into network layer segments called “datagrams”. Each datagram contains the address of the destination host. Once this is done, the source host pops each datagram into the network, i.e., it sends the datagram to its nearby router. For this datagram to reach the ultimate destination host, it needs to traverse through several routers. Each router forwards a datagram that it receives in any of its input links to the next appropriate router. The determination of which router to forward the datagram to, is done by looking at the destination address and its own forwarding table. Thus, to send one packet from one host to another, each router has to make a local decision that is compatible with its next router. In this way, we get a <strong>global convergence on packet delivery</strong> using a series of local decisions at the router-level.</p><p>Note that routing, i.e., the route or path that a packet will traverse within the network layer, is implemented by each router and is not determined by the end-systems. This is very convenient, as it insulates the host application from the changes in the internet’s routing architecture. ( <a href="https://datatracker.ietf.org/doc/html/rfc1122#section-1.1.1">RFC</a> 1122) This is a direct consequence of having a modular protocol stack.</p><p>Also, as another corollary of the modular architecture of the protocol stack, routers remain stateless. They do not maintain any state of the end-to-end flow of information. Each router inspects the IP address of the destination of a packet, and determines the next router to forward it to. This enables the effective utilization of redundant paths: two packets headed for the same destination, may take two different routes.( <a href="https://datatracker.ietf.org/doc/html/rfc1122#section-1.1.1">RFC</a> 1122)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AwH7b3S7YNfUUcju.gif" /><figcaption><em>Source: </em><a href="https://upload.wikimedia.org/wikipedia/commons/f/f6/Packet_Switching.gif"><em>Wikipedia</em></a></figcaption></figure><h3>Link Layer</h3><p>The network layer provides the service of transporting packets between two end-systems, via a series of routers. The link layer protocols provide the service of actually transporting packets from one node (a host, or a router) to another node (a router or a host). This is done by establishing connectivity with the next router and breaking up network layer datagrams into “frames” to transmit them to the next router. In other words, link layer protocols provide the service of converting datagrams into frames and transporting them across each individual link connecting two specific nodes. At each node, the network layer (after determining the next forwarding router/host) passes the Network Layer datagram to the respective link layer protocol, which sends it across to the next node. At the next node, the link layer protocol hands over the packet to the network layer protocol of that node.</p><p>Examples of link layer protocols include WiFi, Ethernet and Point-to-Point protocol.</p><h3>Physical Layer</h3><p>The physical layer provides the service of transporting each individual bit of a given frame from one node to the next. The protocol of this layer will depend on the actual link connecting the two nodes. In other words, physical layer protocols determine how to encode digital information and transmit them across a communication link.</p><h3>End-to-End Argument</h3><p>As shown above, the network layer does not make any guarantees regarding delivery of messages. It is the job of the end-systems (transfer layer and application layer) to ensure integrity, encryption and orderly delivery of information. Thus, as lower layers of the protocol stack do not implement complex functionalities, the internet is designed as a “dumb” network that relies on “smart” end-systems to carry out complex tasks. To put it in another way, the lower level actors (routers) perform simple tasks efficiently, while higher level actors are expected to use the services of the lower level actors to perform complex tasks. By pushing the complexity to the edges, the internet can be scaled to be compatible with any kind of network or device.</p><p><em>Originally published at </em><a href="https://otee.dev/2022/02/02/understanding-the-internet.html"><em>https://otee.dev</em></a><em> on February 2, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f083673959c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Clojure Backend Using Ring, Jetty and Compojure]]></title>
            <link>https://medium.com/@otee.dev/my-first-clojure-backend-using-ring-jetty-and-compojure-a70d9c5d7ca9?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70d9c5d7ca9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Tue, 25 Jan 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-01-26T14:14:28.348Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I discuss how I built my first web-app, RemindMe, using Clojure! The app is deployed here: <a href="https://remind.otee.dev/">https://remind.otee.dev</a></p><h3>Project Scope</h3><p>The <strong>RemindMe</strong> app aims to replicate how flash cards work in the real world. Quoting from <a href="https://en.wikipedia.org/wiki/Flashcard">Wikipedia</a>:</p><blockquote>A flashcard or flash card (also known as an index card) is a card bearing information on both sides, which is intended to be used as an aid in memorization. Each flashcard bears a question on one side and an answer on the other</blockquote><p>Similar to real world flash cards, RemindMe displays a question, which is selected randomly from a set of questions. The user has the option to see a hint or go to the next question (which will again be randomly selected from the question pool). If the user chooses to the see the hint, the hint to that question will be displayed and the user will again have the choice to either proceed to the next question or see the solution. Lastly, if the user chooses to see the solution, the relevant solution is displayed along with the option to proceed to the next question.</p><p>I wanted to build <strong>RemindMe</strong>, as a <strong>tool to recall my solutions to LeetCode problems</strong>. For this reason, the app describes each question as a ‘problem’. Also, while the text of each problem is lifted from LeetCode, the hints and solutions are mine. (Always happy to update my solutions with more optimal ones. Pull requests are welcome!)</p><p>The app reads a JSON file ( data.txt) to access the set of problems, solutions and hints. When we want to add a new problem, we will need to update the JSON file.</p><p>Here are the routes supported by this app:</p><ul><li>/problem/:id: This route loads the problem corresponding to the id path parameter.</li><li>/next: This route redirects to a randomly selected /problem/:id route</li><li>/: Same as /next, it redirects to a new problem route</li><li>/hint/:id: Generates a JSON payload containing the hint for the respective problem (to be used by client-side JavaScript).</li><li>:/solution/:id: Generates a JSON payload containing the hint and solution for the respective problem (to be used by client-side JavaScript).</li></ul><p>Here’s a demo of the <strong>RemindMe</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fa-iC6HBRuTw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Da-iC6HBRuTw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fa-iC6HBRuTw%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/f41c05bbaf27de4dc52d9946339af1bf/href">https://medium.com/media/f41c05bbaf27de4dc52d9946339af1bf/href</a></iframe><h3>Goal</h3><p>The primary goal is to learn how to build and deploy a project using Clojure. But before embarking on this journey, <strong>I first built an identical app using Node.js and the Express framework</strong>. This was helpful, as I did not have to spend much time focusing on the core business logic of the app and its front-end, while working with Clojure and the Ring framework. The Node.js version of the application is hosted on this GitHub Repository: <a href="https://github.com/oitee/remind-me">https://github.com/oitee/remind-me</a></p><p>Thus, the goal of this project is to <strong>re-implement the backend of RemindMe, using Clojure, and the Ring framework</strong>. This project is hosted on a separate repository, called <a href="https://github.com/oitee/aspire">aspire</a>.</p><h3>Step 0: Adding Dependencies to a Leiningen Project</h3><p>For this project, we will need three dependencies:</p><ul><li><strong>Ring</strong>: Ring is a web-framework which is analogous to Express in Node.js. It is used for easier management of HTTP requests, through routes, handlers and middlewares. To quote from its own <a href="https://github.com/ring-clojure/ring">documentation</a>,</li></ul><blockquote>By abstracting the details of HTTP into a simple, unified API, Ring allows web applications to be constructed of modular components that can be shared among a variety of applications, web servers, and web frameworks.</blockquote><ul><li><strong>Ring-Jetty</strong>: Since Clojure does not come with a built-in HTTP server, unlike Node.js, we need to implement a HTTP server. Ring comes with a default support for Jetty, a Java web-server.</li></ul><blockquote>Ring-Jetty is the web server that comes with Ring. It is a Clojure wrapper around Jetty. It is perfectly fine and acceptable and has the easiest setup in my opinion. If you are going to use Ring, it’s the best option. In addition, it is well-maintained and has a lot of users. <em>(</em><a href="https://purelyfunctional.tv/mini-guide/clojure-web-servers/"><em>Eric Normand</em></a><em>)</em></blockquote><p>We will use Ring-Jetty in this project. We can do this by including ring-jetty-adapter in our dependencies.</p><ul><li><strong>Compojure</strong>: This is a routing library for Ring that allows for easy handling of routes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W83F-XMrR8vNOko3.png" /></figure><p>Once the above three dependencies are added, the project.clj will look like this:</p><pre>(defproject aspire &quot;0.1.0-SNAPSHOT&quot;<br>  :description &quot;FIXME: write description&quot;<br>  :url &quot;http://example.com/FIXME&quot;<br>  :license {:name &quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&quot;<br>            :url &quot;https://www.eclipse.org/legal/epl-2.0/&quot;}<br>  :dependencies [[org.clojure/clojure &quot;1.10.0&quot;]<br>                 [ring/ring-core &quot;1.9.5&quot;]<br>                 [ring/ring-jetty-adapter &quot;1.9.5&quot;]<br>                 [compojure &quot;1.6.2&quot;]]<br>  :main ^:skip-aot aspire.core<br>  :target-path &quot;target/%s&quot;<br>  :profiles {:uberjar {:aot :all}})</pre><p>Now, we need to run lein deps on Linux command line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X9tPpRBiOyoKaUfZ.png" /></figure><p>Beware: it may download the entire internet, when we first run lein deps. 😛</p><h3>Step 1: Starting a ‘hello world’ server</h3><p>To start a simple “hello world” server, we need to first write a handler function that will respond to every request( <a href="https://github.com/ring-clojure/ring/wiki/Getting-Started">documentation</a>).</p><p>We then pass this handler to the run-jetty function to respond to requests. The run-jetty function starts an HTTP server that listens on a port and when a request is received on this port, calls the handler function. Later on, when we write more complicated code, the handler function will decide (based on request parameters, routes, methods etc) on how to respond to a certain request. In short, jetty is the HTTP server, run-jetty converts Clojure functions to work well with the Java jetty library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7481ebecd88e0f8bd9fa530209315a42/href">https://medium.com/media/7481ebecd88e0f8bd9fa530209315a42/href</a></iframe><p>Note that we always respond with hello world, and therefore requests to any path will receive the same response. If we print the request object, we can see all the necessary information that will be required for routing requests (eg. URI).</p><pre>{:ssl-client-cert nil,<br> :protocol &quot;HTTP/1.1&quot;,<br> :remote-addr &quot;[0:0:0:0:0:0:0:1]&quot;,<br> :headers<br> {&quot;sec-fetch-site&quot; &quot;none&quot;,<br>  &quot;host&quot; &quot;localhost:3000&quot;,<br>  &quot;user-agent&quot;<br>  &quot;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36&quot;,<br>  ...<br>  &quot;sec-gpc&quot; &quot;1&quot;},<br> :server-port 3000,<br> :content-length nil,<br> :content-type nil,<br> :character-encoding nil,<br> :uri &quot;/aaa&quot;,<br> :server-name &quot;localhost&quot;,<br> :query-string nil,<br> :body<br> #object[org.eclipse.jetty.server.HttpInputOverHTTP 0x2c9dcdc6 &quot;HttpInputOverHTTP@2c9dcdc6[c=0,q=0,[0]=null,s=STREAM]&quot;],<br> :scheme :http,<br> :request-method :get}</pre><h3>Step 2: Routing</h3><p>In the above snippet, we used one function to respond to all requests. However, this would be hard while managing requests with different HTTP methods and/or paths.</p><p>As our project supports multiple routes, we will use routes provided by compojure to determine how a request on a certain route should be responded to (similar to an Express.js app).</p><p>So, the previous handler function should be replaced with app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cd94cb9b80488625cefd347a0febcf3/href">https://medium.com/media/9cd94cb9b80488625cefd347a0febcf3/href</a></iframe><p>Note that:</p><ul><li>defroutes is a macro that returns a Ring handler function. It allows us to define and combine multiple routes under one umbrella (rather, handler).</li><li>Individual compojure routes are macros as well (and they can be used on a stand-alone basis, i.e., without defroutes)</li><li>compojure route macros are based on HTTP methods, i.e., GET PUT etc.</li><li>The path of a request is matched with the first argument of a route macro (notice the &quot;/&quot; after compojure/GET)</li><li>The last argument forms the response for that specific route. Once the HTTP method and path match, this argument will form the response. Instead of being a data value, it can be a function as well, which will have access to the incoming request to form the response.</li><li>The second argument in the GET macro is used for parameters: form and query parameters (we will not be using it for this project)</li><li>There is a way to have a fall-back route, i.e., not-found, to send a response when none of the routes match (here, we are using the Page not found response, when nothing matches).</li></ul><h3>Step 3: Adding Routes of ‘RemindMe’</h3><p>These are the routes used in the <a href="https://github.com/oitee/remind-me/blob/5580d93/src/routes.js">Node.js version of the project</a>:</p><pre>router.get(&quot;/&quot;, renderHome);<br>router.get(&quot;/problem/:id&quot;, getProblem);<br>router.get(&quot;/next&quot;, goToNext);<br>router.get(&quot;/hint/:id&quot;, getHint);<br>router.get(&quot;/solution/:id&quot;, getSolution);</pre><p>We can re-write these routes using compojure and provide specific route handler functions for each route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4ef3da93a72f4951bdfaede1d3c0a87/href">https://medium.com/media/d4ef3da93a72f4951bdfaede1d3c0a87/href</a></iframe><p>There are two things to note here:</p><ul><li>If the URL has a parameter in the path, we can use : to refer to that parameter in the route. This kind of route definition is similar to that of Express.js.</li><li>The second argument to GET is not a vector any more; we are just giving it a name (params) although we may not use it.</li></ul><p>Now, let’s write the route handlers (i.e., the third argument to each compojure route). Let’s start with problem-by-id. Note that we need to access the parameter in the URL path. This can be accessed from the request map. We can print the request map to see the relevant params key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8a8a637574c3428b714653a822d137/href">https://medium.com/media/fc8a8a637574c3428b714653a822d137/href</a></iframe><p>Once we send a request to the path /problem/foo, we can see the entire request map:</p><pre>{:ssl-client-cert nil,<br> :protocol &quot;HTTP/1.1&quot;,<br> :remote-addr &quot;[0:0:0:0:0:0:0:1]&quot;,<br> :params {:id &quot;foo&quot;},<br>...<br> :scheme :http,<br> :request-method :get}</pre><p>We can access the params key to see the value of our path parameter and write our handlers accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f5d524375a2a1768d0efaf26eb9f58/href">https://medium.com/media/24f5d524375a2a1768d0efaf26eb9f58/href</a></iframe><p>Each of the above functions are mentioned in our compojure routes, such that when the request path and method match, the relevant function will be invoked.</p><h3>Step 4: Code Reorganisation</h3><p>Currently, all the handlers and routes are in the same namespace. We can split them into three namespaces: one for starting the server, one for defining the routes, and one for the route handlers:</p><ul><li>aspire.core: This will start the server</li><li>aspire.routes: This will define the routes</li><li>aspire.handlers: This will have the route handler functions</li></ul><p>At this point, the project structure looks like this:</p><pre>.<br>├── LICENSE<br>├── project.clj<br>├── README.md<br>├── resources<br>├── src<br>│   └── aspire<br>│       ├── core.clj<br>│       ├── handlers.clj<br>│       └── routes.clj<br>└── test<br>    └── aspire<br>        └── core_test.clj</pre><p>aspire.core contains the server launching code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683121c8ef30be8cad92f0750912c264/href">https://medium.com/media/683121c8ef30be8cad92f0750912c264/href</a></iframe><p>aspire.routes contains the route definitions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/393208196194f18f0b7536316f163680/href">https://medium.com/media/393208196194f18f0b7536316f163680/href</a></iframe><p>aspire.handlers contains the route handler functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f96b355e120950b5b24fe1c722281fe/href">https://medium.com/media/7f96b355e120950b5b24fe1c722281fe/href</a></iframe><h3>Step 5: Implementing the Business Logic</h3><p>Now that we have up the web server, defined our routes and route-handlers, we can build the actual product features, by appropriately defining the route handler functions. To do this, we need a templating engine and a way to read data from a JSON file.</p><ul><li><strong>Templating Engine</strong>: The <a href="https://github.com/oitee/remind-me">Node.js version of the app</a> used Mustache templating engine. So, we need to support Mustache in Clojure as well. This will ensure that the front-end remains un-changed. For this, we can use de.ubercode.clostache/clostache as a dependency (<a href="https://github.com/fhd/clostache">documentation</a>)</li><li><strong>Data reading</strong>: The actual contents of the project (such as descriptions and solutions of problems etc) are stored in a JSON file which we need to read for serving the request. For this, we can use org.clojure/data.json as a dependency (<a href="https://github.com/clojure/data.json">documentation</a>)</li></ul><h3>Model Component</h3><p>The JSON file containing the problem sets looks like this:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;find-peak-element&quot;,<br>    &quot;problemTitle&quot;: &quot;Find Peak Element&quot;,<br>    &quot;problemDescription&quot;: &quot;A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. You must write an algorithm that runs in O(log n) time.&quot;,<br>    &quot;hint&quot;: &quot;Start with the middle element&quot;,<br>    &quot;solution&quot;: &quot;Start with mid element.\n        If this is a peak, then return it.\n        If this element is less than the next element, it means this element is part of an asceding slope. So, make lo = mid + 1,\n        If this element is less than the earlier element, move to the earlier sub-array, ie, hi = mid - 1\n        At the end, if lo === hi, lo is the peak element. Because it would mean we have reached the end of the array. And edges are peaks, if their adjacent element are smaller than them.&quot;<br>  },<br>  {<br>    &quot;id&quot;: &quot;boats-to-save-people&quot;,<br>    &quot;problemTitle&quot;: &quot;Boats to Save People&quot;,<br>    &quot;problemDescription&quot;: &quot;You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.\n\n        Return the minimum number of boats to carry every given person.\n        &quot;,<br>    &quot;hint&quot;: &quot;Start with sorting the array&quot;,<br>    &quot;solution&quot;: &quot;Sort the array.\n        For each people[hi] + people[lo] &gt; limit, hi-- and boats++.\n        For others, hi-- lo++ boats++\n        At the end, if hi == lo (indicating that there was an odd number of elements), boats++&quot;<br>  },<br>...<br>]</pre><p>We need to parse this JSON file by using clojure.data.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6577ed39d2191863c517acaeba71e44/href">https://medium.com/media/c6577ed39d2191863c517acaeba71e44/href</a></iframe><p>The read-str function (from the namespace clojure.data.json), takes a JSON string and converts it into a valid Clojure data-structure. Owing to the nature of the data contained in the JSON file, data will be a vector of hash-maps.</p><p>Note that we pass an additional argument to read-str, called :key-fn keyword. This ensures that the keys of the hash-maps generated by read-str are keywords instead of strings. Here’s how the hash-map looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c69ba6c5b6c2e1830e4e517dfc05d41/href">https://medium.com/media/0c69ba6c5b6c2e1830e4e517dfc05d41/href</a></iframe><p>Now, we need to convert this vector into a hash-map, where each id will map to the respective hash-map (representing a problem set)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa8a4e1991df4e4bec0d576ebea0627/href">https://medium.com/media/eaa8a4e1991df4e4bec0d576ebea0627/href</a></iframe><p>data-map is an id-to-problem-set hash-map. This will help in retrieving problems from their respective ids.</p><p>Also, we need two additional functions for our route-handlers:</p><ul><li>get: to get a problem set from an id, and</li><li>random-id: for returning a randomly chosen id from the data-map</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0ca51741f4c653ee95d9d761a880103/href">https://medium.com/media/b0ca51741f4c653ee95d9d761a880103/href</a></iframe><h3>Route Handlers</h3><p>We need to write the route handlers for each route. Let’s start with the route handler for /problem/:id</p><p>If the id parameter is correct, this route handler should generate the home page, with the necessary details of the respective problem set.</p><p>To achieve this, we need to render a template file ( home.mustache), using clostache</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98609391db88c060d0971bf9b96be29d/href">https://medium.com/media/98609391db88c060d0971bf9b96be29d/href</a></iframe><p>The render-resource function of clostache.parser is a templating engine. The first argument should be the location of the template file. As per its documentation, render-resource can &quot; <em>render a resource from the </em><strong><em>classpath</em></strong>&quot;.</p><p>A classpath is a “ <em>a sequence of paths that Clojure (or Java) </em><a href="https://lambdaisland.com/blog/2021-08-25-classpath-is-a-lie"><em>checks when looking for a Clojure source file</em></a>”. In a Leiningen project, the following directories are included in the classpath by default: the src, test, classes, test-resources, and resources directories( <a href="https://8thlight.com/blog/colin-jones/2010/11/26/a-leiningen-tutorial.html">source</a>). This means that our template file should be placed in any of these directories, to allow render-resource to access it. Accordingly, the template file ( home.mustache) is placed in a sub-directory ( templates) inside the resources directory of the project.</p><p>To write the route-handler for /next, we need to know how to send a redirection response. For this, we need to require ring.util.response name-space and use the redirect function therein:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867debfee4da3edea4f80a9d5146ae8d/href">https://medium.com/media/867debfee4da3edea4f80a9d5146ae8d/href</a></iframe><p>The other route handlers are similarly constructed. (see the <a href="https://github.com/oitee/aspire/blob/0cd4fca/src/aspire/handlers.clj">code here</a>).</p><h3>Deployment</h3><p>In order this to run this project on our <a href="https://medium.com/@otee.dev/how-to-deploy-an-app-using-google-compute-engine-75265803d17f">Google Cloud Platform (GCP) VM</a>, we have to complete the following steps:</p><ul><li>Compile the code into a Java JAR</li><li>Register our program as a service with Systemd</li><li>Install an NGINX config file and set up a DNS entry</li></ul><h4>Compiling the Code to JAR</h4><p>Because Clojure is hosted on the Java Virtual Machine, Clojure applications are run the same way as Java applications are run.</p><p>How does Java source code get complied?</p><ul><li>First, the Java Compiler converts the source code to Java Byte Code</li><li>Once a program is converted into Java Byte Code, it can be executed by the Java Virtual Machine, which is the runtime environment for Java (<a href="https://en.wikibooks.org/wiki/Java_Programming/Byte_Code">Source</a>)</li><li>The Java Byte Code gets stored in class files; a Java ARchive file, also called JAR, can store a collection of class files (<a href="https://www.ibm.com/docs/en/i/7.4?topic=java-platform">source</a>)</li></ul><p>Clojure source code gets converted to a specific JAR which can be executed by the JVM.</p><p>As our project is built using Leiningen, we can use lein jar to create the JAR file of our project. This file will be stored in the target directory of our project. Instead of simply using lein jar, we can use lein uberjar, which will create a JAR file containing the source code of our project, <strong>along with all its dependencies.</strong> A uberjar is a “a <a href="https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#what-to-do-with-it">single standalone executable jar</a> file”, which makes it easier to deploy. Once a uberjar is prepared, we can run it by simply using java -jar command. Optionally, we can use lein clean to clean our target directory. To run multiple commands successively, we can use lein do. So, here is how we first clean our target directory and then compile our project into a single JAR file:</p><pre>$ lein do clean, uberjar<br><br>Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.<br>Compiling aspire.core<br>2022-01-24 18:38:32.790:INFO::main: Logging initialized @1495ms to org.eclipse.jetty.util.log.StdErrLog<br>WARNING: seqable? already refers to: #&#39;clojure.core/seqable? in namespace: clojure.core.incubator, being replaced by: #&#39;clojure.core.incubator/seqable?<br>WARNING: seqable? already refers to: #&#39;clojure.core/seqable? in namespace: clostache.parser, being replaced by: #&#39;clojure.core.incubator/seqable?<br>WARNING: get already refers to: #&#39;clojure.core/get in namespace: aspire.db, being replaced by: #&#39;aspire.db/get<br>Compiling aspire.db<br>WARNING: get already refers to: #&#39;clojure.core/get in namespace: aspire.db, being replaced by: #&#39;aspire.db/get<br>Compiling aspire.handlers<br>Compiling aspire.routes<br>Created /home/otee/projects/aspire/target/uberjar/aspire-0.1.0-SNAPSHOT.jar<br>Created /home/otee/projects/aspire/target/uberjar/aspire-0.1.0-SNAPSHOT-standalone.jar</pre><p>In order to run the project from a JAR, we need to ensure that we are not reading any files from the local file system. In the present project, all the non-Clojure files are read from the classpath. In the case of data.txt, which hosts the JSON data-set, we cannot directly use the file-path while slurping it. Instead, we have to use the resource method to <a href="https://clojuredocs.org/clojure.java.io/resource">read file from the classpath</a> instead:</p><pre>(slurp (clojure.java.io/resource &quot;data.txt&quot;))</pre><h4>Deploying the uberjar to GCP VM</h4><p>Now that we have our JAR file, we need to send it across to our VM on GCP (alias calculus). We can do this by using the rsync command, which enables the transfer of files over SSH. Interestingly, it <a href="https://phoenixnap.com/kb/how-to-rsync-over-ssh">synchronizes the data being transferred</a> between the different machines: ensuring that only those files are transferred which are new or updated.</p><pre>rsync /home/otee/projects/aspire/target/uberjar/aspire-0.1.0-SNAPSHOT-standalone.jar calculus:/home/oitee.codes/projects</pre><p>Once the JAR is deployed, we can run it on the VM using:</p><pre>java -jar -Xmx32m /home/oitee.codes/projects/aspire-0.1.0-SNAPSHOT-standalone.jar</pre><p>The -Xmx flag is used to specify the maximum heap memory allocation for running a Java program. When we use -Xmx32m, we restrict the memory allocation to 32 MB.</p><h3>Registering with systemd</h3><p>We need to use systemd, to ensure that our application runs consistently. To set up systemd for our application, we need to write a new configuration file ( remind.service) in /lib/systemd/system.</p><pre>sudo nano /lib/systemd/system/remind.service</pre><p>This file should contain the following details:</p><pre>[Unit]<br>Description=remind<br>Documentation=https://github.com/oitee/aspire#readme<br>After=network.target<br><br>[Service]<br>Environment=PORT=4003<br>Type=simple<br>User=oitee.codes<br>ExecStart=/usr/bin/java -Xmx32m -jar /home/oitee.codes/projects/aspire-0.1.0-SNAPSHOT-standalone.jar<br>Restart=on-failure<br><br>[Install]<br>WantedBy=multi-user.target</pre><p><em>For a more detailed explanation of each of these terms, see this </em><a href="https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/"><em>useful post</em></a><em> or my </em><a href="https://medium.com/@otee.dev/how-to-deploy-an-app-using-google-compute-engine-75265803d17f"><em>earlier post on setting up my VM on Google Cloud Compute</em></a><em>.</em></p><p>Note that we need to specify the value of the internal port( PORT=4003) where our server will be listening under the Environment entry. Also, under the ExecStart entry, we cannot use java; instead we have to mention the location of the executable Java file, i.e., /usr/bin/java. (/usr/bin is the &quot;<a href="https://www.pathname.com/fhs/pub/fhs-2.3.html#USRBINMOSTUSERCOMMANDS"><em>primary directory</em></a><em> of executable commands on the system</em>&quot;).</p><p>Now, we need to run the following commands, to have systemd run our application (for more on this, read <a href="https://medium.com/@otee.dev/how-to-deploy-an-app-using-google-compute-engine-75265803d17f">this previous post</a>):</p><pre>sudo systemctl daemon-reload<br>sudo systemctl start remind.service<br>sudo systemctl enable remind.service</pre><p>This should run our application. To see the status of the status of our application, we can use the following command:</p><pre>sudo systemctl status remind.service<br><br>● remind.service - remind<br>     Loaded: loaded (/lib/systemd/system/remind.service; enabled; vendor preset: enabled)<br>     Active: active (running) since Mon 2022-01-24 09:25:30 UTC; 18s ago<br>       Docs: https://github.com/oitee/aspire#readme<br>   Main PID: 178875 (java)<br>      Tasks: 22 (limit: 1159)<br>     Memory: 119.4M<br>     CGroup: /system.slice/remind.service<br>             └─178875 /usr/bin/java -Xmx32m -jar /home/oitee.codes/projects/aspire-0.1.0-SNAPSHOT-standalone.jar<br><br>Jan 24 09:25:30 calculus systemd[1]: Started remind.<br>Jan 24 09:25:33 calculus java[178875]: 2022-01-24 09:25:33.385:INFO::main: Logging initialized @2707ms to org.eclipse.jetty.util.log.StdErrLog<br>Jan 24 09:25:35 calculus java[178875]: WARNING: seqable? already refers to: #&#39;clojure.core/seqable? in namespace: clojure.core.incubator, being replaced by: #&#39;clojure.core.incubator/seqable?<br>Jan 24 09:25:35 calculus java[178875]: WARNING: seqable? already refers to: #&#39;clojure.core/seqable? in namespace: clostache.parser, being replaced by: #&#39;clojure.core.incubator/seqable?<br>Jan 24 09:25:35 calculus java[178875]: WARNING: get already refers to: #&#39;clojure.core/get in namespace: aspire.db, being replaced by: #&#39;aspire.db/get<br>Jan 24 09:25:35 calculus java[178875]: 2022-01-24 09:25:35.264:INFO:oejs.Server:main: jetty-9.4.44.v20210927; built: 2021-09-27T23:02:44.612Z; git: 8da83308eeca865e495e53ef315a249d63ba9332; jvm 17.0.1+12-Ubuntu-120.04<br>Jan 24 09:25:35 calculus java[178875]: 2022-01-24 09:25:35.454:INFO:oejs.AbstractConnector:main: Started ServerConnector@4052913c{HTTP/1.1, (http/1.1)}{0.0.0.0:4003}<br>Jan 24 09:25:35 calculus java[178875]: 2022-01-24 09:25:35.456:INFO:oejs.Server:main: Started @4815ms</pre><h3>Using NGINX to redirect traffic from Port 80</h3><p>To redirect requests to port 80 of our VM to the specific internal port our server will be listening to (4003) , we need to write a configuration file for NGINX. First, we should add a configuration file remind.otee.dev to the /etc/nginx/sites-available.</p><pre>sudo nano /etc/nginx/sites-available/remind.otee.dev</pre><p>This file should contain the following details:</p><pre>server {<br>        listen 80;<br>        listen [::]:80;<br>        server_name remind.otee.dev;<br>        location / {<br>        proxy_pass http://127.0.0.1:4003;<br>        }<br>}</pre><p>Now, we need to enable this configuration by adding a symbolic link to it in the /etc/nginx/sites-available directory:</p><pre>sudo ln -s /etc/nginx/sites-available/remind.otee.dev /etc/nginx/sites-enabled/remind.otee.dev</pre><p>Next, we should restart NGINX:</p><pre>sudo systemctl status nginx<br>sudo systemctl restart nginx</pre><p>Now that NGINX has been configured to redirect requests to <a href="http://remind.otee.dev/">remind.otee.dev</a> to the internal port 4003, we need to set up the custom domain remind.otee.dev and then enforce HTTPS, by using the freely available <a href="https://certbot.eff.org/">Certbot</a> tool provided by <a href="https://letsencrypt.org/getting-started/">Lets Encrypt</a>.</p><p>This concludes the deployment!🎉</p><p>The project is live at: <a href="https://remind.otee.dev/">https://remind.otee.dev</a></p><h3>Further Improvements</h3><p>Here are some of the improvements that can be added in future:</p><ul><li>Move the data-set to SQLite. This will allow us to write data on the file. For example, to track analytics of our app: the number of views, requests for hints and solutions</li><li>Enable adding of new problem sets from the UI:</li><li>This can be done by creating a ‘users’ table, with admin usernames and passwords (using good password storage principles as we did with Twirl)</li><li>Maintaining sessions on addition routes (Middleware for cookie parsing)</li></ul><p><em>Originally published at </em><a href="https://otee.dev/2022/01/25/clojure-backend-using-ring-jetty-compojure.html"><em>https://otee.dev</em></a><em> on January 25, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70d9c5d7ca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who Moved My Cheese: Laziness in Clojure]]></title>
            <link>https://medium.com/@otee.dev/who-moved-my-cheese-laziness-in-clojure-f71f19b29d2a?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/f71f19b29d2a</guid>
            <category><![CDATA[clojurescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[emacs]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[clojure]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-01-19T07:32:30.954Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I try to understand what lazy sequences are and how to create our own lazy sequence in Clojure.</p><h3>Lazy Sequences in Clojure</h3><p><a href="https://clojure.org/reference/sequences">Clojure reference</a> explains laziness as:</p><blockquote>Most of the sequence library functions are lazy, i.e. functions that return seqs do so incrementally, as they are consumed, and thus consume any seq arguments incrementally as well.</blockquote><p>The important parts of this is that many library functions that produce sequences (e.g. lists) do so incrementally, as they are consumed. This means that <strong>unless there is someone to consume the sequence, nothing really happens</strong>.</p><p>This was particularly perplexing to the eyes of a beginner learning Clojure, especially as to why the following the following does not print anything:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3757c67418b92bcac907c2847a4fb823/href">https://medium.com/media/3757c67418b92bcac907c2847a4fb823/href</a></iframe><p>When this function was called with proper arguments, the REPL produced the following output:</p><pre>butterfly.core=&gt; (print-numbers 9)<br>Done printing:  9<br>nil</pre><p>It turns out that the function print-numbers produces a lazy sequence on line 1 (as indicated on the code-block above), i.e., the map produces a lazy sequence. As no one is consuming the sequence from map, it is never really realised. For this reason, the println inside the map is never executed. This is what lazy evaluation means.</p><p>This can be fixed in any of the following ways.</p><h4>Using mapv</h4><p>Use a non-lazy version of map, i.e., mapv</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b22b12412b154cdbadecb25450a0c7/href">https://medium.com/media/48b22b12412b154cdbadecb25450a0c7/href</a></iframe><h4>Using map + doall</h4><p>Wrap map with doall which realises a lazy sequence</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eb51f04fba34b477089b1b89563e3bd/href">https://medium.com/media/0eb51f04fba34b477089b1b89563e3bd/href</a></iframe><h4>Using doseq</h4><p>Instead of generating a sequence, we can use doseq which acts on each element of a sequence</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ac2da70b9407469c52d45e2ed70a5ab/href">https://medium.com/media/8ac2da70b9407469c52d45e2ed70a5ab/href</a></iframe><h4>Using run!</h4><p>A better version (for the present example) than using doseq is to use run! which applies a given function on every element of a sequence, without generating another sequence (unlike map)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b7e1f6a1f4fc780f59dd9aaca013c1/href">https://medium.com/media/b5b7e1f6a1f4fc780f59dd9aaca013c1/href</a></iframe><h3>Generating a Lazy Sequence 💪🏼</h3><p>Let us now try to generate an infinite lazy sequence of prime numbers.</p><p>First, we write a function which returns true if a number is prime</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e1c27c3ddc93386ab1335e1610d23e2/href">https://medium.com/media/3e1c27c3ddc93386ab1335e1610d23e2/href</a></iframe><p>Let us now define an infinite sequence of prime numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/429a1cd8f886948edc056fb5c5115aa1/href">https://medium.com/media/429a1cd8f886948edc056fb5c5115aa1/href</a></iframe><p>This infinite-primes var is doing a filter operation on an infinite sequence of numbers. Because filter and range both produce lazy sequences, this will not halt our program. In fact, this is the power of lazy sequences, that we can compute as many number of prime numbers, as we need <strong>when we need it</strong> without having to know apriori how many we may need.</p><p>Thus, all of the following generates prime number sequences of varying lengths:</p><pre>user=&gt; (take 5 infinite-primes)<br>(2 3 5 7 11)<br>user=&gt; (take 10 infinite-primes)<br>(2 3 5 7 11 13 17 19 23 29)<br>user=&gt; (take 100 infinite-primes)<br>(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541)</pre><h3>Constructing a Lazy Sequence from Scratch 🧙🏼</h3><p>In the above part, we generated a lazy sequence by leveraging the library functions filter and range both of which are lazy.</p><p>In order to construct a lazy sequence from scratch, we can use lazy-seq. But before writing a lazy-primes function, let us write an eager-primes function that constructs a sequence of prime numbers from scratch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9587562a15119b2a351a0ab425433bd/href">https://medium.com/media/a9587562a15119b2a351a0ab425433bd/href</a></iframe><p>Here’s the how eager-primes can be used:</p><pre>butterfly.core=&gt; (eager-primes 8)<br>[2 3 5 7 11 13 17 19]</pre><p>This is not a lazy sequence, because <strong>irrespective of how many primes are consumed, </strong><strong>eager-primes will always generate </strong><strong>n prime numbers, no more, no less</strong>.</p><p>So, in order to make it lazy, first we need to get rid of n, so that the production of primes depends on how many are consumed and not on a pre-defined number. For example, here we need only 10 primes, but eager-primes will still generate 100 primes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43e1995347dda1c36588ed85edb98634/href">https://medium.com/media/43e1995347dda1c36588ed85edb98634/href</a></iframe><p>In order to make it a lazy sequence, we need to stop the recursion. The way to do this is to wrap the recursive call around lazy-seq. What this will do is that it will tell Clojure that if any one is consuming from this sequence, this is the step to repeat. In other words, if we have a pause/resume functionality around recur, we have essentially generated a lazy sequence. But, in practice, we cannot actually use recur because when we use lazy-seq around the recursive call, the recursive call is no longer a tail call. So, we have to make the recursive call by using the function name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85fb6711aa9a0e7657d094b7bea69d4a/href">https://medium.com/media/85fb6711aa9a0e7657d094b7bea69d4a/href</a></iframe><p>Output:</p><pre>butterfly.core=&gt; (def all-primes (primes))<br>#&#39;butterfly.core/all-primes<br><br>butterfly.core=&gt; (take 5 all-primes )<br>(2 3 5 7 11)<br><br>butterfly.core=&gt; (take 10 all-primes )<br>(2 3 5 7 11 13 17 19 23 29)<br><br>butterfly.core=&gt; (take 15 all-primes )<br>(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)</pre><p>Important things to note:</p><ol><li><strong>Why we must use </strong><strong>cons</strong>: cons appends an element to a sequence at the beginning, <strong>without traversing the rest of the sequence</strong>. This is important because, if we are generating an infinite sequence, we cannot traverse the sequence fully because the sequence is infinite. In contrast, conj appends a new element at the end of the sequence, which, by definition, requires traversal of the whole sequence (to find the end). This is why we must use cons instead of conj.</li><li><strong>Use of </strong><strong>lazy-seq</strong>: Whenever Clojure sees lazy-seq it stops evaluation until someone is realising it. This means that a cons on a lazy sequence is a sequence which has not really been computed. It will be computed when someone is traversing that list, i.e., realising it. The way this works is that cons points to an element and a lazy sequence which, again, includes a cons cell that points to an element and another lazy sequence. The Clojure environment evaluates these lazy-seq s as demanded as the traversal progresses. Therefore, it only evaluates that part of the sequence which has been traversed at least once.</li></ol><p>To visualize the above, let us try to understand how a lazy sequence is traversed upon realization. For example, when four elements are taken out of the lazy sequence, the following happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*30wQguDd5eGqFdp3.png" /></figure><p>Every cons cell has a subsequent sequence, which is lazy. This means that it has not been computed. Therefore, only when we traverse that lazy sequence, do we find another cons cell with the next prime number, followed by another lazy sequence. <strong>This can be thought of as the proverbial </strong><a href="https://en.wikipedia.org/wiki/Matryoshka_doll"><strong>Russian Dolls</strong></a>. Only by opening the first doll do you see the next doll (and not any more).</p><p>This traversal of lazy sequences and realisation (and caching of realised cons cells) is transparently done by Clojure, as they are consumed by some enclosing code. As a corollary, by virtue of the REPL having an eval step, lazy sequences are realised on the spot if directly written on the REPL (i.e., the REPL tries to consume the entire lazy sequence).</p><pre>user=&gt; (cons 1 (range))<br>;; this will never finish on the REPL</pre><h3>Who Moved My Cheese: Why laziness is not a bad thing</h3><p>In the book <a href="https://www.amazon.in/s?k=who+moved+my+cheese&amp;i=stripbooks&amp;ref=nb_sb_noss">‘Who Moved My Cheese’</a>, the author says that the lazy mouse ultimately loses out on life because when the going gets tough, the hard-working mouse (eager mouse) finds a solution and the lazy one, out of sheer laziness, perishes.</p><p>However, in a modern-day language like Clojure, a lazy sequence can prove to be very useful because some problems, like the prime numbers sequence, by definition, are infinite. If we built a web-page that displayed a paginated result of prime numbers, any language that did not implement a lazy sequence of prime numbers, would have to re-evaluate all the prime numbers for every page. This means that to generate the 500th prime number, we would have to generate 499 prime numbers and then the 500th one. Consequently, to generate the 501st prime number, we would have to re-generate the first 500 prime numbers all over again (as seen in the eager-primes example above). This in Clojure would not be required because we maintain only one sequence of prime numbers that are realised as required and no recomputaton would be necessary.</p><p><strong>Edit:</strong> <em>In an earlier version, I had mentioned that a lazy sequence can provide efficiency. This is not accurate: a lazy sequence does not improve the inherent algorithmic efficiency of an expression. (However, caching of a lazy sequence does prevent recomputations). Thanks to </em><a href="https://github.com/adityaathalye"><strong><em>Aditya Athalye</em></strong></a><em>, for pointing this out!</em></p><p><em>Originally published at </em><a href="https://otee.dev/2022/01/17/lazy-clojure.html"><em>https://otee.dev</em></a><em> on January 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f71f19b29d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurse Center: Week Two]]></title>
            <link>https://medium.com/@otee.dev/recurse-center-week-two-84a16d6edbb4?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a16d6edbb4</guid>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[recurse-center]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[emacs]]></category>
            <category><![CDATA[clojurescript]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-01-19T07:37:23.864Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is about my second week at the <a href="https://www.recurse.com/">Recurse Center</a>.</p><h3>Clojure</h3><p>One of my primary goals at the Recurse Center, is to learn how to write programs in Clojure. To this end, I had spent the first week familiarising myself with the basic syntax of Clojure. This week, I could delve deeper and wrote some not-so-simple programs.</p><p>Before the start of the retreat, I had asked for suggestions for getting started with Clojure. <a href="https://twitter.com/KapilReddy">Kapil Reddy</a> was kind enough to point me to an on-boarding course, <a href="https://github.com/inclojure-org/clojure-by-example">clojure-by-example</a>, that he, <a href="https://github.com/adityaathalye">Aditya Athalye</a> and a few others had designed.</p><h3>Kapil on Twitter: &quot;Start from https://t.co/YwAhlj1HlN This is a good starting point. You don&#39;t have to figure out editor setup yet. Shoutout to @jysandilya, https://t.co/LIVollpHAT and @in_clojure for course design #Clojure / Twitter&quot;</h3><p>Start from https://t.co/YwAhlj1HlN This is a good starting point. You don&#39;t have to figure out editor setup yet. Shoutout to @jysandilya, https://t.co/LIVollpHAT and @in_clojure for course design #Clojure</p><p>The week began with a long and super helpful Clojure pairing session with <a href="https://github.com/adityaathalye">Aditya</a>, who gave me a detailed walk-through of <a href="https://github.com/inclojure-org/clojure-by-example">clojure-by-example</a>. Until then, I had only read the first three chapters of <a href="https://www.braveclojure.com/clojure-for-the-brave-and-true/">Clojure for the Brave and True</a>. While I had a theoretical overview of some of the basic semantics of Clojure, this pairing session gave a more hands-on take on how to read, evaluate and write expressions in Clojure. This was the perfect start to my week!</p><p>During the rest of the week, I concentrated on completing the next three chapters of Clojure for the Brave and True ( <a href="https://www.braveclojure.com/core-functions-in-depth/">Core Functions in Depth</a>, <a href="https://www.braveclojure.com/functional-programming/">Functional Programming</a>, and <a href="https://www.braveclojure.com/organization/">Organizing Your Project: A Librarian’s Tale</a>). Learning about sequence abstraction was truly fascinating</p><blockquote>It doesn’t matter how a particular data structure is implemented: when it comes to using seq functions on a data structure, all Clojure asks is “can I first, rest, and cons it?&quot; If the answer is yes, you can use the seq library with that data structure<em> [</em><a href="https://www.braveclojure.com/core-functions-in-depth/"><em>source</em></a><em>]</em></blockquote><p>While reading <a href="https://www.braveclojure.com/clojure-for-the-brave-and-true/">Clojure for the Brave and True</a>, I learnt about some of the key concepts of functional programming. Specifically, reading about pure functions and their use-case was a lot of fun! I would like to spend some time reading more on concepts (like ‘referential transparency’, and ‘functional composition’) that are fundamental to functional programming. Also, reading about higher-order functions was a lot of fun as it reminded me of my early adventures with <a href="https://medium.com/@otee.dev/higher-order-functions-1a3d2823aff4">map, reduce and filter</a>.</p><p>I had struggled to visualise the importance of lazy sequences while writing programs. So, I ended up spending considerable amount of time, playing around with lazy sequences. In the end, I published a <a href="https://medium.com/@otee.dev/who-moved-my-cheese-laziness-in-clojure-f71f19b29d2a">blog post (with a cheeky title) summarising my findings</a>.</p><p>As reading several pages of <a href="https://www.braveclojure.com/clojure-for-the-brave-and-true/">Clojure for the Brave and True</a> can get a bit monotonous, I would often take a detour to implement some of the examples and concepts explained in the book. It was particularly satisfying to take up <a href="https://twitter.com/nonrecursive">Daniel’s</a> challenge on <a href="https://www.braveclojure.com/core-functions-in-depth/">Chapter 4</a>:</p><blockquote>If you want an exercise that will really blow your hair back, try implementing map using reduce and then do the same for filter and some after you read about them later in this chapter.</blockquote><p>Here’s my implementation of map-using-reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f209b25c49f87c209f57554e2203c14c/href">https://medium.com/media/f209b25c49f87c209f57554e2203c14c/href</a></iframe><p>Here’s filter-using-reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb1263adbbd0eef234715382e8eded6/href">https://medium.com/media/ffb1263adbbd0eef234715382e8eded6/href</a></iframe><p>And, some-using-reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9848f0d8792f655aa3a560201b6d8bdd/href">https://medium.com/media/9848f0d8792f655aa3a560201b6d8bdd/href</a></iframe><p>Here’s my <a href="https://github.com/oitee/butterfly">GitHub repository</a>, hosting my white-board adventures with Clojure!</p><p>Also, as suggested by Aditya, I keep solving the 4Clojure problems mentioned at the end of each exercise of <a href="https://github.com/inclojure-org/clojure-by-example">clojure-by-example</a>. So far I have solved a handful of them; I intend to solve many more this week. Here’s where I write down my solutions to 4Clojure problems: <a href="https://github.com/oitee/clojure-by-example/blob/master/src/clojure_by_example/4-clojure-exercises.clj">https://github.com/oitee/clojure-by-example/blob/master/src/clojure_by_example/4-clojure-exercises.clj</a></p><h3>Using NGINX to Use a Custom Domain</h3><p>While most of the week was spent on Clojure, I could sneak out some time to complete a long-standing task related to <a href="https://twirl.otee.dev/">Twirl</a>. Twirl is a URL-shorening web app. As it is hosted on Heroku (free tier), the domain name of the app is pretty long( oteetwirl.herokuapp.com). This makes the short links generated by Twirl not so short after all. I used NGNIX on a Google Cloud VM I had spawned recently, to generate a custom short domain name for my application. Twirl is now accessible at: <a href="https://twirl.otee.dev/">https://twirl.otee.dev</a>. This makes the resultant short links shorter! Here&#39;s a detailed <a href="https://medium.com/@otee.dev/making-short-links-shorter-using-nginx-custom-domain-44d2637fb329">account of the steps I followed to complete this task</a>!</p><h3>Others</h3><ul><li>I paired with <a href="https://kanyisa-ntombini.github.io/portfolio/">Kanyisa</a>, to continue working on building a REPL version of the <a href="https://en.wikipedia.org/wiki/Mastermind_(board_game)">Mastermind game</a>. We think we would need one more session to complete this.</li><li>I attended a very insightful session hosted by Julia Evans on How DNS works and how it breaks.</li></ul><p><em>Originally published at </em><a href="https://otee.dev/2022/01/17/recurse-center-week-two.html"><em>https://otee.dev</em></a><em> on January 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a16d6edbb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Short Links Shorter: Using NGINX and  Custom Domain]]></title>
            <link>https://javascript.plainenglish.io/making-short-links-shorter-using-nginx-custom-domain-44d2637fb329?source=rss-c5f10dffc42------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d2637fb329</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Oitihjya Sen]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-01-19T08:39:40.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Make Short Links Shorter: Using NGINX and Custom Domain</h3><h4>A guide on how to shorten short links generated by Twirl.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*5bCIHrTVNaxALKET.jpg" /></figure><p>In this post, I explain how to shorten the short links generated by <a href="https://otee.dev/2022/01/13/making-short-links-shorter.html">Twirl</a>. For example, from oteetwirl.herokuapp.com/l/L5w2 to twirl.otee.dev/l/L5w2.</p><h3>Problem Statement</h3><ol><li><strong>Twirl</strong> is a per-user URL shortening app. To learn more about how Twirl was built and designed, read <a href="https://otee.dev/2021/11/14/twirl-user-management.html">this</a>, <a href="https://otee.dev/2021/12/08/storing-passwords-securely.html">this</a>, and <a href="https://otee.dev/2021/12/20/twirl-link-shortening.html">this</a>. Here’s the GitHub repository hosting Twirl: <a href="https://github.com/oitee/twirl">https://github.com/oitee/twirl</a>.</li><li>Twirl is deployed on <strong>Heroku</strong>, as a free app. It is available at: <a href="https://oteetwirl.herokuapp.com/">oteetwirl.herokuapp.com</a>.</li><li>Custom domains with HTTPS support is not available as a free service on Heroku. This causes the resultant short links generated by Twirl to be not so short, after all.</li><li>Solution: we keep running Twirl on Heroku but use a <strong>shorter custom domain</strong> which will shorten the short links generated by the app. For example, instead of generating <a href="https://oteetwirl.herokuapp.com/l/L5w2"><strong>oteetwirl.herokuapp.com/l/L5w2</strong></a>, the app should generate <a href="https://twirl.otee.dev/l/L5w2"><strong>twirl.otee.dev/l/L5w2</strong></a></li><li>In order to expose this new short link, Twirl should also display the shorter version of short links on its UI.</li></ol><h3>Technical Considerations</h3><p>There are, largely, three ways to go about this:</p><ol><li><strong>Approach I: Migrate Entirely to IaaS</strong>: Run the whole app on a self-owned server, like Google Cloud Compute. This will allow us to choose our domain name and also run the system. But if we do this, we will need to manage the database, and have the server run all the time (unlike Heroku’s auto-sleep option). The bigger concern here is that the world already knows about <a href="https://oteetwirl.herokuapp.com/">oteetwirl.herokuapp.com</a>. In order to not break the user experience, we will not only have to copy the data from the Heroku database to the GCP server but also continuously serve the older short URLs on this app (i.e., have Heroku redirect requests for the current short links to GCP).</li><li><strong>Approach II: Have custom redirection to PaaS</strong>: Provide a redirection mechanism from shorter links (using a custom short domain name) to the main system, which continues to run on Heroku. This has the advantage of cost-efficiency since we already have a GCP server, which was set up for <a href="https://otee.dev/2021/12/31/deploying-to-google-cloud-compute.html">another project</a></li><li><strong>Approach III: Hybrid of I &amp; II</strong>: In Approach I, instead of the lift-and-shift way of migration, we could, in theory, keep the database running on Heroku, but have the app run on GCP. But this will still not be as cost-efficient as Approach II, because the HTTP server on GCP will have to run continuously.</li></ol><p>So, our preferred approach is the second approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*00HcuqAncDtDDj2D.png" /></figure><p><em>The above C4 diagram is generated using </em><a href="https://gist.github.com/oitee/725732646af54024d4bc242608e1cf4e"><em>this</em></a></p><h3>Step 1: Creation of DNS Entry</h3><p>We add the DNS entry for the GCP VM which we had already spawned <a href="https://otee.dev/2021/12/31/deploying-to-google-cloud-compute.html">another project</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*cG1rputXl3PC7mOC.png" /></figure><p>So now, <a href="https://twirl.otee.dev/">twirl.otee.dev</a> points to my GCP VM.</p><h3>Step 2: Setting up NGINX</h3><p>We will loosely follow the steps for rewriting URLs, mentioned <a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/">in the official docs</a>:</p><ol><li>We will use the return directive</li><li>We will redirect to the client using HTTP status 301 (moved permanently)</li><li>We will construct the redirection URL by keeping everything the same, as before, except the hostname.</li><li>We will set up HTTPS using LetsEncrypt</li></ol><p>To do steps 1, 2, 3, we create a new file here: /etc/nginx/sites-available/twirl.otee.dev with :</p><pre>server {<br>    listen 80;<br>    listen 443 ssl;<br>    server_name twirl.otee.dev;<br>    return 301 $scheme://oteetwirl.herokuapp.com$request_uri;<br>}</pre><p>Next, we enable this site, by creating a symlink:</p><pre>sudo ln -s /etc/nginx/sites-available/twirl.otee.dev /etc/nginx/sites-enabled/twirl.otee.dev</pre><p>Next, we should restart NGINX:</p><pre>sudo systemctl status nginx<br>sudo systemctl restart nginx</pre><p>At this point, if we go to twirl.otee.dev it should take us to Twirl, which runs on Heroku. But, since we are using a .dev domain, it is necessary that we create an SSL certificate for twirl.otee.dev so that HTTPS is supported.</p><p>If certbot is installed we can simply use this command : sudo certbot --nginx. If certbot is not installed, it needs to be installed (see <a href="https://certbot.eff.org/instructions?ws=nginx&amp;os=ubuntufocal">documentation</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cSVkGKNoxmccIGW1.png" /></figure><p>Now, the redirection to <a href="https://twirl.otee.dev/">twirl.otee.dev</a> should work. But if it does not, we may have to flush the DNS caches. This can be done for Google Domains here: <a href="https://dns.google/cache">https://dns.google/cache</a>.</p><p>At this point, we have reached our goal of using a short domain name for our short links. For example, the following link should now work: <a href="https://twirl.otee.dev/l/L5w2">twirl.otee.dev/l/L5w2</a>.</p><h3>Step 3: Display Short Links on Twirl</h3><p>While we have enabled redirection of short links with the domain twirl.otee.dev, the Twirl application will still display the longer URL, using Heroku&#39;s default domain name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tiaxoe88yUPJ0ezW.png" /></figure><p>Instead of displaying <a href="https://oteetwirl.herokuapp.com/l/L5w2">oteetwirl.herokuapp.com/l/L5w2</a> we want Twirl to display <a href="https://twirl.otee.dev/l/L5w2">twirl.otee.dev/l/L5w2</a>. Currently, Twirl is deisgned in such a way that the server generates the unique URL path and the final link is constructed by <a href="https://github.com/oitee/twirl/blob/a58e20c/public/views/home.mustache#L139">client-side JavaScript</a> by appending the current domain:</p><pre>function shortLinkHref(link) {<br>  let finalLink = window.location.protocol + &quot;//&quot; + window.location.host + link;<br>  return `&lt;a href=&#39;${link}&#39; target=&#39;_blank&#39;&gt; ${finalLink}&lt;a/&gt;`;<br>}</pre><p>Instead of this approach, we can create the short link at the server-side itself. To do this, we should first expose the intended domain name from the environment on the server. This is required because <strong>the server does not know the domain name on which it is serving requests</strong>. It just knows that it is serving requests on a local port. Even if it was aware of the IP address of the machine (which is sometimes the case), it would still not know which domain names (there can be multiple) maps to that IP address because this part (i.e., domain name to IP address conversion) is necessarily done by the client by making DNS queries. Therefore, the intended domain name should be provided to the server as additional information. This is purely decorative and the server will blindly generate the short URL, by appending the short URL path to the given domain name.</p><p>To enable this, the server was exposed to a new environment variable, namely CUSTOM_DOMAIN_NAME which contains our shorter domain name, namely twirl.otee.dev. Now, every time a request for shortening a link is received, the server sends back the complete short URL (as opposed to just sending the URL path, as was the case earlier).</p><p>According to this design, the front-end does not operate on short-link received from the server. This causes a slight hindrance, as the client-side JavaScript needs to generate requests for enabling and disabling existing short links when the user clicks on the <strong>toggle</strong> button on the home page. Earlier, the client-side JavaScript would generate these requests in the following manner:</p><pre>async function updateStatus(link, currentStatus) {<br>  // &#39;link&#39; is the URL path of a short link, <br>  // &#39;currentStatus&#39; indicates whether a short link is enabled or disabled at the moment<br>  link = link.substring(3);<br>  if (currentStatus) {<br>    await fetch(`/l/disable/${link}`, { method: &quot;POST&quot; });<br>  } else {<br>    await fetch(`/l/enable/${link}`, { method: &quot;POST&quot; });<br>  }<br>  await analyticsGenerator();<br>}</pre><p>To allow the client-side JavaScript to generate the above requests, the server, in addition to sending the complete short URL, also sends the short URL path (without the first three common characters /l/). This allows the above function to operate without many changes:</p><pre>async function updateStatus(linkPath, currentStatus) {<br>  if (currentStatus) {<br>    await fetch(`/l/disable/${linkPath}`, { method: &quot;POST&quot; });<br>  } else {<br>    await fetch(`/l/enable/${linkPath}`, { method: &quot;POST&quot; });<br>  }<br>  await analyticsGenerator();<br>}</pre><p>Twirl, now, displays shorter short links on its home page. 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AAvOah_2ZUb323K3.png" /></figure><p><em>Originally published at </em><a href="https://otee.dev/2022/01/13/making-short-links-shorter.html"><em>https://otee.dev</em></a><em> on January 13, 2022. Link to the original article: </em><a href="https://otee.dev/2022/01/13/making-short-links-shorter.html"><em>https://otee.dev/2022/01/13/making-short-links-shorter.html</em></a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d2637fb329" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/making-short-links-shorter-using-nginx-custom-domain-44d2637fb329">How to Make Short Links Shorter: Using NGINX and  Custom Domain</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>