<?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 Amin Shali on Medium]]></title>
        <description><![CDATA[Stories by Amin Shali on Medium]]></description>
        <link>https://medium.com/@amshali?source=rss-b37022614b0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j1S4EapcsqEwqmaOguJpuA.png</url>
            <title>Stories by Amin Shali on Medium</title>
            <link>https://medium.com/@amshali?source=rss-b37022614b0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:01:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amshali/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[To AI or not to AI…]]></title>
            <link>https://medium.com/@amshali/to-ai-or-not-to-ai-1520d6705060?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1520d6705060</guid>
            <category><![CDATA[humanity]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 22:46:44 GMT</pubDate>
            <atom:updated>2026-04-18T22:51:04.115Z</atom:updated>
            <content:encoded><![CDATA[<p>Oh well, I gotta get this off my chest. At this point, even your grandma is using AI to generate something nice to say to you. But let me tell you what: Most people and companies are using AI the wrong way. And there is something scary in that for me. And if that doesn’t scare you, I am here to enlighten you.</p><h3><strong>The ability to think</strong></h3><p>Our over-reliance on AI is going to make us, how do I put this nicely, less smart in various dimensions of our lives. If you have not seen this yet, you will soon. Give it like 5 more years. It’s already happening in education. Students are using AI to turn in homeworks and projects. This is an even bigger problem at higher education because that is when the students should struggle, research and think hard about real-world problems before they get into the workforce, but they are not. Most answers are being handed to them by AI tools and models.</p><p>Look! You need to think and reason with your own mind and then find yourself being wrong about that reasoning. That struggle is necessary. That helps us strengthen those muscles in your brain. The critical muscle. The reasoning muscle. If you are not doing that, you are losing those muscles. That should scare the hell out of you! Because, look around you in the world. What’s happening? We are being ruled by a bunch of idiotic people. We are going to be in even deeper shit if we continue down this path. They are going to manipulate us even more than they do right now! More easily.</p><h3><strong>AI First!</strong></h3><p>So many companies are rebranding themselves or claiming that they are an AI first company. They are even competing with each other to be “more” AI first! Absurd to put it mildly! You should not be an AI first company! You should be humans first! This is another angle of this capitalism mindset where you go scale the product, grow the company, come up with new ideas which are all good to some extent. But now you have run out of ideas and there is this fake sense of urgency to grow. So let’s squeeze in a bunch of non-sense AI which no one asked for, lay off the workers, because why do we need them? AI is doing everything and for a little while we can enjoy our stock price going up because we showed some short term growth(no matter how fake it might be).</p><p>Put humans first, not AI. No one gives a damn if you use AI or not. That’s implementation details. AI doesn’t suddenly make your business efficient or better. In addition, efficiency is not everything. Think sustainability not efficiency. Many things in nature aren’t efficient, but have sustained for billions of years.</p><p>I am hearing more and more that companies are mandating some sort of OKR for the workforce to have to use AI in their work. Thanks for mandating that! We were already doing that, because we are lazy by nature. You don’t need to mandate it. I’ll tell you what you need to mandate. You need to mandate your workforce to not use AI for a day at least and understand the processes in your business better. Because when the shit comes down, people have to go and fix those. You might say, well, we will have an AI agent investigate and take actions. Good luck with that. That works for a toy project not an enterprise level system.</p><p>However, I would not dismiss the idea that AI agents might some day do all of that even in the enterprise level systems which would have serious economic consequences.</p><h3><strong>Illusion of winning with AI</strong></h3><p>There is nothing special about using AI to generate a piece of text or code or an image for you within a matter of seconds, IMHO. I hear some people saying, oh yeah, I don’t even know this system and I wrote a prompt to generate a script for me which does X and Y. Yayyy! What’s special about that? You want a trophy for that? You should not be proud of that. You should be scared.</p><p>Pressure from higher up execs to ship any garbage generated by AI is laughable. You are trying to compress the time it takes for a quality product to ship. You are sacrificing something really big here. Humans are not trained and wired to process such a huge amount of change. Even your users cannot adapt to such changes in time. Your company is replacing workers with AI agents and pouring millions and billions of dollars into AI companies for “the next token”. You see the broken system of economics here, right? These tokens and the dollars that go into AI companies are the demise of creativity and the rise of stupidity.</p><p>This text took me 2–3 hours to write(on and off over the course of two days). But I enjoyed it! I used my brain. I “thought”. And hopefully my mind is not going to rot. Companies will be realizing soon that the AI race is a joke. That they have to step back and take a serious look at all of this. Humans are at stake here.</p><p><em>Stay Human.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9A2hjIvGMCVJrvPG1qsxA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1520d6705060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 9: Asynchronous Distributed System with Persistent Queuing]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-9-asynchronous-distributed-system-with-persistent-queuing-2c330cc1eae2?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c330cc1eae2</guid>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[queuing]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Sat, 19 Nov 2022 05:52:34 GMT</pubDate>
            <atom:updated>2022-11-19T20:12:49.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In the previous episode(<a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">part 1</a>, <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-2-7240d0bad28c">part 2</a>) we discussed the details of a very simple asynchronous distributed system. We looked at the various components of the system such as <em>queue</em>, <em>progress service</em> and <em>response store</em>.</p><p>We discussed that depending on the level of reliability and SLA that we expect from the system, we can omit some of the components or we must include them in the design. For example, if we can withstand a little bit of failure and clients can retry multiple times, perhaps we don’t have to keep track of requests inside a queue and we can get away with an in-memory queue. However, this is not always an option.</p><p>In some systems, due to more strict reliability checks and expectations, we need to have a queue(or a persistent store such as a DB) to keep track of requests. So, in case one of the workers fails, some other one can pick up the request and process it. This is quite often the requirement in streaming systems where your service is responsible to process a request to ingest some data or take an action on behalf of the client. Clients will just fire a request and go. The service is responsible to reliably fulfill the request with no room for failure. In such cases we cannot loosen the queue requirement and need a <em>persistent queuing system</em> such as <strong>AWS SQS</strong> or <strong>Kafka</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*MiVaOyECgwwlK6uw4_zI1A.png" /></figure><p>Architecture</p><p>In this episode we want to explore the usage of <strong>Amazon SQS</strong>, in our <em>Sum of Primes</em> service. The overall architecture of this augmented service will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqN96mOJYSrW5bX-dFJP8Q.png" /><figcaption>Service with SQS as a queuing system.</figcaption></figure><p>The flow and life of a request in this updated system is as we have depicted in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw6VAg3NLbKphq3NSAtQ-A.png" /><figcaption>Life of a request</figcaption></figure><p>The receipt of a request and en-queuing it can be done by a totally different process than the one which processes the requests. Worker threads can run continuously or intermittently depending on what kind of SLA we need. They can run in the same process as the request handler for simplicity or they can be run in a separate process for better reliability and separation of concerns. Those details can be decided based on the project’s requirements and how much time and budgets it has. But, they too contribute to the performance and reliability of the system.</p><p>Queuing helps us achieve the reliability we need. Most queuing systems such as SQS offer a feature where there is a bound on how much time you can hold on to a request. Hence if a worker has taken a request from the queue and has not deleted the request within a time-frame, that request will get added back to the queue. The assumption is that the processing worker has died or taking too long to process the request for whatever reason. This feature will make sure that all requests are eventually processed even if some workers fail.</p><h4>Dead-letter Queue(DLQ)</h4><p>Dead-letter queue is a concept for further increasing the reliability of the system and making sure that there is a bound on the number of retries.</p><p>Let’s say we fail to process a request five times. Shall we continue with retries? Probably not. We need to put a cap on the number of retries because:</p><ul><li>The request might be malformed.</li><li>The request might be too big to be processed.</li><li>Retries only waste the system’s resources.</li></ul><p>We need to track these requests and process them differently or at least inform on-calls about them. To do so, many queuing systems provide an auxiliary queue called <strong><em>Dead-letter</em></strong> which is designated for such requests. The system will track the number of retries for us and put the request in the respective dead-letter queue if need be.</p><h4>Design Requirements</h4><ul><li>Queuing requests is a must. We choose SQS, because it is simple and free(first 1 million) and requires no maintenance or setup on our part.</li><li>All requests must eventually be processed unless they are very big in which case they should be dealt manually or be sent to another system for processing(non-goal). Request timeout should be parameterized(30 seconds max).</li><li>Request handling and processing should be done in the same server process(for simplicity).</li></ul><p>The rest of the requirements come from the original ones <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">here</a>. With this new requirements in mind, let’s dive into the implementation.</p><p>Implementation</p><p><a href="https://aws.amazon.com/sqs/">SQS</a> is a reliable and simple(API-wise) messaging system by Amazon. Using SQS we don’t have to setup our own Kafka system on K8s, which means less maintenance and point of failures in the system. I choose any SaaS if it is reasonably priced and makes my life easier in terms of maintenance.</p><p>For the purpose of this episode, we create a <em>Standard</em> queue. The exact order of the requests doesn’t matter and they should not block one another, hence we don’t really need a FIFO queue. Once the queue is created, it will have a <em>URL</em> and an <em>ARN</em> which later we use to access and manipulate the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSnD2pKllUfDYy1MJ4g7fQ.png" /><figcaption>Main queue config</figcaption></figure><p>For our SQS queue we also need to setup a dead-letter queue to route the requests we cannot process(e.g. when the input range is too huge). For this queue we will set the visibility timeout to 10 min instead of 30 seconds. This is so that we can properly process the requests if they are taking too long. This is similar to processing a <strong><em>purgatory</em></strong> in many distributed systems. Usually either we need human intervention or a ticket, or that we will process these requests by a secondary system.</p><p>Here is our DLQ setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDgj7mFSs2dBiXsruQwyEw.png" /><figcaption>DLQ Config</figcaption></figure><p>Here we connect the DLQ to the main queue. As can be seen, if we cannot process the request after 3 tries, it will be sent to the DLQ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*v03cl1M1pS1LFna2uuz6HA.png" /><figcaption>Setting up DLQ for the main queue</figcaption></figure><p>The content of the queue is up to you. It is a string and you can interpret it as whatever you like. We will interpret it as JSON.</p><p>Sending messages to the queue is done by the POST handler as follows:</p><pre>  final var now = System.currentTimeMillis();<br>  // Create a response with status QUEUED and add it to the response store:<br>  var response = new SumPrimeResponse(requestId)<br>      .withStatus(SumPrimeResponse.Status.RECEIVED);<br>  response.queuedTimeMs = now;<br>  responseStore.updateResponse(response);<br>  <br>  // Enqueue the request:<br>  Gson gson = new Gson();<br>  gson.toJson(request);<br>  SendMessageRequest sendSqsRequest = new SendMessageRequest()<br>      .withQueueUrl(queueUrl)<br>      .withMessageBody(gson.toJson(request))<br>      .withDelaySeconds(1);<br>  sqs.sendMessage(sendSqsRequest);<br>  response.setStatus(SumPrimeResponse.Status.QUEUED);<br>  responseStore.updateResponse(response);</pre><p>As can be seen in the above gist, we first update the response store with a response and set its status to RECEIVED. Once we send the message to the SQS we change the status of the response to QUEUED.</p><h4>Concurrency Control</h4><p>In order to <em>control the concurrency</em> on the server side as well as the request timeout, we need a way of monitoring the tasks which are running. To do so we keep track of the number of tasks running using an atomic integer. When we submit a task to the executor service we should increase this counter when we are done with it we should decrement it. The challenge in such cases is that you should make sure you always reach the path where you end up decrementing the counter or otherwise you will create a starvation scenario.</p><p>In order to monitor tasks and make sure they finish within the specified timeout limit, we are going to take advantage of the executor service and Java Futures. Every time we run a task we also launch a parallel thread(task) which waits on the result of the original task. If the wait is more than specified timeout, e.g. 30 seconds, it should cancel the task. The following gist shows the pseudo-code for concurrency control and timeout monitoring:</p><pre>...<br>  concurrencySemaphore = new Semaphore(maxConcurrency, true);<br>...<br><br>@Scheduled(fixedDelay = 10, initialDelay = 2000)<br>private void retrieveRequestFromSqs() throws InterruptedException {<br>  concurrencySemaphore.acquire();<br>  var receiveMessageResult =<br>      sqs.receiveMessage(new ReceiveMessageRequest().withQueueUrl(queueUrl)<br>          .withMaxNumberOfMessages(1).withVisibilityTimeout(requestTimeoutSec)<br>          .withWaitTimeSeconds(20));<br>  if (receiveMessageResult.getMessages().isEmpty()) {<br>    concurrencySemaphore.release();<br>  } else {<br>    var msg = receiveMessageResult.getMessages().get(0);<br>    System.out.println(&quot;Got message: &quot; + msg.getBody());<br>    Gson gson = new Gson();<br>    // create task...<br>    var future = executorService.submit(runRequest(gson.fromJson(msg.getBody(),<br>            SumPrimeRequest.class), msg.getReceiptHandle()));<br>    // Monitor the task and cancel if it exceeds the response timeout.<br>    executorService.submit(() -&gt; {<br>      try {<br>        future.get(requestTimeoutSec - 1, TimeUnit.SECONDS);<br>      } catch (InterruptedException | ExecutionException | TimeoutException e) {<br>        future.cancel(true);<br>      }<br>      concurrencySemaphore.release();<br>    });<br>  }<br>}</pre><p>How can we cancel a long-running task though? That is very application specific. In our case the part where it loops over numbers and calculates the primes is a time-consuming part. We should check in that loop whether or not we have to stop because the thread is canceled.</p><pre>public static Long sumPrime(int a, int b) throws InterruptedException {<br>  var sum = 0L;<br>  for (int i = a; i &lt; b; i++) {<br>    // Yield every 10000 computation. We don&#39;t want <br>    // to yield too often.<br>    if (i % 10000 == 0) {<br>      if (Thread.currentThread().isInterrupted()) {<br>        throw new InterruptedException();<br>      }<br>      Thread.yield();<br>    }<br>    sum += (isPrime(i) ? i : 0);<br>  }<br>  return sum;<br>}</pre><h4>K8s Configuration</h4><p>K8s configuration is fairly similar to the one for the previous episode. In this episode we added a secret for AWS key and secret. In addition to that we also added a few more parameters for queue url and concurrency control arguments to the program and the docker file.</p><p>In the previous episode we used a StatefulSet model for deployment, but in this episode, since the servers do not have any state and everything is either in SQS or in the response store we are going to use a simple Deployment K8s’s construct.</p><p>Testing</p><p>Similar to the previous episode we will run a scale test of this system with the same set of queries and configuration. In the previous episode we ran the test with a duration of 100 seconds at 10 QPS. We will run the same test here and the results are:</p><pre>http.codes.200: ..................................... 2000<br>http.request_rate: .................................. 20/sec<br>http.requests: ...................................... 2000<br>http.response_time:<br>  min: .............................................. 3<br>  max: .............................................. 436<br>  median: ........................................... 87.4<br>  p95: .............................................. 228.2<br>  p99: .............................................. 295.9<br>http.responses: ..................................... 2000<br>vusers.completed: ................................... 1000<br>vusers.created: ..................................... 1000<br>vusers.created_by_name.Async sumPrime load test: .... 1000<br>vusers.failed: ...................................... 0<br>vusers.session_length:<br><strong>  min: .............................................. 5094.7<br>  max: .............................................. 5557.2<br>  median: ........................................... 5168<br>  p95: .............................................. 5272.4<br>  p99: .............................................. 5378.9</strong></pre><p>These results are actually very close to what we had in the previous episode where we used an in-memory queue. In the previous episode the p95 was 4147 ms whereas here it is 5272 ms. A small difference due to various network delays. It is a small cost we pay for a greater pay which is more reliability.</p><p>Summary</p><p>In this episode we tried to bring more reliability to the system by adding persistent queuing to our asynchronous distributed system. We also went through the challenges of concurrency control in the servers.</p><p>We discussed how we can implement request timeouts and how the queuing systems such as SQS could help us route big requests to a secondary queue for further processing.</p><p>The code for this episode can be found at <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode09">episode 9</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c330cc1eae2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-9-asynchronous-distributed-system-with-persistent-queuing-2c330cc1eae2">Episode 9: Asynchronous Distributed System with Persistent Queuing</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 8: The one with Asynchronous Distributed Systems(Part 2).]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-2-7240d0bad28c?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7240d0bad28c</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[couchdb]]></category>
            <category><![CDATA[artillery]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 05:17:35 GMT</pubDate>
            <atom:updated>2022-09-13T19:14:34.024Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In the <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">previous part of this episode</a> we looked at the basic concepts of asynchronous distributed systems. We saw the general architecture and towards the end we looked at the design of an asynchronous system for our <em>Sum of Primes</em> service. In this part, we will look at the detailed implementation of this new system. So, expect a lot of code! :)</p><p>The following figure shows how request handling is done in the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-trn-rxJstgqCzV6esKTTg.png" /><figcaption>Sum of Primes Asynchronous System Architecture</figcaption></figure><p>Each server instance has an <em>internal concurrent queue</em> in which it stores the requests. As soon as the request is put into the queue, it is also put into the <em>response store</em> and a response is returned to the client immediately.</p><p>Response store, as mentioned in the <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">previous part</a>, can be a Redis store or MongoDB or a CouchDB. For no particular reason we chose (OK, I just wanted to learn) CouchDB as a response store. To abstract the choice, the server uses the following interface to talk to any response store:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608891caac118e9ed68c8dd9979057b2/href">https://medium.com/media/608891caac118e9ed68c8dd9979057b2/href</a></iframe><p>And here is a CouchDB implementation of this interface using <a href="https://github.com/helun/Ektorp">ektorp</a> library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d391c20219367af3b7395d2649dab078/href">https://medium.com/media/d391c20219367af3b7395d2649dab078/href</a></iframe><p>The implementation class’s full name for the response store is passed to the server as an argument. For example:</p><pre>--response_store_class com.github.amshali.asynchronous.sumofprime.CouchDbResponseRepository</pre><p>This way, we are decoupling the response store implementation from the server’s code. Here is how the server is initialized and response store instance is created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b02c0cd3107e477546399f88586b7a/href">https://medium.com/media/b6b02c0cd3107e477546399f88586b7a/href</a></iframe><p>Server has a pool of threads running inside the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html">executor service</a> which grab work from the queue and compute the responses. They then update the response store with the right status and response when available. In our implementation, the queue will be hidden inside the executor service. As can be seen in the above code, we have instantiated a <em>work stealing pool</em> for the executor service.</p><p>API Implementation</p><p>Here is an example of the POST operation by which a client sends a request to the server.</p><pre><em>POST</em><strong> /sumPrime <br></strong>BODY:<br>{<br>  a: Positive integer<br>  b: Positive integer<br>}</pre><pre>RESPONSE:<br>{<br>  &quot;status&quot;:&quot;QUEUED&quot;,<br>  &quot;sum&quot;:null,<br>  &quot;processingTimeMs&quot;:null,<br>  &quot;queuedTimeMs&quot;:null,<br>  &quot;ttl&quot;:null,<br>  &quot;_id&quot;:&quot;ae93958c-2812-4135-8ab1-037c176439b7&quot;,<br>  &quot;_rev&quot;:&quot;1-24179f86c5df5ac8c3b43a6a40816ca6&quot;<br>}</pre><p>Here is the implementation of the POST:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb5eaa0c6478b4c8e725789a91fae632/href">https://medium.com/media/cb5eaa0c6478b4c8e725789a91fae632/href</a></iframe><p>The GET API which is for polling responses are as follows:</p><pre><em>GET</em><strong> /sumPrime/{requestId}</strong></pre><pre>RESPONSE:<br>{<br>  &quot;status&quot;:&quot;IN_PROGRESS&quot;,<br>  &quot;sum&quot;:null,<br>  &quot;processingTimeMs&quot;:null,<br>  &quot;queuedTimeMs&quot;:26,<br>  &quot;ttl&quot;:null,<br>  &quot;_id&quot;:&quot;ae93958c-2812-4135-8ab1-037c176439b7&quot;,<br>  &quot;_rev&quot;:&quot;2-8d87a0fad8e6b097e15014e889cd6761&quot;<br>}</pre><p>The implementation of GET is fairly simple. It only needs to make a call to the response store:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/665cd9b540a42f796faea726e1351943/href">https://medium.com/media/665cd9b540a42f796faea726e1351943/href</a></iframe><p>Notice how we throw an exception in case the response is not found. This particular exception is handled by the Spring Framework and returned to the user as a NOT_FOUND response.</p><p>This concludes our super simple API. Next we will look at the K8s deployment.</p><p>Deployment in K8s</p><p>The components we need to deploy are:</p><ul><li>Servers(Replicated, StatefulSet)</li><li>CouchDB(using Helm)</li></ul><p><strong>Server Setup</strong></p><p>Since the servers carry some sort of state(the in-memory queue), we found it appropriate to use <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/"><em>StatefulSet</em> deployment</a>. We can use a regular deployment, but with a StatefulSet deployment we could make one of the servers, for example the zeroth one, responsible for cleaning up the CouchDB. The cleanup involves removing all the responses which are past their TTL.</p><p>Dockerfile for server is fairly simple. You can see the <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode08/server">repo</a> for the <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/blob/main/episode08/server/Dockerfile">code</a>.</p><p>The K8s deployment for the server is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4243be8b81ceb7f5cf983c7dd00a9f/href">https://medium.com/media/be4243be8b81ceb7f5cf983c7dd00a9f/href</a></iframe><p>Important thing to notice is how we are passing the CouchDB related environment variables from the secret store to the container. Also we have a load balancer set up on top of the StatefulSet servers.</p><p><strong>CouchDB Setup</strong></p><p>To setup CouchDB inside K8s cluster do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a2d54eaf65d5de5c41a160e45b9421/href">https://medium.com/media/b5a2d54eaf65d5de5c41a160e45b9421/href</a></iframe><p>This will set up CouchDB servers with some dummy username and password which is good for the purpose of this guide. The username and password are stored in a K8s’ as a secret resource. That way, we can later reference those secrets from other K8s deployment YAML files and pass them to the server.</p><p>To deploy the servers, run this:</p><pre>$ kubectl apply -f server/deployment.yaml</pre><p>If everything goes well, we should have servers up and running at this point. Try to get the load balancer’s address:</p><pre>$ kubectl describe services primesum-async-server<br>Name:                     primesum-async-server<br>Namespace:                default<br>Labels:                   app=primesum-async-server<br>Annotations:              &lt;none&gt;<br>Selector:                 app=primesum-async-server<br>Type:                     LoadBalancer<br>IP Family Policy:         SingleStack<br>IP Families:              IPv4<br>IP:                       10.102.99.52<br>IPs:                      10.102.99.52<br>LoadBalancer Ingress:     10.102.99.52<br>Port:                     &lt;unset&gt;  80/TCP<br>TargetPort:               80/TCP</pre><p>Let’s grab the load balancer IP address and try to send a request to the server:</p><pre>$ curl -s -X POST -H &quot;Content-Type: application/json&quot; <a href="http://10.102.99.52/sumPrime">http://10.102.99.52/sumPrime</a> --data &#39;{&quot;a&quot;: 2, &quot;b&quot;: 60000000}&#39;</pre><pre>{&quot;status&quot;:&quot;QUEUED&quot;,&quot;sum&quot;:null,&quot;processingTimeMs&quot;:null,&quot;queuedTimeMs&quot;:null,&quot;ttl&quot;:null,&quot;_id&quot;:&quot;<strong>d483b7b9-df4a-4116-a4c1-10f97f249c89</strong>&quot;,&quot;_rev&quot;:&quot;1-24179f86c5df5ac8c3b43a6a40816ca6&quot;}</pre><p>Given the _id, let’s get the status of the response:</p><pre>$ curl <a href="http://10.102.99.52/sumPrime/d483b7b9-df4a-4116-a4c1-10f97f249c89">http://10.102.99.52/sumPrime/<strong>d483b7b9-df4a-4116-a4c1-10f97f249c89</strong></a><br>{&quot;status&quot;:&quot;<strong>FINISHED</strong>&quot;,&quot;sum&quot;:103468900363400,&quot;processingTimeMs&quot;:30028,&quot;queuedTimeMs&quot;:62,&quot;ttl&quot;:1663021380859,&quot;_id&quot;:&quot;d483b7b9-df4a-4116-a4c1-10f97f249c89&quot;,&quot;_rev&quot;:&quot;3-4a0643c37d835c45ce006e306bbee28f&quot;}%</pre><p>LGTM! :)</p><p>Scale Testing</p><p>It would not be a good build if we don’t scale test it! Scale testing asynchronous systems is a bit more complicated and not as straightforward as synchronous ones. We cannot just measure how quickly one call to the POST method returns. We have to measure the latency of the whole flow, from POST to the final GET when we get the final result and the status is FINISHED. This flow is as follows:</p><pre>0- Start timer<br>1- POST a request<br>2- GET response<br>3- loop until response.status == &quot;FINISHED&quot;<br>3.1- WAIT for 5 seconds<br>3.2- GET response<br>4- Stop timer</pre><p>As you can see in the above test flow, every request actually turns into at least two requests(most likely more than 3 in most cases). So, if we set the <em>arrival rate</em> to 15 requests per second, we are throwing almost 30 requests per second at the servers(We will in fact see this when we run artillery and see its report). This is an <em>important consideration</em> when we are comparing a synchronous system with its asynchronous counterpart. Keeping this consideration in mind, we will set the arrival rate to 10 for our test and given the hardware we have.</p><p>Another important point in the above test flow is how much we wait before poll. If we poll too often, servers will be overloaded with GET requests and their resources are consumed by responding to those as opposed to computing the results. On the other hand, if we poll not so often, that will hurt our latency and performance for each individual request. So, it is a fine line and we need to find it with experiment perhaps. In addition, it is essential to have a good throttling mechanism in place to guard against bad clients.</p><p>We are going to use some advanced features in artillery to do the scale testing. Read more about that <a href="https://www.artillery.io/docs/guides/guides/http-reference#looping-with-custom-logic">here</a>. Here is the artillery test config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db1771358c3fe247b973b1e54711eb1c/href">https://medium.com/media/db1771358c3fe247b973b1e54711eb1c/href</a></iframe><p>Notice the flow in the <em>Async </em><em>sumPrime load test</em> scenario. First it does a POST. It then captures the requestId from the response. Then it enters a <em>loop</em> where it sends GET requests to the server until it sees a FINISHED status. notFinished is a JS function which is defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb4df49cdb087a2323e0345630d91c16/href">https://medium.com/media/fb4df49cdb087a2323e0345630d91c16/href</a></iframe><p>To run the load test run the following command:</p><pre>$ artillery run -t &quot;http://${SERVER_IP}&quot; scale-test.yaml</pre><p>After load test is done, we see the following report:</p><pre>http.codes.200: ................................... 3014<br><strong>http.request_rate: ................................ 30/sec<br></strong>http.requests: .................................... 3014<br>http.response_time:<br>  min: ............................................ 3<br>  max: ............................................ 155<br>  median: ......................................... 30.9<br>  p95: ............................................ 70.1<br>  p99: ............................................ 100.5<br>http.responses: ................................... 3014<br>vusers.completed: ................................. 1000<br>vusers.created: ................................... 1000<br>vusers.created_by_name.Async sumPrime load test: .. 1000<br>vusers.failed: .................................... 0<br>vusers.session_length:<br><strong>  min: ............................................ 4051.4<br>  max: ............................................ 6259.6<br>  median: ......................................... 4147.4<br>  p95: ............................................ 4147.4<br>  p99: ............................................ 6064.7</strong></pre><p>Notice how the arrival rate says <strong>30/sec</strong>, even though we asked for 10 requests per second. Overall, there is more network traffic when we are dealing with asynchronous systems. The performance numbers are not bad but they are not as good as the synchronous ones. Some of this is due to increased network traffic and queuing. As we mentioned before, an asynchronous system has its own advantage and disadvantages.</p><p>Summary</p><p>We went through implementation of an asynchronous distributed system for <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/concurrency-and-distributed-systems-a-guide-with-kubernetes-376cb4cdebf3">Sum of Primes service</a>. We decided that we only need the <em>response store</em> from the <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">three optional components</a> of the distributed system.</p><p>We scale tested the system and realized how an asynchronous architecture would affect the performance.</p><p>We can further explore and expand this very system and use a queue service such as Kafka and test some faulty scenarios and observe the behavior of the asynchronous system. That will be a story for another episode. See you then.</p><ul><li><a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode08">Episode 8 codes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7240d0bad28c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-2-7240d0bad28c">Episode 8: The one with Asynchronous Distributed Systems(Part 2).</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 8: The one with Asynchronous Distributed Systems(Part 1).]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a07b85736814</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[non-blocking]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 21:27:39 GMT</pubDate>
            <atom:updated>2022-09-07T22:41:39.218Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>So far we have been studying synchronous distributed systems. The client sends a request and waits for a response. On the server side of stuff, the servers respond to the requests immediately and a communication link is established between the client and server. That is one way of communication between clients and servers. Another popular way is asynchronous communication.</p><p>In asynchronous communication, the client sends a request to the server and the server, instead of providing the actual response right away, sends back a response to the client confirming that it has received the request. Server will queue the requests. Client then <em>polls</em> the server for the actual response. Server might still respond with something like <em>come back later</em>, but <em>eventually</em> the server will respond with the final response. There is no global clock by which components can coordinate. Synchronous communication is blocking and asynchronous communication is non-blocking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*wlyLNjtobbotjVWbkCxTjQ.png" /><figcaption>Synchronous vs Asynchronous Communication</figcaption></figure><p>As you can imagine, asynchronous communication is a bit more complicated than synchronous communication. It involves following a <em>protocol</em> between client and server and it is not as straightforward as synchronous one. That is not to say that synchronous systems do not have a protocol. They do, but it is usually hidden behind operating system calls. In distributed systems, nothing is really synchronous. We just create an illusion of synchrony by <em>waiting</em>.</p><p>Asynchronous distributed systems are prevalent in business and have their own advantages. Asynchrony would remove the pressure of immediate execution from the server. Server can take its time(still respecting the SLA) and respond when it can. Facebook’s famous query engine, Presto, is asynchronous.</p><p>Note that many services may look synchronous when you deal with them, but in fact they are asynchronous in implementation. Client libraries can hide the asynchronous nature of the server and make it look like the server is synchronous. They do that by <em>busy-waiting</em> or <em>blocking IO</em>. Hence using libraries we can encapsulate the implementation details and make it simpler(or synchronous) for clients to communicate with asynchronous systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZbq94mBiojuC6xVMhhQHA.png" /><figcaption>Blocking Client Library</figcaption></figure><p>Asynchronous distributed systems are more appropriate for non-interactive use-cases. They are not necessarily bad for interactive or dashboarding scenarios, but they could pose some challenges.</p><p>In this episode we want to see how we can design and implement an asynchronous version of the <em>Sum of Primes</em> service.</p><p>Architecture</p><p>Every asynchronous distributed systems follows a more or less generic architecture. Obviously, due to business needs, more components can be added to the whole system, but with respect to asynchrony, they are all like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Sz1NXti0lb-bWYTdIIm28A.png" /><figcaption>Asynchronous System Architecture</figcaption></figure><p>Major new components in this architecture are:</p><ul><li>Request queue: to queue the requests for processing later.</li><li>Response store: to store the responses to be served to clients when they poll.</li><li>Progress service: to inform clients about the progress or status of their requests.</li></ul><p>The rest of the components are always there in a distributed system. However, these three components are optional. They do exist in any asynchronous distributed system in one form or the other, but their full existence is not detrimental to the function of the system.</p><p>Queue</p><p>The implementation of these components could vary significantly depending on what kind of reliability we want from the system or what our SLA is. For example, we could leverage an in-memory queue or a fully-fledged queue service(SQS, Kafka, etc.). Obviously, using something like SQS is a must if we want a very reliable and fault tolerant system. But if we relax the requirements on reliability, we can get away with an in-memory(ephemeral) queue. With that design choice, clients will have to retry in case of any server failures.</p><p>Response Store</p><p>Moreover, we can store responses in an in-memory cache vs a persistent store such as a Relational DB, NoSQL or simply a filesystem such as S3. Either of these decisions will have its own implications with respect to the system’s reliability. If we store responses in memory, we have two limitations:</p><ul><li>Number of responses that can be stored. Hence we have to set a <em>time-to-live(TTL)</em> on responses.</li><li>Server failure will result in re-computation of associated requests(through client retry or server auto-retry).</li></ul><p>With a persistent response store, we have much less limitation on the number of responses that we can keep. Also, we can have a much longer TTL.</p><p>Progress service can be a first-class component in the design or can be hidden in the server’s implementation. It really depends on requirements and whether we want to lift the pressure of polling from our servers.</p><p>Load Balancer</p><p>On the load-balancer side of the story, asynchronous systems create new challenges. Since the communication channel is non-blocking and has to be re-established again and again, load-balancer might have to take into account the <em>client and server affinity</em> depending on prior decisions we have made in the architecture. For example, if responses are stored in the memory of each server, then we will have to know which server we need to go to from the load-balancer when a client does a <em>poll</em>. This is usually done by load-balancer using a <em>cookie</em> stored in the <em>request’s header</em>. <br>But if the responses are stored in a persistent database, any server instance could potentially return the response and there is no need for any affinity mechanism.</p><p>To summarize, requirements and design decisions on these components will impact various details of the implementation and server/client’s interactions.</p><p>Throttling</p><p>Similar to synchronous model, clients can still abuse/misuse the system by excessively polling for responses. To remedy that, we have a few options:</p><ul><li>Develop a client library which will take care of sending requests and receiving responses. This library would decide how often it should poll and follow a safe protocol when communicating with the servers.</li><li>Implement throttling on the server side.</li></ul><p>Doing at least one of these options is a must if we want to have a secure and reliable system.</p><h4>Sum of Primes Asynchronous Distributed System</h4><p>Requirements</p><p>We need the same functional requirements that we presented in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/concurrency-and-distributed-systems-a-guide-with-kubernetes-376cb4cdebf3">episode 1</a>. But with respect to asynchronous distributed system we have the following (non-functional) requirements:</p><ul><li>Simple replicated servers(no workers)</li><li>Simple load-balancer(no affinity)</li><li>TTL of 3 min for responses</li><li>Reliability requirements are loose. Clients should retry in case of any server’s failure after 3 min.</li><li>No progress service. Any server should be able to provide responses or their statuses.</li></ul><p>With those requirements in mind, let’s look at the architecture of the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*FP7ZSItfnWN92R-GyDsN6w.png" /><figcaption>Sum of Primes Asynchronous System Architecture</figcaption></figure><p>As we can see in the above figure, we have <em>omitted the progress service and the queue</em>, because this architecture would satisfy our requirements.</p><p>For <em>response store</em> we can use Redis, MongoDB or CouchDB. Once server receives a request, it creates an entry in the response store with the request id. Initially, it set the value of the entry to IN_PROGRESS like so:</p><pre>a6f39925-4234-450e-a25b-cc3991c68d77 -&gt; {<br>  &quot;requestId&quot;: &quot;a6f39925-4234-450e-a25b-cc3991c68d77&quot;,<br>  &quot;status&quot;: &quot;IN_PROGRESS&quot;,<br>  &quot;payload&quot;: null<br>}</pre><p>And it returns this response to the client immediately. Using the provided requestId, the client can poll for the response later.</p><p>API Spec</p><p>Here is the API spec for this service in an asynchronous model:</p><pre><em>POST</em><strong> /sumPrime <br></strong>BODY:<br>{<br>  a: Positive integer<br>  b: Positive integer<br>}</pre><pre>RESPONSE:<br><strong>{<br>  requestId: String<br>  status: String<br>  payload: String<br>}</strong></pre><p>In order to poll for the status of the response, one should use the following GET endpoint:</p><pre><em>GET</em><strong> /sumPrime/{requestId}</strong></pre><pre>RESPONSE:<br><strong>{<br>  requestId: String<br>  status: String<br>  payload: String<br>}</strong></pre><p>Client must poll until the status is FINISHED. Once that happens, the payload fields will have the actual response in it.</p><p>The poll request can go to any server instance, since the response and its status is stored in the response store using the requestId.</p><p>Here we can see the value of client libraries in asynchronous. They can hide these implementation details from the client and can make it look like we are dealing with a synchronous one.</p><p>In the next part of this episode we will go through the implementation details and how to use Kubernetes to deploy our system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a07b85736814" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-8-the-one-with-asynchronous-distributed-systems-part-1-a07b85736814">Episode 8: The one with Asynchronous Distributed Systems(Part 1).</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 7: Let’s build a distributed cache(Part 3/3: Cache Servers and Consistent Hashing).]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-3-cache-servers-and-consistent-hashing-71bdeae3bba2?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/71bdeae3bba2</guid>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 04:37:18 GMT</pubDate>
            <atom:updated>2022-08-17T03:20:27.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In this part we will see how we can take advantage of <em>Consistent hashing</em> to reduce the rehashing problem. We also learn about the Cache Server’s logic and API. Let’s dive right into it.</p><p>Consistent Hashing</p><p>The idea behind the consistent hashing is that we hash both the keys as well as the cache locations(worker’s IP Address or DNS name) <em>using the same hash function</em> on a <em>circular structure</em>. There are two important things to notice here:</p><ul><li>Cache location(worker’s address) is hashed using the same function that is used to hash the cache keys.</li><li>Hash values are formed on a circular structure.</li></ul><p>Let’s visualize this to learn it better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJcwumv4jIWIwZG46MF08Q.jpeg" /><figcaption>Consistent Hashing on the unit circle</figcaption></figure><p>Using the same hash function, workers are mapped on a circle. We only need to map the hash of their IP Address or DNS name to a point on circle which is fairly easy. This is the code to do so in Java:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e2e528b9d10407747c35717db901c7/href">https://medium.com/media/e7e2e528b9d10407747c35717db901c7/href</a></iframe><p>We are using SHA1 algorithm to get a digest of the key and then call the Java’s built-in hashCode method on that hex string to get an integer. We then get the remainder of dividing that integer hash code by <strong>2π</strong>. That should give us a value <em>between 0 and 2π</em>. <br>Note that if the remainder is negative, we add 2π to it.</p><p>Why do we call SHA1 on the key? Using the hashCode method by itself is not good enough. For close keys it actually gives very close hash codes. For example:</p><pre>&quot;key1&quot;.hashCode() = 3288498<br>&quot;key2&quot;.hashCode() = 3288499</pre><p>However, after getting the SHA1, we are dealing with widely different strings which should have different hash codes.</p><p><strong>How to find the right worker?</strong></p><p>To find the right worker, the cache server will keep a sorted list of workers based on their hash value. For any cache key to lookup, server simply finds the closest worker whose hash value is greater than or equal to the hash value of the key.</p><p>To do so in Java, we keep a sorted set for workers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8bcff1053a88735b7399a713b72539c/href">https://medium.com/media/a8bcff1053a88735b7399a713b72539c/href</a></iframe><p>As can be seen in the above code, we use the ringHash method to compare workers against each other. The following piece of code finds the location of the key between various workers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d7b8cb59ad806d90671374d4322ff83/href">https://medium.com/media/6d7b8cb59ad806d90671374d4322ff83/href</a></iframe><p>As can be seen, we wrap around the circle when there is no ceiling for a key.</p><p><strong>Consistent Hashing Replicas</strong></p><p>Looking at the example above, you can notice a problem right away. Depending on the hash values of workers, the distribution of keys to various workers can be quite asymmetric. That will result in some workers being overloaded. How can we tackle this issue? The idea to solve this is to create replicas of the cache workers over the ring. For example, instead of just one worker 1, we will have 5 of it scattered over the ring with the following names:</p><pre>worker 1-0: hash = 0.5<br>worker 1-1: hash = 1.2<br>worker 1-2: hash = 5.3<br>worker 1-3: hash = 2.9<br>worker 1-4: hash = 4.7</pre><p>This way, the keys will be scattered more equally between various workers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQf1Xcxkz77ZXudhQIAjcA.jpeg" /><figcaption>Consistent Hashing Replicas</figcaption></figure><p>The number of replicas for each worker can be different based on their hardware spec. Better machines with more hardware can have more replicas. Doing so is possible if we publish the worker’s hardware spec to the ZooKeeper along with the worker’s address.</p><p>If a worker is added to the pool or dies, we will have some cache misses. However, those are localized and small compared to re-hashing everything.</p><p>We should tweak the <strong>find-location</strong> code to account for replicas. We can do this easily by stripping anything after the last - from the worker’s name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b152c998494245ff96526f314cf2a1c/href">https://medium.com/media/4b152c998494245ff96526f314cf2a1c/href</a></iframe><p>Accesses to the workerSortedSet must be coordinated and thread-safe. To Make that happen, we use a ReentrantReadWriteLock in methods that access this set.</p><p><strong>Fetching Workers</strong></p><p>As we mentioned in the previous part the server should contact the ZooKeeper to get the list of workers. Once it did that, it will replicate each worker’s address and put them in the sorted set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6746cc12d378b0b5b544327e6eb64204/href">https://medium.com/media/6746cc12d378b0b5b544327e6eb64204/href</a></iframe><p>Cache Server’s API</p><p>The cache server will expose a similar API as worker for accessing the cache. But in the server’s code, we proxy the request to the <em>right</em> worker:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5a5184c47b9fdaa082a290443896c40/href">https://medium.com/media/e5a5184c47b9fdaa082a290443896c40/href</a></iframe><p>One thing to notice in the above code is that we check for the response’s status code and if it is not a 2XX code, we throw an error.</p><p>Deployment</p><p>To deploy the cache servers, we can use a K8s deployment entity. Unlike workers, there is no special state that servers keep and we don’t need them to have any stable DNS names.</p><p>That said, as we demonstrated before, we want to have a <em>Load Balancer</em> in front of the cache server nodes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70b76b06a9fb63738e0d957cbd2aa6f9/href">https://medium.com/media/70b76b06a9fb63738e0d957cbd2aa6f9/href</a></iframe><p>Now, let’s try to hit the cache server’s load balancer:</p><pre># Set aa in cache to 117<br>curl -X PUT -H &#39;Content-Type: application/json&#39; http://10.98.47.24/set/aa --data &#39;117</pre><pre># Get aa from cache<br>curl  -H &#39;Content-Type: application/json&#39; <a href="http://10.98.47.24/get/aa">http://10.98.47.24/get/aa</a></pre><p>Conclusions</p><p>Congratulations! If you have followed this episode from beginning, you have made your distributed cache system. Well done.</p><p>There are a number of details that we can explore in this cache system.</p><ul><li>Adding more cache shards to each worker based on their memory size.</li><li>Variable number of replicas based on worker’s spec.</li></ul><p>But for now, we leave that to the interested readers.</p><p>Important lessons from this episode were:</p><ul><li>The role of zookeeper(or other alike systems) in creating a highly available distributed system.</li><li>Consistent Hashing Scheme</li><li>Yet another important application of coordinator/workers architecture.</li></ul><p>Episode’s full code can be found here:</p><p><a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode07">Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/episode07 at main · amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71bdeae3bba2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-3-cache-servers-and-consistent-hashing-71bdeae3bba2">Episode 7: Let’s build a distributed cache(Part 3/3: Cache Servers and Consistent Hashing).</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 7: Let’s build a distributed cache(Part 2/3: Workers and ZooKeeper).]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-2-workers-and-zookeeper-fb6e7e4fa6d1?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6e7e4fa6d1</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Sun, 14 Aug 2022 23:58:47 GMT</pubDate>
            <atom:updated>2022-08-17T03:20:09.550Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In the previous part of this episode we saw the details of implementation of basic cache and eviction strategy. In this part, we look at the design of the distributed system as a whole. Here is the overall architecture of the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS24Vtpv2qFMX7kErwtfnw.png" /><figcaption>Architecture of the system in more details</figcaption></figure><p>As mentioned before, we have cache servers which handle requests from clients. They are like the coordinator in the coordinator and workers architecture we presented in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-6-the-one-with-coordinator-and-workers-873273d93ae7">episode 6</a>. In that episode we saw that workers registered themselves with the coordinator. However, that is not the only way to discover workers. An alternative design is the one where workers register themselves with a Zookeeper cluster. The servers can then get the IP addresses of workers from Zookeeper.<br>This is a more advanced version of what we saw in episode 6. This new design based on Zookeeper has some advantages:</p><ul><li>Better high availability with multiple servers. No single point of failure.</li><li>Workers are not tied to a specific server/coordinator.</li></ul><p>On the other hand we have to manage a zookeeper cluster which is <em>not</em> the worst thing in the world.</p><p>The important steps in this new cache architecture are:</p><ul><li>Workers add their IP address to zookeeper as an <strong><em>ephemeral</em></strong> <em>znode</em>.</li><li>Servers read the list of worker <strong>znodes</strong> and their content(IP Address) from zookeeper.</li><li>Servers direct the cache request to the right worker based on <strong>consistent hashing on a ring</strong>.</li></ul><p>We are going to briefly explain the consistent hashing on a ring, but if you want some in-depth information on that, please read <a href="https://ably.com/blog/implementing-efficient-consistent-hashing">this article</a>.</p><p>Zookeeper</p><blockquote>ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications.</blockquote><p>Above quote is from Apache ZooKeeper page which says it all. Just know that Zookeeper is great for reliably keeping track(but not limited to this) of configurations of a distributed system.</p><p>To install ZooKeeper on K8s, we are going to simply follow this article from K8s’ website:</p><p><a href="https://kubernetes.io/docs/tutorials/stateful-application/zookeeper/">Running ZooKeeper, A Distributed System Coordinator</a></p><p>After installation run:</p><pre>kubectl get pods,services</pre><p>And you should see an output similar to:</p><pre>pod/zk-0             1/1     Running   0          2d15h<br>pod/zk-1             1/1     Running   0          2d15h<br>pod/zk-2             1/1     Running   0          2d15h</pre><pre>NAME                   TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)             AGE<br>service/kubernetes     ClusterIP      10.96.0.1       &lt;none&gt;        443/TCP             34d<br><strong>service/zk-cs</strong>          LoadBalancer   10.98.70.73     10.98.70.73   2181:31461/TCP      2d15h<br>service/zk-hs          ClusterIP      None            &lt;none&gt;        2888/TCP,3888/TCP   2d15h</pre><p>The zookeeper is available on this K8s’s cluster via the following DNS name:</p><pre><strong>zk-cs</strong>.default.svc.cluster.local</pre><p>Worker</p><p>Each worker, once it is started, will create an ephemeral node with its IP address under /cache/workers/ node. For example if we have 3 workers with IP addresses: 192.168.18.12, 192.68.45.36 and 192.168.192.2 then we will have the following znode structure:</p><pre>[zk: 10.98.70.73(CONNECTED) 30] ls /cache/workers<br>[192.168.18.12, 192.68.45.36, 192.168.192.2]</pre><p>The leaf nodes are <em>ephemeral</em> which means when the worker which holds a connection to the zookeeper dies, <em>the respective znode will go away</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a4cdfa3a87583fb644d8d0a27837d4/href">https://medium.com/media/d1a4cdfa3a87583fb644d8d0a27837d4/href</a></iframe><p>The rest of the code can be found <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode07/worker/src/main/java/com/github/amshali/distributedcache/worker">here</a>.</p><p>Cache servers, must <em>periodically(every 5 seconds or so) get the list of cache workers</em> from zookeeper. Hence when a worker is added or removed from the list, they would know and act accordingly. This can easily be done by a call to the ZooKeepr Java library:</p><pre>zooKeeper.getChildren(&quot;/cache/workers/&quot;, false);</pre><p><strong>Cache API</strong></p><p>Cache API part of worker is as simple as the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fada0f7414e1769cf143e030311d8f0/href">https://medium.com/media/9fada0f7414e1769cf143e030311d8f0/href</a></iframe><p>For now we are not concerned with details of eviction and will focus on that later.</p><p><strong>Deployment</strong></p><p>For workers deployment, we choose a StatefulSets deployment for the following reasons:</p><ul><li>Stable, unique network identifiers.</li><li>Ordered, graceful deployment and scaling.</li><li>Ordered, automated rolling updates.</li></ul><p>The workers’ K8s deployment yaml file is as follows. Notice how we are passing the ZooKeeper’s address to the worker:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/411dc5519b166c56f23f9b38739750cb/href">https://medium.com/media/411dc5519b166c56f23f9b38739750cb/href</a></iframe><p>In the next part of this episode we will go into details of Consistent hashing and cache server’s logic.</p><p>The code for this episode can be found here:</p><p><a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode07">Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/episode07 at main · amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6e7e4fa6d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-2-workers-and-zookeeper-fb6e7e4fa6d1">Episode 7: Let’s build a distributed cache(Part 2/3: Workers and ZooKeeper).</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 7: Let’s build a distributed cache(Part 1/3: Basic cache design).]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-1-137f44c41a48?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/137f44c41a48</guid>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[lru]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[lfu]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Sun, 07 Aug 2022 04:33:04 GMT</pubDate>
            <atom:updated>2022-08-17T03:19:42.158Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In this episode we will take a little detour from the Sum of Primes service and start building a (mini-)distributed cache system. The overall architecture of this distributed cache is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICWMIGxwEwuR-s7XTvVbVA.png" /><figcaption>Distributed cache system architecture</figcaption></figure><p>Facing clients, we have multiple cache servers which act as specialized load-balancers and direct requests to the right cache worker. The cache servers uses a <a href="https://en.wikipedia.org/wiki/Consistent_hashing"><em>Consistent hashing</em></a> method to find the right worker for a request. Consistent hashing helps minimize the re-hashing problem when one of the workers dies or when new workers are added.</p><p>Each cache worker is responsible for actually holding the cache key values. Inside each worker, the total memory is split into multiple shards and each shard is backed by simply a <em>Hash Map</em>(plus some auxiliary data structures) as cache store. Why we have multiple shard in each worker? To increase concurrency and reduce the cost of updating and evicting cache items.</p><p>Cache Shard Design</p><p>Every cache has a max capacity because of memory limitations. Say you have 1GB of memory to work with for every shard. In addition we have the following requirements and limitations for cache entries:</p><ul><li>Key: Max size of 256 bytes</li><li>Value: Max size of 1KB</li></ul><p>Given 1GB of RAM, one can store:</p><p><strong>1GB / (1KB + 256 Bytes + 128 Bytes overhead) ~= 762600 entries in cache.</strong></p><p>When your cache hits that limit, you need an <em>eviction strategy </em>to make room for the new entries.</p><p>There are some common strategies for eviction:</p><ul><li>Least Recently Used(LRU): Evict the entry which was used a long time ago.</li><li>Least Frequently Used(LFU): Evict the entry which is not used often.</li></ul><p>In LRU model, every time an entry is used its <em>usage timestamp</em> is updated to the current time. When we want to evict, we evict the entry with the oldest timestamp.</p><p>In LFU model, every time an entry is used its <em>usage counter</em> is incremented by 1. When we want to evict, we remove the entry with the smallest counter value.</p><p>In part 1 of this episode we will implement a bare-bone cache in Java which supports both of the above strategies and is capable of extension to support other strategies as well.</p><p>Cache Shard Implementation</p><p>The important thing in basic cache implementation is cache eviction strategy. Otherwise, the rest of it is simply calling various get , put and remove functions on a map(e.g. A Java Map). <br>The other important thing is to make sure the cache is thread-safe. Having those two things in mind, let’s dive into the implementation.</p><p>Both LFU and LRU approaches work by assigning an attribute to the keys. In case of LFU, the attribute is a counter which is increased every time the key is accessed(get or set). For example, imagine we have the following items in the cache and we just inserted them:</p><pre>+---------+-------------+--------------------+<br>|   Key   |    Value    | Attribute(Counter) |<br>+---------+-------------+--------------------+<br>| server1 | 192.168.0.1 |                  1 |<br>| server2 |  10.10.1.23 |                  1 |<br>| server3 | 124.0.10.90 |                  1 |<br>| server4 | 172.156.0.3 |                  1 |<br>| server5 | 10.10.45.98 |                  1 |<br>+---------+-------------+--------------------+</pre><p>All of the items have their counter attribute set to 1. Now let’s say the following calls to cache is made:</p><pre>GET server1<br>GET server3<br>SET server4 189.23.2.10<br>GET server1</pre><p>After the above accesses, you’ll have the following updated attributes:</p><pre>+---------+-------------+--------------------+<br>|   Key   |    Value    | Attribute(Counter) |<br>+---------+-------------+--------------------+<br>| server1 | 192.168.0.1 |                  3 |<br>| server2 |  10.10.1.23 |                  1 |<br>| server3 | 124.0.10.90 |                  2 |<br>| server4 | 189.23.2.10 |                  2 |<br>| server5 | 10.10.45.98 |                  1 |<br>+---------+-------------+--------------------+</pre><p>Now, if we have to evict an item from the cache, because say our cache’s max capacity is 5 and we cannot add any new items, we should either evict server2 or server5 since they have the least attribute value(1).</p><p>The similar scheme happens for LRU cache, except instead of increasing a counter, we are setting the attribute to the access time(in nano/milliseconds):</p><pre>+---------+-------------+----------------------+<br>|   Key   |    Value    | Attribute(timestamp) |<br>+---------+-------------+----------------------+<br>| server1 | 192.168.0.1 |        1659816127182 |<br>| server2 |  10.10.1.23 |        1659816123467 |<br>| server3 | 124.0.10.90 |        1659816127110 |<br>| server4 | 172.156.0.3 |        1659816122152 |<br>| server5 | 10.10.45.98 |        1659816125923 |<br>+---------+-------------+----------------------+</pre><p><strong>Problem</strong>: The main issue is that we need an efficient way of finding and updating the attribute values of the items in the map. To be precise we need to preserve the <em>total ordering</em> of items at all times.</p><p>The best data structure for doing this is perhaps a <em>Binary Search Tree(BST)</em>. With an efficient implementation of BST using <em>Red-Black</em> trees, we can add remove and update items in the tree in <em>O(log(m))</em>, where <em>m</em> is the number of items in the cache. For example if the cache shard has a maximum capacity of 2²⁰ items. Then each access to the cache could cost 20 operations which is not bad as long as our cache is limited and is not growing boundlessly. We can compensate for the limits on the cache shard size by adding more shards and adding more cache <em>workers</em>. That will put a bound on <em>O(log(m))</em> running time and also enables us to access various shards concurrently.</p><p>Every cache has an <em>Eviction Manager</em>. Eviction manager is responsible for tracking accesses to the cache items and updating the associated attribute(counter or timestamp) accordingly. Here is the interface for the EvictionManager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca279eb734a6145e66d1a72515bd96a/href">https://medium.com/media/eca279eb734a6145e66d1a72515bd96a/href</a></iframe><p>When it is time to evict an item, cache would ask the eviction manager to give it a candidate item for eviction via selectKeyToEvict method. Cache is also responsible to let the manager know when a key is accessed or deleted.</p><p>The LFU and LRU implementations have a lot in common and hence we create an abstract class which encapsulates their common properties. This class is called SmallestAttributeEvictionManager . It is based on the idea that we want to evict the cache item with smallest attribute whether it is a counter or a timestamp:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/966fed2c03ca5e49f74956ce4db04484/href">https://medium.com/media/966fed2c03ca5e49f74956ce4db04484/href</a></iframe><p>In the above class, the keySet is a SortedSet which keeps the total ordering of items in it at all times and can tell us what is the smallest item in the set. TreeSet is a very good implementation for SortedSet , using Red-Black BST. A TreeSet would need a <strong>comparator</strong> to compare items together. Comparator compares items based on their attribute value which can be retrieved from the attributeMap field.</p><p>Now, the LFU eviction manager, simply increase a counter from zero upon every access to cache keys. The comparator, first compares the value of the counters and if they were equal it compares the value of keys together. Here is the implementation of LFU eviction manager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56cf6693674ce4693ee7b863b7850332/href">https://medium.com/media/56cf6693674ce4693ee7b863b7850332/href</a></iframe><p>The cache interface itself is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ceb9e86eede43ab2039dfacfd29f15a/href">https://medium.com/media/0ceb9e86eede43ab2039dfacfd29f15a/href</a></iframe><p>The cache implementation of this interface would take an eviction manager as input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ea2043e71d3d096522196f0cbd6ab2b/href">https://medium.com/media/2ea2043e71d3d096522196f0cbd6ab2b/href</a></iframe><p>The eviction manager’s access method is called inside get, set method.</p><p>In order to make the CacheImpl thread-safe, we are using a ReentrantLock to guard each method of the cache. We could use the synchronized keyword on each method, but this lock has some nice properties and features which could be beneficial.</p><p>Now let’s take a look at cache methods’ implementations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7a3237311033a94ba0665e5722628be/href">https://medium.com/media/d7a3237311033a94ba0665e5722628be/href</a></iframe><p>Eviction</p><p>When it comes to how we want to do the eviction there are a few options:</p><ul><li>We can be proactive and run a scheduled process inside cache to evict the cache items if the number of items in the cache is over a certain threshold or when cache is above 80% of its maximum capacity.</li><li>We could check the size of the cache inside the set function and run the eviction process if necessary.</li><li>Eviction can evict one item or many items from the cache. It makes more sense to evict many items because we will pay a one-time cost to evict many and we probably don’t have to do that for some time.</li></ul><p>Whatever is the strategy for eviction, we can implement it with the current setup that we have. Here is a simple implementation that I have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134762d02af335325c28949d8dfe8994/href">https://medium.com/media/134762d02af335325c28949d8dfe8994/href</a></iframe><p>This concludes our bare-bone implementation of a basic cache. In the later parts of this episode, we will dive into creating worker and server processes for a true distributed system.</p><p>Find the code for this episode in <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode07">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=137f44c41a48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-7-lets-build-a-distributed-cache-part-1-137f44c41a48">Episode 7: Let’s build a distributed cache(Part 1/3: Basic cache design).</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 6: The one with coordinator and workers.]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-6-the-one-with-coordinator-and-workers-873273d93ae7?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/873273d93ae7</guid>
            <category><![CDATA[coordinator]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[statefulsets]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 03:45:30 GMT</pubDate>
            <atom:updated>2022-08-04T15:08:46.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>So far we have seen only one distributed system’s architecture and that is copying(replicating) a single code across different nodes. All the nodes are essentially running the same code and all the instances are more or less the same in terms of logic. <br>However, there is another important architecture which is used in many critical software projects(such as many database systems). That is <strong>coordinator(master)/workers</strong> architecture.</p><p>In this architecture, not all nodes are running the same code and logic. There is <em>usually a single coordinator</em>(or master) node and there are many worker nodes. The overall goal is to divide big requests, which would require lots of CPU or RAM on a single machine, into smaller tasks so that they can be done faster and more reliably in a distributed fashion.</p><p><strong>Coordinator node is responsible for:</strong></p><ul><li>Handling client’s requests</li><li>Dividing up requests into smaller tasks(if necessary)</li><li>Sending small tasks to worker nodes</li><li>Keeping track of which tasks are done</li><li>Retrying failed tasks</li><li>Keeping track of current running worker nodes</li><li>Bundling up the final response from responses received from worker nodes</li><li>Communicating the response to the client</li></ul><p><strong>Worker nodes are responsible for:</strong></p><ul><li>Handling a defined task(e.g. running a query over S3 files, or computing sum of primes over a small range)</li><li>Sending the result back to the coordinator nodes</li><li>Updating their status(number of current tasks running, available CPU, RAM etc.) with the coordinator node</li></ul><p>The main goal of this episode is to introduce this architecture and to demonstrate the implementation details of it using our <em>Sum of Primes</em> example in K8s.</p><p>Worker</p><p>We are going to start with the worker node’s logic in our Sum of Primes project. In this project, a worker node should:</p><ul><li>Announces itself to the coordinator</li><li>Serves sum of prime task sent from the coordinator</li></ul><p><strong>Announcing oneself to the coordinator</strong></p><p>On the coordinator’s side, we should have an API hosted on a port which accepts incoming requests for registering a worker. For now we assume that this API exists and is running on port 80 of the server. We have to supply the coordinator’s address to the workers upon their creation as a command line argument or as an environment variable.</p><p>The API for registering a worker looks like this:</p><p>PUT /worker/register/{workerId}</p><p>Usually this sort of internally faced API is hosted on a specific and non-public port on the server. In our case, the API for a client to send requests is hosted on port 80 and the API for workers to register themselves is also hosted on port 80. Interested readers can explore how they can create two API on two different ports depending on their language or framework they choose.</p><p>We create a class called ServerStub which is responsible for abstracting away the details of communication with the coordinator like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb55871501b6027399816dd5284bd393/href">https://medium.com/media/fb55871501b6027399816dd5284bd393/href</a></iframe><p>The worker should implement a logic for periodically registering itself with the coordinator. We don’t want to do that too often though. Every 1 second is a reasonable choice. Spring framework has a declarative way of running a periodic task without having to deal with threads.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b7f69bb50f077c7c428d31d5709bbc4/href">https://medium.com/media/1b7f69bb50f077c7c428d31d5709bbc4/href</a></iframe><p>The worker, as can be seen in the above code, registers its IP address with the coordinator. This way the coordinator can use the worker’s IP address to send tasks to it. In the above code we also have an if condition which prevents this process from registering if the serverStub is still not available or if the worker is shutting down. <br><em>Note:</em> Before sending the IP address we are replacing dots with dashes. This is because the local DNS address of containers in K8s looks like the following:</p><pre>pod-ip-address.my-namespace.pod.cluster-domain.example</pre><pre><strong>172-17-0-3</strong>.default.pod.cluster.local<br><strong>10-34-52-61</strong>.cluster0.pod.cluster.local</pre><p><strong>Serving the sum of prime requests on the worker side</strong></p><p>Previously in the simple replicated version of the sum of prime numbers we exposed an API to the clients which directly computed the sum of primes. In this new architecture, that very API will be implemented on the worker. On the coordinator node, however, we have to tweak the implementation to divide up the requests into smaller ones and send them to the workers.</p><p>Here we focus on the worker’s logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc18322dc0c5b5f6d9e33db784884b4/href">https://medium.com/media/2fc18322dc0c5b5f6d9e33db784884b4/href</a></iframe><p>This is pretty much what we have on the worker side. For simplicity, the worker listens on port 80. In K8s world, you can pretty much listen on any port you want without any limitations.</p><p>Now, let’s move on to the <em>Coordinator</em> side.</p><p>Coordinator</p><p>On the coordinator side, we want to focus on two end-points:</p><ul><li><em>Worker registration</em>: internal facing for workers to use.</li><li><em>Sum of primes</em>: external facing for clients to use.</li></ul><p>Master or coordinator node needs to talk to workers via the exposed REST API. To do so, similar to worker side, we create a stub for worker API as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9484c44ab15c8cacf114eac065748b15/href">https://medium.com/media/9484c44ab15c8cacf114eac065748b15/href</a></iframe><p>Coordinator talks to each of the workers using their associated stub. This abstracts away the details of communication with workers.</p><p>As we explained before, coordinators should expose an endpoint for workers to be able to register themselves. This is simply a <em>REST PUT</em> endpoint which accepts the worker’s IP address as its parameter. Upon receiving a request on this endpoint, the coordinator will store the worker’s IP address and start sending requests to it. The endpoint implementation looks like this in Spring:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d985228da7d566c16685440c21ad7f66/href">https://medium.com/media/d985228da7d566c16685440c21ad7f66/href</a></iframe><p>In the register implementation, we have <em>two major data structures</em> for keeping track of workers. One is the workerLastUpdate which is a <strong>concurrent map</strong> of worker ids to a timestamp(milliseconds since epoch). The timestamp represents the last time we received a ping from the worker. This is to ensure that if we didn’t receive a ping after a certain amount of time, we will remove the worker from the registered pool.</p><p>The other important data structure is a <strong>blocking queue</strong> of worker stubs. For each active worker we create a worker stub and put it in a blocking queue. When we receive a request we grab a worker from the queue and send a request to it. Once we receive a response from a worker we put the worker back on the free list. This will ensure that we don’t overwhelm workers with requests if they are busy serving one already. We are not limited to sending one task to one worker. We can have a counter and max the number of concurrent tasks for each worker to 2, 3 or any other choice. However, for simplicity we are going to limit it to 1 for now.</p><p>We also added an extra utility API endpoint to get the current list of active workers from the coordinator’s standpoint. This is useful for debugging purposes.</p><p>To refresh the list of workers and eliminate the non-active ones, we should run a housekeeping process every so often. This housekeeping process can be run as a scheduled job every second on the coordinator and fix up the two data structures we presented above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dd26a6595de485409e011c787ae914f/href">https://medium.com/media/9dd26a6595de485409e011c787ae914f/href</a></iframe><p>In the above code, we go over the worker’s last update map and remove any worker that’s not sent an update for more than 5 seconds. Alongside removing the worker from the map, we also remove it from the free worker queue. <br>It is possible that we send a request to a worker and the worker dies shortly after that. Hence on the coordinator side we need proper <em>timeout and retry mechanisms</em> to handle failure cases properly. That will be the topic of another episode.</p><p><strong>Sum of primes endpoint implementation</strong></p><p>The implementation of this endpoint is different from the one we saw in episode 1. Here we should divide up the request into smaller tasks and divide it between workers.</p><p>Coordinator <em>splits</em> the input range into smaller ranges(with no overlaps). The split size is 2,500,000. For example if the input is a = 10 and b = 3,700,000, then we will have two tasks:</p><p>Task 1: a = 10, b = 2,500,010<br>Task 2: a = 2,500,011, b = 3,700,000</p><p>These two tasks are then sent to free workers to compute. Coordinator then waits for the responses to come back from the workers, sum them up and send the final result back to the client.</p><p>The following code shows the implementation of this endpoint with relevant comments inline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94847d93403920efebf71e17bea80145/href">https://medium.com/media/94847d93403920efebf71e17bea80145/href</a></iframe><p>This sums up the important details of this new computation model for the sum of primes service.</p><p>Now, let’s see how to configure the service in Kubernetes.</p><p>Kubernetes Configuration</p><p>First, we need two different docker files. We could also use one docker file, but I found it easier to have two different ones for coordinator and workers.</p><p>The coordinator docker file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fd44b6eda2e18427774e60d7ba44f91/href">https://medium.com/media/1fd44b6eda2e18427774e60d7ba44f91/href</a></iframe><p>The worker’s docker file is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8b36e242bb722c8352cae66e50c1ee/href">https://medium.com/media/ba8b36e242bb722c8352cae66e50c1ee/href</a></iframe><p>As you can see, the coordinator’s address is passed to the worker container via an <em>environment variable</em> which we will set in the K8s config file.</p><p>StatefulSets</p><p>Since coordinator has a state, it is appropriate to use the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/"><strong>StatefulSets</strong> K8s</a> application deployment. StatefulSets offers stable naming and ordering guarantees. Many databases usually have primary vs secondary instances. Secondary instances can become primary when the primary instance is down. In these scenarios StatefulSets is a very useful concept. <br>In our simple example service we do not have secondary instances. However, we can still benefit from properties of a StatefulSets deployment. For example, the deterministic naming convention of a StatefulSets will become helpful in our application.</p><p>We only have a single coordinator and hence we use a StatefulSets with a single instance. The K8s deployment file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4f9b48af6e6e544fc5866dc9aaf2fc/href">https://medium.com/media/3d4f9b48af6e6e544fc5866dc9aaf2fc/href</a></iframe><p>In the above config we have allocated 1 CPU and 1GB of RAM to the coordinator. Ideally, we would want to allocate more resources to coordinator node. But in our simple service running on my personal computer, this is enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c5efc9ea3a9e24705c409cf066e73b/href">https://medium.com/media/a5c5efc9ea3a9e24705c409cf066e73b/href</a></iframe><p>Workers’ deployment follow a simple replicated deployment model which is stateless. Important thing to notice here is how we pass the coordinator’s address to the worker.</p><pre>env:<br>    - name: COORDINATOR<br>      value: &quot;<a href="http://primesum-server/">http://primesum-server/</a>&quot;</pre><p>We are addressing the coordinator by its name. K8s’ DNS will take care of resolving this name to the right pod as long as both workers and coordinator are in the same K8s’ <strong>namespace</strong>. Namespaces are basically free in K8s and you can create as many as you like.</p><p>Also note that we have allocated 1 CPU to each worker and initially there are 10 worker replicas.</p><p>Finally we should create a K8s’ service endpoint on top of our coordinator so that we can connect to it. In order to easily connect to this service, we opt for a <em>LoadBalancer</em> service type. This also enables us to possibly add more coordinators in the future for high availability(A future episode).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af5a9a04a39b4eeef6e91c1a75773564/href">https://medium.com/media/af5a9a04a39b4eeef6e91c1a75773564/href</a></iframe><p>Running the Application</p><p>To run this application follow the instructions in the <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/blob/main/episode06/README.md">README</a> file. We ran a load test at 15 QPS with the above configurations and here are the results:</p><pre>http.codes.200: .............................. 1500<br><strong>http.request_rate: ........................... 15/sec<br></strong>http.requests: ............................... 1500<br>http.response_time:<br>  min: ....................................... 101<br>  max: ....................................... 2747<br>  median: .................................... 561.2<br>  p95: ....................................... 1130.2<br>  p99: ....................................... 1620<br>http.responses: .............................. 1500<br>vusers.completed: ............................ 1500<br>vusers.created: .............................. 1500<br>vusers.created_by_name.sumPrime load test: ... 1500<br>vusers.failed: ............................... 0<br>vusers.session_length:<br>  min: ....................................... 103.5<br>  max: ....................................... 2752.1<br><strong>  median: .................................... 572.6<br>  p95: ....................................... 1130.2<br></strong>  p99: ....................................... 1652.8</pre><p>Running at 15 QPS was not throttled at all and the results are actually pretty impressive and even better than the replicated model we saw in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-2-the-one-with-replication-db5333421553">episode 2</a>.</p><p>But the true power of this architecture is in handling big/large requests. In the code for this episode you will find a new batch of queries, the <strong>medium</strong> ones. The medium batch is on average twice as big as the small ones. We run the medium workload at 5 QPS against the replicated architecture with no coordinator and the one with coordinator and here are the results:</p><p>The simply replicated architecture:</p><pre><strong>http.codes.200: .............................. 422<br>http.codes.429: .............................. 78<br></strong>http.request_rate: ........................... 5/sec<br>http.requests: ............................... 500<br>http.response_time:<br>  min: ....................................... 13<br>  max: ....................................... 36331<br>  median: .................................... 14332.3<br>  p95: ....................................... 30040.3<br>  p99: ....................................... 33199.7<br>http.responses: .............................. 500<br>vusers.completed: ............................ 500<br>vusers.created: .............................. 500<br>vusers.created_by_name.sumPrime load test: ... 500<br>vusers.failed: ............................... 0<br>vusers.session_length:<br>  min: ....................................... 16.2<br>  max: ....................................... 36366.1<br>  median: .................................... 14332.3<br><strong>  p95: ....................................... 30040.3<br></strong>  p99: ....................................... 33199.7</pre><p>And the result for the coordinator/workers architecture is:</p><pre><strong>http.codes.200: .............................. 460<br>http.codes.429: .............................. 40<br></strong>http.request_rate: ........................... 5/sec<br>http.requests: ............................... 500<br>http.response_time:<br>  min: ....................................... 0<br>  max: ....................................... 13914<br>  median: .................................... 9999.2<br>  p95: ....................................... 12459.8<br>  p99: ....................................... 13497.6<br>http.responses: .............................. 500<br>vusers.completed: ............................ 500<br>vusers.created: .............................. 500<br>vusers.created_by_name.sumPrime load test: ... 500<br>vusers.failed: ............................... 0<br>vusers.session_length:<br>  min: ....................................... 2.2<br>  max: ....................................... 13916.3<br>  median: .................................... 9999.2<br><strong>  p95: ....................................... 12459.8<br></strong>  p99: ....................................... 13497.6</pre><p>While both of these are serving similar number of requests the coordinator/worker architecture has a much better response time. We truly see the power of <strong>Divide and Conquer</strong> in action.</p><p>In future episodes, we will talk about some improvements to this architecture. In particular we will see how we can extend the design to a multi-coordinator one for higher availability.</p><p>Links</p><ul><li><a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode06">Episode 6 code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873273d93ae7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-6-the-one-with-coordinator-and-workers-873273d93ae7">Episode 6: The one with coordinator and workers.</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 5: The one with auto-scaling.]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-5-the-one-with-auto-scaling-afa9a2253387?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/afa9a2253387</guid>
            <category><![CDATA[utilization]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[horizontal-pod-autoscaler]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 01:49:00 GMT</pubDate>
            <atom:updated>2022-07-09T02:11:27.821Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>Any business would want to maximize their profit. They would want to get the maximum amount of work/output from the least amount of resources, which makes a lot of sense — getting the most bang for your buck. In any software business, we want to maximize the <strong>server utilization</strong>. Ideally, we want to utilize 100% of the server’s capacity. But is that possible? Even if it is possible, is it the right thing to do?</p><p>In order to <em>efficiently and economically </em>make use of the available hardware and be responsive at the same time, we should <strong>horizontally</strong> scale our services up and down. What is horizontal scaling? When the load is high, we increase the number of worker nodes(or containers) to accommodate the higher load and stay under the required SLA. On the other hand, when the load is low, we want to decrease the number of workers and turn down the excess hardware to save money. That is horizontal scaling.</p><p>Let’s lead this discussion with some questions and looking back at <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-2-the-one-with-replication-db5333421553">episode 2</a> when we introduced replication.</p><ul><li>What metric shall we use for server utilization?</li><li>How does server utilization affect performance and response time?</li><li>What is the best server utilization target value?</li></ul><p>We are going to re-run the experiments from episode 2 to see the effect of utilization on performance.</p><p>Prerequisites</p><p>I am using the sysstat Linux package to make CPU/Memory measurements on my system. To install this on Ubuntu, simply run the following command:</p><pre>sudo apt install sysstat</pre><p>Once you install this package you will have access to pidstat and sar binaries which are very useful for when we are load testing.</p><p>Utilization</p><p>What metric shall we use for server utilization? The metrics we can easily measure on the server are CPU, Memory and IO usage. Between these metrics, CPU is usually the most expensive in terms of dollar value. We usually want to reduce the CPU usage or get the most out of it. So we mostly focus on this metric for server utilization measurements.</p><p>Once you install the sysstat package you will have access to sar binary. Using sar you can sample the average CPU usage over a period of time. For example the following sar command will print CPU usage every 5 seconds.</p><pre>14:02:45 ✓  ~ » sar -u 5<br>02:10:35 PM     CPU     %user     %nice   %system   %iowait    %steal     %idle<br>02:10:40 PM     all      2.77      0.00      1.24      0.22      0.00     95.76<br>02:10:45 PM     all      4.53      0.00      1.64      0.17      0.00     93.66<br>02:10:50 PM     all      2.35      0.00      1.36      0.13      0.00     96.16</pre><p>The experiment we want to run here is as follows. Run the replication <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode02">code from episode 2</a>, multiple times with varying request’s arrivalRate. We then sample the CPU usage and compare it with performance we get from each run. Our performance metric is the <em>p95</em> execution time. For the purpose of this experiment we are going to effectively turn off throttling by setting the throttling threshold to 2000. After running the load tests five times for arrival rates = 5, 10, 15, 20 and 25 and collecting the average CPU load and running time, we can chart the p95 against the average CPU usage as shown in the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*MnK-G45lcI0q9HZx_TIueQ.png" /><figcaption>P95 vs Average CPU Utilization</figcaption></figure><p>As you can see in the above diagram, performance(p95) starts to really suffer when CPU utilization goes above 70%. As a matter of fact by the time the CPU utilization is above 75%, we have violated the SLA terms(&gt; 5 seconds to run).</p><p>Increasing CPU utilization only pays off up to a certain point. After that, servers would spend a lot of time context switching between a lot of tasks and would not be able to run any of them within an accepted time-frame, and hence the unacceptable performance.</p><p>As we saw in the above graph, 66% CPU utilization is actually the sweet spot and a good utilization target for many applications. Going above this target could potentially put us at the risk of over-utilization, hurting the performance and missing the SLA. We will use this value when we want to setup our auto-scaling in K8s. Ideally we always want to keep the average CPU utilization near this target value by adding or removing worker nodes dynamically. That is when auto-scaling comes into play.</p><p>To learn more about utilization I highly recommend this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHda5tMrLJqc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHda5tMrLJqc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHda5tMrLJqc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c25c6f38fd3f4a76049e3f31369288/href">https://medium.com/media/36c25c6f38fd3f4a76049e3f31369288/href</a></iframe><p>HPA</p><p><a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaling</a>(HPA) is a K8s mechanism to help us with automation of horizontal scaling. K8s offers a rich API with plenty of configuration options to control pod scaling based on various system metrics.</p><p>For example the following HPA declaration will scale the respective pod based on CPU utilization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f61ef781547977632c1b1a26db367fb4/href">https://medium.com/media/f61ef781547977632c1b1a26db367fb4/href</a></iframe><p>It increases or decreases pod instances to keep the average CPU utilization near 60%. Important thing to remember is that this is done based on hardware resources availability.</p><p>K8s follows a specific algorithm(which can be parameterized) to do the auto-scaling. The details of the algorithm can be found in this <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/#algorithm-details">link</a>. But in simple terms, and in the case of the above config, when it sees that the CPU utilization is above 60% for more than 15 seconds(this is configurable), it adds new pods. On the other hand, if the CPU utilization is less than 60% for more than 5 minutes(again configurable), it scales down the pods.</p><p>Let’s put this into use for our little Sum of Primes service. This is the HPA config for our service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/054083d2bbaeee86a221ee5f064a2944/href">https://medium.com/media/054083d2bbaeee86a221ee5f064a2944/href</a></iframe><p>For this episode we changed the code to deploy only once replica at the beginning. Using the above HPA config, K8s will automatically create a new replica when the CPU utilization goes above 66%.</p><p>Links</p><ul><li><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-2-the-one-with-replication-db5333421553">Episode 2</a></li><li><a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode02">Episode 2 code</a></li><li>This <a href="https://github.com/amshali/Concurrency-and-Distributed-Systems-A-guide-with-Kubernetes/tree/main/episode05">episode’s code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afa9a2253387" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-5-the-one-with-auto-scaling-afa9a2253387">Episode 5: The one with auto-scaling.</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 4: The one with probes.]]></title>
            <link>https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-4-the-one-with-probes-95a551fc3994?source=rss-b37022614b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a551fc3994</guid>
            <category><![CDATA[livenessprobe]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[startupprobe]]></category>
            <category><![CDATA[probe]]></category>
            <category><![CDATA[readinessprobe]]></category>
            <dc:creator><![CDATA[Amin Shali]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 22:58:03 GMT</pubDate>
            <atom:updated>2022-07-07T22:58:03.741Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency and Distributed Systems: A guide with Kubernetes</h4><p>In the <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-3-the-one-with-resiliency-eba33c2af24d">previous episode</a> we talked about fault tolerance and resiliency. In this episode we want to talk about <strong><em>startup</em></strong>, <strong><em>liveness</em></strong> and <strong><em>readiness</em></strong> probes. These probes are feedback and control mechanisms which help with resiliency and fault tolerance in a way.</p><p>These Kubernetes probes, while very useful, if not configured correctly could lead to daunting problems in the system that are hard to debug. These are signals to K8s management system which tell about the followings:</p><ul><li>Whether a container has started or not.</li><li>Whether a container is ready or not.</li><li>Whether a container is alive or not.</li></ul><p>Each of these signals would entail an action somewhere in the system.</p><ul><li>Once the startup probe passes, K8s starts to direct traffic to the container.</li><li>If the readiness probe fails , K8s will stop traffic to the container until the probe passes.</li><li>If the liveness probe fails, K8s will restart the container.</li></ul><p>Startup</p><p>This probe is used to signal whether an app or container has successfully started. If this probe is configured, K8s will ignore the other probes(liveness and readiness) until the startup probe succeeds. We highly recommend that you configure this probe. When we auto-scale and add new nodes in a cluster, we need a sure way to know whether a worker’s container has started or not before starting to send traffic to it. Some apps are pretty straightforward and fast to start. On the other hand, there are apps and services which require seconds to minutes before they are available to serve. This startup time could be due to the following things:</p><ul><li>Process loading into memory. Java apps for example may take tens of seconds to start and load into memory.</li><li>The application needs to load data over the network. They might need to load configuration files or machine learning models from an S3 bucket, etc. All of that would take an indeterminate amount of time.</li><li>They might be waiting on other downstream services to start.</li></ul><p>Having a reliable startup signal helps with a more robust system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*bkpp4pkV4mFt7z5_XaLjHQ.png" /><figcaption>Timeline of a startup probe.</figcaption></figure><p>Here are some example of defining startup probes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d80650712412bf31b677cec31fc4b33/href">https://medium.com/media/3d80650712412bf31b677cec31fc4b33/href</a></iframe><p>In the above example, K8s will run the probe by sending an http request on the specified path and port, or run the command(second example) inside the container. In the case of http, it will look for a 200 response code and in the case of the command, it expects a successful run with an exit code of 0.</p><p>Make sure you are choosing reasonable values for periodSeconds, failureThreshold and initialDelaySeconds. Account for possible failures and set some proper thresholds. This all depends on the app and your specific requirements.</p><p>There is a small subtlety when it comes to configuring this probe(as well as readiness probe) in some applications. If you have a coordinator/worker architecture where there is a coordinator that has some workers doing tasks for it, you need to be careful on how you configure the startup probe. In such applications, usually, the worker nodes send a signal to the coordinator or to a discovery server and announce that they are ready to work.</p><p>If the application specific readiness signal is not aligned properly with the K8s startup probe signal, it could lead to issues. That is because K8s only allows connections to the container <em>after</em> it sees the startup probe. To demonstrate this, let’s look at the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*7Ezm_nVyIUQir8OaJIJqcA.png" /><figcaption>Mis-aligned startup probe and application signal.</figcaption></figure><p>As can be seen in the above diagram, the worker sends a ready to do work signal to the coordinator. Coordinator, with the assumption that it can reach the worker’s container, sends requests to the worker but fails because the container is not open to accepting connections yet. Hence the first two requests, in this example, will fail. Make sure that your application-specific startup/readiness signals are aligned properly with the K8s probes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*7tKzvYdkoZ_LNXNXZv1c1w.png" /><figcaption>Timeline of a properly aligned startup probe.</figcaption></figure><p>It’s worthwhile to emphasize that when we are dealing with service dependencies of such, we need to be careful when configuring these probes. To see more examples of how to define startup probes, visit this <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-startup-probes">link</a>.</p><p>Readiness</p><p>Readiness probe is very similar to startup probe, but it is used throughout the lifetime of the container. It is meant to check periodically if the app is still ready to work or not. If it is not ready, K8s will stop sending requests to it until it is ready again. Why would the app not be ready?</p><ul><li>It is overloaded.</li><li>It might need to do some housekeeping or cleanup.</li><li>Some of its dependencies(A cache, a database, etc.) are not working or are unreachable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JAFPEk1JL37m4T_Z9Y5_kQ.png" /><figcaption>Timeline of a readiness probe.</figcaption></figure><p>Defining readiness probe is very similar to the startup probe and you can find some examples of it in this <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-readiness-probes">link</a>.</p><p>Livesness</p><p>This probe is designed to test the status of a container and restart the container if it is not live. You app/container may become unresponsive for various reasons:</p><ul><li>A bug in the system.</li><li>Waiting for another resource indefinitely(A deadlock which can be considered a hard to track bug).</li><li>Becoming too overloaded.</li></ul><p>In such situations, sometimes the best thing to do to automatically resolve the problem is to restart the process(container). That is when this probe will become handy. Syntax wise, configuring this probe is similar to the previous two. But watch out how to set the various parameters. Set a reasonable initialDelaySeconds and make sure to give it enough failureThreshold before declaring the container dead.</p><p>Let’s look at an example of a liveness probe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca3a6926125586e2935ac5aa35da61b/href">https://medium.com/media/4ca3a6926125586e2935ac5aa35da61b/href</a></iframe><p>This is a http probe hosted on port 8888. The probe is checked every 10 seconds and will be tried 2 times before giving up. Every time K8s checks this probe, it waits timeoutSeconds = 4 before declaring a failure. Here is an example of this probe in action which leads to restarting the container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-ClF5zBt0x6lj76MmuPqQ.png" /><figcaption>Timeline of a failed liveness probe.</figcaption></figure><p>In summary, these are important probes to be configured in K8s. However, one has to careful when configuring them or otherwise it could lead to unforeseen issues in a distributed system with inter-service dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a551fc3994" width="1" height="1" alt=""><hr><p><a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with/episode-4-the-one-with-probes-95a551fc3994">Episode 4: The one with probes.</a> was originally published in <a href="https://medium.com/concurrency-and-distributed-systems-a-guide-with">Concurrency and Distributed Systems: A guide with Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>