<?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 CocCoc Techblog on Medium]]></title>
        <description><![CDATA[Stories by CocCoc Techblog on Medium]]></description>
        <link>https://medium.com/@coccoctechblog?source=rss-b5c0e13a5ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*d_pKwXOO0uffmUSozb3SWg.png</url>
            <title>Stories by CocCoc Techblog on Medium</title>
            <link>https://medium.com/@coccoctechblog?source=rss-b5c0e13a5ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:19:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coccoctechblog/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[Finer permission control using K8s Admission Controller]]></title>
            <link>https://coccoctechblog.medium.com/finer-permission-control-using-k8s-admission-controller-6bab8e0b9822?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bab8e0b9822</guid>
            <category><![CDATA[admission-controller]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 09:03:54 GMT</pubDate>
            <atom:updated>2022-04-06T02:49:20.941Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Situation</strong></h3><p>In our company, the whole company is using only one unified K8s cluster, and department services are separated by namespaces with different service accounts. Developers have the same set of permissions on corresponding namespace, basically only describe / logs to debug their own services. This architecture is simplest and easy to maintain for a small infra team, yet secured enough.</p><p>On the rise of <a href="https://developerexperience.io/">DX</a>, we want to open more permissions for our beloved devs, for example let them delete pods for restarting services / cronjobs, or create a deployment / cronjob by themselves without the need of sysadmins or intermediary like jenkins… so they will be happier at work!</p><h3>Problem</h3><p>There are problems arose:</p><ul><li>With CREATE permission for deployments / cronjobs, developers can leverage to have privilege escalation and get root or doing some nasty things on the physical hosts. Or simply they create too much rubbish in the system.</li><li>With DELETE permission for pods, a naughty developer can intentionally or mistakenly drop mission-critical services running inside the namespace, for example redis, cassandra, elasticsearch…, causing chaos to the whole system.</li></ul><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">Kubernetes RBAC</a> just could not solve these issues. We want them to be happy, but we also dont want us to suffer.</p><p>Here comes Admission Controller for the rescue.</p><h3>Admission Controller</h3><p>There’s a long official document on k8s.io, therefore we wont go too deep and theoretic into it. In this blogpost we just focus on <a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/">Validating Admission Controller</a>, which validates the k8s manifest before make it applied and persisted in etcd. We dont want to make use of Mutating counterpart because the applying manifests will be different with the original ones stored in version control, making confusion for operations.</p><p>Look at the diagram below and it can explain itself a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcRUn7yaEydeBwmNsuEKCQ.jpeg" /><figcaption>Source: sysdig.com</figcaption></figure><p>Basically when a manifest comes, Admission Controller invokes a AdmissionReview request to a webhook service (a HTTPS webserver). If the webserver return “OK” then the manifest is accepted, otherwise it will be rejected. Our job is simply to build a HTTPS webserver following format defined by Admission Controller, and we have full control of what to accept or reject according to the infomation including who requests and the manifest requested!</p><p>Having known that, we will try making ourselves a simple admission controller to reject deletion of critical services.</p><h3>Admission Webhook Service</h3><p>The demo will be using Python’s Flask webserver, as it’s more familiar to me. You can easily find others in the Internet using Go as well.</p><p>Firstly, we need to identify the format of <a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#validatingwebhookconfiguration-admissionreviewversions-0">AdmissionReview request</a> and <a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#admissionreview-response-allow-0">AdmissionReview response</a>. There will be 2 functions responsible for parsing request and templating response.</p><pre>def populate_ret(allowed, msg):<br>    return jsonify(<br>        {<br>            &quot;apiVersion&quot;: &quot;admission.k8s.io/v1&quot;,<br>            &quot;kind&quot;: &quot;AdmissionReview&quot;,<br>            &quot;response&quot;: {<br>                &quot;allowed&quot;: allowed,<br>                &quot;uid&quot;: request.json[&quot;request&quot;][&quot;uid&quot;],<br>                &quot;status&quot;: {<br>                    &quot;message&quot;: msg<br>                }<br>            }<br>        }<br>    )<br>---<br>def populate_info():<br>    #print(json.dumps(request.json, indent=4))</pre><pre>    info = {}</pre><pre>    info[&quot;namespace&quot;] = request.json[&quot;request&quot;][&quot;namespace&quot;]<br>    info[&quot;name&quot;] = request.json[&quot;request&quot;][&quot;name&quot;]<br>    ... # extract what you need<br>    <br>    return info</pre><p>Secondly, after getting all the needed information we can decide to accept or reject the AdmissionReview.</p><pre># Validate DELETE on POD only<br><a href="http://twitter.com/app">@app</a>.route(&quot;/validate-delete&quot;, methods=[&quot;POST&quot;])<br>def validate_delete():<br>    info = populate_info()<br>    allowed = True<br>    msg = &quot;&quot;</pre><pre>    # Whitelist is allowed<br>    for user in WHITELIST_USER:<br>        if info[&quot;user&quot;][&quot;username&quot;].startswith(user):<br>            return populate_ret(allowed, msg)</pre><pre>    for pod in SYSTEM_ENTITY:<br>        if info[&quot;name&quot;].startswith(pod):<br>            allowed = False<br>            msg = &quot;deletion of {} prohibited&quot;.format(info[&quot;name&quot;])<br>            return populate_ret(allowed, msg)</pre><pre>    return populate_ret(allowed, msg)</pre><p>The simplified code shows that we can define WHITELIST_USER — for power users who can delete everything , and SYSTEM_ENTITY — for restricted services — which can not be deleted by ordinary users. We can add more variables to apply restriction on some specific namespaces only.</p><p><strong>The curiosity of TLS handling<br></strong>If you have already known about Admission Controller, you will be curious about how we handle the TLS, as Admission Webhook Service have to be HTTPS. In our company, we’ve been already using Ingress-nginx for HA and TLS termination, for this webhook service we also offload the TLS termination to Ingress, so that our webserver will be much simpler.</p><p>It’s simple like that! Let’s test it out. I’ve removed myself from WHILELIST to test, and was trying to delete a redis pod. This is the result</p><pre>Error from server: admission webhook &quot;validate-delete&quot; denied the request: deletion of redis-cluster-xxx is prohibited</pre><p>While deleting other pod outside SYSTEM_ENTITY is still ok. Our Validating Admission Controller is working as expected!</p><h3>Conclusion</h3><p>K8s Admission Controller renders permission control to the very deep details. With it, we can control almost everything that’s defined in the manifest, according to our needs, basically everything that you can imagine of. For that, permissions for developers can be loosen but still under control, we’ve granted freedom under surveillance, and both developers and sysadmins can be happy at the same time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bab8e0b9822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Log-Structured Merge-Tree storage engine to a toy database]]></title>
            <link>https://medium.com/coccoc-engineering-blog/from-log-structured-merge-tree-storage-engine-to-a-toy-database-672092091bde?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/672092091bde</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 05:42:09 GMT</pubDate>
            <atom:updated>2021-12-30T05:43:48.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpOPb2kx6oIDlxjbTYnbwg.jpeg" /></figure><h3>Preface</h3><p>We’ve heard of Log-Structured Merge-Tree (LSMTree) for many times recently, when many high scalable NoSQLs are gaining popularity such as Cassandra, HBase, LevelDB, Elasticsearch… We may have a very brief idea on how they work under the hood theoretically, but we haven’t touch that in depth. We know the engine’s pros and also the cons in comparison with BTree, we learn by heart that “LSMTree is write-preferrable, and BTree vise-versa”, but do we actually understand why it has these characteristics?</p><p>In this blogpost, we do not guarantee that you’ll understand every aspect of LSMTree DBMS, but we’ll together build a key-value toy database, that follows the idea of the engine. Consequently, we will know a little bit deeper on how it works through the toy we build, from theory to practice. Surprisingly, it’s not that hard as we only read and imagine first-hand!</p><h3>Log-Structured Merge-Tree</h3><p>LSMTree is a data structure that allows append-only operations, that’s why it stands on its name, “Log-structured”. The database is a simply a very big log containing all the key-value pairs, and all the modifications such as create, update, delete are treated the same — insert new records into the big log. The design sounds very unintuitive in the first look, but it brings to the table a remarkable benefit which no other engines can afford: being append-only means writes will always be sequential, maintaining high throughput, low latency, no disk seek, no write amplification (as in BTree)... Now you have a faint idea on why LSMTree is write-preferable. Let’s go on, a database is not that simple.</p><p>Of course LSMTree is not a silver bullet for everything, its read performance is sometimes horibly slow in comparison with traditional BTree counterparts. To understand why read is slow, we need to look at the read path (which happens when a read query comes)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipKru9lYpGEgfQ1tjHrpKw.png" /><figcaption>Read path in Cassandra</figcaption></figure><p>Leaving out all the complications on the diagram above, write path, which doesnt require disk seeks, are very opposite to read path, which needs to check data from all the database segments, containing Memtables (the data segments in memory) and SSTables (the data segments on disk). The indexes and caches can help a bit, but eventually large data need to be scanned because the key can be existed in many places (due to append-only). This is opposite to BTree, when the read can find exact location for a key without scanning all the data.</p><p>Understanding Read and Write is crucial for understanding a database, even it’s just a very surface of a full-featured DBMS. But for the purpose of this blogpost, it’s enough for us to get ahead building our toy. Let’s get our hand dirty.</p><h3>Simple Key-Value datastore</h3><p>First of all, I’m gonna use Python for that demonstration because of its human-readable code. Python dictionary — a built-in data structure — will be leveraged for our task.</p><p>The very first KV datastore, with whole database is inside memory. I call the memory data structure “memtable” — borrowed from Cassandra. All the modifications will be using set() , and get() is for read.</p><pre>#!/usr/bin/env python3<br><br>import json<br>import logging<br><br>logging.basicConfig(level=logging.DEBUG)<br><br>class LSMTree():<br>    def __init__(self):<br>        self.memtable = {}</pre><pre>    def set(self, key, value):<br>        self.memtable[key] = value</pre><pre>    def get(self, key):<br>        if key in self.memtable:<br>            data = self.memtable[key]</pre><p>Next, we’ll need a bit of durability, for that our precious data would not be lost when the database shutdown. Function flush() will be called when database exit, and it has to flush all the data from memtable to disk. The startup() function do the opposite job, read all the data from disk and push back to memtable , so we can operate on that in-memory database.</p><pre>from pathlib import Path<br><br>DBPATH = &quot;/var/lib/lsm/&quot;</pre><pre>class LSMTree():<br>    def __init__(self, dbpath=DBPATH):<br>        ...<br>        self.db_file = self.path + &quot;db&quot;<br>        Path(self.path).mkdir(exist_ok=True)<br>        Path(self.db_file).touch(exist_ok=True)</pre><pre>    # flush memtable to persistent db file<br>    def flush(self):<br>        logging.debug(&quot;event: FLUSHING&quot;)<br>        json.dump(self.memtable, open(self.db_file, &quot;w&quot;))</pre><pre>    # for durability<br>    def shutdown(self):<br>        logging.debug(&quot;event: SHUTTING DOWN&quot;)<br>        self.flush()</pre><pre>    def startup(self):<br>        logging.debug(&quot;event: STARTING&quot;)<br>        self.memtable = json.load(open(self.db_file, &quot;r&quot;))</pre><p>Whenever startup, the whole DB will be reloaded into our memory, so it’s unusable with large dataset. Anyway, without index there’s nearly impossible to operate without scanning the whole dataset, and implementing index is out of scope of this blogpost, so we leave it as is. There’s not any LSMTree characteristics for now.</p><h3>Journaling</h3><p>There’s problem with current setup, if the DB is crashed during operations then the data between DB startups will be lost. Nearly all DBMS now are having a mechanism called “journaling” (or commit log) to deal with this kind of loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*Sn0ptK_qg_MdHsVSFWh5Zw.png" /><figcaption>journaling</figcaption></figure><p>First, database after receiving a write query will append that update info into journal (which resides on disk), then if it succeed, update will be taken place on memtable (on memory, would be very fast). After step 2, it returns to the client to acknowledge that write is successful (non-blocking because it doesnt need to wait for disk write). If the crash happens during flushing memtable to disk, database when startup can replay the update on journal to recover lost updates.</p><p>Let’s implement journal for our db</p><pre>class LSMTree():<br>    def __init__(self, dbpath=DBPATH):<br>        ...<br>        self.journal_file = self.path + &quot;journal&quot;<br>        Path(self.journal_file).touch(exist_ok=True)</pre><pre>        # Configs<br>        self.journal_line_limit = 5</pre><pre>    def set(self, key, value):<br>        # journaling for durable writes<br>        self.journal(key, value)<br>        # update value in memtable<br>        self.memtable[key] = value<br>    <br>    def journal(self, key, value):<br>        data = {key: value}<br>        json.dump(data, open(self.journal_file, &quot;a&quot;))<br>        with open(self.journal_file, &quot;a&quot;) as f:<br>            f.write(&quot;\n&quot;)<br><br>        self.rotate()</pre><pre>    # rotate journal, keep only last line when exceeding limit<br>    def rotate(self):<br>        data = []<br>        with open(self.journal_file, &quot;r&quot;) as f:<br>            data = f.read().splitlines()<br><br>        if len(data) &gt;= self.journal_line_limit:<br>            logging.debug(&quot;event: ROTATING&quot;)<br>            new_data = data[-1]<br>            with open(self.journal_file, &quot;w&quot;) as f:<br>                f.write(new_data)<br>                f.write(&quot;\n&quot;)</pre><pre>    # read journal into memtable on startup<br>    def startup(self):<br>        logging.debug(&quot;event: STARTING&quot;)<br>        data = {}<br>        with open(self.journal_file, &quot;r&quot;) as f:<br>            for line in f.readlines():<br>                jline = json.loads(line)<br>                # merge<br>                data = {**data, **jline}<br>        self.memtable = data</pre><p>We even implement a cool feature that rotating the journal log when it exceeds a threshold, for not growing too large. Basically our DB is single threaded so no need to keep too many records on journal.</p><p>You can notice that for now, we haven’t load the whole DB into memtable, only journal for recovery after crash, so get() is not working properly at the moment. We’ll implement the idea of LSMTree to operate on part of dataset instead of a whole, for better performance.</p><h3>Write-Ahead Log</h3><p>If our memtable hold too much data while the journal is rotated, a crash can clear all the un-journaled in-memory data. We need to find a way to flushing in-memory dataset into persistent disk before the journal is cleared out. There’re 2 common approaches employed by databases nowadays:</p><ol><li>flush the memtable to persistence file on every update operation. This method slows down the database significantly in tradeoff with consistency.</li><li>flush the memtable to persistence file according to its size or how long it hasn’t been flushed, or periodically (determined by space and time). We’ll choose this approach with config memtable_obj_limit = 5</li></ol><p>If the memtable is flushed to main database file db_file , it’ll be very slow because whole db need to be reread and rewritten. In LSMTree DB, memtables flush to sstables, then sstables will be merged together to a bigger sstables (Merge-Trees) by other asynchronous threads/processes, so older sstables will be untouched until merges happen (compaction), and main processing threads’ performance wont be affected.</p><p>We will inherit this characteristic, by flushing our memtable to a file called Write-Ahead Log (WAL), and after sometimes, merge wal with main db file. In official term, our wal and db files can be considered as 2 separated SSTables. Basically, we can use as many WALs as needed, but for sake of simplicity we use only one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2myT7fwS8CK-TZlaQsCY-A.png" /><figcaption>flush process flow</figcaption></figure><p>In short, main advantages of using WAL (or SSTables in Cassandra or alike):</p><ul><li>updates will be appended to persistence, no in-place update</li><li>separate a big db files into many small chunks, read can check latest chunks to get the latest data without scanning all the chunks</li></ul><p>Our DB is quite enough with write, let’s get back to read.</p><h3>Reading in LSMTree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJUscdtaCxYFkIgxCF8oiw.png" /><figcaption>Read path</figcaption></figure><p>We’re not having 3 chunks of data: memtable, wal and db. Memtable contains the latest data, so if we can get what it’s needed from memtable, disk access is not required. The idea applies to all DBMS as can be seen in Bufferpool in MySQL, WiredTiger cache in MongoDB and so on…</p><pre>    def get(self, key):<br>        data = None<br>        # check if value is in memtable<br>        if key in self.memtable:<br>            data = self.memtable[key]<br>        else:<br>            # else check all sstables (wal + db)<br>            wal = self.load(self.wal_file)<br>            if key in wal:<br>                data = wal[key]<br>            else:<br>                db = self.load(self.db_file)<br>                if key in db:<br>                    data = db[key]</pre><pre>        # If tombstone<br>        if data == self.tombstone:<br>            data = None</pre><pre>        return data</pre><p><strong>Delete by inserting tombstones</strong></p><p>The main problem of LSMTree is deleting is tricky because of no in-place replacement. For deleting we need to seek from all the chunks and delete that key if any. To overcome this issue the database insert a “tombstone” to the key which is suppose to be deleted (term and mechanism borrowed from Cassandra). For that, “delete” semantic is still append-only operation.</p><p>As in the read path depicted above, whenever it read the tombstone, the key is considered deleted. It will be truly deleted by merge (or compaction)</p><pre>    # For merging main db + wal<br>    def merge(self):<br>        wal = self.load(self.wal_file)<br>        db = self.load(self.db_file)<br>        # Dict merge python 3.5+ semantics<br>        merged = {**db, **wal}<br>        # remove tombstone<br>        removed = []<br>        for k in merged:<br>            if merged[k] == self.tombstone:<br>                removed.append(k)<br>        for k in removed:<br>            merged.pop(k)<br>        <br>        logging.debug(&quot;event: MERGING&quot;)<br><br>        json.dump(merged, open(self.db_file, &quot;w&quot;))<br><br>        # clear wal<br>        with open(self.wal_file, &quot;w&quot;) as f:<br>            f.truncate()</pre><h3>See what a toy can do</h3><pre>l = LSMTree()<br>l.startup()<br>l.upsert(&quot;1&quot;, &quot;1&quot;)<br>l.upsert(&quot;2&quot;, &quot;2&quot;)<br>l.upsert(&quot;2&quot;, &quot;3&quot;)<br>l.upsert(&quot;3&quot;, &quot;3&quot;)<br>l.upsert(&quot;4&quot;, &quot;4&quot;)<br>l.upsert(&quot;5&quot;, &quot;5&quot;)<br>l.upsert(&quot;6&quot;, &quot;6&quot;)<br>l.delete(&quot;6&quot;)<br>print(l.get(&quot;6&quot;))<br>print(l.get(&quot;5&quot;))<br>l.shutdown()</pre><pre>--- runtime output</pre><pre>DEBUG:root:event: STARTING<br>DEBUG:root:self.memtable: {&#39;1&#39;: &#39;1&#39;}<br>DEBUG:root:memtable_objs: 1<br>DEBUG:root:self.memtable: {&#39;1&#39;: &#39;1&#39;, &#39;2&#39;: &#39;2&#39;}<br>DEBUG:root:memtable_objs: 2<br>...<br>DEBUG:root:event: ROTATING<br>DEBUG:root:self.memtable: {&#39;6&#39;: &#39;delete_tombstone&#39;}<br>DEBUG:root:memtable_objs: 1<br>None<br>5<br>DEBUG:root:event: SHUTTING DOWN<br>DEBUG:root:wal: {&#39;1&#39;: &#39;1&#39;, &#39;2&#39;: &#39;3&#39;, &#39;3&#39;: &#39;3&#39;, &#39;4&#39;: &#39;4&#39;, &#39;5&#39;: &#39;5&#39;}<br>DEBUG:root:wal_objs: 5<br>DEBUG:root:event: FLUSHING<br>DEBUG:root:event: MERGING<br>DEBUG:root:event: MERGING</pre><p>As can be seen, key “6” was deleted so its value is “delete_tombstone”, and on MERGING event, it’s eventually deleted. get(&quot;6&quot;) returns None even before MERGING as designed.</p><p>We’ve completed a very first demonstration on how to build a functioning key-value database. As it’s not nearly applicable in any serious application, the idea of LSMTree is realized and being understandable in just ~100 lines of code, and can be developed even more for new features and better performance. Most of all, the toy opens paths for understanding LSMTree storage engine in more complex, complicated well-known databases such as Cassandra, Elasticsearch… which is the main purpose of this demonstration.</p><h3>References</h3><ul><li><a href="https://github.com/wintdw/python-lsmtdb">https://github.com/wintdw/python-lsmtdb</a></li><li><a href="https://dev.to/creativcoder/what-is-a-lsm-tree-3d75">https://dev.to/creativcoder/what-is-a-lsm-tree-3d75</a></li><li>Cassandra The Definitive Guide (3rd Edition) — Chapter 9: Reading and Writing Data</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=672092091bde" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/from-log-structured-merge-tree-storage-engine-to-a-toy-database-672092091bde">From Log-Structured Merge-Tree storage engine to a toy database</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webserver’s Concurency Models in Python]]></title>
            <link>https://medium.com/coccoc-engineering-blog/webservers-concurency-models-in-python-529af709b7a?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/529af709b7a</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 15:25:59 GMT</pubDate>
            <atom:updated>2021-10-01T03:12:30.172Z</atom:updated>
            <content:encoded><![CDATA[<p>In the very beginning, I was wondering how a webserver works, how mighty Apache — extremely dominating in the market at that time — was struggling with high traffic environments, how Nginx’s event-driven architecture beautifully solved C10K problem, and long after, how NodeJS got the community hype. At the heart of all the mentioned brands, there is concurrency models, which play the very crucial role in the modern webserver technologies — powering most of the Internet traffic worldwide nowadays.</p><p>In this blogpost, we’re going through the development of the tech tree, from a very primitive to more advanced models that’re prevalent today. We even take a look on the infamous Python’s <em>GIL</em> in action, and finally find out which models are more appropriate on which situations.</p><p>Why Python? Because it’s much easier to implement examples, even the very low-level interfaces such as socket, multiplexing IO, threading… And we can use most of the cognitive energy for understanding the mechanisms under the hood rather than the language itself. Let’s make some fun with Python!</p><p>Before going further, embrace yourself with these knowledges, just a bit:</p><ul><li>Processing / Threading</li><li>Socket</li><li>Multiplexing IO</li></ul><h3>The Naive server</h3><p>Let’s implement a simple client-server architect, using the primitive <em>socket()</em> system call</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1959a57ae243b645add546e00cf10bc/href">https://medium.com/media/a1959a57ae243b645add546e00cf10bc/href</a></iframe><p>In short, the service opens port <em>40404</em> locally, which <em>accept()</em> connections, and return result of 35th element of the Fibonacci sequence.</p><p>Why 35th? With it the test machine ultilizes fullly 1 CPU core (out of 4) and takes approx 4s to complete the recursive function — which is suitable for demonstration.</p><p>For the sake of simplicity, I didnt paste the client code here, but it’s as simple as calling socket’s <em>connect()</em> and <em>recv()</em>. Notably, 10 client processes will be forked simultaneously to connect to server for the purpose of checking the model’s concurency. All the codes will be included in the end.</p><p>Here comes the result</p><pre># time python3 client.py<br>2021-09-29 22:20:06.716157: [22090] Connecting 127.0.0.1:40404<br>...8 more times<br>2021-09-29 22:20:06.732502: [22099] Connecting 127.0.0.1:40404<br>b&#39;9227465&#39;<br>...8 more times<br>b&#39;9227465&#39;</pre><pre>real 0m39.847s</pre><pre>---<br># python3 naive.py<br>2021-09-30 17:00:37.553617: [12857] Accepting (&#39;127.0.0.1&#39;, 21464)<br>2021-09-30 17:00:41.563199: [12857] Processed (&#39;127.0.0.1&#39;, 21464)<br>2021-09-30 17:00:41.563701: [12857] Accepting (&#39;127.0.0.1&#39;, 21466)<br>2021-09-30 17:00:45.579824: [12857] Processed (&#39;127.0.0.1&#39;, 21466)<br>2021-09-30 17:00:45.580463: [12857] Accepting (&#39;127.0.0.1&#39;, 21468)<br>...</pre><p>~40s for 10 iterations of Fibonacci function. Remember this number, because we’ll get back to it very soon. 10 requests come at once, but 1 can be served at at time, others need to wait.</p><p>It can be clearly seen that the server use blocking, serialized model, which is the simplest one of all. One process can only serve one request at a time. Is it the slowest server?</p><h3>The MultiProcessing model</h3><p>The naive implementation raises a question, how to scale the webserver for it to serve more concurent requests? As one process can only serve one request at a time, the simple approach is to increase number of processes so the service can utilize more available resources in the system (in our case it’s CPU for calculating Fibonacci). Python provides <em>multiprocessing</em> libary for this purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc308fd74621a67ecb3798d38635bd5/href">https://medium.com/media/dfc308fd74621a67ecb3798d38635bd5/href</a></iframe><p>The code is pretty much the same with the previous implementation, just call function <em>process()</em> 4 times in 4 different processes using <em>multiprocessing</em> lib. Now we have 4 processes which can ultilize fullly 4 CPU cores (can be observed by <em>top</em>).</p><pre># time python3 client.py<br>2021-09-29 22:42:17.309141: [22696] Connecting 127.0.0.1:40404<br>...<br>b&#39;9227465&#39;</pre><pre>real 0m12.063s</pre><pre>---<br># python3 proc.py<br>2021-09-30 17:01:14.770677: [12938] Accepting (&#39;127.0.0.1&#39;, 21488)<br>2021-09-30 17:01:14.773363: [12939] Accepting (&#39;127.0.0.1&#39;, 21490)<br>2021-09-30 17:01:14.775600: [12940] Accepting (&#39;127.0.0.1&#39;, 21492)<br>2021-09-30 17:01:14.775894: [12941] Accepting (&#39;127.0.0.1&#39;, 21494)<br>2021-09-30 17:01:18.991079: [12939] Processed (&#39;127.0.0.1&#39;, 21490)<br>2021-09-30 17:01:18.991468: [12939] Accepting (&#39;127.0.0.1&#39;, 21496)<br>2021-09-30 17:01:19.114944: [12940] Processed (&#39;127.0.0.1&#39;, 21492)<br>2021-09-30 17:01:19.115302: [12940] Accepting (&#39;127.0.0.1&#39;, 21498)<br>2021-09-30 17:01:19.162694: [12941] Processed (&#39;127.0.0.1&#39;, 21494)<br>2021-09-30 17:01:19.162910: [12941] Accepting (&#39;127.0.0.1&#39;, 21500)<br>2021-09-30 17:01:19.215741: [12938] Processed (&#39;127.0.0.1&#39;, 21488)<br>...</pre><p>Expectedly nearly 4 times faster, 4 requests was served concurrently, the 2 last requests is serving in the last iteration, that’s why total time is 4x3 = 12s.</p><p>The multiprocessing model is simple, appeared in the very beginning days of webserver era yet still prevalent in the market today with the very well known examples of php-fpm, wsgi modules…, and even modern Apache with prefork MPM. There’re reasons to do so.</p><h3>The Threading model</h3><p>As all know about the disavantages of spawning too many processes, threading comes into play. Thread is lightweight, consumes less memory, easier communication with other threads by shared memory…, but it comes with a cost of complexity and synchronization hell. Nearly everyone runs into problem of race condition at least one in his life which is hard to debug.</p><p>Let’s try it with our demonstration, the <em>threading</em> library has the similar interface to <em>multiprocessing</em> one, so the switching will be very simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec7c909da41028340249e3c6ae336094/href">https://medium.com/media/ec7c909da41028340249e3c6ae336094/href</a></iframe><p>The result, guess what?</p><pre># time python3 client.py<br>2021-09-30 16:33:46.530893: [12243] Connecting 127.0.0.1:40404<br>...<br>b&#39;9227465&#39;</pre><pre>real 0m43.169s</pre><pre>---<br># python3 thread.py<br>2021-09-30 17:02:42.883735: [13052] Accepting (&#39;127.0.0.1&#39;, 21512)<br>2021-09-30 17:02:42.890233: [13052] Accepting (&#39;127.0.0.1&#39;, 21514)<br>2021-09-30 17:02:42.890349: [13052] Accepting (&#39;127.0.0.1&#39;, 21518)<br>2021-09-30 17:02:42.890456: [13052] Accepting (&#39;127.0.0.1&#39;, 21516)<br>2021-09-30 17:02:59.937182: [13052] Processed (&#39;127.0.0.1&#39;, 21514)<br>2021-09-30 17:03:00.020148: [13052] Accepting (&#39;127.0.0.1&#39;, 21520)<br>2021-09-30 17:03:00.333162: [13052] Processed (&#39;127.0.0.1&#39;, 21512)<br>2021-09-30 17:03:00.343931: [13052] Accepting (&#39;127.0.0.1&#39;, 21522)<br>2021-09-30 17:03:00.660173: [13052] Processed (&#39;127.0.0.1&#39;, 21516)<br>2021-09-30 17:03:00.681185: [13052] Accepting (&#39;127.0.0.1&#39;, 21524)<br>2021-09-30 17:03:00.810254: [13052] Processed (&#39;127.0.0.1&#39;, 21518)<br>2021-09-30 17:03:00.815903: [13052] Accepting (&#39;127.0.0.1&#39;, 21526)<br>...</pre><p>4 requests were served at a time, however 4x slower in response time (~16s each). Total time ~4x multiprocessing model.</p><p>That is such a big disappointment. For our common knowledge this result doesn’t make sense. Threading performance should be at least equal to multiprocessing if not better, but it performed in this case even worse than single process, single thread model in the first demonstration. If you’re thinking of a magical unknown stuff inside Python interpreter, then hooray, you’re correct. It’s the so-called GIL that people usually talking about.</p><p>In short, GIL is a global process lock for keeping only one thread running in a process (about the reason and details we will not cover in this post). In our case 4 threads was running in concurrency, but only one can take the lock and ultilize CPU at a time, and each thread has a timeslice to run before being preemtively switched to another thread (sounds like OS’s CPU scheduler?).</p><p>So what threading is useful for? Let’s take one more test</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba7344cd354f37979b23a6017dda6af4/href">https://medium.com/media/ba7344cd354f37979b23a6017dda6af4/href</a></iframe><p>Usually there’re 2 types of applications: IO-bound and CPU-bound. For Fibonacci pure CPU is used, so the function is CPU-bound. As we previously know one Python can not ultilize more than 1 CPU core because of GIL so that threading will not be beneficial for CPU-bound applications. How about IO-bound counterpart?</p><p>Let’s check the result with <em>sleep()</em> function (simulated IO-bound such as waiting for network / disk io)</p><pre># time python3 client.py<br>2021-09-30 16:58:39.342335: [12779] Connecting 127.0.0.1:40404<br>...<br>b&#39;None&#39;</pre><pre>real 0m12.072s</pre><pre>---<br># python3 thread.py<br>2021-09-30 17:05:43.228304: [13177] Accepting (&#39;127.0.0.1&#39;, 21544)<br>2021-09-30 17:05:43.229373: [13177] Accepting (&#39;127.0.0.1&#39;, 21546)<br>2021-09-30 17:05:43.230724: [13177] Accepting (&#39;127.0.0.1&#39;, 21548)<br>2021-09-30 17:05:43.231274: [13177] Accepting (&#39;127.0.0.1&#39;, 21550)<br>2021-09-30 17:05:47.232686: [13177] Processed (&#39;127.0.0.1&#39;, 21544)<br>2021-09-30 17:05:47.232909: [13177] Accepting (&#39;127.0.0.1&#39;, 21552)<br>2021-09-30 17:05:47.233211: [13177] Processed (&#39;127.0.0.1&#39;, 21546)<br>2021-09-30 17:05:47.233294: [13177] Accepting (&#39;127.0.0.1&#39;, 21554)<br>2021-09-30 17:05:47.234927: [13177] Processed (&#39;127.0.0.1&#39;, 21548)<br>2021-09-30 17:05:47.235022: [13177] Accepting (&#39;127.0.0.1&#39;, 21556)<br>2021-09-30 17:05:47.235451: [13177] Processed (&#39;127.0.0.1&#39;, 21550)<br>...</pre><p>Now thing looks normal. Threads waiting for IO wont be affected by GIL. So now you know why Python’s threading is suggested to be used on IO-bound applications only. Another reason for not using threading is thread safety concern on synchronization, which we wont cover it here. For Python webservers, multiprocessing is still somewhat preferable.</p><h3>Non-blocking?</h3><p>On above processing / threading models, the socket is blocking. Which means when the thread / process is serving a request, it blocks other requests from processing, and it let them wait until the socket is free again. In the non-blocking mode, the socket does not block requests, instead return immediately error EAGAIN: Resource temporarily unavailable so the client wont wait. The client can retry another time, and do another useful stuff rather than waiting doing nothing.</p><p>Time to build a non-blocking client. It’s quite troublesome in the beginning when we need to get familiar with something new. But trust me thing will be easier as time goes by.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700978a6f9f3b7508384c66efefb2e54/href">https://medium.com/media/700978a6f9f3b7508384c66efefb2e54/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*HkiBxxmoV-1KJV-AlpHDCA.png" /><figcaption>Simple non-blocking, polling algorithm</figcaption></figure><p>In the single thread, single process model, client is blocking for 4s waiting for a result from the server. With non-blocking mode, we’ll try using 4s to do something more meaningful while waiting for the result. In this demonstration only 1 request is sent to the server.</p><pre># time python3 nonblocking-client.py<br>2021-09-30 21:16:46.464402: Connecting 127.0.0.1:40404<br>2021-09-30 21:16:46.464687: Still waiting, doing Fibonacci 31<br>1346269<br>2021-09-30 21:16:48.037938: Still waiting, doing Fibonacci 31<br>1346269<br>2021-09-30 21:16:49.613336: Still waiting, doing Fibonacci 31<br>1346269<br>2021-09-30 21:16:50.359646: Data returned<br>Returned from Server: b&#39;9227465&#39;</pre><pre>real 0m3.945s</pre><pre>---<br># python3 naive.py<br>2021-09-30 21:16:46.464813: [20196] Accepting (&#39;127.0.0.1&#39;, 22836)<br>2021-09-30 21:16:50.359540: [20196] Processed (&#39;127.0.0.1&#39;, 22836)</pre><p>As can be seen, while waiting for Fibonacci(35), the client take the time to calculate 3x Fibonacci(31) (~1.5s/each)</p><p>Non-blocking mode is very useful for IO-bound tasks, ask the process can use the time waiting to do other tasks, without the need of threading or subprocessing. Operating systems support polling mechanisms called Multiplexing IO with the syscalls <em>select(), poll(), epoll(), kqueue()</em>… which helps non-blocking programming becomes more popular.</p><h3>The asynchronous, non-blocking Event-driven architecture</h3><p>The non-blocking demonstration above is a bridge to the last model, which is the heart of the most effective, prevalent, prominent webservers these days such as Nginx, NodeJS, Lighttpd… The technology is called event-driven architecture, and the core of the architecture is an Event Loop. Simply put, event loop is a loop inside a process, which triggers callbacks based on events.</p><blockquote>Think of the state machine like the rules for chess. Each HTTP transaction is a chess game. On one side of the chessboard is the web server — a grandmaster who can make decisions very quickly. On the other side is the remote client — the web browser that is accessing the site or application over a relatively slow network.<br> — Inside NGINX: How We Designed for Performance &amp; Scale</blockquote><p>Application does not block on events, that’s why it’s non-blocking, possible to accept a lots of requests simultaneously. Requests will be put into a run-loop, and then processed asynchronously until completion. Event loop can be very fast, but as single threaded nature, one single blocking call will block the whole process, which causes all the accepted requests blocked as well. We wont go into too much details here, because it may take several days to talk clearly about the event driven architecture. Time to make some codes!</p><p>Python supports eventloop with high-level interface called <em>asyncio</em> library. The syntax itself is quite difficult for ones not familiar with event-driven beforehand, but let’s just focus on ideas, not the language itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b1cbb3f53582c6278a4ee446126fd1d/href">https://medium.com/media/7b1cbb3f53582c6278a4ee446126fd1d/href</a></iframe><p>Similar to threading model, we will test the server with CPU-bound and IO-bound functions.</p><p>IO-bound first, where event-driven shines the most. As usual 10 request comming to the server instantly.</p><pre># time python3 client.py<br>2021-09-30 22:05:08.030330: [21375] Connecting 127.0.0.1:40404<br>...<br>b&#39;None&#39;</pre><pre>real 0m4.068s</pre><pre>---<br># python3 eventloop.py<br>2021-09-30 22:05:08.032579: [21373] Accepting (&#39;127.0.0.1&#39;, 23074)<br>2021-09-30 22:05:08.032932: [21373] Accepting (&#39;127.0.0.1&#39;, 23076)<br>2021-09-30 22:05:08.034144: [21373] Accepting (&#39;127.0.0.1&#39;, 23078)<br>2021-09-30 22:05:08.036164: [21373] Accepting (&#39;127.0.0.1&#39;, 23080)<br>...<br>2021-09-30 22:05:12.045846: [21373] Processed (&#39;127.0.0.1&#39;, 23092)</pre><p>All requests were accepted at once, and they finished at the same time. Total time is 4s, which mean the concurrency performed pretty nicely.</p><p>Next, CPU-bound, expectedly, the server use only 1 process, so the CPU utilization could not go higher than 1 core, eventually the response will be slow. How slow actually?</p><pre># time python3 client.py<br>2021-09-30 22:09:12.402979: [21493] Connecting 127.0.0.1:40404<br>...<br>2021-09-30 22:09:12.414549: [21502] Connecting 127.0.0.1:40404<br>b&#39;9227465&#39;<br>...<br>b&#39;9227465&#39;</pre><pre>real 3m57.475s</pre><pre>---<br># python3 eventloop.py<br>2021-09-30 22:09:12.404250: [21491] Accepting (&#39;127.0.0.1&#39;, 23110)<br>2021-09-30 22:09:35.934708: [21491] Processed (&#39;127.0.0.1&#39;, 23110)<br>Executing &lt;Task finished coro=&lt;handle() done, defined at eventloop.py:24&gt; result=None created at eventloop.py:42&gt; took 23.531 seconds<br>2021-09-30 22:09:35.939693: [21491] Accepting (&#39;127.0.0.1&#39;, 23112)<br>2021-09-30 22:09:59.947985: [21491] Processed (&#39;127.0.0.1&#39;, 23112)<br>Executing &lt;Task finished coro=&lt;handle() done, defined at eventloop.py:24&gt; result=None created at eventloop.py:42&gt; took 24.009 seconds<br>...<br>Executing &lt;Task finished coro=&lt;handle() done, defined at eventloop.py:24&gt; result=None created at eventloop.py:42&gt; took 23.801 seconds</pre><p>24s for one request, and it was even running sequencially. Simply the fib() was blocking the loop, causing the whole process stalled. The event loop model is unbelievably slow when handling CPU-bound tasks, most interesting that it’s even much slower than single process, single thread model. This result proves that event loop is not always a silver bullet for everything, and we need to use it with care. Remember back in the days when Nginx having a lot of misteries related to <a href="https://serverfault.com/questions/666214/slow-download-big-static-files-from-nginx/812737">blocking issues</a>?</p><p>We’ve gone through so much code and models, we’ve seen how GIL hindered threading performance, we’ve seen the power of well-known event-driven architecture as well as the disadvantages. Concurrency is difficult, but fun to play with. About the applicability of each mechanisms, I hope that you can find out by yourself after the long examples, and write better codes. Have fun concurrency!</p><p><strong>Further readings:</strong></p><ul><li><a href="https://github.com/wintdw/webserver.git">https://github.com/wintdw/webserver.git</a></li><li>Chapter 63 Alternative IO Models — The Linux Programming Interface — Michael Kerrisk</li><li><a href="https://www.aosabook.org/en/nginx.html">https://www.aosabook.org/en/nginx.html</a></li><li><a href="https://www.nginx.com/blog/thread-pools-boost-performance-9x/">https://www.nginx.com/blog/thread-pools-boost-performance-9x/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529af709b7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/webservers-concurency-models-in-python-529af709b7a">Webserver’s Concurency Models in Python</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Redis Stories]]></title>
            <link>https://medium.com/coccoc-engineering-blog/the-redis-stories-25b0de525246?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b0de525246</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[system-development]]></category>
            <category><![CDATA[sysadmin]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 09:53:22 GMT</pubDate>
            <atom:updated>2021-07-01T06:33:53.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_j_xCxZF4Pz4OfoFZviAw.png" /></figure><p>We’ve probably heard of, or even used Redis quite frequently as part of our infrastructure. Redis is everywhere, which can be a caching layer, a message queue, or even a memory database, whatever it is, performance is always the main objective of using Redis. In Coccoc infrastructure, Redis has being used from the begining, with the simplest design of a single instance, gradually evolved into more complex and complicated systems — especially when partnering with Kubernetes — with a lot of stories to tell, including both successes and failures… In this blogpost, we are going to go through several milestones of Redis history on the path of development of the systems.</p><h3>The High Availability desire — Redis Sentinel</h3><p>In the very eary stage, we mostly used Redis as a cache layer for many upstream applications. Theoretically, this layer can be unavailable, the cache can be lost and the applications must still be functioning well during the Redis failures, but actually some of them sometimes did not behave that way, they failed along with Redis (oops!). There might be problems with the application designs, so we filed the issues to the dev teams for improvements. Meanwhile, as an infrastructure team, securing the night sleep is as important as fixing the design bug, we decided those cache layers should also be high available, which would help reducing conflicts and headaches from both infra and devs. Redis Sentinel — the official high availability solution for Redis — was initially considered for implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75j4D6tLz8AaayjX89_3ZA.png" /><figcaption>Redis Sentinel Setup</figcaption></figure><p>The minimum number of instances for a healthy Redis Sentinel setup is 5, where 2 instances for Data nodes (master &amp; slave), and other 3 for Sentinels (quorum), which maintains the high availability for the cluster when either Data or Sentinel nodes fails.</p><ul><li>In case of a Redis master node fails, Sentinels consensus on promoting the slave to take over the role, and client requests will be routed to this new master. There is only 1 master at a time, but many slaves.</li><li>In case of minority of Sentinels fails, the other Sentinels still form a majority so the client requests are still served normally</li><li>In case of majority of Sentinels fails, for avoiding split-brain, all the other Sentinels will stop serving client requests. However, the Data nodes are still working and doesnt aware of the Sentinel failures, but as traffics could not routed to the Data nodes, the whole cluster still fails.</li></ul><p>With this setup, the system can tolerate at max 1 data nodes and/or 1 sentinel failures at a time, but no more. Furthermore, for making HA from one single instance, we need 4 more instances to form the smallest Sentinel cluster to be functioning robustly, which is kind of resource wasted. But finally, we achieved HA for Redis!</p><h3>Another High Availability but better — Active Active Replication</h3><p>The complexity of Redis Sentinel urges us to find another approach, why do we need Sentinels at all, why dont Data nodes failover itselves? Unfortunately, Redis single instance still does not support automatic failover, however, we can eliminate the need of Sentinels with another solution provided by Redis: Active — Active replication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTPhAqj51HK-DOE_lPAWHw.png" /><figcaption>Active-Active Database</figcaption></figure><p>In the Master — Slave replication, a write could not occur on slave, for maintaining the consistency. In this Active — Active replication, both instances can issue writes on their local databases, and use asynchronous replication to maintain consistency. For this replication model, a common question already arose: How does the two instances handle conflicts?</p><p>Redis claims to implement CRDB (Conflict-free Replicated Database) for handling conflicts. Put simply, the cluster doesnt require concensus or coordination between replicas, the latest operations usually overwrite the prior values. The consistency for this replication model is very weak in comparision with other kinds of databases, so this setup should be used with caution. In our infrastructure, only service data when the consistency is not a major concern (mostly cache) should be stored in Redis.</p><p>The very simple demonstration for a eventually convergence in the Active — Active setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9xTrtf-EbDe-sVaN9ujww.png" /><figcaption>Conflict-free eventual convergence</figcaption></figure><p>Side note, Active — Active replication is only available on Redis Enterprise. KeyDB (the free community fork version from Redis) supports Active Replica, which has the same functionality with Active — Active replication from Redis.</p><h3>The Single-Threaded nature strikes, and an Approach to Multicore Redis</h3><p>We all know Redis is single-threaded, probably because the author still wants to maintain its simplicity, and Redis is harly seen fully utilized its CPU core. Actually on the most busy systems in our infrastructure, Redis did frequently consume full 100% CPU, the latency consequently became skyrocketed because of longer processing queue. There were definitely a need to find an affordably scalable solution for Redis.</p><p>At first, to maintain the simplicity of our cluster, we decided to use multiple Redis single instances to utilize more CPU cores, and the setup was called Redis-multicore at that time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mnvv3oV5oeJYKHyx_W1Kg.png" /><figcaption>Redis multicore</figcaption></figure><p>As depicted above, the Redis instances does not have any relationship with others, the only stuff that needs to care about the whole structure is the Applications which employ the Redis multicore setup. The Applications will have its own sharding mechanism — the heart of the setup. The most simple sharding algorithm is to divide the keyid to the number of instances and get the modulo: m = k % i, after that the key can be stored into the appropriate instance.</p><p>This setup has its own characteristics:</p><ul><li>Very simple to implement</li><li>One or more Redis instances down doesnt affect the alive ones, and affects just part of the Applications</li><li>Adding / Removing Redis instances to the farm will affect the whole sharding mechanism</li><li>All the Applications which need to use the same dataset need to employ the same sharding mechanism</li><li>At that time we did not implement replicas for the whole cluster. If it’s necessary, Active — Active replication for each Redis shard may be the good choice, but it will add up to the complexity of the overall system</li><li>The hardwork (sharding) is left for the Applications, which is uncontrollable for the infrastructure team</li><li>Migrating those Redis instances to other servers takes much of the manual effort</li></ul><p>Although there are quite some advantages, this setup is not very suitable for the high traffic, complicated infrastructure. Fortunately, Redis 3.0 introduced the new concept of distributed system: The Redis Cluster.</p><h3>The Cluster on the Cloud</h3><p>The multicore setup, had been working for quite a long time without a big issue. However, problems arose when a server hosts too many Redis instances, the bandwidth gradually became bottlenecked, moreover, the servers containing those instances also needed upgrading after some time. There is always a need for some of the Redis instances to be migrated somewhere else without affecting the production services. It might take a lot of time and effort for every Redis migration…</p><p>Meanwhile, we have been employing the power of the cloud provided by Kubernetes — the container orchestration platform recently, and with the help of containerization, application migrations between servers should be no longer a pain, which is the necessary solution in this situation. We decided to bring the whole big Redis infrastructure to the cloud! And even better, we wanted to make Redis truly fault-tolerant, high-available and scalable by replacing multicore with Redis Cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMsjNpsvaFoeTntC4OBZkA.png" /><figcaption>Redis Cluster</figcaption></figure><p>We talk about Redis Cluster first, it has predefined 16384 shards, and shards can be allocated into nodes. One single nodes can contains more than one shards, as depicted above. Applications can ask any node in the cluster, if the node can not serve directly (because of being slave, or doesnt contains the keys), it will redirect the application to the correct node by MOVED or ASK command.</p><p>When a master is down, the slave corresponding to the master can automatically take over the role (without the need of Redis Sentinel), so that the cluster can function properly.</p><p>In short, the main advantages of Redis Cluster over Redis multicore:</p><ul><li>There is no manual sharding mechanism needed</li><li>Adding / Removing nodes on the cluster is very simple and straightforward. Autorebalance supported</li><li>Replica &amp; Autofailover supported</li></ul><p>This approach solves many of the outstanding issues with Redis multicore, however, node migration is still a pain, and this is where Kubernetes really shines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8Q0cZbhBQ8EXWYr9mByWA.png" /><figcaption>Redis Cluster on the cloud</figcaption></figure><p>Setting up Redis Cluster on Kubernetes should have some caveats considered:</p><ul><li>For password-protected Redis, we need a secret storage for Redis container to fetch the password and apply. We use Vault in our infrastructure</li><li>Redis Cluster instance stores a configuration file on persistent storage for keeping cluster state on restarts. Container is ephemeral by nature and it doesnt preserve this file, so we need a shared storage system for this usage. CephFS is chosen</li><li>There may be a need for sysctl tunings (<em>transparent hugepage</em>, <em>somaxconn…</em>) which can be configured using <em>initContainers</em></li><li>The very important issue, is to make slaves and masters reside on the different servers, so when one or more physical servers down, the replicas of a data shard must not be down together, or the failover will not succeed. This can be solved by using <em>nodeAntiAffinity</em></li></ul><p>Finally, at this step, we probably deal will most of the problems experienced, and the clusters have been working well most of the time.</p><h3>The Ever-Evolving Cluster</h3><p><strong>The long-foreseen issues with Network FileSystem</strong></p><p>Kubernetes platform supports very many flexible approaches, and we as well never stop trying to find the most appropriate solutions for our systems. With the huge dependency on CephFS, Redis cluster is never considered stable enough. One day, the small network partition incident caused all of the Redis Cluster instances in the very critical system failed at once, moreover, Redis pods could not restart themselves (all were in Terminating state, but couldnt really terminated because of stuck FS. You know, network FS always sucks). That incident triggered an alert that our systems are still not perfect, and we still have headroom for the ultimate target of “securing our sleep”. And here we still go.</p><p>Actually, using CephFS just for keeping configuration files on restart is just a waste, but how to decouple Redis from Ceph? There is still a need for Redis Cluster containers to retrieve the last-saved config files just before starting the main process, so it could join the old cluster smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lIf-bMudM0sOny4Q1ohjA.png" /><figcaption>The design of preserving config file without network FS</figcaption></figure><p>Just before the container terminated, it pushes the last-saved configuration to the centralized conf storage, and then when it respawns, the initContainer pulls the config file from the same location, so the main process can start and join the cluster. The conf storage can be set up very simply by a rsync daemon, nginx HTTP, or even S3 interface by Ceph. The conf storage needs to be high-available as well, or the complete HA design for Redis Cluster will be less meaningful.</p><p>For this approach, network FS is not necessary anymore, and we can get rid of the network partition problem causing all the clusters to hang indefinitely.</p><p><strong>Single-threaded architecture strikes again</strong></p><p>With the help of Redis Cluster, one single cluster can utilize more than one CPU cores, and it help a lot on high traffic sites. However, when we need to create a big cluster which can utilize 24 cores, we need to create 24 instances for masters, and another 24 instances for slaves, which becomes a very tedious task to maintain the cluster.</p><p><a href="https://docs.keydb.dev/blog/2019/10/07/blog-post/">KeyDB</a> again comes into rescue, which supports multithreading. However, from real-world usage, one single instance should not be used with more than 2 cores, or latency will increase significantly (maybe because of synchronization between threads?). Reducing number of instances 2 times is also a big achievement, though.</p><p><strong>Time is always precious</strong></p><p>There are situations when Redis instances need to be migrated to other physical hosts, for maintenance. We haven’t understood clearly why, but in the events of replication resync when the slave nodes respawn, the latency is always higher (depsite Redis states that the master will spawn another process for dumping data). For that, the syncing process should be as fast as possible. The fact that a normal synchronization of 12–15G data between master slave can take up to 30 minutes, so the applications suffer from 30mins of higher latency, which is untolerable.</p><p>We come to <em>diskless replication— </em>the feature supported by Redis 2.8.18<em>, </em>as depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6tawkpJAOSD_zU3M03rEg.png" /><figcaption>Above is normal replication. Below is diskless replication</figcaption></figure><p>Diskless replication needs only 1 dumping-to-disk steps, which takes most of the time. Eventually, we reduce the replication period by nearly 50%, equally 50% less latency-suffered time, which is also a big achievement.</p><h3>Endings</h3><p>Redis provides wide range of solutions, each will be suitable for different problems. Trying step by step is the way we learned what would be appropriate for each purpose. For now our infrastructure consists of clusters, active-active replication, and even single instances… depending on what we really need. The management, however, becomes much more pleased than days of the past.</p><p>There are still several stories on how we operate, monitor, tune performance, backup/restore the cluster, and about incidents we faced, but it is long already. Going through all the stages from the beginning to the setup as of now requires much of the efforts and experiences, but we are happy on what we currently have, and what we already learned throughout the days.</p><h3>References</h3><ul><li>Redis Master — Master Replication <a href="https://redislabs.com/wp-content/uploads/2017/02/04-Yossi-Gottlieb-Redis-Labs.pdf">https://redislabs.com/wp-content/uploads/2017/02/04-Yossi-Gottlieb-Redis-Labs.pdf</a></li><li>The official Redis Documentation: <a href="https://redis.io/topics/">https://redis.io/topics/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b0de525246" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/the-redis-stories-25b0de525246">The Redis Stories</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Computing: Paxos Algorithm (Part 2)]]></title>
            <link>https://medium.com/coccoc-engineering-blog/distributed-computing-paxos-algorithm-part-2-4d684b2c504d?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d684b2c504d</guid>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[paxos]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 16:35:36 GMT</pubDate>
            <atom:updated>2021-03-28T16:45:53.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foreword</h3><p>In the <a href="https://medium.com/coccoc-engineering-blog/distributed-computing-consensus-protocol-part-1-d461a151368b">previous blogpost</a>, we’ve discussed the neediness of consensus protocol in the distributed computing era and the most commonly known 2-phase-commit algorithm. In the second installment of this series, <strong>Paxos </strong>— the consensus protocol will be explained in a simplified manner, about its mechanism, the differences in comparison with 2PC and how it can solve the outstanding issues that 2PC leaves over.</p><h3>Overview</h3><p>Let’s review what are the problems that the algorithm needs to address:</p><p>Consensus protocol liveness property:</p><ul><li>For many values proposed at the same time, only one is chosen.</li><li>When the value is chosen, all the nodes eventually learn the value.</li></ul><p>2PC outstanding problems:</p><ul><li>When one or more nodes (excluding coordinator) fail at <em>prepare</em> phase, the transaction is always aborted, which is not efficient.</li><li>When the coordinator fails after <em>prepare</em> phase, the process block indefinitely until it recovers.</li></ul><p><strong>Paxos properties</strong></p><p>Paxos is designed to be a modern and non-blocking consensus protocol — for replacing classic 2PC algorithm — in which failure of one single node doesnt prevent others from deciding the transaction will be commited or aborted, even the failed node is coordinator, or not. In fact, Paxos maintains availability of the protocol if majority of the cluster agrees on decision.</p><p>According to the liveness properties of a consensus protocol, we define 3 roles which act separately:</p><ul><li>Proposers: the nodes which can propose value.</li><li>Acceptors: the nodes which can decide to chose a value. This role is similar to <em>coordinator</em> in 2PC.</li><li>Learners: the nodes which learn the value after being chosen.</li></ul><p>Basically, Paxos node can take multiple roles, even all.</p><h3>Implementation</h3><p>In an assumption that there’re 2F+1 servers in total. If at any time F+1 (quorum) acceptors agree on one proposal, it is chosen.</p><p>Paxos is operating in the following 2 phases, just like 2PC:</p><ul><li>Prepare: <br>To check if the acceptors are accepting any other proposal, and if not,<br>prevent acceptors from accepting any older proposals.</li><li>Accept (<em>Commit </em>in 2PC):<br>for accepting value and propagate the information to all the learners.</li></ul><p>The algorithm can be demonstrated in the diagrams below:</p><p><strong>Single proposer, no conflicts scenario</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*0FC_IwE2CQSkhLd6JPBS9g.png" /><figcaption>Paxos failure-free, no conficts scenario</figcaption></figure><ul><li>In the first phase, a proposer want to propose a value, it chooses a ballot number ID (which can be timestamped — for keeping track of message order), let say, 5, and sends a message PREPARE 5 to majority (or all) of the acceptors, for checking if the acceptors can accept proposals or not.</li><li>The acceptors, at the moment, havent been accepting any proposal, send back message PROMISE 5 to the proposer.</li><li>When the proposer receives replies from majority of the acceptors, it then sends a message ACCEPT-REQUEST 5 &#39;cat&#39;. At this moment it’s actually proposing a value.</li><li>The acceptors send ACCEPT 5 &#39;cat&#39; to the proposer and all the learners. The consensus is reached.</li></ul><p>Supposingly there’re 3 acceptors, if at any time 1 of them dies, the other two are still functioning and accepting proposals, the process is still working fine. It solves the 2PC’s problem when the coordinator fails, the whole process stops.</p><p>The beauty of Paxos will be shown more clearly when conflicts happen.</p><p><strong>Two proposers, conflicting scenario</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJ1LCfdF2cuGLKJ6yZIRug.png" /><figcaption>2 proposers, conflicting scenario</figcaption></figure><ul><li>Proposer 1, wants to make a proposal, sends to the acceptors message PREPARE 5. The acceptors at this time haven’t yet promised or accepted any value, they send back message PROMISE 5. But after that, it is off for some time, because of network partition, or hardware failure, the state is still kept on proposer and acceptors.</li><li>Proposer 2, at later time, also wants to make another proposer, sends to the acceptors message PREPARE 4. The acceptors already promised with ID 5, so<strong> they ignore all older IDs</strong> (which are less than 5).</li><li>Proposer 2 haven’t received PROMISE message, it sends another message with increased ID PREPARE 6. Because the ID is higher, and acceptors haven’t yet accepted any value, it makes another promise with message PROMISE 6.</li><li>Proposer 2 after receiving messages from acceptors, it send ACCEPT-REQUEST 6&#39;dog&#39; to propose value, and acceptors send back ACCEPT 6 &#39;dog&#39; to it and propagate to all learners. Consensus is reached at this step.</li><li>Moreover, Proposer 1 after some times recovers, still keeps track of the PROMISE message (but haven’t learned the state of the cluster), sends to the acceptors message ACCEPT-REQUEST 5 &#39;cat&#39; for proposing a value. But at the moment the acceptors already accepted ID 6, so they consider the message was from the past, and ignore it.</li><li>Proposer 1 after message timeout, restart the process and send message with increasing ID 7 PREPARE 7. The acceptors accept it, but they have accepted proposal already, send back message PROMISE 7 accepted 5, &#39;dog&#39;, to notify the proposer that they have the accepted value.</li><li>At this point, Proposer 1 <strong>can only propose the same value with the already accepted value</strong>, which is dog in this situation. The message ACCEPT-REQUEST 7 &#39;dog&#39; is sent to the acceptors, and consensus will be reached again with the same value. Proposer 1 also learns the value dog if it was missed previously.</li></ul><h3>Conclusion</h3><p>Paxos, as described and demonstrated above, is a non-blocking fault-tolerant consensus protocol, and differs from 2PC that the consensus progress is still made when majority of nodes are still functioning. These properties not only help distributed system increase scalability but also maintain availability. Paxos was introduced long ago and getting more and more adoption for modern distributed systems such as Zookeeper, Elasticsearch, Cassandra, Ceph…</p><p>On the next blogpost, we’ll go into another consensus protocol called Raft, which has quite similar properties with Paxos but is considered easier to understand, and is also getting more and more attention nowadays.</p><h3>References</h3><ul><li>Paxos made simple — Leslie Lamport: <a href="https://lamport.azurewebsites.net/pubs/paxos-simple.pdf">https://lamport.azurewebsites.net/pubs/paxos-simple.pdf</a></li><li>Consensus on Transaction Commit — Jim Gray and Leslie Lamport, Microsoft Research: <a href="https://www.microsoft.com/en-us/research/uploads/prod/2004/01/twophase-revised.pdf">https://www.microsoft.com/en-us/research/uploads/prod/2004/01/twophase-revised.pdf</a></li><li>The Paxos algorithm — Google TechTalks: <a href="https://www.youtube.com/watch?v=d7nAGI_NZPk&amp;t=205s">https://www.youtube.com/watch?v=d7nAGI_NZPk&amp;t=205s</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d684b2c504d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/distributed-computing-paxos-algorithm-part-2-4d684b2c504d">Distributed Computing: Paxos Algorithm (Part 2)</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Computing: Consensus Protocol (Part 1)]]></title>
            <link>https://medium.com/coccoc-engineering-blog/distributed-computing-consensus-protocol-part-1-d461a151368b?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/d461a151368b</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 16:19:59 GMT</pubDate>
            <atom:updated>2021-03-28T13:11:20.601Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Foreword</strong></h3><p>You may have heard of <em>Transaction </em>— which is very important feature to maintain atomicity of the database. For those who dont know, atomicity guarantees updates to the database either <strong><em>all</em></strong> occur, or <strong><em>nothing</em></strong> occurs.</p><p>On a single node database, transaction is usually implemented by the storage engine, using a well-known technique called binary log (MySQL), transaction log (Oracle)… However, things become complicated when multiple nodes come into play. When a distributed transaction is commited <em>independently</em> on all of the nodes, there will be a case that the commit succeeds on some nodes and fails on others, which violates the atomicity guarantee. Therefore all the nodes need to be aware of each other, and together agree on a decision: commit or abort — what is called <strong>consensus protocol</strong>. Consensus is not only applied for atomic commit, but also other situation such as: leader election, or any operation required agreement from multiple nodes. This gradually becomes one of the most important and fundamental issue to deal with in distributed computing era, when multiple machines cooperate to solve one big problem.</p><p>In this series, we will go through several consensus algorithms that are powering the fault-tolerant distributed systems nowadays, including the most common protocols:</p><ul><li>Two-Phase Commit (2PC): the most well-known classic commit protocol. 2PC and it’s variants are used by many traditional distributed databases, including Oracle, MySQL NDBCluster</li><li>Paxos: modern algorithm used by Ceph, Cassandra. Zookeeper uses Zookeeper Atomic Broadcast (ZAB) which is also inspired by Paxos</li><li>Raft: designed to be simpler to understand than Paxos, used by Etcd</li></ul><h3>Consensus Protocol requirements</h3><p><strong>Stability</strong>: Once the node is on <em>Committed</em> or <em>Aborted</em> state, it stays on that state forever</p><p><strong>Consistency</strong>: It’s impossible for one or more nodes on <em>Committed</em> state and other are <em>Aborted</em> state</p><h3>Two-phase commit (2PC)</h3><p>As stated in its name, 2PC divided a single commit request into 2 phases:</p><ul><li>Prepare</li><li>Commit</li></ul><p>The initiating node which receives the transaction from client will be the <strong>coordinator.</strong> There is one and only coordinator on 2PC mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RU2H39TnJvKK0nxAlufKA.png" /><figcaption>2 phases of 2PC</figcaption></figure><p><strong>Process phase (before 2PC)</strong></p><p>This phase happens normally just as normal transaction in single node database, but <em>without commit </em>(which will be organized in 2PC)</p><ul><li>Coordinator sends write request to all the nodes</li><li>A node records info in the redo log (transaction log) so that it can either commit or rollback the transaction</li><li>The node places a <em>distributed lock</em> on modified tables/rows, which prevents reads uncommited</li><li>It then writes data to the database, but not commit the changes</li></ul><p><strong>Prepare phase</strong></p><ul><li>If the node successfully writes, it sends back <strong>prepared message</strong> to the coordinator. The node promises to commit successful if requested to commit, in other word, it removes the right to abort the transaction by itself</li><li>The coordinator check and count the response, if any node doesnt send <em>prepared, </em>or <em>aborts </em>the request, coordinator sends <strong>abort</strong> to all the nodes, and the change will be rolled back. If all reply <em>prepared,</em> coordinator makes a definitive decision to commit the transaction</li><li>The prepare phase is the differentiated step from normal transaction which helps coordinator (the cluster) make definitive decision according to each nodes’ statuses</li></ul><p><strong>Commit phase</strong></p><ul><li>Coordinator send <strong>commit message</strong> to all the participating nodes so that the write is actually commited</li><li>Distributed lock removed</li><li>If any node fails to commit at this phase (disk failure, outage), the coordinator retries forever until it succeeds</li></ul><p><strong>Problem of 2PC</strong></p><p>Blocking: right after all the nodes vote “<em>prepared</em>”, coordinator fails. Because the nodes cannot abort the transaction without coordinator’s request after being<em> prepared</em>, they are blocked indefinitely until coordinator recovers — in order to find out the final decision.</p><p>Latency: as depicted in the diagram above, 2PC occurs after transaction is processes, and necessarily increases the overall latency. Moreover, until the node knows the final decision, it blocks other transactions from running. Additionally, if one or more participating nodes fails during 2PC, the transaction as well is aborted, making extra effort for coordinator to retry the transaction.</p><h3><strong>Summary</strong></h3><p>2PC is popular <em>blocking</em> mechanism for distributed computing, but it comes with high latency, low throughput (because of blocking), poor scalability (the larger the system, the longer it needs to wait, transaction aborted when any node fails), no availability (only 1 coordinator). There’re several algorithms developed from 2PC to overcome the limitations such as 3PC or non-blocking 2PC (NDBCluster), which removes the blocking problem with the cost of extra latency. It is, however, not widely used.</p><p>On the next part we’ll take a look on other modern algorithms which solve the limitation of 2PC and are being used on many distributed applications nowadays.</p><p><strong>References</strong></p><ul><li><a href="https://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_txns003.htm#ADMIN12222">https://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_txns003.htm#ADMIN12222</a></li><li><a href="http://dbmsmusings.blogspot.com/2019/01/its-time-to-move-on-from-two-phase.html">http://dbmsmusings.blogspot.com/2019/01/its-time-to-move-on-from-two-phase.html</a></li><li>Consensus on Transaction Commit — Jim Gray and Leslie Lamport, Microsoft Research</li><li>Chapter 9, Designing Data-Intensive Applications</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d461a151368b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/distributed-computing-consensus-protocol-part-1-d461a151368b">Distributed Computing: Consensus Protocol (Part 1)</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Zero-Copy Using sendfile()]]></title>
            <link>https://medium.com/swlh/linux-zero-copy-using-sendfile-75d2eb56b39b?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/75d2eb56b39b</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[zero-copy]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 10:26:57 GMT</pubDate>
            <atom:updated>2020-12-02T09:40:56.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Zero-copy?</h3><p>What’s happening under the hood when the OS is copying a file / transfering a file to another host? For our naked eyes the process can be simple, OS first reads content of the file, then writes it to another file, then it’s done! However, things become complicated when we look more closely and memory is taken into account.</p><p>As depicted in the dataflow below, the file read from disk must go through kernel system cache — which resides in the kernel space, then the data is copied to userspace’s memory area before being written back to a new file — which then in turn goes to kernel memory buffer before really flushed out to disk. The procedure takes quite many unnecessary operations of copying back and forth between kernel and userspace without actually doing anything, and the operations consume system resources and context switches as well. There’re room for improvement.</p><p>Zero-copy technique comes into play with the purpose of eliminating all the unnecessary copies. In the Linux world the system call for that kind of work is <strong><em>sendfile().</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BzxNcdOAGP1FmhOb2PSXQ.png" /><figcaption>Differences between data transfer using read()+write() / sendfile()</figcaption></figure><h3>What is Zero-copy</h3><p><em>sendfile()</em> claims to make data transfer happening under kernel space only — i.e data transferred from kernel system cache to NIC buffer (or traversed through kernel system cache if local copy), thus doesnt require context switches as in read+write combination. <em>sendfile() </em>has now been widely used as a supported data transfering technique especially under <strong><em>nginx </em></strong><em>and</em><strong><em> kafka.</em></strong></p><p>For ease of understanding we demonstrate a simple local file copy rather than file transfer over networking, and all the code’s error checking procedures are left out for clarity as well.</p><p><strong><em>readwrite.c</em></strong></p><pre>#include &lt;unistd.h&gt;<br>#include &lt;sys/types.h&gt;<br>#include &lt;sys/stat.h&gt;<br>#include &lt;fcntl.h&gt;</pre><pre>#define BUF_SIZE 4096*1000</pre><pre>int main(int argc, char **argv) {<br>    char buf[BUF_SIZE];<br>    const char *fromfile = argv[1];<br>    const char *tofile = argv[2];<br>    struct stat stat_buf;<br>    int fromfd = open(fromfile, O_RDONLY);<br>    fstat(fromfd, &amp;stat_buf);<br>    int tofd = open(tofile, O_WRONLY | O_CREAT, stat_buf.st_mode);</pre><pre>    int n;<br>    while ((n = read(fromfd, &amp;buf, sizeof(buf))) &gt; 0) {<br>        write(tofd, &amp;buf, n);<br>    }<br>}</pre><p><strong><em>buf[BUF_SIZE]</em></strong> is the <em>user-space buffer</em> that we’re talking about, as can be seen for every iteration, <em>read()</em> copies data from file (through system memory cache) to this buffer, and <em>write()</em> copies data from the buffer to another file (through system memory buffer)</p><p>In the process memory map, <em>buf[BUF_SIZE]</em> can be seen as a allocation of 4MB on stack area. Reducing the buffer size can help reduce the waste of memory, but it in turn increases number of read() and write() system calls, which is expensive as well.</p><pre>00007f53e08f6000       4       4       4 rw---   [ anon ]<br>00007fff5a6b1000    4012    4008    4008 rw---   [ stack ]<br>00007fff5ab3e000      12       0       0 r----   [ anon ]<br>00007fff5ab41000       8       4       0 r-x--   [ anon ]</pre><p>In the example, we demonstrate only one file transfer, for many transfers the memory waste might be significantly noticable using this naive technique.</p><p><strong><em>sendfile.c</em></strong></p><pre>#include &lt;sys/types.h&gt;<br>#include &lt;sys/stat.h&gt;<br>#include &lt;fcntl.h&gt;<br>#include &lt;sys/sendfile.h&gt;</pre><pre>#define BUF_SIZE 4096*1000</pre><pre>int main(int argc, char **argv) {<br>    const char *fromfile = argv[1];<br>    const char *tofile = argv[2];<br>    struct stat stat_buf;<br>    int fromfd = open(fromfile, O_RDONLY);<br>    fstat(fromfd, &amp;stat_buf);<br>    int tofd = open(tofile, O_WRONLY | O_CREAT, stat_buf.st_mode);</pre><pre>    int n = 1;<br>    while (n &gt; 0) {<br>        n = sendfile(tofd, fromfd, 0, BUF_SIZE);<br>    }<br>}</pre><p>There’s no user-space buffer for <em>sendfile().</em> For that reason, sendfile can send all the data from file at once, which eliminates the need of BUF_SIZE and a while loop, however we still keep it for comparing with read/write technique.</p><h3>Performance benchmark</h3><p>Copy of a ~1G file. BUF_SIZE = 4K.</p><p><strong>readwrite</strong></p><pre>syscall            calls    total       min       avg       max     <br>                               (msec)    (msec)    (msec)    (msec)<br>   --------------- -------- --------- --------- --------- --------- <br>   read              244797 16974.624     0.002     0.069   457.333<br>   write             245169  2182.295     0.004     0.009   268.689</pre><p>number of read / write is nearly the same, read() takes significanly more time because of major page faults.</p><p><strong>sendfile</strong></p><pre>syscall            calls    total       min       avg       max   <br>                               (msec)    (msec)    (msec)    (msec)   <br>   --------------- -------- --------- --------- --------- ---------<br>   sendfile          245261 13559.231     0.004     0.055   185.970 </pre><p>number of sendfile() calls is by half of the total of read()+write(), which also helps reduce total execution time. For context switches, there’s lack of observation tool so it’s difficult to show the differences.</p><p>In conclusion, <em>sendfile()</em> brings to the table several benefits, including reduction of context switches, memory usage, number of system calls, and eventually faster operations. It is, however, not the silver bullet for everything, we once encountered the <a href="https://trac.nginx.org/nginx/ticket/1870">problem of large file download on nginx,</a> therefore usage of <em>sendfile()</em> should be considered and tested carefully before production use.</p><h3>References</h3><ul><li>Chapter 61 — The Linux Programming Interface — Michael Kerrisk</li><li><a href="https://developer.ibm.com/articles/j-zerocopy/">https://developer.ibm.com/articles/j-zerocopy/</a></li><li><a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#sendfile">http://nginx.org/en/docs/http/ngx_http_core_module.html#sendfile</a></li><li><a href="https://kafka.apache.org/08/documentation.html">https://kafka.apache.org/08/documentation.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75d2eb56b39b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linux-zero-copy-using-sendfile-75d2eb56b39b">Linux Zero-Copy Using sendfile()</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding authorization to a running Kafka cluster]]></title>
            <link>https://medium.com/coccoc-engineering-blog/adding-authorization-to-a-running-kafka-cluster-e13e39c5b70e?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13e39c5b70e</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 04:16:21 GMT</pubDate>
            <atom:updated>2020-09-25T04:16:21.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*D0Xk8hmBB3zuyhGl1TDu3A.png" /></figure><p>We have several Kafka clusters of growing importance at CocCoc. As usage scales up, we would like to get a handle on the dataflow components. We decided to enforce producer/consumer ACLs on them to ensure data provenance, using Kafka built-in Authorizer which stores settings in Zookeeper.</p><h3>Starting points</h3><ul><li>Kafka cluster with PLAINTEXT (port 9092) and SASL_PLAINTEXT (let’s say port 9093) listeners for clients, and broker interconnect using PLAINTEXT</li><li>Kafka version ≥ 2 for very useful prefixed ACL support in <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-290%3A+Support+for+Prefixed+ACLs">KIP-290</a></li><li>Firewall on production clusters, restricting Kafka ports (both because <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-252+-+Extend+ACLs+to+allow+filtering+based+on+ip+ranges+and+subnets">subnet-based allow-hosts is not implemented yet</a>, and to reduce search-space for running services)</li><li>Kafka connects to Zookeeper with SASL, and sets <a href="https://docs.confluent.io/current/security/zk-security.html">strict ACL on its znodes</a></li></ul><p>We become wound up with producer/consumer access restriction on topics, and having minimal disruption to production services.</p><p>Reference guides:</p><ul><li>Confluent <a href="https://docs.confluent.io/current/security/index.html#security">security guides</a></li><li><a href="https://docs.confluent.io/current/kafka/post-deployment.html">Operations guide</a>, with tips such as <a href="https://docs.confluent.io/current/kafka/post-deployment.html#rolling-restart">restarting controller last</a></li><li>The WIP Kafka internal notebook <a href="https://jaceklaskowski.gitbooks.io/apache-kafka/">https://jaceklaskowski.gitbooks.io/apache-kafka/</a> also has some commentary on the implementation (as of Kafka 2.4)</li></ul><p>Overall, we follow these steps:</p><ol><li>Get devs into the know</li><li>Dig into tickets/environments/configs/code for topic usage</li><li>Let’s not break production, it’s running and making money for everyone</li><li>Add config with a safety fallback and gradually remove it as experience allow</li></ol><p>These efforts will take time and could be dead-end, so they can proceed slowly in parallel with preparing the cluster. On the configuration side, we have these rough steps:</p><ol><li>Make brokers connect to each other as an all-powerful account</li><li>Prepare special accounts for monitoring services</li><li>Set up ACL entries in ZK, with fallback allowance</li><li>Apply authorizer on 1 broker to collect usage</li><li>Update ACL entries, gradually remove fallbacks</li></ol><h3>Setting up Accounts</h3><p><strong>SuperUser</strong></p><p>To start, we define a kafka_cluster SASL user. Then we do a rolling update of broker’s config:</p><ul><li>in <a href="https://kafka.apache.org/25/documentation.html#security_sasl">JAAS KafkaServer section</a>, add username=&quot;kafka_cluster&quot;<br>password=&quot;super-duper-password&quot;</li><li>in server.properies, add security.inter.broker.protocol=SASL_PLAINTEXT, and<br>super.users=User:kafka_cluster</li></ul><p>On restart, each broker will connect to the others over<br>SASL_PLAINTEXT, as we can verify that with ss -tnpr dport eq :9093 , as well as broker/controller log.</p><p><strong>Monitoring account</strong></p><p>For monitoring, we create an account to use with <a href="https://github.com/cloudworkz/kafka-minion#features">Kafka Minion,</a> having some special access beyond other service accounts:</p><ul><li>operation Describe --cluster</li><li>operation DescribeConfigs --topic:&#39;*&#39;</li><li>operation Read --topic:__consumer_offsets</li></ul><h3>Monitoring Denials</h3><p>To detect trouble, we setup alert for is Denied in /var/log/kafka/kafka-authorizer.log. This should not fire for valid access on clusters in production.</p><pre>INFO Principal = User:reporter is Denied Operation = Write from host = 192.168.90.189 on resource = Topic:LITERAL:services-report (kafka.authorizer.logger)</pre><p>To collect actual usage, we need to enable log Authorizer at DEBUG level.</p><pre># Access denials are logged at INFO level, change to DEBUG to also log allowed accesses<br>log4j.logger.kafka.authorizer.logger=DEBUG, authorizerAppender</pre><p>The log is very verbose, with 2 lines for each allowed operation:</p><pre>DEBUG principal = User:kafka_cluster is a super user, allowing operation without checking acls. (kafka.authorizer.logger)<br>DEBUG Principal = User:kafka_cluster is Allowed Operation = ClusterAction from host = 10.3.4.120 on resource = Cluster:LITERAL:kafka-cluster (kafka.authorizer.logger)</pre><p>During transition period, we leave User:* with Read/Write on each prefix/topic. Not using allow.everyone.if.no.acl.found=true because the presence of any ACL on a topic negates that setting, denying unlisted accesses (thus “if no acl found”), so we can’t transition each topic/prefix to tight ACLs individually. We can also protect cluster resources effectively, or new resource types in newer Kafka versions.</p><h3>Enforcing ACLs</h3><p>We will be using ACLs in 2 types:</p><ul><li>Topic Prefixes</li><li>Topic Literals</li></ul><p>The ACLs eval flow is laid out in <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-11+-+Authorization+Interface">KIP-11</a>, and we can also look at <a href="https://github.com/apache/kafka/blob/2.1/core/src/main/scala/kafka/security/auth/SimpleAclAuthorizer.scala#L151-L162">SimpleAclAuthorizer</a> itself. We started out with broad ACLs:</p><ul><li>Try to use<em> topic-prefixed ACL</em>, if naming convention is already in place. This helps cut down on ZK data size/load and automatically applies to future topics. For other specific needs, <em>topic-literal ACL</em> will be added after prefixed ACL is already applied</li><li>Allow all accounts + <em>ANONYMOUS</em> to <em>Describe</em> topics: can cause no harm, and to <em>Describe/Read</em> consumer-groups: status quo, and we don’t have to coordinate with client/devs about group naming</li><li>Convenient flags --producer/--consumer also add/remove <em>Describe/Create</em> operations, which can make reviewing harder, and risk revoking <em>Describe</em> when revoking <em>Read/Write</em></li><li>We are not using Exactly-once semantics yet, so you may need to read more on <a href="https://kafka.apache.org/21/documentation.html#upgrade_11_exactly_once_semantics">IdempotentWrite ACLs</a></li><li>We do it on one broker only, and gather Denial statistics for it, to make sure the ACL doesnt disrupt the production usage</li></ul><h3>Monitoring Post-enforcement</h3><p>Beyond Denied alerting, we can dissect &amp; analyze DEBUG level lines to confirm that ACLs cover all legitimate usage. For authorization, resources are checked as their <a href="https://github.com/apache/kafka/blob/2.1/core/src/main/scala/kafka/security/auth/SimpleAclAuthorizer.scala#L112-L114">LITERAL form</a>, not PREFIXED as defined in ZK. Extract pair of lines with User:* and see if any ACL need to be added besides existing rules.</p><p>Example ACL and log:</p><pre>Current ACLs for resource `Topic:LITERAL:bench32`:<br>User:serviceP has Allow permission for operations: Write from hosts: *<br>User:serviceT has Allow permission for operations: Read from hosts: *<br>User:ANONYMOUS has Allow permission for operations: Read from hosts: 10.3.4.47</pre><pre>Current ACLs for resource `Topic:PREFIXED:bench3`:<br> User:serviceY has Allow permission for operations: Read from hosts: *<br> User:serviceY has Allow permission for operations: Write from hosts: *</pre><p>When account serviceY writes to topic bench32 , the log is:</p><pre>DEBUG operation = Write on resource = Topic:LITERAL:bench32 from host = 10.0.2.194 is Allow based on acl = User:serviceY has Allow permission for operations: Write from hosts: * (kafka.authorizer.logger)<br>DEBUG Principal = User:serviceY is Allowed Operation = Write from host = 10.0.2.194 on resource = Topic:LITERAL:bench32 (kafka.authorizer.logger)</pre><p>Another example based on wildcard account:</p><pre>Current ACLs for resource `Topic:LITERAL:bench11`:<br> User:* has Allow permission for operations: Read from hosts: *<br> User:* has Allow permission for operations: Write from hosts: *<br> User:serviceM has Allow permission for operations: Write from hosts: *</pre><p>In this case, log <em>may</em> look like this, despite serviceM having a concrete ACL:</p><pre>DEBUG operation = Write on resource = Topic:LITERAL:bench11 from host = 10.0.2.194 is Allow based on acl = User:* has Allow permission for operations: Write from hosts: * (kafka.authorizer.logger)<br>DEBUG Principal = User:serviceM is Allowed Operation = Write from host = 10.0.2.194 on resource = Topic:LITERAL:bench11 (kafka.authorizer.logger)</pre><p>On high-traffic clusters, this pair of log lines will be interleaved with other lines, and we have no solution for untangling those.</p><p>If your cluster is using SSL, the principal will be client certificate’s Distinguished Name (eg User:CN=service X,OU=Dept A,DC=example,DC=org ), but you can use <a href="https://docs.confluent.io/current/kafka/authorization.html#tls-ssl-principal-user-names">custom mapping rules</a> to make account name easier to read. With SASL_SSL, the SASL username will be used instead, you don’t have to worry about certificate DN.</p><p>Some other type of logs we found safe to ignore:</p><ul><li>Super-user operations:DEBUG Principal = User:kafka_cluster is Allowed<br>,DEBUG principal = User:kafka_cluster is a super user, allowing operation without checking acls. (kafka.authorizer.logger)</li><li>Always allowed operations/resources we set above: operation Describe, resource Group:LITERAL:)</li></ul><h3>Finalizing the ACLs</h3><p>As stated above, we only enforce ACL for only one broker in the initial phase, now it’s the time for the finale.</p><ul><li>After setting proper monitoring for Denials, we gradually remove <em>User:*</em> and <em>ANONYMOUS</em> until there’s none of them. The process is long and tiresome, because we need to collect the thorough list of producers/consumers and cooperate with developers for making changes in Kafka users.</li><li>When everything is fine, gradually apply ACLs to all of the brokers. And <em>restart the controller last.</em></li></ul><h3>Future enhancements</h3><p>Besides setting up the clusters, we can take this opportunity to:</p><ul><li>Replace password-exposed service accounts with new ones saved on <a href="https://medium.com/coccoc-engineering-blog/secret-management-architecture-9d3a575d7fb?source=---------5------------------">central secret management</a></li><li>Map out data flows, and shut down abandoned topics or dead-end producers</li><li>Be alert to ACL trouble on DEV clusters before going to PROD</li><li>Prepare Kafka accounts for moving services/tools out of ANONYMOUS access, eg <a href="https://github.com/elastic/beats/issues/8387">filebeat will support SCRAM SASL</a> in a future version</li><li>Shutdown PLAINTEXT port (without SASL)</li></ul><p>We hope our experience bring you some ideas for safeguarding your data. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13e39c5b70e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/adding-authorization-to-a-running-kafka-cluster-e13e39c5b70e">Adding authorization to a running Kafka cluster</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KVM guest’s CPU flags]]></title>
            <link>https://medium.com/coccoc-engineering-blog/kvm-guests-cpu-flags-5d3ac9525421?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d3ac9525421</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kvm]]></category>
            <category><![CDATA[sysadmin]]></category>
            <category><![CDATA[virtualization]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 11:29:23 GMT</pubDate>
            <atom:updated>2020-07-14T07:02:36.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>The way of KVM: guest’s CPU flags</h3><p>Coccoc uses <strong><em>KVM </em></strong><em>(Kernel-based Virtual Machine)</em> virtualization infrastructure as a private cloud solution, and improving its performance and stability is always a challenging yet exciting task. In this blogpost, we will go through a brief description of cpu flags, and see how a little tweak on CPU flags can improve quite significant performance on a virtual machines for particular situations.</p><h3><strong>CPU flags</strong></h3><p>CPU flags (aka CPU features) simply are attributes of CPU, denoted which features it supports. The features can be simple as calculating floating point unit, hyperthreading technology, or ability to extend physical memory to 64-bit address…</p><p><strong>Notable CPU flags (Intel CPU)</strong></p><p>The full list of features can be seen at reference, but most of them are cryptic and may not give any benefit to general users. Below are some important features which are being used everyday that we should know about:</p><ul><li><strong>ht</strong>: <em>Hyper-Threading — </em>improves parallelism of computations</li><li><strong>lm</strong>: <em>Long mode</em> — supports 64-bit architecture</li><li><strong>vmx</strong>: <em>Virtual Machine Extention</em> — which must be enable for software virtualization services (KVM, VMWare, VirtualBox…) to work</li><li><strong>fpu</strong>: <em>Floating Point Unit</em> — supports floating point operations</li><li><strong>aes-ni</strong> (or simply <strong>aes</strong>):<em> Advanced Encryption Standard new instructions — </em>improves the speed of encryption / decryption operations using AES</li><li><strong>pae: </strong><em>Physical Address Extension — </em>ability to use more than 4G memory for 32bit CPU</li><li><strong>avx: </strong><em>Advanced Vector Extensions</em> — allows a (quite drastic) speed up in certain floating point operations.</li><li><strong>rdrand: </strong><em>Read Random Number </em>— an instruction for returning random numbers from an Intel on-chip hardware random number generator.</li><li><strong>pse: </strong><em>Page Size Extension — </em>allows for pages larger than the traditional 4 KB size (Hugepage)</li><li><strong>hypervisor:</strong> the box is a virtual machine running on a hypervisor</li><li><strong>pcid, spec-ctrl, ssbd: </strong>improvements or fixes for <em>Meltdown (CVE-2017–5754)</em>, <em>Spectre (CVE-2017–5753 and CVE-2017–5715)</em>, <em>CVE-2018–3639</em></li></ul><p>Full list of CPU features: <a href="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/arch/x86/include/asm/cpufeatures.h">https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/arch/x86/include/asm/cpufeatures.h</a></p><p>Usually, for newer CPU generations and Linux distributions, all the features will be enabled by default. If not somehow, they need to be manually enabled on BIOS if the CPU supports.</p><h4><strong>How to check CPU flags</strong></h4><pre># grep ‘flags’ -m1 /proc/cpuinfo<br>flags  : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36...</pre><p>The problem is, not all flags from host machine passed down to guest machine. Let’s make a simple check:</p><pre><strong>host#</strong> <em>grep ‘flags’ -m1 /proc/cpuinfo<br></em>flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 popcnt lahf_lm epb pti tpr_shadow vnmi flexpriority ept vpid dtherm ida arat<br></pre><pre><strong>vm#</strong> <em>grep -m1 ‘flags’ /proc/cpuinfo</em><br>flags : fpu de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx lm constant_tsc rep_good nopl pni ssse3 cx16 sse4_1 sse4_2 x2apic popcnt hypervisor lahf_lm</pre><p><strong>vm</strong> is a machine running on <strong>host</strong>. Differences can be seen as the vm possesses much less flags than its parent. The question is, if the cpu flags are beneficial, why arent they enabled for virtual machines?</p><p>The answer is simple: <em>compatibility</em>. By default, KVM sets the cpu mode to <em>custom </em>with <em>generic</em> model— to ensure that a persistent guest sees the same hardware no matter what host the guest is booted on. For that, many flags would be removed because that model doesnt support them. Sometimes, however, the flags are truly necessary, for example our VMs will be acting as nginx reverse proxy especially for terminating TLS requests, therefore <em>AES intruction set</em> may sound helpful because it improves en/decryption speed thus reducing CPU ultilization. How can we enable them back on the virtual machines?</p><p>We need to go a bit deeper on how KVM virtualizes the CPU models on guest machines.</p><h3>KVM CPU models</h3><p>KVM supports <a href="https://manpages.ubuntu.com/manpages/disco/man7/qemu-cpu-models.7.html">3 cpu modes types</a>:</p><pre><strong>Host</strong> <strong>passthrough</strong><br>  This passes the host CPU model features, model, stepping, exactly to the guest. Note that KVM may filter out some host CPU model features if they cannot be supported with virtualization. Live migration is unsafe when this mode is used as libvirt / QEMU cannot guarantee a stable CPU is exposed to the guest across hosts. This is the recommended CPU to use, provided live migration is not required.</pre><pre><strong>Custom (Named</strong> <strong>model)<br>  </strong>QEMU comes with a number of predefined named CPU models, that typically refer to specific generations of hardware released by Intel and AMD. These allow the guest VMs to have a degree of isolation from the host CPU, allowing greater flexibility in live migrating between hosts with differing hardware.</pre><pre><strong>Host model<br>  </strong>This uses the QEMU &quot;Named model&quot; feature, automatically picking a CPU model that is similar the host CPU, and then adding extra features to approximate the host model as closely as possible. This does not guarantee the CPU family, stepping, etc will precisely match the host CPU, as they would with &quot;Host passthrough&quot;, but gives much of the benefit of passthrough, while making live migration safe.</pre><p>By default KVM uses <em>custom </em>mode and set the CPU model to <em>generic — </em>which misses important flags: <em>aes</em>, <em>pcid</em> and <em>rdrand</em>. If live migration is a concern, use <em>Host model</em>, otherwise, <em>Host passthrough</em> should be used to maximize the features the host’s CPU supports.</p><p>To check host supported cpu models:</p><pre>virsh cpu-models x86_64</pre><p><strong>How to check VM’s cpu model</strong></p><p>Command:</p><pre># grep -m1 ‘^model name’ /proc/cpuinfo </pre><pre><em><br># VM with default custom mode</em><br>model name : QEMU Virtual CPU version 2.5+</pre><pre><em># VM with host passthrough mode</em><br>model name : Intel(R) Xeon(R) CPU E5-2620 0 @ 2.00GHz</pre><pre><em># VM with host model mode</em><br>model name : Intel Core Processor (Broadwell)</pre><p>You can see on VM with default <em>custom</em> mode: model name is set to <em>generic</em>: <em>QEMU Virtual CPU version 2.5+</em>, as stated above. For VM with <em>host passthrough</em> mode, cpu model is exactly as host (<em>Intel(R) Xeon(R) CPU E5–2620 0 @ 2.00GHz</em>). Finally, VM with <em>host model</em> mode has model name <em>Intel Core Processor Broadwell</em><strong><em>, </em></strong>which is the Intel E5v4 CPU model family.</p><p>If you use <em>libvirt</em> version 3.x.x, you could check libvirt ‘s supported models and features at <em>/usr/share/libvirt/cpu_map.xm</em>l.</p><h4><strong>Customize VM’s CPU features:</strong></h4><p>VM’s CPU features can be customized. For example, to disable flag <em>vmx</em> on mode<em> host-model</em>:</p><pre>&lt;cpu mode=’host-model’&gt;<br>&lt;feature name=”vmx” policy=”disable”/&gt;<br>…<br>&lt;/cpu&gt;</pre><p>To force flag<em> pcid</em> on <em>Westmere</em> cpu model, mode <em>custom</em></p><pre>&lt;cpu mode=’custom’&gt;<br>&lt;model name=”Westmere”/&gt;<br>&lt;feature name=”pcid” policy=”force”/&gt;<br>…<br>&lt;/cpu&gt;</pre><h3><strong>Benchmark</strong></h3><p>Back to the ealier question on how we utilizes AES flag to improve CPU performance of a guest machine, there comes a simple benchmark comparing AES and non-AES supported VMs (which is unset by default on most of our VMs).</p><p>Specifications for the benchmark:</p><ul><li>2 VMs with the same specs, Linux version on the same host machine</li><li>One with <strong><em>aes</em></strong> flag support, one not</li><li>Test conducted with <em>openssl</em> command</li></ul><p><strong>OpenSSL speed</strong></p><p>Openssl does encryption on data with blocksizes of 16 to 16384 bytes. The result is number of blocks being encrypted in 3s — the higher, the better.</p><ul><li>Command syntax:</li></ul><pre>openssl speed -evp ALGORITHM</pre><ul><li>Algorithms:<em> aes-128-cbc, aes-128-ecb, aes-256-cbc, aes-256-ecb</em></li><li>Test results:</li></ul><p>Without AES:</p><pre>type         16B      64B     256B    1024B  8192B 16384B<br>aes-128-cbc: 19152619 5827224 1468417 393755 48273 23641<br>aes-128-ecb: 21475462 6253476 1600296 403782 50619 25348<br>aes-256-cbc: 15636784 4544210 1160296 293959 36771 17964<br>aes-256-ecb: 17229248 4722559 1183129 295750 37942 18916</pre><p>With AES:</p><pre>type         16B      64B      256B     1024B   8192B  16384B<br>aes-128-cbc: 64249971 19536390 5166846  1306203 164213 82282<br>aes-128-ecb: 69093254 52865397 24689283 7128295 931459 468685<br>aes-256-cbc: 49234258 14323288 3721274  942664  117652 58871<br>aes-256-ecb: 54851495 43010007 19586093 5452521 725470 363480</pre><p>The results are obvious, AES enabled helps improve openssl speed by at least <strong>3x</strong>, which is quite a suprising number.</p><p>In practice, <em>aes</em> helps <em>nginx+tls</em>’s CPU ultilization reduce at around <strong>10–20%</strong> on production, where high number of en/decryptions take place.</p><h3>Conclusion</h3><p>KVM is a widely used virtualization infrastructure in the world (Google Cloud and AWS also use it under the hood). Deep understanding about KVM and its virtualization technology may open paths for better tunings. Besides, we now know how one simple flag can help a lots on CPU performance, which can be applied on bare-metal environment as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d3ac9525421" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/kvm-guests-cpu-flags-5d3ac9525421">KVM guest’s CPU flags</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load-balancing for K8s services in Coccoc Infrastructure]]></title>
            <link>https://medium.com/coccoc-engineering-blog/load-balancing-for-k8s-services-in-coccoc-infrastructure-eda3cd93cbf5?source=rss-b5c0e13a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda3cd93cbf5</guid>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 09:31:24 GMT</pubDate>
            <atom:updated>2020-06-24T09:28:05.904Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preface</h3><p>For a very long time, the infrastructure at Coccoc only supports traditional services running on physical hosts. Recently on the rise of microservices, the trendy container orchestration technology K8s has been adapted as a big part of the grand design. Therefore, the infrastructure also needs a huge shift to not only support conventional but containerized microservices as well. In this article we’re gonna go through how load-balancing is being implemented to publish K8s services from a very old-fashioned setup.</p><h3>Load-balancing infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Asp7q6BYUgyFtdWw422imw.png" /><figcaption>simple traditional LB infrastructure</figcaption></figure><p>As depicted above, the primitive infrastructure for load-balancing architecture is straightforward:</p><ul><li>4 LBs are Internet-facing servers which utilizes master-backup <em>VRRP (Virtual Router Redundancy Protocol)</em> providing high availability and load-balancing solution for the backend services. This case the 2nd server is master and taking the <em>VIP </em>(<em>floating virtual IP</em>), distributing load to 3 underlying backends</li><li>LB framework is implemented using <em>keepalived, </em>employing native Linux kernel module <em>IPVS (Linux Virtual Server)</em></li><li>Balancing algorithm is <em>WRR (weighted round robin)</em>, basically the 3 backends are taking the same weight</li></ul><p>This setup works nicely with traditional services which run on physical hosts for a long time. However, recently we’ve been adapting Kubernetes to the infrastructure, and this LB setup has a remarkable limitation:</p><ul><li>If using Pods’ IPs, they’re ephemeral, while IPVS configuration needs fixed IPs</li><li>Service’s IP can be static, but there’re bigger issue:<br>For using IPVS, the backend server also needs the VIP configured on its interfaces so it doesnt drop the packets forwarded to. While K8s’s IP is just a virtual one which lives inside <em>calico</em>’s network infrastructure (<em>iptables</em>), it’s not really an actual IP for real interface and so that it couldnt receive the packets forwarded from keepalived</li></ul><p>In short, Real Server’s (RS) addresses couldn’t be k8s’s ips. There needs to be real physical backends.</p><p>So the problem becomes how backends connect to K8s services, or pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ekb-8LfTF9KxYo2F4gSuaA.png" /><figcaption>How to publish K8s services?</figcaption></figure><h3>Traditional approach</h3><p>The simplest publishing method is to make Nginx reverse proxy on each backends, <em>proxy_pass</em>’ing to k8s’s services using DNS-based service discovery (provided by <em>CoreDNS</em>). For example:</p><pre>location / {<br>    proxy_pass &quot;<a href="http://telcos-api.browser-prod.svc.cluster.local/">http://music.browser-prod.svc.cluster.local/</a>&quot;;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnqhOD4TwRWvYMdkbgRf6A.png" /><figcaption>Nginx proxy_pass to K8s service</figcaption></figure><p>For this approach:</p><ul><li>Real servers’ ips are still backends’ ips, which is acceptable for <em>keepalived</em></li><li>Load-balancing and high availability are now K8s service’s responsibility, controlled by DNS Round Robin (headless service) or iptables’s TCP load-balancing. Nginx proxy knows nothing about the underlying pods so it couldn’t handle load-balancing by itself</li></ul><p>Besides, some tunings are necessary to make it really works:</p><p><strong>DNS caching issue</strong></p><p>Whenever services are redeployed, the IPs change (unless the services’ IPs are static). By default nginx caches domains for 60s, so it can only detect IP change after around 60s, which make service unavailable for the same amount of time! This is HUGE.</p><p>Solution: make the DNS cache TTL shorter:</p><pre>resolver 127.0.0.1 valid=1s;</pre><p><strong>Remote Addr preservation issue</strong></p><p>Client IPs go through L7 reverse proxy will not be preserved and changed to proxy’s IP. In several case we still need this information for rate limiting, ACL, monitoring…</p><p>Solution: use <a href="http://nginx.org/en/docs/http/ngx_http_realip_module.html">nginx’s <em>real ip</em> module,</a> making use of <em>X-Forwarded-For</em> header:</p><pre>set_real_ip_from  172.16.16.0/24;<br>real_ip_header    X-Forwarded-For;<br>real_ip_recursive on;</pre><p>With the solutions to the corresponding issues, this is the simplest approach that <strong>works</strong> to make a K8s service published to the outside. Practically it works fine for most of the time, despite of some outstanding problems:</p><ul><li>Load-balancing and high-availability is totally controlled by DNS RR or iptables<br>Due to the fact that the upstream for <em>proxy_pass</em> contains only 1 domain, there’ll be no retry from nginx if it marks the upstream as failure. Nginx only acts as a gateway for k8s services, not providing any high-availability or load-balancing mechanism</li><li>Misconfiguration of deployment’s <em>readinessProbe</em> makes requests sent to failed pods (and without retry as stated above), because service DNS doesnt remove it from IP pool</li><li>New dummy nginx configuration (only for proxy_pass) needs to be created on backend servers for every new k8s service</li></ul><h3>Nginx Ingress approach</h3><p>This is a native <a href="https://kubernetes.github.io/ingress-nginx/">K8s service discovery</a>, which means the ingress controller can communicates directly with the pods, not through the service, hence load-balancing doesnt need to rely on K8s service anymore. Let’s see if it can fit in the on-premise infrastructure.</p><p>Firts, let’s get a brief description of what <em>Ingress controller</em> and <em>Ingress </em>(<em>resource</em>) are. We’re talking specifically about<em> Nginx Ingress controller.</em></p><p><strong>Ingress Controller</strong></p><ul><li>An nginx instance that utilizes Ingress resources as configuration</li><li>Native K8s service discovery without relying on DNS-based service discovery</li><li>Content-based routing support</li><li>TLS termination support</li></ul><p><strong>Ingress Resource</strong></p><ul><li>Configuration for Ingress controller</li></ul><p><strong>The Implementation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0zOb5ky3YfypfJ-nrfLDg.png" /><figcaption>Nginx Ingress approach</figcaption></figure><ul><li>Under LBs, there are 2 physical servers acting as Nginx Ingress controller backends. Actually for each K8s namespace there’ll be different pair of ingress controller servers for better separation, but for the sake of simplicity we don’t go in to details here</li><li>Nginx ingress controller is a pod running on physical host with <em>hostNetwork</em> port 80 and 443</li></ul><p>What we have with this approach:</p><ul><li>For every exposing service, there’s only a need of one simple Ingress resource</li><li>Much importantly, nginx ingress controller supports retries when requests fail regardless of <em>readinessProbe,</em> and handle load-balancing by itself without dependancy on other service discovery. The ingress controller becomes real load-balancer, not just a simple proxy_pass machine as in previous implementation</li></ul><p>For this setup, nginx controller as a native K8s load-balancer actually solves all the problems that we faced in the traditional approach. The load-balancing infrastructure now becomes the mix of conventional services and cloud native applications.</p><h3>Closing thoughts</h3><p>Adapting K8s is not an easy task, and everything from infrastructure side also needs to change accordingly. Load-balancing just plays a part in the big picture, besides monitoring, logging, storage…</p><p>There’re also several other solutions for K8s load-balancing such as <em>envoy, contour, ambassador, haproxy, traefik…</em> We chose nginx just because it is simple, familiar enough, and supported natively by K8s.</p><p>Nginx ingress controller is the bridge for publishing K8s services to the outside and it blends nicely in the heavily bare-metal focused infrastructure. However, nginx does support LB on Layer 7 only, which offers possibility for adapting other K8s’s Layer 4 load-balancer candidates in the future plan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda3cd93cbf5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/load-balancing-for-k8s-services-in-coccoc-infrastructure-eda3cd93cbf5">Load-balancing for K8s services in Coccoc Infrastructure</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>