<?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 KaFai C on Medium]]></title>
        <description><![CDATA[Stories by KaFai C on Medium]]></description>
        <link>https://medium.com/@bruteforcecat?source=rss-e7b68404dfe3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*dZBPP7o1_wXwbL4yImfpdg.png</url>
            <title>Stories by KaFai C on Medium</title>
            <link>https://medium.com/@bruteforcecat?source=rss-e7b68404dfe3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:01:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bruteforcecat/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[Database Lock in Elixir? Why and How? And the Alternative in Elixir]]></title>
            <link>https://medium.com/@bruteforcecat/database-lock-in-elixir-why-and-how-and-the-alternative-in-elixir-6e0581156ee3?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0581156ee3</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 09:17:01 GMT</pubDate>
            <atom:updated>2019-03-18T19:49:27.030Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I got a question in a recent interview about locking in Database. I found that I actually lack insufficient knowledge of this essential part of building a robust application. I would like to share my finding on this topic here.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfOAJYIfkbxZ5SmrMLyJig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/bchywV6UEbE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Barbalis</a> on <a href="https://unsplash.com/search/photos/lock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Why?</p><p><strong>It’s all about race condition.</strong></p><p>A big part of most web applications is used to store some data, probably in a database. Imagine in a simple case of updating a user credit in an online book shop. A user can spend this credit earned by the previous purchase.</p><pre>defmodule BookOrdering do<br>  def purchase_book_with_credit(user_id, book_id) do<br>    with {:ok, book} &lt;- get_book(book),<br>         {:ok, new_user_credt_balance} &lt;- UserCreditBalance.charge(user_id, book) do<br>      publish_event(:purchase_book_with_credit_success)<br>      :ok<br>    end<br>  end<br>end</pre><pre>defmodule UserCreditBalance do<br>  def charge(user_id, book) do<br>    credit_balance = get_credit_balance(user_id)<br>    update_balance(credit_balance, credit_balance.amount - book.cost)<br>  end<br>end</pre><p>For any non-trivial web application, there will be some sort of concurrency supported. And assume we are using the <a href="https://phoenixframework.org/">Phoenix</a> web framework in elixir, each HTTP request will start as a connection process in <a href="https://github.com/ninenines/ranch">Ranch</a>.</p><p>Now image a user open 10 browser windows and press purchase at the same time. What will happen could be treated as spawning multiple processes and calling the purchase_book_with_credit</p><pre>Enum.each(1..10, fn _ -&gt;<br>  spawn(fn -&gt; purchase_book_with_credit(user_id, book_id))<br>end)</pre><p>This will create a possibility of race condition in which the new amount of a user credit might change after it gets read and before it gets committed. This bug-prone pattern could be generalized as read-modify-write.</p><p>Luckily, SQL database provides us lock which disallows two database sessions to update the same data.</p><h3>Pessimistic Locking</h3><h4>Row Level Locking</h4><p>For our above specific example, it could be easily solved by using row-level lock provided in SQL withSELECT FOR UPDATE .</p><p>In Ecto, you could do</p><pre>User |&gt; where(u.id == ^current_user) |&gt; lock(&quot;FOR UPDATE&quot;)</pre><h4>Transaction <strong>Isolation Level</strong></h4><p>Depends on how you structure your code involving an Ecto query, it’s usually unnecessary and decreasing performance(Lock contention) to add a lock for all query.</p><p>In most cases, it will be more suitable to set the transaction isolation level to Repeatable read which looks something like this</p><pre>defmodule UserCreditBalance do<br>  def charge(user_id, book) do<br>    Repo.transaction(fn -&gt;<br>      Repo.query!(&quot;SET TRANSACTION ISOLATION LEVEL REPEATABLE READ&quot;)<br>      credit_balance = get_credit_balance(user_id)<br>      update_balance(credit_balance, credit_balance.amount - book.cost)<br>    end)<br>  end<br>end</pre><p>In this case, the SQL database will abort the update if it detects the row read has been updated and performs a rollback which essentially does the same locking for you.</p><h3>Optimistic Locking</h3><p>The biggest downside of using pessimistic locking is the decrease in performance. In reality, multiple transactions involving the same row can usually be complete with affecting others. In this case, optimistic locking will be a better solution and this will be implemented in application-side and <a href="https://hexdocs.pm/ecto/Ecto.Changeset.html#optimistic_lock">Ecto also provides it</a>.</p><p>And it’s implemented by adding an integer column and a changeset function optimistic_lock and Ecto can use the integer column to check if the data has been changed before committing it.</p><h3>Using Process as an Alternative</h3><p>Although database lock is powerful, they are not the best in performance and it might not able to help if the operation involves other data living outside of SQL database(maybe :ets or an external API).</p><p>For the above example of purchasing a book, we could generalize it as a problem of serializing access to some resources. We could use the power of Erlang process in which the mailbox is received and could be handled synchronously.</p><p>There could be lots of different implementation. My first naive implementation is to spawn a child GenServer work with a unique identifier under a dynamic supervisor and its sole purpose is to take a thunk and execute it synchronously and send the result back to the caller.</p><p>This approach works fine for the above case as we can use user_id as the unique identifier and pass &amp;UserCreditBalance.Charge/1 as a thunk. We can achieve the same lock effect without a database lock. Also, there will not be a <a href="https://severalnines.com/blog/understanding-deadlocks-mysql-postgresql">deadlock</a> problem.</p><p>The downside of it will be using more memory due to copying data created in the worker process to the caller process. Also, if you are running more than one node, the nodes have to be connected and use some kind of global registry to achieve this.</p><p>There is a nicer library written in Erlang called <a href="https://github.com/whitfin/sleeplocks">Sleeplocks</a> which also spawn a process with a unique identifier but the process will only keep the total number of slots, the processes currently holding references to the lock, and a queue of waiting processes trying to acquire a lock. So it avoids the data copying as described in the above naive approach.</p><p>Please let me know what’s your thought on these and comment if there are other better alternatives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0581156ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Processes in BEAM]]></title>
            <link>https://medium.com/@bruteforcecat/understanding-processes-in-beam-e5f2a85e6a43?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5f2a85e6a43</guid>
            <category><![CDATA[beam]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Sat, 02 Mar 2019 23:41:01 GMT</pubDate>
            <atom:updated>2019-03-02T23:41:01.224Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you are been working on Elixir or Erlang, you will not be unfamiliar with processes. They are the most important building block of highly concurrent system in BEAM. We will look into it in this article in order to understand how it make fault-tolerant and scalable.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZhCcr3UYWIwlH_ItofxjQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/VMKBFR6r_jg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Suzanne D. Williams</a> on <a href="https://unsplash.com/search/photos/process?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Process is just memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*qAohrwsR5WdweLBs-jxQzA.png" /><figcaption>A much-simplified illustration of Erlang process. Captured from <a href="https://happi.github.io/theBeamBook/">the BEAM book</a></figcaption></figure><p>A process is a simple C struct which contains 4 main memory area, stack, heap, mailbox and process control block. So spawning a process essentially means creating this struct and an empty heap for dynamic memory allocation.</p><h3>Sending Message</h3><p>Having only isolated execution is not particularly useful if we can’t talk to them. In process in BEAM, they communicate by sending messages.</p><p>Before BEAM support SMP(Symmetrical Multi Processor), there is only scheduler which runs in the main process thread. So sending a message basically means copying data from the sender’s heap to the receiver process heap.</p><p>With SMP, BEAM support multiple schedulers, we can’t simply copy data and write into receiver memory without extra caution. It will need to acquire lock a lock from the receiver process before writing data. When the lock cannot be acquired, it will put data into a heap fragment and move to heap after garbage collection.</p><h3>Preemptive Scheduling</h3><p>One of the nicest features of BEAm is how it executes code. There could be thousands of thousands process in BEAM, a scheduler is responsible for picking a process from run queue. A preemptive scheduler has the power to preempt execution and resume them at a later time when reduction(including like function calls, garbage collecting in the heap, sending message) exceeds the maximum number.</p><p>This gives all the process a fair share of execution time. And in practice, it means that the system will still be responsive mostly even there is heavy computation or even an infinite loop happen in some processes which are important to build a responsive, realtime system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5f2a85e6a43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Doesn’t Vector Exist in Elixir Natively?]]></title>
            <link>https://medium.com/@bruteforcecat/why-doesnt-vector-exist-in-elixir-natively-b0aff4b51630?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0aff4b51630</guid>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 08:57:42 GMT</pubDate>
            <atom:updated>2019-02-12T00:44:04.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Is Vector Not Used in Elixir?</h3><p>A Vector(array with adjustable size) is a collection of values indexed by contiguous integers and it is a very commonly used collection data structure in most languages. However, it’s not available natively in Elixir.</p><p>Let’s have a brief understanding of List first.</p><h4>List</h4><p>The most commonly used data structure in Elixir is a list, more specifically singled-linked list. In fact, the list is heavily used in almost all functional programming languages because of its simple definition. A linked-list consist of a head and a tail which is also a list with a special case of an empty list. When you write [1,2,3,4] , what happens under the hood is [1|[2|[3|[4]]]] . The only required operator | is called <strong>cons</strong>.</p><p>In a language supporting Algebraic data type, it’s easy to write single linked-list in a concise way.</p><p>data List a = Nil | Cons a (List a) # in Haskell</p><p>List is super efficient for any operation on the first element, O(1). The recursive nature of list works really well with functional programming as recursion is our counterpart, loop construct, in the imperative programming world.</p><p>It also works well with pattern matching.</p><pre>[x | xs] = [1,2,3] # x =&gt; 1, xs =&gt; [2,3]<br>[x1, x2 | xs] = [1,2] # x1 =&gt; 1, x2 =&gt; 2, xs = []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-A-HyzdVdQBHQ6tAJoxgDg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/KraXdvWzKNw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thomas Tucker</a> on <a href="https://unsplash.com/search/photos/sequence?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Vector</h4><p>There is no Elixir native Vector but we could still use the <a href="https://github.com/erlang/otp/blob/maint/lib/stdlib/src/array.erl">array</a> existed in Erlang. Array in Erlang can be resized so they are basically Vector.</p><p>In general, vector provides efficient random access by index, O(1) and smaller memory footprint in heap and faster traversal.</p><p>However, the benefit above is not the case in Erlang/Elixir. All data structure is immutable in Elixir. To achieve this, array is implemented using a tree structure to build a nested tuple. To update an element in the array, we have to copy the entire tuple(using :erlang.setelement/3 )in the node that the element belongs. It uses a tree with leaf size 10 to have a balance between write and read performance. Therefore, we dun have the performance boost as an array/vector in an imperative world.</p><h4>So what can we do if we want random access to a collection?</h4><p>If your data size is small and fixed, a tuple is usually more suitable to be used in Elixir.</p><p>If you do need to have a large collection with indexed access, you can use Map with an integer as key and you can also use all enumerable function as Map implemented Enumerable protocol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0aff4b51630" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Cryptography for Web Developer — Ep. 2— Symmetric Encryption]]></title>
            <link>https://medium.com/@bruteforcecat/learning-cryptography-for-web-developer-ep-2-symmetric-encryption-cc9edeef38c1?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9edeef38c1</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[cipher]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Sat, 09 Feb 2019 09:38:30 GMT</pubDate>
            <atom:updated>2019-02-09T09:38:30.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning Cryptography for Web Developer — Ep. 2— Symmetric Encryption</h3><p>Encryption consists of two components, an algorithm(cipher) and a secret value(key). The term symmetric means the key used for encryption and decryption is the same. They can be represented by mathematical-like notation as follow:</p><p>C = E(P, K)</p><p>P = D(C, K)</p><p>P = D(E(P, K), K) where P is plaintext, K is the key, C is the ciphertext, E is the encryption function and D is decryption function.</p><h4>SUBSTITUTION CIPHERS</h4><p>One of the most famous and simple ones is the Caeser Cipher. It basically works by substituting the original letter are replaced with other letters based on some rules. There is also transposition which only changes the order of characters.</p><p><em>A simple Haskell implementation is written below. (only work for lower-case)</em></p><pre>module CaesarCipher (encrypt, decrypt) where</pre><pre>import Data.Char</pre><pre>type SecretKey = Int</pre><pre>charToNum :: Char -&gt; Int<br>charToNum c = ord c - ord &#39;a&#39;</pre><pre>numToChar :: Int -&gt; Char<br>numToChar n = chr (ord &#39;a&#39; + n)</pre><pre>shift :: Int -&gt; Char -&gt; Char<br>shift n c = numToChar $ (charToNum c + n) `mod` 26</pre><pre>encrypt :: SecretKey -&gt; String -&gt; String<br>encrypt n xs = [shift n x | x &lt;- xs]</pre><pre>decrypt :: SecretKey -&gt; String -&gt; String<br>decrypt = encrypt . negate</pre><p>It’s totally feasible to crack it just by brute-force which only takes you 26 iteration. You also can use frequency analysis to find the key that produces the result closest to the frequency distribution of English alphabet using like <a href="https://en.wikipedia.org/wiki/Chi-squared_test">Chi-squared test</a>.</p><p>A modified version is called Vigenère Cipher. And it could be implemented as(<em>(only work for lower-case)</em></p><pre>module VigenereCipher (encrypt, decrypt) where</pre><pre>import Data.Char</pre><pre>type SecretKey = String</pre><pre>charToNum :: Char -&gt; Int<br>charToNum c = ord c - ord &#39;a&#39;</pre><pre>numToChar :: Int -&gt; Char<br>numToChar n = chr (ord &#39;a&#39; + n)</pre><pre>shift :: (Int -&gt; Int -&gt; Int) -&gt; Char -&gt; Char -&gt; Char<br>shift op offsetChar ch = numToChar $ flip mod 26 $ (charToNum ch) `op` (charToNum offsetChar)</pre><pre>encrypt :: SecretKey -&gt; String -&gt; String<br>encrypt secret = zipWith (shift (+)) (cycle secret)</pre><pre>decrypt :: SecretKey -&gt; String -&gt; String<br>decrypt secret = zipWith (shift (-)) (cycle secret)</pre><p>Vigenère Cipher is slightly secure. It requires much more permutation to see the pattern between ciphertext and plaintext.</p><p>If the key is <em>N</em> letters long, then <em>N</em> different permutations will be used for every <em>N</em> consecutive letters. However, this can still result in patterns in the ciphertext because every <em>N</em>th letter of the message uses the same permutation. That’s why frequency analysis works to break the Vigenère cipher, as you saw earlier.</p><p>However, if the secret key is as long as the plaintext and non-repeating and only used one time, the ciphertext will appear like random to the attacker because there is no way to see any pattern from the ciphertext by Frequency analysis. This approach is called one-time pad. It’s not practical in most use case as it requires the secret key to be as long as the plaintext.</p><p>Now we have a brief idea of how symmetric encryption work. We will explore one-way hashing which is very useful and appears everywhere in our web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9edeef38c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Cryptography for Web Developer — Ep. 1 — HTTPS]]></title>
            <link>https://medium.com/@bruteforcecat/learning-cryptography-for-web-developer-ep-1-https-62d59c17488e?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d59c17488e</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 08:50:57 GMT</pubDate>
            <atom:updated>2019-02-09T09:39:31.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning Cryptography for Web Developer — Ep. 1 — HTTPS</h3><p>Cryptography is essential in making our Internet secure and private. Its usages are all over the places, like online payment, messaging, digital signature and the hottest topic, cryptocurrency or better called as decentralized ledger technology.</p><p>Even though I have been coding professionally for more than 4 years, I am an absolute noob in cryptography and yet I decided to start learning it on a regular basis and will start this blogging series. Hopefully, it could be helpful for others, especially web developers. And the first episode will be about HTTPS.</p><h4>TCP/IP Networking 101</h4><p>In our web development, we will have our server that responds to request coming through the network. Those requests are usually HTTP protocol(other application protocols like SMTP, IMAP, FTP etc). The process could be simplified as follow</p><ol><li>Get target IP address by asking DNS</li><li>OS creates a socket connection with the remote server by TCP Handshake</li><li>Sending the actual HTTP request after TCP connection established</li></ol><p>A more important question here is how does the data get sent to the desired target IP address?</p><p>First, all data will be divided into packets(binary format). The packet will have its own standard structure like header, body so the receiver can understand when &amp; how to extract and merge them into a complete data. The communication path between two computers is usually not direct and they usually have to be relayed through routers.</p><pre>traceroute medium.com # you can see what gateway the packet has to go through before going to Medium server</pre><p>The advantage of sending data in packets is to enable the Internet to be able to scale well efficiently. (think about if we send the whole file in one gigantic packet and if it’s lost/corrupted during the relay and then we have to send the whole again). And all packets are equal thanks to the <a href="https://en.wikipedia.org/wiki/Net_neutrality">net neutrality</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oj3nGCJahBrkzFTUeeyDkQ.jpeg" /></figure><p>TCP/IP itself is not a secure transport protocol. It has to be implemented in the application protocol layer. And the most used application protocol HTTP is also not secure (plain text) by default. The packets sent through the Internet can be read by lots of people, like packet-sniffing in a local WIFI network.</p><p>Let’s think about how to solve it?</p><h4>Symmetric Encryption</h4><p>An easy solution might introduce symmetric encryption which means the encryption and description are both done with the same key. However, another question is how these two parties agree on the key used for encryption?</p><h4>Asymmetric Encryption</h4><p>To avoid coming to an agreement on the same key, we can use asymmetric encryption in which we have two keys which are mathematically linked, one for encryption and another for decryption.</p><p>So theoretically, the client can always use server public key to encrypt request and server use client public key to encrypt the response. And the attacker cannot decrypt it because of only server and client has their own private key. But in practice, asymmetric encryption is computation heavy and thus slow down the communication.</p><p>So in HTTPS, we use <strong>both</strong> of them.</p><h4>HTTPS = HTTP + TLS/SSL</h4><p>And the simplified HTTPS flow is as follow</p><ol><li>The client sends a “Client Hello” message containing max SSL supported version, cipher suites and some random string that’s used later the server respond with a similar message.</li><li>The server responds with “Server Hello” that containing the public key of the server</li><li>The client sends an encrypted message using the server public key containing symmetric encryption algorithm and a symmetric key to the server</li><li>Continue using an agreed symmetric key.</li></ol><p>However, here we have another problem which is how could client be sure that the public key obtained is actually from the server but not attackers? To secure that, we need a third party that ensures the public key actually belongs to the domain we are requesting. So in step 2, the server will actually send with an SSL/TLS certificate that contains the Certificate Authority(CA), digital signature owner name, domain along with the public key. And the browser will verify it with CAs.</p><p>In the following series, I will go deeper to look into some basic building block on cryptography like pseudo-random number generator, hashing, detail of symmetric encryption etc.</p><p>Check out <a href="https://medium.com/@bruteforcecat/learning-cryptography-for-web-developer-ep-2-symmetric-encryption-cc9edeef38c1">Ep. 2 — Symmetric Encryption</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d59c17488e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do we choose Elixir/Erlang]]></title>
            <link>https://medium.com/@bruteforcecat/why-do-we-choose-elixir-erlang-a6ef065dae3c?source=rss-e7b68404dfe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ef065dae3c</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[erlang]]></category>
            <dc:creator><![CDATA[KaFai C]]></dc:creator>
            <pubDate>Sat, 03 Nov 2018 00:56:52 GMT</pubDate>
            <atom:updated>2018-11-09T10:13:40.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency, Intentional Programming Style</p><h4>Concurrency</h4><p>In Erlang, we use message passing concurrency model. There is no shared memory between each Erlang process and they communicate each other by sending Erlang term to another mailbox. And because there is an only immutable data structure in Erlang. We don’t need to avoid about state get mutated by another process.</p><p>In Erlang, a process is like an object in OOP. The creator of Erlang even once said Erlang is the <a href="https://soundcloud.com/elixirfountain/elixir-fountain-2016-01-08-joe-armstrong">most object-oriented programming language</a>. They are very lightweight and used extensively.</p><p>And with OTP framework which provides lots of common abstraction like GenSever which provide common behavior of client-server communication(synchronous &amp; asynchronous), process name registration and so on. These are very nice tools for you to deal with runtime concurrency concern.</p><p>In Erlang VM, it treats the recipient process of the local node and remote connected node the same. So it leads to the fact Erlang/Elixir is very good at being distributed.</p><h4>Intentional Programming Style</h4><p>In Elixir/Erlang, we don’t write defensive code. Instead, we deliberately express our intention by lines of codes. For example,</p><pre>{:ok, client} <strong>=</strong> :gen_tcp<strong>.</strong>accept(socket)</pre><p>First, it’s not a typical assignment like other mainstream languages. It’s called pattern matching. and it binds the value to the variable if there is valid pattern got matched. However, when the pattern is not matched(maybe, :gen_tcp.accept(socket) return {:error, :closed} ), a MatchError will be raised and the process will crash.</p><p>This might sounds scary to you. However, process crashing is super common in daily Erlang/Elixir program. That’s because, in most elixir application, a fault tolerant mechanism called OTP will be used. And the core idea is to always have supervisor process which solely principle is to monitor and restart children process once they exit. This guarantee the program itself will still continue to run normally.</p><p>The benefit of it is to have clean code with strong intent. Comparing to normal Java/Javascript program, you rarely see try catch and if x !== null these kind of code.</p><h4>And much more</h4><p>There are, of course, much more good thing in Erlang like</p><ol><li>Typespec. A way to declare a type for data and function and along with dialyzer which is a type checker. It provides a fairly good enough type-checking to prevent some bugs in runtime earlier.</li><li>Erlang Release. It’s a package of BEAM bytecode and usually, it also contains Erlang runtime(ERTS) which means it’s “almost” completely self-contained. And with docker, we can have repeatable deployment and avoid the difference of build target.</li><li>Remote Shell. You can easily have REPL on the running production system and you can even compile and inject some modules in a running system. This is super useful when we find some bug that&#39;s hard to be reproduced in local. That’s all because of the nature of “Very late binding” in Erlang.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ef065dae3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>