<?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 Melodies Sim on Medium]]></title>
        <description><![CDATA[Stories by Melodies Sim on Medium]]></description>
        <link>https://medium.com/@melodiessim98?source=rss-6858c678cde5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HvdsKRxQWgup0NHGWY7pCA.jpeg</url>
            <title>Stories by Melodies Sim on Medium</title>
            <link>https://medium.com/@melodiessim98?source=rss-6858c678cde5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:57:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@melodiessim98/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[Deep Dive into Remote Procedural Calls (RPC)]]></title>
            <link>https://levelup.gitconnected.com/deep-dive-into-remote-procedural-calls-rpc-41d72fb98293?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d72fb98293</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Sun, 23 May 2021 22:51:26 GMT</pubDate>
            <atom:updated>2021-05-23T22:51:26.989Z</atom:updated>
            <content:encoded><![CDATA[<h4>The goal of using RPC is to make communication between the client and server seem like a regular procedural call.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vYbH8r3gaeF_uzcN" /><figcaption>Photo by <a href="https://unsplash.com/@lemonvlad?utm_source=medium&amp;utm_medium=referral">Vladislav Klapin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was first introduced to <strong>R</strong>emote <strong>P</strong>rocedural <strong>C</strong>all (RPC) while working on a software engineering entry task back in December. I soon learned that RPC is an essential component employed in many of my company’s distributed infrastructures. As a new intern, I didn’t fully understand the benefits RPC brings to the table. I was just contented to finish up my entry task and start working on my internship project.</p><p>If you are in the same boat as me, let me try to explain what RPC is. RPC is a <strong>layer of abstraction that enables easy-to-program communication between a client and server</strong>. With RPC, messy details of network protocols are encapsulated and hidden away. It is no secret that RPC holds a major role in distributed systems today.</p><p>In writing this short article, I hope to provide some intuitions behind RPC, something I wished I could appreciate more when I was implementing my entry task back then. I will also discuss some edge cases in the event of network and server failures, and general techniques that can be used to deal with such failures.</p><blockquote>This article is the second post of the Deep Dive into Distributed System Series, which seeks to dig deeper into common concepts or mechanics used in distributed systems. Check out the first post here.</blockquote><p><a href="https://levelup.gitconnected.com/deep-dive-into-primary-secondary-replication-for-fault-tolerance-6ba203b06901">Deep Dive into Primary/Secondary Replication for Fault Tolerance</a></p><h3>Role of RPC in Client-Server Architectures</h3><p>To understand how RPC plays its role as a key piece of distributed system machinery, we have to examine the goals of RPC and the context where RPC is needed. RPC is used mainly in the client-server model as a layer of abstraction to simplify the inter-communication between clients and servers.</p><p>In many distributed systems, the client-server model is used to partition workloads between providers of a service called servers and service requesters called clients [1]. Often clients and servers communicate over a computer network on separate hardware, but both client and server may reside in the same machine [1]. A client usually initiates communication services with servers, which await incoming requests. For example in a web application, clients refer to the front-end which the users directly interact with, and servers refer to the backend that processes requests and returns the result to the client processes.</p><p>The goal of RPC is to make communication between the client and server seem like a regular procedural call. From the client’s point of view, RPC abstracts away the details of making network calls, and of parsing requests and responses, making it seems that the client is just calling a regular function to process the request. This simplifies things for the client — the client can focus on the main logic of the app and leave the details to the RPC library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NfK1qAImR8dx3-Hi__2q1Q.png" /><figcaption>Structure of how RPC is used in client-server communication.</figcaption></figure><p>As seen in the Figure above, a client will call stub functions (that seem like another regular function), which contains calls to the RPC library. The RPC library marshals the requests and sends them over the network to the server. The request is received and unmarshalled by the RPC library before getting dispatched to the respective handler function in the server. After the handler functions generate the desired result, the RPC library marshalls the result into a response which is sent back to the client for unmarshalling. The client will receive the result as a return value of the stub function that was initially called.</p><h3>Edge Cases: How to Deal with Failures</h3><p>Distributed systems typically involve tens to thousands of machines. Failures are inevitable. We have to deal with failures to provide a robust and available service. Some of the most common forms of failure include lost packets, broken network communication, slow or crashed servers.</p><h4>What does a failure look like to the Client RPC library?</h4><p>However, it is rarely straightforward to detect what failures have occurred. Let’s consider how a failure will look like from the client RPC’s perspective. Here’s we list a few possible scenarios that could happen in event of failures:</p><ul><li>The client never sees a response from the server.</li><li>The client does <em>*not*</em> know if the server saw the request!</li><li>Maybe the server never saw the request.</li><li>Maybe the server executed but crashed just before sending a reply.</li><li>Maybe the server executed, but the network died just before delivering the reply.</li></ul><p>The figure below depicts three failure scenarios where the client does not receive a response and is unable to distinguish between the three failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZmOAO-yTFibhodZ47z6ifg.png" /><figcaption>All three scenarios above are indistinguishable from the client’s perspective — the client did not receive a response in any of the three cases.</figcaption></figure><h4>Handling Failures in RPC</h4><p>The simplest way to handle failures is using a “Best-Effort” approach where the client will retry several times before giving up. For example, let’s consider a client executes a Get(key) command in a simple key-value store (server):</p><ol><li>Get(key) will wait for a response for a pre-defined timeout period.</li><li>If no response is received after the timeout, re-send the request.</li><li>Repeat this a few times.</li><li>Give up and return an error to the client.</li></ol><p>However, as some of you can tell, the best-effort approach is not the best (pun intended). It can sometimes even cause serious problems in some applications. Consider the case when the same client tries to execute 2 different Put(key, value) commands:</p><ul><li>Put(5, 10)</li><li>Put(5, 20) — run shortly after Put(5,10)</li></ul><p>What will Get(5) yield? Depending on the network conditions and packet delay, even though Put(5,20) is executed by the client after Put(5,10), it is still possible to yield a value of 10 from Get(5). Can you see why?</p><p>For operations that are not idempotent (i.e. applying the operations more than once will result in a different result), the best-effort approach can also lead to unexpected results. For example, addition is not an idempotent operation because if Add(1) is executed twice to a variable of initial value 0, we will get 2, instead of 1 when Add(1) is executed only once. In contrast, an idempotent operation would be Put(5, 5) because executing it twice will result in the same result as executing it only once. Suppose that a client retries to execute an Add(1) command after a timeout, however, the first Add(1) command arrives at the server after the timeout. The state will be 2, instead of the expected 1.</p><p>Depending on the business requirements of the service, these behaviors may not be acceptable. A better way to handle failure is the “at most once” scheme. The idea is that the server will detect duplicate requests using unique IDs and return the previous reply instead of re-running the handler function. This means that non-idempotent operations will be executed at most once, avoiding the problem described above.</p><p>How about an “exactly-once” scheme where we can guarantee that every request sent is executed only once eventually? This is the ideal case but it is more complicated to implement in practice. The intuition behind such a scheme would be to use unbounded retries with duplicate detection. A fault-tolerant system is also required to ensure that no requests are lost due to server crashes.</p><h3>References</h3><p>[1] Client-server model — Wikipedia <a href="https://en.wikipedia.org/wiki/Client%E2%80%93server_model">https://en.wikipedia.org/wiki/Client%E2%80%93server_model</a></p><p>[2] MIT 6.824 RPC and Threads Note <a href="https://pdos.csail.mit.edu/6.824/notes/l-rpc.txt">https://pdos.csail.mit.edu/6.824/notes/l-rpc.txt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d72fb98293" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deep-dive-into-remote-procedural-calls-rpc-41d72fb98293">Deep Dive into Remote Procedural Calls (RPC)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Understanding of FLP Impossibility for Distributed Consensus]]></title>
            <link>https://levelup.gitconnected.com/practical-understanding-of-flp-impossibility-for-distributed-consensus-8886e73cdfe5?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8886e73cdfe5</guid>
            <category><![CDATA[flp]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[system]]></category>
            <category><![CDATA[consensus]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Sun, 09 May 2021 16:48:06 GMT</pubDate>
            <atom:updated>2021-05-09T16:48:06.653Z</atom:updated>
            <content:encoded><![CDATA[<h4>How are distributed consensus algorithms such as Raft implemented in the real world despite the FLP Theorem?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ObDdJ6rettKdDLdR" /><figcaption>Photo by <a href="https://unsplash.com/@guilhermevt?utm_source=medium&amp;utm_medium=referral">Guilherme Teixeira</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>FLP (<strong>F</strong>ischer, <strong>L</strong>ynch, and <strong>P</strong>aterson) Impossibility is one of the most fundamental results in distributed systems and has been taught in many Computing undergraduate courses. Given the scale of data and computation, distributed systems (scaling services with more machines) are essentially the default pattern used to build scalable system infrastructures today. Distributed consensus becomes crucial as the machines need to agree upon a consistent state to provide a coherent service.</p><p>The FLP theorem answers the following fundamental question on consensus:</p><p><em>In an asynchronous distributed system, is there a deterministic consensus algorithm that can satisfy agreement, validity, termination, and fault tolerance?</em></p><p>As the “Impossibility” term in the theorem suggests, Fisher, Lynch, and Paterson have shown that it is impossible to implement consensus algorithms that tolerate even a single node fault.</p><p>Given that existing consensus algorithms such as Raft and Zookeeper are commonly in use today in large distributed systems where node failures are not only common but expected to occur, the FLP result can be counterintuitive and even confusing. I too faced this disconnect between the theoretical FLP result and real-world consensus algorithms when learning about Raft. Writing this article I hope to shed light on</p><ul><li><strong>Practical perspectives of the FLP Theorem</strong> in the context of real-world systems.</li><li>How industry-recognized consensus algorithms such as Raft overcome the FLP Impossibility result.</li></ul><h3>Problems synonymous to Distributed Consensus</h3><p>So why are we concerned about the distributed consensus problem? In a distributed system, the different machines (nodes) often need to maintain some form of agreement on the state. In fact, distributed consensus comes in many forms — <strong>it is unavoidable in distributed systems to face one of these variants of consensus</strong>. Examples of problems that have been shown to be synonymous with consensus are:</p><ol><li>Leader election (Used to elect a node to become the leader/primary node e.g. in Raft)</li><li>Shared logs (in replicated log systems)</li><li>Atomic broadcast (e.g. primary node will broadcast operations to secondary nodes in primary/secondary replication)</li></ol><p>To learn more about primary/secondary replication, do check out:</p><p><a href="https://levelup.gitconnected.com/deep-dive-into-primary-secondary-replication-for-fault-tolerance-6ba203b06901">Deep Dive into Primary/Secondary Replication for Fault Tolerance</a></p><h3>Understanding the FLP Impossibility Theorem</h3><p>Before we can reframe the FLP theorem in practical lenses, we have to first understand the claims of the Impossibility Theorem and the context in which the Theorem is set in.</p><h4>Asynchronous Network Model</h4><p>The most basic prerequisite of the FLP impossibility theorem is the asynchronous network model. What are the characteristics of the asynchronous model how does it differ from the synchronous model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WruxCKFMJYxJihxxqwe2nA.png" /><figcaption>Under the asynchronous network model, we do not have accurate node failure detection.</figcaption></figure><p>In an asynchronous model, the message propagation delay from one node to another node is finite but unbounded. This means that if a node does not receive messages, it cannot judge exactly whether the sender node has crashed or that the message just got delayed. In other words, we cannot determine exactly whether a node has crashed or not based on timeout mechanisms. In contrast, in synchronous network models, message delays are bounded and node crashes can be reliably detected.</p><p>Under asynchronous network settings, the FLP theorem additionally assumes i) message channels do not drop messages ii) non-byzantine failures (there are no malicious parties).</p><h4>The Impossibility Triangle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpruNi4VAg4-UvNm6FatMw.png" /><figcaption>FLP theorem: We cannot have all three properties at the same time under the asynchronous network model.</figcaption></figure><p>Under the asynchronous network model, the FLP theorem claims that we cannot achieve all 3 properties of Termination, Agreement, and Fault Tolerance. We describe the three properties as follows:</p><ol><li>Termination (Liveness): All nodes (that have not failed) eventually decide.</li><li>Agreement (Safety): All nodes (even nodes that have failed after deciding) that decide should decide on the same value. If all nodes have the same initial input, that value should be the only possible decision value.</li><li>Fault Tolerance: All nodes require that a protocol must also effective in case of node failures.</li></ol><p><strong>Note that the FLP Theorem does NOT claim that:</strong></p><ul><li>Distributed consensus is impossible in general.</li><li>We cannot have any of the three properties listed above. In fact, Raft has shown that we can have both Agreement and Fault Tolerance, but not Termination.</li></ul><p><strong>Instead, FLP Theorem claims that:</strong></p><ul><li>We cannot have all three properties at the same time under the asynchronous network model.</li><li>Particularly under the synchronous network model (where message delays are bounded), there exists an algorithm that satisfies all three desired properties.</li></ul><p><strong>THE IMPLICATION: </strong>In the real world, we can <strong>make sacrifices (one of the three properties) or relax constraints (e.g. on the asynchronous model) </strong>to come up with a consensus algorithm that meets business needs. We will discuss how modern consensus algorithms make these tradeoffs in the next section.</p><h3>Cross-examining constraints in real-world systems</h3><p>Now that we understand what the FLP Theorem is claiming, we can finally put our practical lens on and examine how we can apply this knowledge to real-world systems! In the previous section, we have seen that we can often relax the constraints of the asynchronous model. The Table below cross-examines the constraints made by the asynchronous model with real-world distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xGwQlXGV5CVVJUTxI8eNxw.png" /><figcaption>The real-world system supports a partially synchronous network model, where failures can be quite reliably detected via timeout mechanisms.</figcaption></figure><p>Interestingly, in the real world, we often have a more relaxed version of the asynchronous model where failures can be adequately detected via timeout mechanisms. The pre-determined timeout thus acts as a user-configurable bound on message delays in this partially synchronous network model.</p><p>Furthermore, in practice, consensus algorithms often choose to sacrifice one of the three properties of the impossibility triangle. In a distributed system, node failures are almost inevitable. Therefore, fault tolerance must be taken into consideration. The FLP impossibility means that any consensus protocol can only have either termination or agreement property in addition to fault tolerance.</p><p>Raft, for example, sacrifices termination to achieve fault tolerance and agreement properties (in theory, it is possible for Raft’s leader election to undergo split votes infinitely many times, thus never terminate). To reduce the odds of the protocol not terminating and thus not making progress, Raft makes use of randomized election timeouts. In fact, randomized algorithms are common strategies in many consensus algorithms.</p><p>In conclusion, we have seen that in practice we can relax the constraints made by the FLP Theorem, as well as sacrifice either agreement or termination to achieve distributed consensus that meets our business needs.</p><p>If you are interested in learning more about large distributed systems, check out some of my previous posts here:</p><ul><li><a href="https://levelup.gitconnected.com/the-google-file-system-the-distributed-file-system-that-google-built-68463670ac57">The Google File System: the distributed file system that Google built</a></li><li><a href="https://levelup.gitconnected.com/lessons-learnt-from-scaling-memcached-in-production-86778ab616c7">Lessons Learnt from Scaling Memcached in Production</a></li><li><a href="https://levelup.gitconnected.com/paper-summary-mapreduce-simplified-data-processing-on-large-clusters-58dac068462e">MapReduce: Simplified Data Processing on Large Clusters</a></li></ul><h3>References</h3><p>[1] <a href="http://www.cs.cornell.edu/courses/cs6410/2016fa/slides/18-distributed-systems-flp.pdf">http://www.cs.cornell.edu/courses/cs6410/2016fa/slides/18-distributed-systems-flp.pdf</a></p><p>[2] <a href="https://www.alibabacloud.com/blog/from-distributed-consensus-algorithms-to-the-blockchain-consensus-mechanism_595315">https://www.alibabacloud.com/blog/from-distributed-consensus-algorithms-to-the-blockchain-consensus-mechanism_595315</a></p><p>[3] <a href="https://medium.com/pyrofex/on-flp-impossibility-c0280bb965da">https://medium.com/pyrofex/on-flp-impossibility-c0280bb965da</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8886e73cdfe5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/practical-understanding-of-flp-impossibility-for-distributed-consensus-8886e73cdfe5">Practical Understanding of FLP Impossibility for Distributed Consensus</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Primary/Secondary Replication for Fault Tolerance]]></title>
            <link>https://levelup.gitconnected.com/deep-dive-into-primary-secondary-replication-for-fault-tolerance-6ba203b06901?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ba203b06901</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 03:49:03 GMT</pubDate>
            <atom:updated>2021-04-27T03:49:03.957Z</atom:updated>
            <content:encoded><![CDATA[<h4>Do you really understand how replication works?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g_EUBKsdeUyrifrI" /><figcaption>Photo by <a href="https://unsplash.com/@arstyy?utm_source=medium&amp;utm_medium=referral">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why should you care about replication?</h3><p>A very common tradeoff pattern in distributed systems today is presented as follows: to scale up services and achieve high performance, a common strategy used is to shard data horizontally across many servers. Having many servers mean the probability of failures has increased proportionately, and we can no longer avoid failures. The only thing we can do is to make sure that we are well-prepared for them. To achieve this fault tolerance, companies deploy replication as a key strategy to provide high availability of the data.</p><h3>Why should you read this article?</h3><p>While replication may seem deceivingly straightforward (just replicating the states in different servers), various considerations have to be taken before implementing replication in production. For example, how can we detect when a server fails, and how a replacement server can be quickly warmed up to take over the failed server.</p><p><strong>This article aims to provide readers with:</strong></p><ol><li>A deep understanding of replication.</li><li>High-level considerations of implementing replication in production.</li><li>Typical strategies employed in industries today.</li></ol><h3>What is Primary/Secondary Replication?</h3><p>Primary/secondary (P/S) replication is one of the 2 main forms of replication, where the primary replica typically relays the operations to secondary replicas, ensuring that operations are performed in the same order. The other form of replication is when all replicas have the same weight (i.e. there is no primary/leader replica).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yln7Rc8wHhqps2vVe6Ko8w.png" /><figcaption>Figure 1: Two use cases of primary/secondary replication: 1) Primary/Backup replication and 2) Replication with a coordinator.</figcaption></figure><p>In Figure 1, we describe two use cases of P/S replication.</p><ol><li><strong>Primary/Backup</strong> <strong>Replication</strong>: Primary replica handles all client requests and directly responds to the client. The primary replica forwards the client requests or the new state to the secondary replica to keep the secondary in sync. Here, the secondary replica acts more like a backup and assumes the primary role only when the primary replica fails.</li><li><strong>Replication with a coordinator: </strong>The primary replica acts as a coordinator and its main role is to ensure that the states in all replicas are in sync. For operations that alter the state, the primary replica will make sure the operations are replayed in all replicas in the same order. For operations that do not alter the state, the client can request from any replica.</li></ol><p>As alluded above, to replicate states we can either i) transfer the entire state over from primary to secondary replicas each time the state is changed or ii) take a replicated state machine approach where we only relay the operations that lead to the state change. It is clear that if the state is very big, transferring the entire state is very inefficient. In fact, most industry solutions today implement the replicated state machine approach precisely because of this reason.</p><h4>Replicated State Machine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Bopm-RBew6JJhMxFBhjJ9g.png" /><figcaption>Figure 2: A replicated state machine. Given that all replicas start from the same state, and perform only deterministic operations in the same order, we can expect all replicas have the same end state.</figcaption></figure><p>In a replicated state machine approach, we do not transfer the whole state, but only relay the operations that lead to the state change. The intuition behind the replicated state machine approach is that systems can often be modeled as deterministic state machines. If two deterministic state machines start in the same initial state and provide the same inputs in the same order, then they will go through the same sequence of states and produce the same outputs.</p><p>In a replicated state machine, clients send write operations to the primary replica which will sequence and send the operations to all secondary replicas in the same order. All replicas will then execute the operations. Given that all replicas start from the same state, and perform only deterministic operations in the same order, we can expect all replicas to be in sync with the same end state.</p><h3>Big questions to think about replication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FC-fqhhSrK9Cx1C1" /><figcaption>Photo by <a href="https://unsplash.com/@earbiscuits?utm_source=medium&amp;utm_medium=referral">Juan Rumimpunu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Implementing replication in a distributed system is challenging especially if we do not have a single coordinator to make the decisions. Even with a coordinator, we must be prepared to deal with the failure of the coordinator and not let this be a single point of failure. The main difficulties lies in:</p><ol><li><strong>Dealing with the loss of communication</strong>: How to deal with a temporary loss in communication resulting in errors such as TCP timeout, or even permanent ones such as a network partition?</li><li><strong>Dealing with the lack of accurate failure detection</strong>: In asynchronous distributed systems, there is no upper bound to the message delays. Thus, it is impossible to differentiate whether the server has failed or that the message simply hasn’t arrived. It is also difficult to differentiate between a server failure and network partition (servers that were originally connected to each other, now lose communication and believe each other has crashed).</li></ol><p>We will list some of the fine-tuned questions that need to be answered before implementing replication to provide high availability for our services in production. Subsequently, we will discuss a few of these questions in the context of large distributed systems deployed in the industries today.</p><ol><li>At what level do we want replicas to be identical?</li><li>Does the primary replica need to wait for the secondary replica to complete its operations before replying to the client?</li><li>How do we detect failures and perform a fast failover to a secondary replica?</li><li>If a secondary replica fails, how do we quickly warm up a replacement?</li><li>How can we deal with a split-brain situation where the primary and secondary replicas lose communication?</li><li>We assume that we can model our system as a deterministic state machine. How do we deal with non-deterministic operations such as generating timestamps?</li></ol><h4>At what level do we want replicas to be identical?</h4><p>We have to decide at which level do we want to replicate. The most common way is to replicate at the application-level state. For example, for a distributed database like SQL, we replicate the database’s tables. This is often more efficient because the primary replica only sends application-level operations to the secondary replicas. However, this also means that the application code in the servers often has to be modified and have to understand how fault tolerance is implemented. For example in distributed SQL databases, the primary server writes the operations to the Binlog and behaves differently from the secondary servers.</p><p>An alternative (not commonly employed) approach is to replicate the state at the machine level i.e. replicate the registers and RAM content. This allows us to replicate any existing server without modification to the application-level code! In fact, this is how VMware vSphere 4.0 implements its replication scheme [1]. However, the biggest downside to this approach is that this requires the forwarding of machine events such as interrupts, and thus may require machine-level modifications.</p><h4>Does the primary replica need to wait for the secondary replicas to complete their operations to respond to the client?</h4><p>We know previously that primary replicas will forward a sequence of operations to the secondary replicas. However, sometimes, secondary replicas may fail to execute the operations and be left in a different state from the primary replica. A simple solution implemented by Google File System (GFS)[2] is for secondary replicas to send back a success status to the primary after executing the operations. If the primary does not hear from at least one of the secondary replicas, it will ask the client to retry the operation. However, this will result in the inconsistency of replicas even with retries if the operations are not idempotent. While one replica may fail to execute, other replicas could be successful in the write operation, leading to diverging states. Note that for the GFS use case, such inconsistency is acceptable and mitigated by application-level checks.</p><p>Another solution to this problem is to use a two-phase commit, where the secondary replicas have to send an acknowledgment to the primary replica that it is ready to execute. Only when all replicas have replied to the primary will all replicas execute the operations at the same time.</p><h4>How do we detect failures and perform a fast failover to the secondary replica?</h4><p>One common strategy to detect failures is to send regular heartbeat messages between the primary and secondary servers. If a heartbeat message is not received by a fixed time period, the server is declared to have failed. If the primary replica has been detected to fail, one of the secondary replicas will become the new primary.</p><h4>How can we deal with a split-brain situation where the primary and secondary replicas lose communication?</h4><p>We can anticipate a problem that arises with using heartbeat to detect failures. An absence of a heartbeat message can be indicative that a server has failed, but it can also be caused by a network partition or loss of connection between the primary and secondary replicas. If a network partition occurred, the secondary replica may become mistaken that the primary has failed (when it hasn’t and is still actively handling client requests), and prematurely assume the primary role. Now, we have two primary servers handling client requests and relaying the operations to secondary replicas. This is known as the split-brain problem and will lead to diverging states in the replicas.</p><p>VMware vSphere 4.0 [1] prevents the split-brain problem by having the primary and secondary replicas access the same shared memory, and before assuming the primary role, a secondary replica is required to run a CAS operation. If the operation fails, it means that the primary is still alive and running. Google File System [2] implements a different solution. It uses a single master to coordinate the allocation of the primary and secondary servers.</p><h4>If a secondary replica fails, how do we quickly warm up a replacement?</h4><p>We could employ state transfer from an existing replica to the new replacement server. If the state is very large, the process can be arduous. If there are operation logs generated, we can also replay all the (recent) operations to the new server.</p><h3>When is replication worth the Nx expenses?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*omLb0X2NObnOuReY" /><figcaption>Photo by <a href="https://unsplash.com/@joshappel?utm_source=medium&amp;utm_medium=referral">Josh Appel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Equally important as understanding the technical aspect is justifying the business use case for replication. To implement replication of N factor, we need N times more servers, thus N times greater expenses. To determine the worth of replication, we have to consider how critical it is to lose the data in a fault. In large systems such as Google File System [2], replication is crucial because it is expensive to lose data.</p><h4>What kind of failures can replication deal with?</h4><p>We also have to be mindful that not all failures can be alleviated by replication.</p><p>Generally, replication can deal with fail-stop failures where the server crashes and stops operating. Causes of fail-stop failures can include cut in power supply and natural disasters. Having more replicas (possibly in different geographical locations) can help to limit the client’s downtime caused by fail-stop failures.</p><p>However, replication cannot deal with failures caused by defects in the hardware or bugs in the software and configurations. Usually, such failures are often correlated, meaning that they can cause all replicas to crash at the same time. We sometimes have mechanisms such as checksums that can detect such errors.</p><h3><strong>Epilogue</strong></h3><p>We’ve mostly talked about the core ideas but it’s impossible to dive into all the details in a short article. Hopefully, this article will serve as a starting point for you to explore more on your own. If you are interested in learning more about large distributed systems, check out some of my previous posts here:</p><ul><li><a href="https://levelup.gitconnected.com/the-google-file-system-the-distributed-file-system-that-google-built-68463670ac57">The Google File System: the distributed file system that Google built</a></li><li><a href="https://levelup.gitconnected.com/lessons-learnt-from-scaling-memcached-in-production-86778ab616c7">Lessons Learnt from Scaling Memcached in Production</a></li><li><a href="https://levelup.gitconnected.com/paper-summary-mapreduce-simplified-data-processing-on-large-clusters-58dac068462e">MapReduce: Simplified Data Processing on Large Clusters</a></li></ul><h3>References</h3><p>[1] Daniel J. Scales, Mike Nelson, and Ganesh Venkitachalam. VMware, Inc. (2010). The Design of a Practical System for Fault-Tolerant Virtual Machines. <a href="http://nil.csail.mit.edu/6.824/2020/papers/vm-ft.pdf">http://nil.csail.mit.edu/6.824/2020/papers/vm-ft.pdf</a></p><p>[2] Sanjay Ghemawat, Howard Gobioff, Shun-Tak Leung (2003). The Google File System. <a href="https://pdos.csail.mit.edu/6.824/papers/gfs.pdf">https://pdos.csail.mit.edu/6.824/papers/gfs.pdf</a></p><p>[3] MIT 6.824 Notes <a href="https://pdos.csail.mit.edu/6.824/notes/l-vm-ft.txt">https://pdos.csail.mit.edu/6.824/notes/l-vm-ft.txt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ba203b06901" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deep-dive-into-primary-secondary-replication-for-fault-tolerance-6ba203b06901">Deep Dive into Primary/Secondary Replication for Fault Tolerance</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Google File System: the distributed file system that Google built]]></title>
            <link>https://levelup.gitconnected.com/the-google-file-system-the-distributed-file-system-that-google-built-68463670ac57?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/68463670ac57</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 20:24:37 GMT</pubDate>
            <atom:updated>2021-04-23T11:24:45.415Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learned from the distributed file system that many Google applications like BigTable, MapReduce are built on top of.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HlBw6IQpoLhfzOnK" /><figcaption>Photo by <a href="https://unsplash.com/@ro_ka?utm_source=medium&amp;utm_medium=referral">Robert Katzki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This article summarises the main lessons learnt from The Google File System (GFS) paper published in 2003 [1].</blockquote><h3>What is GFS?</h3><p>Google File System (GFS) is a <strong>scalable distributed file system</strong> for large distributed data-intensive applications. It provides fault tolerance even with inexpensive commodity hardware, and delivers high average performance to a large number of clients. GFS is widely deployed within Google as a storage platform for applications that require the generation and processing of large data sets.</p><h4>Why you should read the Google File System paper?</h4><ol><li>Incorporates many of the recurring themes in Distributed Systems: parallel performance, fault tolerance, replication, and consistency.</li><li>GFS represents a successful real-world design. Many Google applications such as BigTable and MapReduce are built on top of GFS.</li><li>The GFS paper (2003) is well written and includes the authors’ various considerations from the application level to the network level.</li></ol><h4>What were the main contributions of the GFS paper to the industry in 2003?</h4><ul><li>Despite writing about basic ideas of distribution, sharding, fault-tolerance, the use of GFS was huge in scale (larger scale than most academic systems).</li><li>Used in industry, and shared about Google’s real-world experience.</li><li>Demonstrated successful use of weak consistency.</li><li>Demonstrated successful use of single master.</li></ul><h3>What were the problems GFS was trying to solve?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XOes5MO5ZllhQxbW" /><figcaption>Photo by <a href="https://unsplash.com/@officestock?utm_source=medium&amp;utm_medium=referral">Sebastian Herrmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Google needed a large-scale and high-performant unified storage system for many of its internal services such as MapReduce and their internal web crawler services. In particular, this storage system must:</p><ol><li>Be global. Any client can access (read/write) any file. This allows for sharing of data among different applications.</li><li>Support automatic sharding of large files over multiple machines. This improves performance by allowing parallel processes on each file chunk and also deals with large files that cannot fit into a single disk.</li><li>Support automatic recovery from failures.</li><li>Be optimized for sequential access to huge files and for read and append operations which are the most common.</li></ol><p>In particular, the authors optimized GFS for high sustained bandwidth (target applications place a premium on processing data in bulk at a high rate), but not necessarily for low latency (GFS is typically used for internal services and is not client-facing).</p><h3>The big picture of GFS (Architecture)</h3><p>Let’s go over the big picture of GFS. We will be covering 3 main design choice made by the authors of GFS in this section, namely i) choosing to use only a single master, ii) the choice of storing only some Metadata in non-volatile storage, and iii) the choice of consistency guarantees.</p><p>GFS consists of a single master and multiple chunkservers and is accessed by multiple clients. Files are divided into fixed-sized chunks of 64MB. Each chunk has an immutable and globally unique chunk handler, which is assigned by the master at the time of chunk creation. By default, each file chunk is replicated on 3 different chunkservers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*-v9XEykkOODFgi6rNWe1hg.png" /><figcaption>Figure 1: High-level overview of GFS Architecture. Adapted from [1].</figcaption></figure><h4>Single Master</h4><p>The master maintains all the file system metadata. This includes mapping from file to chunks, chunk locations, etc. The master also periodically sends HeartBeat messages to the chunkserver to give it instructions and collect its state (Figure 1).</p><p><strong>Advantage of a single master:</strong> Vastly simplifies GFS design as the single master can make sophisticated chunk placement and replication decisions using global knowledge.</p><p><strong>Possible disadvantages of a single master:</strong></p><ol><li>Single point of failure. Have to regularly checkpoint critical metadata into non-volatile storage.</li><li>Could be a point of performance bottleneck. Must minimize master involvement in reads and writes.</li></ol><p>With regards to Point 2, a client never reads and writes file data through the master. As you can see in Figure 1, a client asks the master which chunkserver it should contact, caches this information for a limited time, and interacts with the chunkserver directly for read and write operations.</p><h4>Metadata</h4><p>Metadata is stored in the master <strong>in-memory </strong>while data is stored in the chunkservers. This allows master operations to be very fast and also allows the master to efficiently perform periodic scans through its entire state in the background. The periodic scanning is used to implement chunk garbage collection, chunk migration, etc.</p><p>The master stores 3 major types of metadata:</p><ol><li>File and chunks namespaces</li><li>Filename → array of chunk handlers</li><li>Chunk handler → list of chunk servers, primary chunk server, chunk version number</li></ol><p>Note that the first 2 types of metadata are kept persistent by logging mutations to an operation log stored on the master’s local disk, and replicated periodically to remote machines. However, the master does not store the chunk location information persistently. Instead, it asks each chunkserver about its chunks at master startup and whenever a chunkserver joins the cluster. This is because the chunkservers are the authoritative source of data for chunk location and primary status information.</p><h4>Consistency Guarantees by GFS</h4><p>GFS provides a relaxed consistency model, which works well for Google’s highly distributed application but remains relatively simple and efficient to implement. Here, the authors describe two states of a file region (Table 1):</p><ol><li>A file region is <strong>consistent</strong> if all clients will always see the same data, despite which replica they read from.</li><li>A file region is <strong>defined</strong> if after a mutation it is consistent and the clients will see what the mutation writes in its entirety (i.e. the mutation is written without being interleaved by other data from other mutations).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*HiTCQrLbi469KEWI9Tfa5w.png" /><figcaption>Table 1: File Region State after Mutation. Adapted from [1].</figcaption></figure><p>When a non-concurrent mutation succeeds (all replicas report success), the file region is defined and thus, consistent. However, in the event of concurrent successful mutations, the file region is consistent but may not be defined: all clients see the same data but typically it consists of interleaved fragments from multiple mutations. A failed mutation (at least 1 replica does not report success) indicates that the file region is not consistent and thus, not defined. In such events of failure, the GFS client simply re-runs the mutation.</p><p><strong>Atomic operations</strong></p><p>GFS provides some atomic guarantees. File namespace mutation (e.g. file creation) is atomic and is handled exclusively by the master. Namespace locking guarantees atomicity, and the master’s operation log defines a global total order of these operations.</p><p>In contrast to regular writes or append operation, GFS provides a record append operation that guarantees that the data to be appended is performed at least once atomically even in the presence of concurrent mutations, but at an offset of GFS choosing. GFS will return the offset of the appended data to the client.</p><h4>Chunk replicas</h4><p>To ensure that after a sequence of successful mutations, the file region contains the data written by the last mutation, GFS i) applies mutation to chunk replicas in the same order by appointing a primary replica and ii) uses chunk version numbers to detect any replica that has become stale because it has missed mutations while its chunkserver was down.</p><p>Stale replicas will never be involved in a mutation or given to clients asking the master for chunk locations. They are garbage collected at the earliest opportunity.</p><h3>What are the key lessons learned from GFS?</h3><ol><li>Weak consistency may be viable even in production, given that there exists some form of application-level checks.</li></ol><blockquote><em>GFS clients should rely on record append, instead of overwrites because of the atomic guarantees by record append. Record append’s append-at-least once semantics preserves each writer’s output. Readers can deal with the occasional padding and duplicate records by adding extra information such as checksums and unique identifiers to filter out duplicate records.</em></blockquote><blockquote><em>GFS clients also perform checkpointing by atomically renaming the file to a permanent name after writing all data, or checkpointing how much has been successfully written. Checkpoints can also include application-level checksums.</em></blockquote><p>2. Global cluster file system as a universal infrastructure is useful for many data-intensive applications.</p><p>3. A single master may be viable if we separate the metadata in the master from the storage in chunkservers, and minimize client calls to master.</p><p>4. We can make use of file chunking for parallel throughput.</p><p>5. Using a primary replica chunkserver to sequence writes to all replicas.</p><p>However, in hindsight, there were some shortcomings or not so great areas of GFS design:</p><ol><li>Single master performance may not be so great. In retrospect, Google started to witness problems when the number of files increased significantly over the years.</li></ol><blockquote><em>Going from a few hundred terabytes up to petabytes, and then up to tens of petabytes… that really required a proportionate increase in the amount of metadata the master had to maintain. Also, operations such as scanning the metadata to look for recoveries all scaled linearly with the volume of data. So the amount of work required of the master grew substantially. The amount of storage needed to retain all that information grew as well. [3]</em></blockquote><p>2. There was a lack of automatic fail-over to master replica. Engineers used to have to manually perform load checkpoint of master state and perform failover. This is slow and unproductive.</p><p>3. The consistency model used by GFS may be too relaxed in practice [3].</p><p>Check out my summary on MapReduce here!</p><p><a href="https://levelup.gitconnected.com/paper-summary-mapreduce-simplified-data-processing-on-large-clusters-58dac068462e">MapReduce: Simplified Data Processing on Large Clusters</a></p><h3>References</h3><p>[1] Sanjay Ghemawat, Howard Gobioff, Shun-Tak Leung (2003). The Google File System. <a href="https://pdos.csail.mit.edu/6.824/papers/gfs.pdf">https://pdos.csail.mit.edu/6.824/papers/gfs.pdf</a></p><p>[2] MIT 6.824 2020 GFS Notes <a href="https://pdos.csail.mit.edu/6.824/notes/l-gfs.txt">https://pdos.csail.mit.edu/6.824/notes/l-gfs.txt</a></p><p>[3] GFS: Evolution on Fast-forward (2009) <a href="https://queue.acm.org/detail.cfm?id=1594206">https://queue.acm.org/detail.cfm?id=1594206</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68463670ac57" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-google-file-system-the-distributed-file-system-that-google-built-68463670ac57">The Google File System: the distributed file system that Google built</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MapReduce: Simplified Data Processing on Large Clusters]]></title>
            <link>https://levelup.gitconnected.com/paper-summary-mapreduce-simplified-data-processing-on-large-clusters-58dac068462e?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/58dac068462e</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 13:21:10 GMT</pubDate>
            <atom:updated>2021-05-09T14:35:56.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learned from the distributed large-scale computation pipeline that Google built.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uY5diOv5UJIKuQg-" /><figcaption>Photo by <a href="https://unsplash.com/@rajeshwerbatchu7?utm_source=medium&amp;utm_medium=referral">Rajeshwar Bachu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is MapReduce?</h3><p>MapReduce is an interface that enables automatic parallelization and distribution of large-scale computation while <strong>abstracting over “the messy details of parallelization, fault-tolerance, data distribution, and load balancing”</strong> [1].</p><p>As the name suggests, MapReduce is inspired by the <em>map</em> and <em>reduce</em> functions present in many functional languages. These functions allow MapReduce to parallelize large computation easily and use re-execution as a key mechanism to deal with failures.</p><h3>What were the problems MapReduce was trying to solve?</h3><p>Before MapReduce, Google has implemented hundreds of computations that process a large amount of raw data to compute various derived data.</p><p>They found that most of these computations were conceptually straightforward. However, the difficulty comes in the form of large input data whose computation has to be distributed across up to thousands of machines to complete in a reasonable time. Some of these issues that arise with distributed computation are:</p><ol><li>How to parallelize the computation</li><li>How to distribute the large input/output data</li><li>How to handle failures</li></ol><p><strong>The main goal of MapReduce is hence to provide an easy-to-use interface even for programmers without experience in distributed and parallel systems</strong> by abstracting all the details of parallelization, fault-tolerance, data distribution, and load balancing away.</p><p>A benefit that comes with the main goal is that it becomes easier to improve the performance of a computation process by simply adding new machines to the cluster because MapReduce automatically handles all the abstractions for programmers.</p><h3>The big picture of MapReduce (Architecture)</h3><p>We can express a computation using MapReduce in the form of 2 user-defined functions: Map and Reduce.</p><p>map := (k1, v1) → list(k2, v2)</p><p>reduce := (k2, list(v2)) → list(v3)</p><p><em>Map</em>: Takes a data input (key, value) pair and produces a set of intermediate (key, value) pairs. The MapReduce library groups together all intermediate values associated with the same intermediate key I and passes them to the Reduce function.</p><p><em>Reduce</em>: Accepts an intermediate key and a set of values for that key. It merges these values to form a possibly smaller set of values. Note that the intermediate values are supplied to the reduce function via an iterator. This allows us to handle lists of values that are too large to fit in memory.</p><p>Note that in practical use cases, we can chain multiple MapReduce jobs — the output from the Reduce operations is often fed as input into another MapReduce job, or possibly another distributed application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*2nKeNIDzEhXopYLONXoFVw.png" /><figcaption>Figure 1: High-level overview of an execution of a MapReduce job. Adapted from [1].</figcaption></figure><p>Note that the input data is partitioned into a set of M input files. These smaller input files can then be processed in parallel by different machines. The input data of each Reduce invocation is partitioned into R splits using a user-defined partitioning function. Both M and R are specified by the user.</p><p>Figure 1 shows the overall flow of a MapReduce job. The following sequence of actions will occur when a user calls a MapReduce job (the numbered labels in Figure 1 correspond to the numbers in the list below):</p><p>1. Input files are split into M pieces typically 16–64MB (Google uses GFS to partition input data automatically) by the user program. It then starts up many copies of the program on a cluster of machines.</p><p>2. One of the copies of the program is special — the master. The rest are workers that are assigned work by the master. There are M Map tasks and R Reduce tasks to assign. The master picks idle workers and assigns each one a Map task or a Reduce task.</p><blockquote>Note that in 2004, network bandwidth was a huge bottleneck and the authors wanted to minimize passing data through the network. As described in the Section of Locality Optimisation, the Master tends to schedule map jobs to machines already containing the input data. Thus, the map jobs are usually run in the same local machine as the input data (no need to transfer the input files through the network).</blockquote><p>3. A worker who is assigned a map task reads the contents of the corresponding input file. It parses key/value pairs and passes each pair to the user-defined Map function. The intermediate key/value pairs produced by the Map function are buffered in the memory of the Map worker.</p><p>4. Periodically, the buffered pairs are written to the local disk of the Map worker, partitioned into R regions by the Reduce partitioning function. The locations of these buffered pairs on the local disk are passed back to the master, who is responsible for forwarding these locations to the Reduce workers.</p><blockquote>Note that Reduce jobs only begin after all map jobs are completed (refer to the FAQ section).</blockquote><p>5. When a Reduce worker is notified by the master about these locations, it uses remote procedure calls to read the buffered data from the local disks of the Map workers.</p><p>When a Reduce worker has read all the intermediate data, it sorts them by the intermediate keys so that all occurrences of the same key are grouped together. The sorting is needed because typically many different keys map to the same reduce task. If the amount of intermediate data is too large to fit in memory, an external sort is used.</p><p>6. The reduce worker iterates over the sorted intermediate data and for each unique intermediate key encountered, it passes the key and the corresponding set of intermediate values to the user’s Reduce function. The output of the Reduce function is appended to a final output file.</p><p><em>To summarise Steps 5 and 6, these are the steps a Reduce worker takes:</em></p><p>A. After all Map jobs are completed, Reduce workers will pull the intermediate data (from a partition) from the local disk of all map workers.</p><p>B. Reduce workers will sort the data by the intermediate keys.</p><p>C. After sorting, the workers will pass the intermediate keys in order to Reduce function.</p><p>D. The output of Reduce function is appended to a final output file.</p><p>7. When all Map tasks and Reduce tasks have been completed, the master wakes up the user program.</p><h3>What are the key lessons from MapReduce?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hvbG5dCkGBOQyGiu" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>1. <strong>Restricting the programming model</strong> makes it easier to parallelize and distribute computations and to even make such computation fault tolerance.</p><p>For MapReduce, the authors restrict the model to accept key/value pairs, and the output also is key/value pair. Doing so allowed them to implement the computation into Map and Reduce functions that make parallelize the computation easier.</p><p>2. <strong>Redundant executions</strong> can be used to reduce the impact of slow machines (stragglers) and to handle machine failures and data loss.</p><p>In the event of worker failures, MapReduce master simply re-executes the work done by the unreachable worker and continues to make forward progress.</p><p>In the event of “stragglers” (A straggler is a machine that takes an unusually long time to complete one of the last few Map or Reduce tasks, thus prolongs the total time needed), the master schedules backup executions on the remaining in-progress tasks when the MapReduce operation is close to completion. These redundant backup processes can speed up the total time needed to complete all tasks.</p><h3>When is MapReduce not suitable?</h3><p>1. When you need real-time processing, MapReduce may not be the fastest option.</p><p>2. It’s not always very easy to implement each and everything into a sequence of Map and Reduce functions.</p><p>3. When your intermediate processes need to talk to each other (Map and Reduce jobs are run in isolation).</p><p>4. When you need to handle streaming data. Notice that all the input data processed by MapReduce are first processed in batches by Map workers, then by Reduce workers.</p><p>5. When you can get the desired result in a local machine. “It’s obviously less painful to configure and manage a standalone system as compared to a distributed system.” [2]</p><h3>FAQ</h3><ol><li>Does the shuffle process (pulling of intermediate data from all map workers) in Reduce workers happen concurrently with Reduce operations?</li></ol><p>No, it doesn’t. The Reduce worker will alternate between shuffling data from map workers, and sorting the intermediate data and passing the sorted data into the Reduce function.</p><p>2. Do the Reduce operations occur concurrently with Map operations?</p><p>No. You can think of the Map and Reduce operations as occurring in batches. The Reduce workers have to wait for all map jobs to be completed to begin working on shuffling, sorting, and passing data into Reduce functions.</p><p>This is because MapReduce guarantees ordering, i.e. within a given partition, the intermediate key/value pairs are processed in increasing key order (refer to Section 4.2 of [1]).</p><p>In other words, in order for Reduce operations to begin, the entire partition must be collected first, then sorted, before the calls to Reduce functions can be made.</p><p>The only way to be sure we have the entire partition is to wait for all map operations to be completed so that all input slices have been processed.</p><h3>References</h3><p>[1] Jeffrey Dean and Sanjay Ghemawat (2004). MapReduce: Simplified Data Processing on Large Clusters. <a href="https://pdos.csail.mit.edu/6.824/papers/mapreduce.pdf">https://pdos.csail.mit.edu/6.824/papers/mapreduce.pdf</a></p><p>[2] Stack Overflow Post <a href="https://stackoverflow.com/questions/18585839/what-are-the-disadvantages-of-mapreduce">https://stackoverflow.com/questions/18585839/what-are-the-disadvantages-of-mapreduce</a></p><p>[3] Class of 2021 NUS DYOM for MIT 6.824 for the FAQ section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58dac068462e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/paper-summary-mapreduce-simplified-data-processing-on-large-clusters-58dac068462e">MapReduce: Simplified Data Processing on Large Clusters</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learnt from Scaling Memcached in Production]]></title>
            <link>https://levelup.gitconnected.com/lessons-learnt-from-scaling-memcached-in-production-86778ab616c7?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/86778ab616c7</guid>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 16:03:33 GMT</pubDate>
            <atom:updated>2021-04-06T16:03:33.196Z</atom:updated>
            <content:encoded><![CDATA[<h4>Key considerations and strategies to build a highly available cache solution for business use cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dGyqtON3ENJdqoXK" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Memcached is a well-known, simple, in-memory cache solution and is used by several large companies such as Facebook, Twitter, and Pinterest. The main use case for Memcached is look-aside caching, to reduce the load on the database. Unlike Redis, Memcached, known for its simplicity, does not offer any in-built high availability features.</p><h3>The Problem</h3><p>As the scale of a cache cluster expands, high availability (HA) becomes a critical issue. How do we respond quickly in situations where a cache server crashes temporarily or even permanently? How do we prevent request overload to our Database servers?</p><p>While there have been a few open-source Memcached HA solutions (the most popular being Mcrouter by Facebook), such solutions may not entirely fit one’s business use cases. For example, Mcrouter ensures best-effort eventual consistency (i.e. stale data may still occur especially when there is replication), whereas some specific use cases may require higher data consistency. One might also need more control over tradeoffs between availability, consistency, performance, and cost-effectiveness for different business use cases.</p><p>Furthermore, at the time of writing, Mcrouter uses a forked version of Memcached that uses Leases to ensure eventual consistency [1]. Leases are not available in the recent versions of open-sourced Memcached, making Mcrouter non-trivial to adapt in general Memcached infrastructure.</p><blockquote>This article does <strong>not</strong> aim to describe a fixed solution for scaling Memcached.</blockquote><p>Having worked on scaling Memcached for the past 4 months, my aim is to consolidate the key strategies and considerations made to <strong>build a highly available cache solution while meeting consistency needs for business use cases.</strong> The strategies are not Memcached-specific and could be applied to similar look-aside cache solutions.</p><h3>What does a Highly Available Cache Solution Entail</h3><p>So what does a highly available cache solution entail? We identified three of the most crucial features in a highly available solution:</p><ol><li><strong>Cache Replication</strong></li><li><strong>Cold Cache Warmup</strong>: Are there any warm backup caches to cushion the increase in load to the database in the event of crash failures?</li><li><strong>Automatic and Fast Failover</strong>: Are we able to detect and correct crash failures fast enough?</li></ol><p>While the motivation behind cache replication is similar to having a warm cache backup in the event of node failures, replication can be more powerful because it can also help to increase the total queries per second the Memcached cluster can handle. For example, if we adopt a strategy where read traffic is directed to either replica, the load to a single Memcached can be reduced by a factor of the number of replicas, thus overall across the replicas, we can support higher queries per second (QPS).</p><p>However, often in exchange for higher availability, consistency is sacrificed. For example with 2 replica Memcached, we not only must concern ourselves with the consistency between Memcached and DB, but also with the consistency between the 2 replica Memcached.</p><p>This is also reported by Amazon that from their experience, there typically exists a trade-off between ACID (C stands for consistency) properties and availability. We will discuss strategies that balance this trade-off in the later section.</p><h3>Main Business Use Cases for Caching</h3><p>To understand how to balance the trade-off between consistency and availability, we need to identify the business use cases and their needs. There are generally 2 main categories of use cases for caching:</p><ol><li>Look-aside cache (Database is the authoritative source of truth)</li><li>Cache as authoritative storage (where the cache is now an authoritative source of truth)</li></ol><p>While the main usage of Memcached typically is as a look-aside cache, some business use cases may make use of the cache as the authoritative storage in which consistency may become more important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*RTMiS7_-RUIdefcD2SOpJQ.png" /><figcaption>Figure 1: The remote marker mechanism uses Memcached as an authoritative source of data to store markers. This mechanism is used to minimize the probability of reading stale data in replica databases.</figcaption></figure><p>In Facebook’s Scaling Memcached paper, a use case for the cache as authoritative storage is described: a <em>remote marker </em>mechanism is used to minimize the probability of reading stale data in replica databases for use cases that requires a strong level of consistency. The problem described in the paper originates from the fact that replica databases may lag behind the master database (DB) and sometimes this replication lag is non-negligible (e.g. when the master DB and replica DBs are in different geographical regions).</p><p>As seen in Figure 1, when new data is written in the master DB, the client will also write a marker into Memcached. Typically the expiration time for the marker is very short. Subsequently, before a client reads the data from the DB, it will check if the remote marker exists in the cache. If the marker exists, it implies that the data is recently written or updated, and the client will read from the master DB, else, it will read from the replica DBs.</p><h4>Choosing the Right Consistency Guarantees</h4><p>After identifying our business use cases, we need to select the right consistency guarantees. For example, in the cache as an authoritative storage use case, we might need a strong consistency between Memcached replicas because the data is only stored in the cache and the cache is the authoritative source of truth. In other business situations, eventual consistency might be sufficient, and we can focus our strategies towards maintaining higher availability or optimizing performance.</p><p>There are 2 main consistency relations we need to consider:</p><ol><li>Consistency between Memcached replicas (if replication is employed)</li><li>Consistency between the Database and Memcached</li></ol><p>As our focus is on scaling Memcached infrastructure, we will not concern ourselves with the consistency between Master DB and replica DBs.</p><p>The following are several consistency levels that are typically required on a business level. Keep in mind that high consistency is usually a trade-off for availability, performance (low latency, high throughput), or/and cost.</p><ol><li><strong>Strong consistency</strong></li></ol><p>Strong consistency between Memcached replicas guarantees that Memcached replicas have the same data and that different read requests to the replicas will return the same result. Such strong consistency between Memcached replicas may be required in cases when the cache is used as authoritative storage, or when inconsistent data could have critical business repercussions. For example, in the case of the remote marker mechanism (described above), a cache miss could lead to clients reading from the replica DB which may contain stale data.</p><p>2. <strong>Eventual consistency</strong></p><p>Eventual consistency guarantees that if no new updates are made to a given data item, <strong>eventually</strong> all get requests to that item will return the last updated value. Most if not all cache use cases will require at least eventual consistency.</p><p>3. <strong>Allowing stale data (for a limited time) in exchange for lower latency</strong></p><p>By identifying situations where returning slightly out-of-date data is acceptable, we could employ strategies that allow stale data to be returned for a bounded time in order to reduce latency.</p><p>5. <strong>Sequential consistency</strong></p><p>By Lamport’s definition:</p><blockquote>Sequential consistency implies that operations appear to take place in some total order, and that that order is consistent with the order of operations on each individual process.</blockquote><p>In the context of distributed cache, sequential consistency guarantees that the order of operations received by the Memcached server is consistent with the partial order of operations sent by each individual client. That is, every client sees that their operations are performed in order (even though their operations may be interleaved with operations sent by other clients).</p><h3>Strategies to Scale A Distributed Cache</h3><p>After analyzing our business cases and the consistency level they require, we are now ready to discuss strategies to scale our distributed cache solution. Each of the strategies discussed arises from different problems faced in production when scaling the Memcached infrastructure.</p><h4>1. Performing cache invalidations upon data update</h4><p>One problem that arises in Memcached infrastructure is race conditions from concurrent writes, leading to infinitely stale data present in the cache. This can be detrimental to the business logic because even eventual consistency is not guaranteed.</p><p>For example, consider a single instance of Memcached where concurrent writes from clients may sometimes be re-ordered, i.e. if we employ a naive “write to DB then write to cache” strategy, the order of writes to DB may differ from the order of writes to Memcached, which leads to indefinitely stale data. The main problem is because writes are not idempotent nor commutative.</p><blockquote>“We choose to delete cached data instead of updating it because deletes are idempotent. Memcache is not the authoritative source of the data and is therefore allowed to evict cached data” [1].</blockquote><p>A common strategy to avoid this issue is to use cache invalidation upon updating the DB because deletes are idempotent. For example, in the Scaling Memcached at Facebook paper [1], authors present that upon a DB write for a data item x, an invalidation pipeline that runs a daemon <em>mcsqueal</em> will read the DB log and then, issue invalidation for the same data item x (i.e. delete command) to Memcached. Then, when a client receives a cache miss, they will get the data item directly from the DB and write the most recent value to Memcached.</p><p>To prepare for unexpected cases such as transient network failure, we need to ensure that the invalidation daemon keeps retrying delete commands in the same order until succeeded so that invalidation requests are not lost in the event when a Memcached instance disconnects. To reduce the load on the invalidation pipeline during a node failure, the retry can be implemented in an exponential backoff fashion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*SqG1AvU2iHOFEFl0koY6Ww.png" /><figcaption>Adapted from [1].</figcaption></figure><p>This approach minimizes the risk of concurrent writes being re-ordered because deletes are idempotent, and if multiple clients update the same data item concurrently, the database will be responsible for ordering the updates and delete the data item from Memcached.</p><p>However, there is still a small risk of ending up with stale data using this strategy. Consider the given race condition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff3bb448df8d9f7f1acaac7eef9482a6/href">https://medium.com/media/ff3bb448df8d9f7f1acaac7eef9482a6/href</a></iframe><p>To solve this issue, Facebook uses a CAS-like (check-and-set) approach called leases on the Memcached server side. However, at the time of writing, Leases are not available in the recent versions of open-sourced Memcached.</p><h4>2. Client-side vs server-side approach</h4><p>While scaling cache infrastructure, it is usually a good idea to embed the complexity of the system into either a stateless client or standalone proxy. This greatly simplifies Memcached and allows one to focus on making it highly performant for specific use cases. In order to scale up Memcached infrastructure, we found that there are two general approaches we can take:</p><p>a) Library that can be embedded into applications (client-side approach)</p><p>b) Standalone proxy (can be a client-side proxy process like Mcrouter or server-side proxy)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FMSjgrBFTGCSnXvYZfJlWA.png" /></figure><p>An example of a standalone client proxy is Mcrouter [1] which is typically deployed as a sidecar of the client machine, meaning it is separate from the client API library [5]. An example of a server-side proxy is to deploy an LVS load balancer to split traffic amongst different Memcached replicas in the same consistent hashing slot. The main advantage of using a standalone proxy solution is that there is less or no code modification on the client side.</p><p>Deploying a server-side proxy as compared to a client proxy also reduces the need for code addition and changes, thus lowering the risk of bugs and making it easier for existing teams to convert to the new solution. However, a server-side proxy may require additional cost (in the form of another physical machine / dedicated rack). We will look into how we can use both strategies to achieve High Availability in the Replication Strategies section.</p><h4>3. Replication Strategies</h4><p>We have seen in the Consistency section that different business needs may require very different consistency or availability guarantees. Sometimes, we may even need to cater to more than one vastly different use case in the same cache infrastructure. To meet these business objectives, we have to employ specific strategies to balance these trade-offs. We will discuss a few of these replication strategies in this section. Note that the scale in which we are examining is one specific replication cluster (i.e a single slot of the consistent hashing algorithm).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MQNdOEakwr0aT4J_5E7eiA.png" /><figcaption>Our strategies will focus on one specific Memcached consistent hashing slot.</figcaption></figure><ol><li>Primary Memcached node with automatic failover to cold backup</li><li>Write to any node; Get from any node.</li><li>Write to all nodes; Get from any node</li><li>Write to all nodes; Get only from primary Memcached node</li></ol><p><strong>Primary Memcached node with automatic failover to cold backup</strong></p><p>This strategy doesn’t support replication or warm cache backup; it mainly supports automatic failover when the Memcached node fails. In the event of a Memcached failure, routing traffic to a cold cache will lead to cache misses and hence an increase in DB load. However, if the DB can withstand a few Memcached nodes’ worth of load, this solution may be suitable as a temporary solution.</p><p>A possible implementation of this strategy is by using a server-side strategy: We can add a layer of Virtual Router Redundancy Protocol (VRRP) between the client and Memcached servers. VRRP performs automatic failure detection and failover such that if the active physical Memcached master fails, another physical machine will be selected to automatically replace it.</p><p><strong>Write to any node; Get from any node.</strong></p><p>Note that Facebook implemented this strategy using a client-side proxy Mcrouter. This strategy can also be implemented in the form of a server-side proxy using a load balancer such as LVS to split traffic between Memcached replicas.</p><p><em>Pros</em>: Replicas split the load of traffic amongst themselves, thus, overall more QPS can be supported. Since the split of traffic is random, we can expect the key distribution to be even among the replicas. Thus, we are guaranteed to have warm backups in the event of a portion of the replicas failing.</p><p><em>Cons</em>: Cannot ensure repeatable reads amongst replicas because writes are not guaranteed to end up in all replicas. For use cases that require high level of consistency such as using the cache as authoritative storage, this solution may not be sufficient.</p><p><strong>Write to all nodes; Get from any node</strong></p><p>This strategy aims to support full replication in all replicas, i.e. writes will be propagated to all replicas (synchronously).</p><p><em>Pros</em>: If implemented properly, can support a high level of consistency among different Memcached replicas. Since the requests are split among the different replicas, overall QPS that can be supported in one consistent hashing slot also increases by the factor of the number of replicas.</p><p><em>Cons</em>: It is not trivial to guarantee that all Memcached replica will be consistent with each other, especially with a client side approach. This is because we have to manage the situation when a write to Memcached fails due to temporary network delays.</p><p><strong>Try to write to other nodes; Get only from the primary Memcached node</strong></p><p>This strategy relaxes the condition of the previous strategy: i.e. attempt to achieve full replication. Upon a cache miss, Memcached will fetch the new data from DB and write to the primary Memcached node in a synchronous fashion, before writing to the secondary nodes in an asynchronous fashion. Get queries will only be directed to the primary Memcached.</p><p><em>Pros</em>: Able to maintain warm Memcached replica backups assuming that a majority of the asynchronous writes will succeed. Since Get queries are only handled by the primary Memcached node, in most normal situations, it is not as critical to ensure consistency between primary node and backups.</p><p><em>Cons</em>: Again, it is not trivial to guarantee all replicas will be consistent with one another. In the event that the primary Memcached node fails, the backup that is promoted to the primary node may contain some stale data.</p><p>Furthermore, since only one primary node is utilized in handling all query traffic, the overall QPS that can be supported in one consistent hashing slot remains the same.</p><h4>4. Achieving Failover</h4><p>Failover refers to the act of falling back onto a secondary service/machine if the primary machine fails. Failover is a critical aspect of any high availability solution and includes two main components: Failure detection and gradual failover to another Memcached replica or backup. Ideally, we want to achieve fast failover and sometimes automatic failover.</p><p>One common way to detect node failures is to perform a health check is via sending periodic heartbeat to servers using a Daemon script. Servers that reply to the heartbeat are deemed healthy and we can keep track of this healthy list of servers in a central configuration center like ETCD/Zookeeper which can be accessed by the client processes. One possible way to support gradual failover is via server-side strategies such as VRRP which supports such high availability features.</p><p>In conclusion, as the scale of Memcached increases, one has to keep in mind the trade-offs between consistency, availability, and performance and this intricate balance between these factors depends on the business use cases that Memcached is supporting.</p><p>Thank you for reading! Do check out my earlier post on how to benchmark Memcached performance here:</p><p><a href="https://medium.com/swlh/the-complete-guide-to-benchmark-the-performance-of-memcached-on-ubuntu-16-04-71edeaf6e740">The Complete Guide to Benchmark the Performance of Memcached on Ubuntu 16.04</a></p><h4>References</h4><p>[1] Scaling Memcached at Facebook <a href="https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf">https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf</a></p><p>[2] Dynamo: Amazon’s Highly Available Key-value Store <a href="https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf">https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf</a></p><p>[3] Memcached <a href="https://memcached.org/">https://memcached.org/</a></p><p>[4] Notes on Scaling Memcached at Facebook <a href="https://pdos.csail.mit.edu/6.824/notes/l-memcached.txt">https://pdos.csail.mit.edu/6.824/notes/l-memcached.txt</a></p><p>[5] Scaling Cache Infrastructure at Pinterest <a href="https://medium.com/pinterest-engineering/scaling-cache-infrastructure-at-pinterest-422d6d294ece">https://medium.com/pinterest-engineering/scaling-cache-infrastructure-at-pinterest-422d6d294ece</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86778ab616c7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lessons-learnt-from-scaling-memcached-in-production-86778ab616c7">Lessons Learnt from Scaling Memcached in Production</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Benchmark the Performance of Memcached on Ubuntu 16.04]]></title>
            <link>https://medium.com/swlh/the-complete-guide-to-benchmark-the-performance-of-memcached-on-ubuntu-16-04-71edeaf6e740?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/71edeaf6e740</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 15:59:12 GMT</pubDate>
            <atom:updated>2021-02-15T07:46:07.115Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Benchmark the Performance of Memcached on Ubuntu 16.04</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Xbui1JdABxN8UbRE2rQBcg.jpeg" /><figcaption>Banner image from [1].</figcaption></figure><h3>What is Memcached</h3><blockquote>Memcached is<strong> a free &amp; open source, high-performance, distributed memory object caching system</strong>, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. [1]</blockquote><p>Memcached is known for its simplicity as a distributed cache. Its simple design promotes not only quick deployment, ease of development but also has been reported to be faster than other cache system like Redis in performance comparisons.</p><p>Benchmarking or stress testing is crucial for testing the bottlenecks and safe lines in any system. This article serves as a guide on how to stress test Memcached servers using a popular Memcached tool memaslap.</p><h3>Introduction to Memaslap</h3><p><a href="http://docs.libmemcached.org/bin/memaslap.html">Memaslap</a> is a popular load generation and benchmarking tool for memcached servers (or servers abiding by memcached protocol). It supports configurable workload such as requests rate, the number of concurrent connections, key size and value size distribution, get/set proportion, and so on. Memaslap also displays key statistics such as latency.</p><p>Do not mix up memaslap with its 2 other cousins: <strong>memslap and memcslap</strong>. memcslap is installed when installing libmemcached and if you used homebrew to download memcached you will end up with memslap. To get memaslap, you have to build from source (see below for instructions).</p><p>memslap and memcslap are <strong>not</strong> too useful as they do not show stats nor accept useful parameters such as threads or time. Building from source and using <strong>memaslap is the most recommended way</strong>.</p><h3>Installing Memaslap (Ubuntu)</h3><p>You should download memcached if you haven’t already done so using sudo apt update &amp;&amp; sudo apt install memcached. You can check the status of memcached by running sudo systemctl status memcached.</p><p><strong>Run the following commands:</strong></p><ol><li>Download the source code of libmemcached library from <a href="https://launchpad.net/libmemcached/+download">here</a>.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/225e193b7d3caec378d28e7980f7f9f7/href">https://medium.com/media/225e193b7d3caec378d28e7980f7f9f7/href</a></iframe><p>You should see an output similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*AEwyhmcE36Y6fMIJQL0R1w.png" /></figure><h4><strong>Additional tips for running memaslap:</strong></h4><ol><li>You should consider pre-populating memcached with items before any stress test to better simulate the live production environment. Prepopulation can be done using memaslap.</li><li>If you are running high concurrency, you can increase your max TCP socket connections by running: sudo sysctl -w net.core.somaxconn=65535. Check <em>somaxconn</em> by running: sudo sysctl -a | grep somax</li><li>By default, memaslap keeps to the default Memcached expiration time which is 10800s or 3 hours. However, this may be too long in some live production environments where expiration time is much shorter. To customize this expiration time, you can modify <strong>clients/ms_conn.c at line 454 </strong>and rebuild libmemcached using the above steps.</li></ol><blockquote>line 454: c-&gt;item_win[i].exp_time= 0; // this is in terms of seconds</blockquote><h3>Configuring the value size distribution</h3><p>To simulate live production traffic, sometimes we want to configure a specific distribution of values set and get. We could also configure the value size distribution for pre-populating Memcached. Note that memaslap also allows for the configuration of key size distribution.</p><h4>Obtaining live item size distribution</h4><p>To obtain the production distribution of item size in Memcached servers, we can use <em>memcached-tool</em> to help us.</p><ol><li>Clone memcached official repository: <a href="https://github.com/memcached/memcached">https://github.com/memcached/memcached</a></li><li>Run ./memcached/scripts/memcached-tool:&lt;memcached-port&gt; display</li></ol><p>An example output will be: (where first column represents slab number)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*qER7obPCUE9srFQmzMZzsg.png" /></figure><p>An alternative is to use <a href="https://github.com/davidfoliveira/memcached-tool-ng">memcached-tool-ng</a> which includes the efficiency of slab memory used.</p><h4>Configuring value sizes on memaslap</h4><p>Note that value size here is <strong>NOT the same </strong>as item sizes that we have collected above.</p><blockquote><em>An item will use space for the full length of its key, the internal datastructure for an item, and the length of the data.</em></blockquote><p>A generic formula I found for converting live item sizes to value sizes for memaslap configuration is:</p><p><strong>Item Size = Key Size + Value Size + fixed_constant</strong></p><p>I would suggest fixing the key size and running a few trials of memaslap to calculate the value of fixed_constant. A possible consideration for the key length is that you might want it to be sufficiently long to allow enough <strong>distinct keys</strong>.</p><p>In summary:</p><ol><li>Collect production item sizes distribution.</li><li>Run a few trials to find out the mapping from item sizes distribution to value sizes distribution for memaslap config.</li></ol><h3>Conclusion</h3><p>From my experience, the following are some recommended steps to benchmark the performance of memcached servers:</p><ol><li>Pre-populate Memcached with items.</li><li>Run memaslap with specified configurations for benchmark test.</li><li>Restart the memcached server(s) under test.</li><li>Repeat from step 1 for the next stress test.</li></ol><p>That’s all, enjoy benchmarking your memcached servers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGAs1O-ZmfBJGBCDcj0Kpg.jpeg" /><figcaption>Image from <a href="https://medium.com/hackernoon/api-testing-using-supertest-1f830ce838f1">https://medium.com/hackernoon/api-testing-using-supertest-1f830ce838f1</a>.</figcaption></figure><h3>References</h3><p>[1] <a href="https://memcached.org/">https://memcached.org/</a></p><p>[2] <a href="http://docs.libmemcached.org/bin/memaslap.html">http://docs.libmemcached.org/bin/memaslap.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71edeaf6e740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-complete-guide-to-benchmark-the-performance-of-memcached-on-ubuntu-16-04-71edeaf6e740">The Complete Guide to Benchmark the Performance of Memcached on Ubuntu 16.04</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connection Pooling: 3 Things You Need to Know to Build a Connection Pool From Scratch.]]></title>
            <link>https://medium.com/swlh/connection-pooling-3-things-you-need-to-know-to-build-a-connection-pool-from-scratch-9d9d4d5ff396?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9d4d5ff396</guid>
            <category><![CDATA[connection-pool]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 09:15:06 GMT</pubDate>
            <atom:updated>2021-01-03T07:05:56.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x71Co8d0a9oYOdGAXTQ_0A.jpeg" /></figure><p>Connections are everywhere! To communicate between 2 parties, we need connections. We use them in modern web stack and apps: from server-client to server-database interactions. But why don&#39;t we hear about it often?</p><p>Abstraction! Details on connections are often abstracted away (and for good reason!). However, if you are planning to build your own program with great performance, a firm understanding of what goes under the hood is definitely an advantage!</p><p>In this article, I will be starting off with a common problem to motivate the use of connection pooling. I will then share 3 important tips for building an efficient connection pool, ending off with an example to tie it all together.</p><p><em>P.S. The code examples are written in Golang which is awesome.</em></p><h3>The Problem</h3><p>Let&#39;s consider a typical web scenario when we have 2 servers, a frontend, and a backend communicating. Note that this example can be extended to other forms of connections.</p><p>Each time the Frontend wants to communicate with Backend, it opens a new connection. When Frontend is done, it closes the connection. Imagine if we have 1000 requests per second, this would mean opening and closing 1000 connections every second! This is very <strong>inefficient</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*um87CL68WVxbg3S7Kt-kKQ.png" /></figure><p>But do we need to close the connections every time? Probably not. A better option here would be to <strong>reuse</strong> them. Here is when connection pooling comes to save the day!</p><h3>Connection pooling: Save cost by reusing!</h3><p>A connection pool keeps idle connections alive (instead of closing them). When the Frontend needs a connection, it calls a Get() function to get an existing connection from the pool instead of opening a new one. Once the communication is done, Frontend can release the connection back into the pool for reuse.</p><p>No more opening and closing connections with every request!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*v69O5ue7E15lbbjp51IQaA.png" /></figure><p>This sounds great! So how do we implement a connection pool?</p><h3>MOT: Three concepts to keep in mind when building your own connection pool</h3><h4>1. Methods:</h4><p>There are 4 main methods to implement in the Connection Pool:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b36de98b8d0606aac7ca2ae2b046da3f/href">https://medium.com/media/b36de98b8d0606aac7ca2ae2b046da3f/href</a></iframe><p>To simplify things, the connection in the example is a <em>net.Conn </em>which is a stream-oriented network connection from Golang standard net library<em>. </em>In general, it is recommended to create a wrapper around your connections.</p><p>See examples of how to implement these methods in the <em>Connection pool libraries in Golang </em>section.</p><h4><strong>2. Options</strong></h4><p>Not all connection pools should be configured the same way — applications have different load patterns and hence render different settings to optimize their performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*a89t8MPldkaTCHJP.jpeg" /></figure><p>Here are some possible options that you can include to make your connection pool more versatile to different use cases:</p><p><strong>MaxIdleConnections</strong></p><blockquote>The maximum number of idle connections per address that are kept alive by the connection pool.</blockquote><p>Consider the expected traffic rates and latency while setting this parameter. MaxIdleConnections should be set higher than peak parallel requests.</p><p>Related parameter: <em>MaxIdleTime</em></p><p><strong>MaxIdleTime</strong></p><blockquote>The maximum amount of time an idle connection can stay alive. If not specified, connection stays active until discarded or when the pool enters inactive state.</blockquote><p><strong>MaxActiveConnections</strong></p><blockquote>The maximum number of connections that can be active per address at any given time.</blockquote><p>When the server faces some transient performance issue such as a temporary increase in latency, more connections will be created, which in turn aggravates the situation. MaxActiveConnections ameliorates this by imposing a cap on the number of connections created.</p><p>Related parameters: Is<em>Wait, WaitTime</em></p><p><strong>IsWait</strong></p><blockquote>A boolean flag indicating pool&#39;s response when connections equal to MaxActiveConnections.</blockquote><blockquote>When set to true, calling Get() waits until the number of connections fall below MaxActiveConnections before returning an active connection. When set to false, return nil (or error) without waiting.</blockquote><p><strong>WaitTime</strong></p><blockquote>Indicates how long to wait for number of connections to fall below MaxActiveConnections before returning nil (or error).</blockquote><h4>3. Thread Safe</h4><p>Our connection pool implementation also has to be thread-safe to protect against race conditions resulted from concurrent requests.</p><p>We can achieve thread-safe by using mutex or in the case of Go, <a href="https://tour.golang.org/concurrency/3">buffered channels</a>. Refer to <em>Connection pool libraries in Golang </em>section for more examples on how to implement this.</p><h3>Still curious? More details and examples</h3><h4>When to reuse and when to discard connections</h4><p>It is important to make sure that the connections we release back into the pool are not corrupted.</p><p>To do so, we can add a simple function on the Receiver Server side to determine if the connection is reusable. If the connection is reusable, release it back to the pool, else discard it instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a1b5ef2401f83f8769e52caf41b457/href">https://medium.com/media/e7a1b5ef2401f83f8769e52caf41b457/href</a></iframe><h4>Changes to server behavior with connection pooling</h4><p>Note that we should initialize the connection pool only in the Sender server. Both servers should not manually close or open new connections, and leave this to the Connection Pool instead. Instead, both servers should access the exposed connection pool methods to Get, Release, or Discard connections.</p><h4>Connection pool libraries in Golang</h4><p>The best way to implement your own connection pool is to study how others have done it! Here are some popular libraries in Golang:</p><ul><li><a href="https://github.com/fatih/pool">fatih/pool</a></li><li><a href="https://github.com/dropbox/godropbox/tree/master/resource_pool">dropbox/godropbox</a></li></ul><p>That&#39;s all! Thank you for reading and let me know if you would find it helpful if I post an article on the implementation of the connection pool. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9d4d5ff396" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/connection-pooling-3-things-you-need-to-know-to-build-a-connection-pool-from-scratch-9d9d4d5ff396">Connection Pooling: 3 Things You Need to Know to Build a Connection Pool From Scratch.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: The power of protocols]]></title>
            <link>https://melodiessim98.medium.com/protocol-oriented-programming-in-swift-7b1f762cafd5?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1f762cafd5</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ipad]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Wed, 13 May 2020 05:13:13 GMT</pubDate>
            <atom:updated>2020-05-13T08:12:17.938Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Swift’s protocols and how to apply them to improve code performance and modular flexibility</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZiW7-hTNHo-VhW8" /><figcaption>Photo by <a href="https://unsplash.com/@brookelark?utm_source=medium&amp;utm_medium=referral">Brooke Lark</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>At the heart of Swift’s design are two powerful programming paradigms: protocol-oriented programming (POP) and class-based inheritance. POP helps solve some of the problems arising from class-based inheritance such as <strong>intrusive inheritance, implicit sharing, and lost-type relationships</strong>.</p><p>POP also improves model flexibility with new features such as retroactive modeling using Protocol Extensions. Furthermore, as Swift doesn’t offer multiple inheritances of classes, POP can help achieve that by making classes/structs conform to multiple protocols instead.</p><p>In the following sections, we will examine:</p><ul><li>how to apply protocols to achieve greater code performance, flexibility, and maintainability</li><li>highlight new features POP brings i.e. <strong>the Self keyword</strong></li><li>see some scenarios where class-based inheritance is still preferred</li></ul><p><strong>Disclaimer: </strong>This article aims to summarise the key points raised regarding POP by several <strong>really </strong>informative and interesting sources (links in the References section).<em> The author would definitely recommend checking out those links.</em></p><h4><strong>1. Use protocols with value types</strong></h4><p>Unlike traditional subclassing, both structs and classes in Swift can conform to protocols. This eradicates the problem of implicit sharing inherent in inheritance, where classes contain mutable reference semantics. Consequently, the code becomes more maintainable and predictable.</p><p>Simply put, implicit sharing is when:</p><ul><li>A hands B some data ‒ But still holds a reference to the data</li><li>If A mutates the data ‒ B is caught off-guard</li></ul><figure><img alt="Implicit sharing when using reference type semantics in inheritance (Image from Google)" src="https://cdn-images-1.medium.com/max/880/1*UJ0wj6on_O6Y8K5Y5L2DTg.png" /><figcaption>Implicit sharing when using reference type semantics in inheritance (Image from Google)</figcaption></figure><h4><strong>2. Use protocol extensions for greater modular flexibility</strong></h4><p>Protocol extensions can bring about greater modular flexibility and code reduction in 2 ways:</p><p><strong><em>a. Retroactive modeling</em></strong></p><p>With extensions, classes or structs can be dynamically remodeled to add new methods. For example, if you wanted to implement methods or operators for CGRect class (provided by the Apple Standard Library), you could do so by creating an extension. Furthermore, the extension can also be made to adopt one or more protocols.</p><pre>extension CGRect: Shape {</pre><pre>  func area() -&gt; CGFloat { return size.width * size.height }</pre><pre>}</pre><p>This is also really useful in situations where you might need to handle separate classes or structs in a similar way. For more information, <a href="https://www.youtube.com/watch?v=2CMsgER7WG4">refer to this video</a>.</p><p><strong><em>b. Default implementation of protocol methods</em></strong></p><p>As there isn’t the concept of Abstract classes in Swift, with inheritance, we have to define all the methods of a base class and any changes later could result in a change in the subclass implementation.</p><p>With protocols extension, we can now provide default implementation for methods. This not only improves flexibility by decoupling the protocol from the class/struct, but also can reduce code duplication in common methods between classes or structs conforming to the protocol.</p><h4><strong>3. Use protocols to achieve multiple inheritances</strong></h4><p>In Swift, multiple inheritances of classes are not allowed. However, when it comes to protocols, there is no limit to how many a struct or class can conform to.</p><p>The implication? We can now further refactor our code into protocols that <em>truly do one thing </em>(Single Responsibility principle).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4122318a3760d2eaee64ef2a8e8ca5/href">https://medium.com/media/3f4122318a3760d2eaee64ef2a8e8ca5/href</a></iframe><h4><strong>4. No override protection for protocols</strong></h4><p>As protocols do not support final or override keywords that classes do, objects conforming to the protocols might not be alerted when the protocol methods changed.</p><p>As shown in the snippet below, Circle is not notified when the area method has been renamed to boundingBoxArea in Geometry protocols. Though there isn’t an explicit error here, in practice, area could have become obsolete and is no longer being called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f52079b4230ffb797e18259b94dd092e/href">https://medium.com/media/f52079b4230ffb797e18259b94dd092e/href</a></iframe><h4><strong>5. Using Self to avoid lost-type relationships</strong></h4><p>What are lost type relationships? Suppose we want to implement a precedes method inOrdered which checks the precedence of Ordered objects (refer to code snippet).</p><p>If we want to create a new classNumber implementing Ordered , we will have to perform a downcast as we have to preserve the signature of precedes. Whenever you see a forced down-cast it is generally a code smell — it is a good sign that some important type relationships have been lost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ba6cfdf3a0ad5695df6d00f6cb9ebb1/href">https://medium.com/media/9ba6cfdf3a0ad5695df6d00f6cb9ebb1/href</a></iframe><p>Some of you might then ask: if we useOrdered as a protocol, wouldn’t the signature of precedes(other: Ordered) remain the same, so the same issue remains?</p><p>Here is where we could use <strong>Self.</strong> Self is a placeholder for the type’s that going to conform to that protocol. Let’s see how we could use Self in our Ordered example to preserve type information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caf9dc1f1f7a92b087ce33e54fd76f6f/href">https://medium.com/media/caf9dc1f1f7a92b087ce33e54fd76f6f/href</a></iframe><p>Now, we want to create abinarySearch method, let’s compare how this would look like for the 2 different implementations with and without Self.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1079c892d4c151a9517b8a3d461ddf61/href">https://medium.com/media/1079c892d4c151a9517b8a3d461ddf61/href</a></iframe><p>Notice that with Self, collections have become homogeneous rather than heterogeneous. We have traded dynamic polymorphism for static polymorphism, but in return for the extra type information given to the compiler, it becomes more optimizable [1].</p><p>Furthermore, this might be useful in some contexts where we want to compare only among homogeneous objects.</p><p>In summary, this table describes the 2 worlds provided by Self-requirement in protocols:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4r_bNIkGDHL9BI_Zt6E-sw.png" /><figcaption>From the slide of Protocol-oriented Programming in Swift — WWDC 2015 <a href="https://developer.apple.com/videos/play/wwdc2015/408/">https://developer.apple.com/videos/play/wwdc2015/408/</a></figcaption></figure><h4><strong>6. Generic protocols using associated types</strong></h4><p>There are a few other features that protocols bring to the table: for example, like a Generic class, we also have generic protocols using associated types. For more information, you can refer to <a href="https://www.youtube.com/watch?v=n3unwIghoeE">this video</a>.</p><h4><strong>7. When are classes still preferred over protocols?</strong></h4><p>So, are classes completely obsolete with the advance of POP? Not at all! Here is a non-exhaustive list of situations where classes are still preferred:</p><ul><li>When you intentionally want implicit sharing ie. when using a value type does not make sense. (Consider a Window object, does it make sense to copy a Window object?)</li><li>Do not fight the system, if a framework expects you to subclass and work with classes, do so! E.g. Swift Cocoa libraries are implemented with classes, and you are expected to inherit these classes and work with them. However, when the class gets too big, you should circumspect and consider using non-classes to refactor your code.</li></ul><p>Thanks for reading!</p><p>Follow me for more articles on Protocols and Swift that I might be releasing soon! :) Don’t forget to leave multiple claps if you enjoyed this article!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c8tEgX7br1efI5ar" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>References:</h4><p>[1] Protocol-oriented Programming in Swift — WWDC 2015 <a href="https://developer.apple.com/videos/play/wwdc2015/408/">https://developer.apple.com/videos/play/wwdc2015/408/</a></p><p>[2] Protocol Oriented Programming — Advanced Swift Programming — raywenderlich.com <a href="https://www.youtube.com/watch?v=ekYdBcl3dzs">https://www.youtube.com/watch?v=ekYdBcl3dzs</a></p><p>[3] Protocol Oriented Programming — FlawlessiOS — Medium <a href="https://medium.com/flawless-app-stories/protocol-oriented-programming-2c448013b96a">https://medium.com/flawless-app-stories/protocol-oriented-programming-2c448013b96a</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1f762cafd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to host an Apollo Graphql Server on GAE with Cloud Firestore]]></title>
            <link>https://medium.com/swlh/how-to-host-an-apollo-graphql-server-on-gae-with-cloud-firestore-f2f33aa8ee15?source=rss-6858c678cde5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2f33aa8ee15</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Melodies Sim]]></dc:creator>
            <pubDate>Thu, 07 May 2020 22:09:34 GMT</pubDate>
            <atom:updated>2020-05-13T08:02:20.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C8Jx2gcDi1Ini_fv" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck V.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will be a quick guide on how to bootstrap a Graphql server on Google App Engine, using Firestore as a cloud database.</p><p><em>Main libraries used:</em></p><ol><li>Typescript</li><li>Apollo Server Express</li><li>Firestore Admin</li><li>Google Cloud SDK</li></ol><p>Access the full code here: <a href="https://github.com/Happytreat/graphql-ts-gae-boilerplate">https://github.com/Happytreat/graphql-ts-gae-boilerplate</a></p><h4>Setup Typescript in your project</h4><ol><li>Run yarn init and follow the prompts to create your project. The entry point for your app will be dist/index.js.</li><li>Install tsc globally to transpile .ts code using yarn add global tsc</li><li>Install other dependencies using: yarn add tslint @types/node tslint-config-airbnb typescript ts-node-dev --dev</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45513490909edd1650c4c6f935ea0d85/href">https://medium.com/media/45513490909edd1650c4c6f935ea0d85/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d7962813cbb5dde5b3c2f2e778be62/href">https://medium.com/media/12d7962813cbb5dde5b3c2f2e778be62/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c8219637fda357a7e81e5585551e04/href">https://medium.com/media/a6c8219637fda357a7e81e5585551e04/href</a></iframe><p>Both the dev and start script can be used to run your project in the localhost. The start script will be useful for GAE deployment later on.</p><h4>Connect to GAE</h4><p>Download the <a href="https://cloud.google.com/sdk/install">Cloud SDK</a> on your local machine. Then, set up a project on <a href="https://console.cloud.google.com/">Google Cloud Platform</a>.</p><p>To deploy your app on GAE, you will need an app.yaml and also specify your Node version in the package.json. We will use Node 10.x.x for compatibility with Firestore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dad91b6351146161bf0d44998d0f9e7/href">https://medium.com/media/0dad91b6351146161bf0d44998d0f9e7/href</a></iframe><p>Add the following lines to your package.json:</p><pre>&quot;scripts&quot;: {</pre><pre>  &quot;deploy&quot;: &quot;gcloud app deploy&quot;</pre><pre>},</pre><pre>...</pre><pre>&quot;engines&quot;: {</pre><pre>  &quot;node&quot;: &quot;10.x.x&quot;</pre><pre>}</pre><p>Finally, run npm run deploy</p><h4>Setup a simple GraphQL API</h4><p>Install dependencies by running:</p><p>yarn add graphql express apollo-server-express apollo-server-core and yarn add @types/express @types/graphql --dev</p><p>We will create a simple endpoint for graphql at /graphql.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb588fb9fe49edfe4aa560590b5f0e90/href">https://medium.com/media/eb588fb9fe49edfe4aa560590b5f0e90/href</a></iframe><p>At this point, we can run npm run dev and access the graphQL playground interface at URL above.</p><h4>Connecting to Firestore</h4><p>Run yarn add firebase-admin firebase then you can initialize your firestore db using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03a6c18277f9a39e79a9fb2233d10cd5/href">https://medium.com/media/03a6c18277f9a39e79a9fb2233d10cd5/href</a></iframe><h4>(Optional) GraphQL Modularity and Schema design</h4><p>As you can imagine, when your GraphQL application starts to grow, the complexity of the schema (typeDefs and resolver) will grow out of hand. To organize your code, it is ideal to split up schema types and their respective resolvers into different files [4]. Refer to the <a href="https://github.com/Happytreat/graphql-ts-gae-boilerplate/blob/master/src/schema.ts">schema.ts</a> for an example.</p><p>Now, we are done with the basic building block for our project using the different stack! Refer to here for the full code here: <a href="https://github.com/Happytreat/graphql-ts-gae-boilerplate">https://github.com/Happytreat/graphql-ts-gae-boilerplate</a></p><h4>References</h4><p>1. <a href="https://medium.com/google-cloud/apollo-graphql-server-on-google-app-engine-in-under-5-minutes-bbd64050e9ff">https://medium.com/google-cloud/apollo-graphql-server-on-google-app-engine-in-under-5-minutes-bbd64050e9ff</a></p><p>2. Graphql server for express, connect, hapi, koa and more <a href="https://github.com/apollographql/apollo-server">https://github.com/apollographql/apollo-server</a></p><p>3. firestore | javascript sdk | firebase <a href="https://firebase.google.com/docs/reference/js/firebase.firestore">https://firebase.google.com/docs/reference/js/firebase.firestore</a></p><p>4. Modularizing your Graphql schema code <a href="https://www.apollographql.com/blog/modularizing-your-graphql-schema-code-d7f71d5ed5f2">https://www.apollographql.com/blog/modularizing-your-graphql-schema-code-d7f71d5ed5f2</a></p><p>5. Graphql schema design: building evolvable schemas <a href="https://www.apollographql.com/blog/graphql-schema-design-building-evolvable-schemas-1501f3c59ed5">https://www.apollographql.com/blog/graphql-schema-design-building-evolvable-schemas-1501f3c59ed5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2f33aa8ee15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-host-an-apollo-graphql-server-on-gae-with-cloud-firestore-f2f33aa8ee15">How to host an Apollo Graphql Server on GAE with Cloud Firestore</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>