<?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 Deepshi Garg on Medium]]></title>
        <description><![CDATA[Stories by Deepshi Garg on Medium]]></description>
        <link>https://medium.com/@deepshig?source=rss-f324b341a551------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E4_K1h8vtpCjQRDuaztffg.png</url>
            <title>Stories by Deepshi Garg on Medium</title>
            <link>https://medium.com/@deepshig?source=rss-f324b341a551------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:30:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepshig/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[Golang app to control other pods in Kube cluster!]]></title>
            <link>https://blog.branchkey.com/golang-app-to-control-other-pods-in-kube-cluster-ee6dfd533361?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6dfd533361</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 09:33:12 GMT</pubDate>
            <atom:updated>2023-04-17T09:33:12.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang solution to tweak the configurations of other microservices/pods in the Kubernetes cluster</h4><p>We, at BranchKey, are proud owners of a self managed Kubernetes infrastructure deployed on bare metal machines, using only open source tools. Yes, you guessed it right… it definitely does not come easy 😂</p><p>A lot of times, it takes us long to solve problems which have one click solutions in AWS or GCP. But it also gives us the freedom to understand the problems in depth, explore available open source solutions and implement them from scratch. Thus, we have an extensive knowledge and a thorough control of our system. It reduces the time and effort for infrastructure maintenance like debugging, scaling, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A8ErEVcsLGsJsDN5" /><figcaption><a href="https://media.licdn.com/dms/image/C4D12AQE592YSdeRLBQ/article-cover_image-shrink_600_2000/0/1585874059123?e=2147483647&amp;v=beta&amp;t=bacsGv9uoDwG9fu9oZWItJcy84Al_oDjvqJg1oDzzmk">Image Source</a></figcaption></figure><p>One such problem is that of being able to tweak the configurable values of applications without having to go through the entire VCS deployment pipeline. Every application has certain values which need to be tweaked based on environment, load requirement, etc. For example, the database hosts and ports, the REST client configuration like the timeouts, and request volume, and others.</p><blockquote>Solved in brute force, we hard coded these values in the code, packed them in the docker image, and deployed the corresponding application with updated image. Every change of configuration needed all these steps to be done using the VCS, thus costing us about 10–15 minutes depending on the deployment pipeline.</blockquote><p>In normal scenarios, it is bearable. However in times of production issues, or experimental runs, it becomes super annoying to wait 15 minutes for every small configuration change 😱 Even a typo in hostname could cost us another 15 minutes 😖</p><h4>A quicker solution was needed 🤷‍♀</h4><p>We needed a key-value store which could keep track of all the current configurations of all applications, and expose APIs to update them. It also needed to redeploy the application with updated values, or update them in the corresponding Kube container at run-time.</p><p>We explored off the shelf solutions like <a href="https://etcd.io/docs/v3.3/learning/why/#comparison-chart">etcd and others</a>, however they didn&#39;t particularly fit the flow of the containers being automatically notified once a configuration is updated.</p><p>And so, the following Golang application was designed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEJRoLwW-oDPBSYetwRAiA.png" /><figcaption>Application Configuration Manager: A Golang Application</figcaption></figure><ul><li>It takes in env files and converts them into Kubernetes <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">ConfigMaps</a>.</li><li>It also stores the files in a persistent storage for the purposes of failure recovery, idempotency, and data consistency.</li><li>Whenever an existing config is updated (or more key-value pairs are added), it restarts the corresponding deployment.</li></ul><p>Once a new configMap is created, we <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#configure-all-key-value-pairs-in-a-configmap-as-container-environment-variables">update the corresponding deployment yaml</a> to make sure it fetches environment variables:</p><pre>apiVersion: apps/v1 <br>kind: Deployment<br>metadata:<br>  name: test-deploy<br>spec:<br>  containers:<br>    - name: test-container<br>      image: test-image<br>      command: [ &quot;/bin/sh&quot;, &quot;start&quot;, &quot;command&quot; ]<br>      envFrom:<br>      - configMapRef:<br>          name: pre-defined-config-map<br>  restartPolicy: Always</pre><p>Important thing to note here is that a mere change in config map is not enough to restart a Kubernetes deployment. Instead, we patch the deployment with a current timestamp annotation, which ultimately restarts it with a rollout strategy.</p><pre>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;time&quot;<br><br> metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br> &quot;k8s.io/apimachinery/pkg/types&quot;<br> &quot;k8s.io/client-go/kubernetes&quot;<br> &quot;k8s.io/client-go/rest&quot;<br>)<br><br>func Deploy(ctx context.Context, deploymentName string) {<br>  config, _ := rest.InClusterConfig()<br>  client, _ := kubernetes.NewForConfig(config)<br><br>  data := fmt.Sprintf(`{<br>    &quot;spec&quot;:{<br>      &quot;template&quot;:{<br>        &quot;metadata&quot;:{<br>          &quot;annotations&quot;:{<br>            &quot;kubectl.kubernetes.io/restartedAt&quot;:&quot;2023-04-05T13:02:47Z&quot;<br>  }}}}}`, time.Now().String())<br>  <br>  client.AppsV1().Deployments(namespace).Patch(<br>  ctx, deploymentName, types.StrategicMergePatchType,<br>  []byte(data), metav1.PatchOptions{FieldManager: &quot;kubectl-rollout&quot;})<br>}</pre><p>Even though this is very custom made solution, which still has a lot of limitations, like it does not track if the deployment was successful, it solved for our current use case.</p><blockquote>It brought down the configuration tweaking time from 15 minutes to only a few milliseconds 🔥 🎊 🎉</blockquote><p>The development of this <em>config manager</em> not only solved our problem, but also gave us an opportunity to gain insights about how config maps are managed in Kubernetes, and why just another key value store isn’t a complete answer to our problem.</p><p>We, at BranchKey, love to explore things to their core, and try to devise the simplest solutions possible. Of course efficiency and maintainability is a driving factor 💯</p><p>Keep tabs on this space to know more of our interesting explorations 👾</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6dfd533361" width="1" height="1" alt=""><hr><p><a href="https://blog.branchkey.com/golang-app-to-control-other-pods-in-kube-cluster-ee6dfd533361">Golang app to control other pods in Kube cluster!</a> was originally published in <a href="https://blog.branchkey.com/">BranchKey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn from our mistakes in Golang]]></title>
            <link>https://blog.branchkey.com/learn-from-our-mistakes-in-golang-1954f38260a1?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/1954f38260a1</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 07:51:05 GMT</pubDate>
            <atom:updated>2022-09-09T07:51:05.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two of the bugs we encountered in our Golang code, which were most easily resolvable, but took us a long time to debug</h4><p>Programmers may agree that writing application code is a venturesome task in itself, for you can’t predict which line could result in the most bizarre bug ever. Of course, we perform basic testing to eliminate the obvious errors 🤷‍♀ But here I am talking about the most peculiarly perplexing ones. We have all been there, where we keep staring at the same code again and again, praying to every God in the world, for that buggy piece of code to reveal itself 🙏 🤯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*PVWE__aUrcWhPCyv" /><figcaption><a href="https://media.giphy.com/media/bVJmilgAPW43cdpniz/giphy.gif">Source</a></figcaption></figure><p>Here, in this blog, we aim to summarise our journeys through 2 such bugs in our Golang application code. We hope to make your lives easier in case you encounter the same situation ✨</p><h3><strong>Bug # 1: Unexpected URL Encoding</strong></h3><p><strong><em>Context: </em></strong>We, at BranchKey, are proud users of self-implemented bare-metal infrastructure. Hence, as a solution for object-storage, we are are exploring <a href="https://min.io/">MinIO</a>. A use case demands public access to private data, using <a href="https://docs.min.io/docs/upload-files-from-browser-using-pre-signed-urls.html">pre-signed URLs</a>, similar to what <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html">AWS S3 provides</a>. We hoped to use the <a href="https://pkg.go.dev/github.com/minio/minio-go/v7">minio golang client</a> for the same.</p><p><strong><em>Problem: </em></strong>When using <a href="https://docs.min.io/docs/golang-client-api-reference.html#PresignedGetObject">this</a> code example from official client documentation, we got the status code <em>403 Forbidden</em> with the following error:</p><pre>&lt;Error&gt;<br>    &lt;Code&gt;AccessDenied&lt;/Code&gt;<br>    &lt;Message&gt;Access Denied.&lt;/Message&gt;<br>    &lt;Key&gt;test-file.txt&lt;/Key&gt;<br>    &lt;BucketName&gt;input-files-bucket&lt;/BucketName&gt;<br>    &lt;Resource&gt;/input-files-bucket/test-file.txt&lt;/Resource<br>    &lt;RequestId&gt;1712DE228B2B5EAB&lt;/RequestId&gt;<br>    &lt;HostId&gt;aa545e0e-5a90-42c0-850f-269fbf4ec210&lt;/HostId&gt;<br>&lt;/Error&gt;</pre><p><strong><em>Debugging: </em></strong>While the error clearly states that is an access issue, we started looking into the <a href="https://docs.min.io/minio/baremetal/security/minio-identity-management/policy-based-access-control.html">bucket access policies</a>. Had to read tonnes of documentation!! It says everywhere that minio simulates S3 implementations, hence it was S3 policy documentation next 😶 The major distraction here was that the URL would return success, and the file was downloaded the moment we changed the bucket access to public . This made us more and more sure that we needed a custom bucket policy to resolve this issue, even though all docs said pre-signed URLs work perfectly on private buckets.</p><p><strong><em>Solution:</em></strong> After 2 days of tedious googling, reading minio and S3 documentation, and all the stack over flow answers on the topic, <a href="https://stackoverflow.com/questions/51803734/s3-signedurl-fails">this</a> appeared! And it worked 🥳 🤩 The issue turned out to be so orthogonal to our predictions. Basically:</p><blockquote>While converting a URL to string, Golang encodes it in a way that all the &amp; characters are replaced by \u0026 . Just by replacing them back in the URL manually, we could make it work <em>😱</em></blockquote><p>That was one hell of a debugging session for such a dumb error 😂</p><h3><strong>Bug # 2: Be mindful when using goroutines</strong></h3><p><strong><em>Context: </em></strong>In BranchKey, our authentication system is a golang application with a PostgreSQL Database. There are different entities, each related to the other in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUZCZ9U5R4jpcuMwGN-n3A.png" /><figcaption>BranchKey Entity Relation</figcaption></figure><p>In terms of relational schema, each of the child entities keeps a record of its parent via a <a href="https://www.postgresql.org/docs/current/tutorial-fk.html"><em>Foreign Key</em></a> connection to the parent entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNRzKb8jEHCzNlL2iSFbvw.png" /><figcaption>[FK] denotes the corresponding Foreign Key connection</figcaption></figure><p><strong><em>Problem: </em></strong>We provide APIs to manage these entities. The APIs to delete a parent entity, for example the DELETE tree API should also delete all the corresponding child <em>branches</em> and <em>leaves</em>, along with the deletion of the <em>tree </em>itself. Similarly, a DELETE branch request should:</p><ul><li>Revoke the <em>sessions</em> of each <em>leaf</em>, delete all its traces in the system like the corresponding event queue to receive download events, etc., and delete the <em>leaf</em> record itself</li><li>Revoke the <em>sessions</em> of this <em>branch, </em>delete all its traces like <em>branch-config</em>, <em>branch-run-details</em>, etc., and delete the <em>branch</em> record itself</li><li>Update the corresponding <em>tree-config</em> to delete this branch</li></ul><p>We were doing all these tasks concurrently using <a href="https://gobyexample.com/goroutines"><em>goroutines</em></a><em> </em>and <a href="https://gobyexample.com/waitgroups"><em>wait-groups</em></a>, as shown in this code snippet:</p><pre>wg := &amp;sync.WaitGroup{}<br>for _, l := range leaves {<br>    wg.Add(2)<br>    go deleteLeafSession(ctx, l.ID, wg)<br>    go deleteLeafEventQueue(ctx, l.ID, wg)<br>}<br><br>wg.Add(7)<br>go deleteLeavesInTreeConfig(ctx, treeID, len(leaves), wg)<br>go deleteBranchSession(ctx, branchID, wg)<br>go deleteLeafRecordsForBranch(ctx, branchID, wg)<br>go deleteBranchConfig(ctx, branchID, wg)<br>go deleteBranchRunDetails(ctx, branchID, wg)<br>go deleteBranchEventExchange(ctx, branchID, wg)<br>go deleteBranch(ctx, branchID, wg)<br>wg.Wait()</pre><p>Everything was working as expected, except the last function call, i.e., the record for this <em>branch</em> was not getting deleted from the database.</p><p><strong><em>Debugging: </em></strong>Firstly, we made them all sequential. This fixed the issue. This meant the code is right, but concurrency is creating a problem. Hence, as a next step, we added detailed logs to each of these function calls.</p><p><strong><em>Solution: </em></strong>Logs helped us devise that</p><blockquote>Since all the calls are being fired at the same time (or at very small interval), <em>leaf</em> records are still not deleted from the database when we attempt to delete the <em>branch</em> record. Hence the deleteBranch() call was facing pq: violates foreign key constraint error <em>🤦‍♀</em></blockquote><p>Thus, we pulled out the deleteBranch() function call from the asynchronous list, and made it synchronously after all the other calls were completed.</p><pre>wg := &amp;sync.WaitGroup{}<br>for _, l := range leaves {<br>    wg.Add(2)<br>    go deleteLeafSession(ctx, l.ID, wg)<br>    go deleteLeafEventQueue(ctx, l.ID, wg)<br>}<br><br>wg.Add(6)<br>go deleteLeavesInTreeConfig(ctx, treeID, len(leaves), wg)<br>go deleteBranchSession(ctx, branchID, wg)<br>go deleteLeafRecordsForBranch(ctx, branchID, wg)<br>go deleteBranchConfig(ctx, branchID, wg)<br>go deleteBranchRunDetails(ctx, branchID, wg)<br>go deleteBranchEventExchange(ctx, branchID, wg)</pre><pre>wg.Wait()</pre><pre>deleteBranch(ctx, branchID, wg)</pre><p>This fixed the issue. We had to perform similar changes in DELETE tree and DELETE user APIs also. As a thumb rule, being a little mindful while invoking concurrent functions never hurts 🤭</p><p>Well we continue to learn from our mistakes, and share our learnings hoping to ease up your life. For more such stories of interesting findings at BranchKey, follow this space 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1954f38260a1" width="1" height="1" alt=""><hr><p><a href="https://blog.branchkey.com/learn-from-our-mistakes-in-golang-1954f38260a1">Learn from our mistakes in Golang</a> was originally published in <a href="https://blog.branchkey.com/">BranchKey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-hosting Gitlab CI/CD Runners]]></title>
            <link>https://blog.branchkey.com/self-hosting-gitlab-ci-cd-runners-42c88957e13f?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c88957e13f</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Tue, 24 May 2022 11:27:47 GMT</pubDate>
            <atom:updated>2022-05-24T11:27:47.697Z</atom:updated>
            <content:encoded><![CDATA[<h4>Provisioning Gitlab runners on AWS with an optimised infrastructure design</h4><p>In this age of agile development over containerised microservices, manual deployment is too cumbersome of a process. Keeping a tab of the versions deployed on all environments for each microservice, provisioning an upgraded deployment at the development of every new feature or bug fix, maintaining the specific configurations and databases in synchronisation with the development process, and whatnot! 😓</p><blockquote>Thus emerges a need for <a href="https://www.redhat.com/en/topics/devops/what-is-ci-cd">continuous integration and continuous deployment</a> over an automated infrastructure.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*mNXrrLEOEeuzNrAo.jpg" /><figcaption><a href="https://journeyofquality.files.wordpress.com/2020/11/cicd-tools.jpg">Source</a></figcaption></figure><p>In BranchKey, we solved this problem using <a href="https://docs.gitlab.com/ee/ci/"><strong>Gitlab CI/CD</strong></a>. This choice was made mainly because we already use Gitlab as our VCS, and thus extending to the native CI/CD integration seemed to be an obvious first approach.</p><p>GitLab CI/CD can be integrated into the system infrastructure as separate entities called <a href="https://docs.gitlab.com/runner/"><em>runners</em></a><em>. </em>Gitlab provides its own free runners, with a limited resource and time usage. To be able to control the usage parameters, we at BranchKey, decided to deploy our own runners. These can be deployed as Docker containers, or as individual VM instances.</p><p>We decided to explore the <a href="https://docs.gitlab.com/runner/install/linux-manually.html">VM deployment</a> option using AWS infrastructure. The easiest approach would have been to deploy multiple EC2 instances, each of which would serve as a single runner. But this would not be the most cost efficient way. We could schedule them to turn off during the non-working hours, but would still be charged for multiple large instances running unused most of the time.</p><blockquote>It is always preferred to optimise infrastructural costs as much as possible <em>💰</em></blockquote><p>Thus, we came up with an alternative. The idea, as shown in Figure 1, was to deploy a single very small EC2 instance running all the time, and ready to accept GitLab pipeline jobs whenever needed. Since this is a small VM (preferably a <em>t4g.nano</em>), it would not add to a lot of operational cost. But given its small size, it won’t be capable enough to run the jobs. Thus, it would spawn a larger EC2 instance (could be <em>t3a.large</em>) every time there is a job available, run the job over this new instance, and shut it down once done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JR7l_ChXdzzN0xMbkWXlLQ.png" /><figcaption>Figure 1</figcaption></figure><p>While this seemed like a perfect approach, it gave errors while configuring. GitLab Runner configuration file exposes <a href="https://docs.gitlab.com/runner/configuration/autoscale.html#additional-configuration-information">auto scaling parameters</a>, where <em>IdleCount </em>defines the number of runner machines in idle states. Given the low usage of BranchKey, we wanted this to be <em>zero</em>. This meant spawning an instance when a job is available, and kill it later, keeping no instance idle. However, instance was not being killed, and rather, a new instance was being spawned at every job. This is an <a href="https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4221">open issue in GitLab</a>. This would mean multiple EC2 instances running infinitely, and thus adding to infrastructure cost for no reason. Contrarily, when the <em>IdleCount</em> value was being set to something other than <em>zero</em>, instances were getting created on AWS one after the other without any of them being actually getting allocated to a job. This <a href="https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4193">issue</a> is also open in the community.</p><h4>Hence, we had to discard this approach entirely.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*Cck8T_cHZDNtQwrv.gif" /><figcaption><a href="https://i.imgur.com/T7UdjEt.gif">Source</a></figcaption></figure><p>Exploring further, we decided to give the <a href="https://docs.gitlab.com/runner/install/docker.html">container runner deployment</a> a try. This would mean running the gitlab-runner process as a docker service on an EC2 instance. We followed the official documentation to install, configure and register the runner, and it worked successfully 🎊🎉 , except that two issues were encountered:</p><ol><li>Access issues for GitLab servers in accessing the runner instance in a private subnet in AWS. This was resolved by provisioning an elastic load balancer to grant access to this private instance.</li><li>A TLS issue in the DIND (Docker in Docker) ecosystem, where the docker containers of the jobs were not able to communicate with the base docker image of the runner. This was resolved by mounting the <em>ca-certs</em> volume into the runner docker instance, as described <a href="https://docs.gitlab.com/runner/faq/#docker-machine-error-unable-to-query-docker-version-cannot-connect-to-the-docker-engine-endpoint">here</a>.</li></ol><p>In attempts to optimise infrastructure resource usage, we could spawn multiple of these runner processes in different docker containers on the same instance. Since it was a large instance, we could provision upto 3 runners on each. This was better than provisioning an instance for each runner separately. Further, we provisioned a very small EC2 instance, as shown in Figure 2, to schedule these large instances. A cronjob to start and stop the large instances in accordance with the working hours of the developers was deployed on this small instance.</p><figure><img alt="sdsfd" src="https://cdn-images-1.medium.com/max/1024/1*Yk2pYcbovFo-4EjOAk5Tpg.png" /><figcaption>Figure 2</figcaption></figure><blockquote>This not only gave us control over our gitlab runners, but also allowed us to provision them in a cost effective manner. Additionally, it can be scaled as per need 💯</blockquote><p>The whole process of arriving at this solution was not easy, but definitely worth it. Although it did seem tempting to use Gitlab’s own runners at first, this exercise did give us an idea of how things work underneath, and a better understanding of CI/CD as a tool. We at BranchKey believe in experimenting with things, while also maintaining resource efficiency. Watch this space for more such stories from our implementation cycles! 🎊🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c88957e13f" width="1" height="1" alt=""><hr><p><a href="https://blog.branchkey.com/self-hosting-gitlab-ci-cd-runners-42c88957e13f">Self-hosting Gitlab CI/CD Runners</a> was originally published in <a href="https://blog.branchkey.com/">BranchKey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring a Golang Application]]></title>
            <link>https://blog.branchkey.com/structuring-a-golang-application-3c15030681e0?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c15030681e0</guid>
            <category><![CDATA[domain-driven-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 10:07:44 GMT</pubDate>
            <atom:updated>2022-05-20T09:57:46.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>Domain Driven Design within a Golang microservice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Txg3y1k2Y62K49ej" /><figcaption><a href="https://camo.githubusercontent.com/2b507540e2681c1a25698f246b9dca69c30548ed66a7323075b0224cbb1bf058/68747470733a2f2f676f6c616e672e6f72672f646f632f676f706865722f6669766579656172732e6a7067">Source</a></figcaption></figure><p>At BranchKey, we follow microservices architecture where a single microservice is responsible for a unique business functionality like authentication, authorisation, maintaining file histories, etc. Let us analyse the structural overview of one of these, say, authentication service.</p><p>The authentication service provides <em>create/update/fetch/delete entity details </em>APIs for the three user <em>roles</em> identified in BranchKey consumer platform: <em>tree, branch</em> and <em>leaves. </em>Each of these roles entails to its own list of parameters, needed to be stored and accessed in correspondence to the API triggered. Additionally, we also manage sessions as a part of authentication service. Sessions are role neutral entities which serve the <em>login, logout </em>and <em>authenticate</em> APIs. They have their own parameters to maintain and validate accesses, expire and revoke the tokens, and facilitate login and logouts.</p><blockquote>Thus, we observed four database domains in here: trees, branches, leaves &amp; sessions</blockquote><p>To ease up the design and maintenance of the database for this service, we decided to create four tables in our relational database, one for each of the <em>domains. </em>Moreover, as <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice"><em>Domain Driver Design</em></a><em> </em>principles advocate, we structured our application code into four domains (<a href="https://www.golang-book.com/books/intro/11">packages</a> in Golang terms) as well. This not only helped us encase the features and parameters of each domain into its own package, but also made the inter-package interaction easier with exposed interfaces. For instance, the <em>login</em> API belongs to <em>sessions</em> package. However, it needs to validate the entity credentials before creating a login record in the database. Owing to the domain driven packaging, each of the <em>tree/branch/leaf</em> packages exposes a <em>validate_credentials()</em> interface, which can be invoked by the <em>sessions</em> package, without caring about its internal implementation. Thus, we derived the following structure of code.</p><pre>|- <strong>tree</strong><br>|- <strong>branch</strong><br>|- <strong>leaf</strong><br>|- <strong>sessions</strong><br>|- main.go<br>|- server.go</pre><h4>But what all do we encase in a package?</h4><p>We have five layers in our Golang microservices. Iterating in top down fashion:</p><ul><li><strong>Layer 1: </strong><em>Router: </em>This layer starts a server and exposes the APIs (REST APIs in case of authentication service) for external clients to use this service</li><li><strong>Layer 2: </strong><em>API Handler: </em>This layer defines the contracts for the APIs exposed in <em>layer 1.</em> It performs basic checks on the input received from the clients before passing it on to the service layer for further processing. Also, it formulates the desired contractual response to be returned to the client, in accordance with the response received from the service in <em>layer 3.</em></li><li><strong>Layer 3: </strong><em>Service logic: </em>Here we perform the needed logical operations on the client data passed on by the handlers in <em>layer 2. </em>Furthermore, if a request needs multiple downstream operations to be triggered, like a database query, a call to another service, a message publication in an event queue, etc., they are all sequentially or concurrently invoked in this layer.</li><li><strong>Layer 4: </strong><em>Data model: </em>This layer defines the models to be used to store/get data from the database or other external clients. It exposes methods implemented over these models, to be invoked by the service in <em>layer 3. </em>These methods design the call to the external service, for instance, the queries to the database.</li><li><strong>Layer 5: </strong><em>External connection manager:</em> This layer provides the <em>client </em>objects to connect to the databases, other downstream services, the queues, etc. The methods in <em>layer 4</em> use these clients to finally perform the desired operations on the external entities.</li></ul><p>We have generic implementations of <em>layers 1 &amp; 5</em>. This means, we have only one router, exposing all the API endpoints on a single server port. Similarly, we have one single implementation for each of the external connection clients. Every domain is however, free to create its own client object and use it accordingly. Further, the <em>handlers</em> in <em>layer 2</em> can be divided into subdomains, or can be packaged all together. It highly depends on the programmer’s choice. Keeping them together facilitates the use of shared loggers, request authentication validators and response formulation methods. However, if there are too many of them, there is a risk of lowering the maintainability of the single <em>handler</em> package. It is then we could subdivide them into further domains.</p><p><em>Layers 3 &amp; 4</em> are highly domain specific. In terms of our authentication service, <em>layer 4 </em>defines the data models for each of our domains in the database. Similarly, <em>layer 3</em> provides methods to perform logical operations on those data models. For instance, for a <em>login</em> request, <em>layer 3</em> is responsible to call the <em>tree</em> service for verifying the input credentials, and then invoking the <em>login_session</em> call of the <em>sessions</em> domain in <em>layer 4. </em>Thus, we encase these two layers in a single domain package. Tracing these back to our code structure:</p><pre>|- <strong>tree<br>   </strong>|- service.go                     <em>// layer 3</em><br>   |- db_model.go                    <em>// layer 4</em><br>|<br>|-<strong>branch<br>   </strong>|- service.go.                    <em>// layer 3</em><br>   |- db_model.go                    <em>// layer 4</em><br>|<br>|- <strong>leaf<br>   </strong>|- service.go.                    <em>// layer 3</em><br>   |- db_model.go                    <em>// layer 4</em><br>|<br>|- <strong>sessions<br>   </strong>|- service.go.                    <em>// layer 3</em><br>   |- db_model.go                    <em>// layer 4</em><br>|<br>|- <strong>handlers </strong>                         <em>// layer 2</em><strong><br>   </strong>|- handler1.go<br>   |- handler2.go<br>   |- .... so on<br>   |- logger.go <br>   |- response.go<br>|<br>|- <strong>connection_manager </strong>               <em>// layer 5</em><strong><br>   </strong>|- database_driver_client.go<br>   |- http_client.go<br>|<br>|- <strong>router </strong>                           <em>// layer 1</em><strong><br></strong>   |- server.go<br>|<br>|- main.go</pre><blockquote>As mentioned before, this structure helps in inter-domain interactions without making them chaotic. Also, it helps us plan the implementation of new incoming features, by segregating them according to which domains they belong in, and thus keeping other domains untouched during development.</blockquote><p><strong><em>Where do we start the development of a new application?</em></strong></p><p>Once there is an idea for the inception of a new microservice, we have a basic structure of what the broad domains are, what data needs to be dealt with in each of them and what operations are to be performed for each domain. This helps us in designing the data models and their methodic implementations first. Hence, we start with connection drivers of <em>layer 5</em>, and use them for <em>layer 4 </em>implementations of each domain. Further, we build the <em>layer 3</em> over these implementations, by incorporating the translations and validations of the expected client input into the data models. Finally, we define the exact API contracts in <em>layer 2, </em>and expose those endpoints in <em>layer 1.</em></p><p>It can be done the other way round as well. If API contracts are fixed and data models are to be derived, we can work our way in a top-down approach, by writing the handlers first, and then the service layers, followed by the data models. However, this approach is prone to leading into sub-optimal data models and queries. Extra care needs to be taken to avoid these.</p><blockquote>At BranchKey, we follow a bottom up approach! ✅</blockquote><p>This summarises our design and development process for a Golang microservice. It helps us conceptualise a business requirement into technical domains, and translate it into viable endpoints. It has worked for us so far, but we are constantly experimenting with many other things.</p><p>Watch this space for many more of our explorations 🎊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c15030681e0" width="1" height="1" alt=""><hr><p><a href="https://blog.branchkey.com/structuring-a-golang-application-3c15030681e0">Structuring a Golang Application</a> was originally published in <a href="https://blog.branchkey.com/">BranchKey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The journey from Python to GoLang]]></title>
            <link>https://blog.branchkey.com/the-journey-from-python-to-golang-c5f444fa3f0a?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f444fa3f0a</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 11:17:23 GMT</pubDate>
            <atom:updated>2022-02-10T11:17:23.126Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhancing our consumer platform to provide federated learning at scale.</h4><p>From a software engineer’s perspective, BranchKey provides a consumer platform which exposes <a href="https://api.branchkey.com/docs/#/">APIs</a> to perform federated learning and download the aggregated results. We authenticate and authorise every incoming request using our in-house solutions, cache the input files, asynchronously aggregate them, and notify the clients when an aggregation result is ready to be downloaded.</p><blockquote>Needless to say, all of this is designed as a microservices architecture</blockquote><p>Inception of BranchKey happened with the prototyping of a federated learning algorithm. Python, as a programming language, became the obvious choice because it provides a wide community support for such data science problems. To maintain consistency in technical stack, we extended the use of Python for other microservices as well. For instance, our Authentication Service implements Python Flask, with a PostgreSQL DB backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wq_TtlT6s2rrBHE9mxeqdg.png" /><figcaption>Authentication Service: Overview</figcaption></figure><p>This looked promising. We followed all the Flask framework conventions to develop a production grade service. Subjecting to a load-testing script which fired about <em>25 requests per second</em> for each of the APIs, we obtained a response time of about <em>150 ms</em>. This isn’t that bad! Especially when we were using a Kubernetes single pod deployment on a machine with <em>2 vCPUs</em> and <em>4 GBs</em> memory. Our service used only <em>0.7</em> of the CPU and <em>325 MBs</em> of memory 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*4NnqYfOk9pNSErji88uPHw.png" /><figcaption>Authentication Service: Response Times</figcaption></figure><p>Meanwhile, as an experiment, we started exploring GoLang for software development. There occurred a use case for a similar CRUD application with a PostgreSQL DB backend. We needed a File History Service to store the aggregated result files, and serve them on demand. The index data of each file was stored in the PostgreSQL DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVxe33FhZa4MYH4qty-eqg.png" /><figcaption>File History Service: Overview</figcaption></figure><blockquote>To our surprise, for the same load, this service responded within <em>30 ms</em> 😱 Further, it used only <em>0.05</em> of the CPU and <em>23.5 MBs</em> of the memory 🤯</blockquote><p>We were bound to dig around more into this. Since both these services were essentially performing read and write operations on a PostgreSQL backend, such a massive difference in performance and infrastructure usage would directly affect the scalability. More so for authentication service, because every incoming request is mandatorily authenticated. Digging in, we discovered that within our ecosystem, a Python application takes up about 9 times more memory than a GoLang application in no-data and no-load state.</p><figure><img alt="Golang Kubernetes Pod Top" src="https://cdn-images-1.medium.com/max/572/1*ps-W9U0Dy8I3v_eiw9AxvQ.png" /><figcaption>Spot the Python Application(s)</figcaption></figure><h4>But why?!</h4><ul><li>GoLang is a compiled language which generates machine code for execution, it outperforms interpreted scripting languages like Python.</li><li>GoLang is built for high concurrency. Unlike multi-threading in Python, GoLang works with <em>goroutines.</em> As stated <a href="https://golangbot.com/goroutines/">here</a>, they basically enable software based concurrency rather than hardware based. A single OS thread could facilitate a 1000 goroutines.</li><li>In terms of memory usage, as <a href="https://dave.cheney.net/2014/06/07/five-things-that-make-go-fast">Dave Chaney states</a>, Python consumes about 6 times more memory than GoLang to store similar variables.</li><li>Additionally, for memory allocations, GoLang not only exploits compile time interpretations like C/C++, but also uses a run time garbage collector like Java. This surpasses the lack of memory management in Python.</li></ul><blockquote>These not only lead to lower memory usage and faster processing, but also lower the need for computation power.</blockquote><p>While there are many blog posts out there which compare Python and GoLang in terms of ease of writing and maintaining code, seeing the effects of infrastructural performance was exciting. They not only sold us over the goodness of GoLang, but also convinced us to rewrite the existing Python services.</p><p>As a result, except the federated learning algorithm, most of our consumer platform is now being developed in GoLang 🤞</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f444fa3f0a" width="1" height="1" alt=""><hr><p><a href="https://blog.branchkey.com/the-journey-from-python-to-golang-c5f444fa3f0a">The journey from Python to GoLang</a> was originally published in <a href="https://blog.branchkey.com/">BranchKey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastermind : Multi Agent Analysis]]></title>
            <link>https://medium.com/@deepshig/mastermind-the-game-b93c360f2fba?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/b93c360f2fba</guid>
            <category><![CDATA[mastermind]]></category>
            <category><![CDATA[multi-agent-simulation]]></category>
            <category><![CDATA[logical-thinking]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 11:17:03 GMT</pubDate>
            <atom:updated>2020-06-30T14:38:22.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastermind : Multi Agent Analysis</h3><h4>Starting with Modal Logic Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*4GMtW0V3Um-F0r73.jpg" /><figcaption><a href="https://www.fromthegrapevine.com/lifestyle/mastermind-board-game-mysterious-history">Image Source</a> : The board game setup for mastermind</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Mastermind_(board_game)">Mastermind</a> is a code-breaking game of two players, where the code-maker decides on a secret code, and the code-breaker attempts to guess it. When both players are considered to belong to the system as a whole, the game becomes a perfect example of a <a href="https://en.wikipedia.org/wiki/Multi-agent_system#:~:text=A%20multi%2Dagent%20system%20(MAS,a%20monolithic%20system%20to%20solve."><em>multi-agent system</em></a><em>. </em>We<em> </em>made an attempt to logically analyse this system, with the help of tools provided by <a href="https://en.wikipedia.org/wiki/Epistemic_modal_logic">epistemic modal logic</a>.</p><blockquote>Do not worry if you are new to this, we will try it address it in as simpler manner as possible.</blockquote><p>For the purpose of our implementation, we defined the game as follows. There are two players :</p><ul><li>Player 1 : Code-maker</li><li>Player 2 : Code-breaker</li></ul><p>The game starts with code-maker deciding on a secret code, which needs to be guessed by the code-breaker within 3 guesses. There are 6 colours available in total. The secret code and every guess needs to abide by following rules :</p><blockquote>Length of code/guess should be 4. All of these 4 colours should be different, i.e., duplicates are not allowed</blockquote><p>Once code-maker decides over a secret code, code-breaker attempts to guess it. Each move consists of a guess by code-breaker. Code-maker analyses this guess, and generates a feedback based on its equivalency to the secret code. This feedback, having 4 elements, is in accordance with the following rules :</p><ul><li>If element value = 1 : It means the colour and position both are correctly guessed for the colour at this position.</li><li>If element value = 0 : It means this colour is present somewhere in the code, but not at this position.</li><li>If element value = -1 : It means this colour is not at all present in the code.</li></ul><p>Code-breaker uses this feedback and its previous move, to generate the next move. If it is able to make a correct guess within 3 moves, it wins, otherwise the code-maker wins.</p><p><strong>Epistemic Logic Application</strong></p><p>We use <a href="https://en.wikipedia.org/wiki/Kripke_structure_(model_checking)#:~:text=A%20Kripke%20structure%20is%20a,whose%20edges%20represent%20state%20transitions.">Kripke Models</a>, to analyse the logical aspects of the two agents (players) present in the game here. We need three important things to define a Kripke Model for our system: agents, worlds and relations.</p><p>Agents are the different entities in the system which possess the potential to influence the system state. In our system, we have the 2 players, i.e., the code-maker is agent 1, where as the code-breaker is agent 2.</p><p>A world is a possible scenario, or a state the system can possibly be in. In our case, we can say that every valid combination of colours constitutes a possible world. The world which is true in real scenario, is however, called the <em>real world</em>. It means, the secret code is the real world here. The code-maker considers only the real world to be possible, because it knows the actual code. However, code-breaker considers all the possible worlds in the beginning of the game, because it has no idea of what the actual code is. Therefore, with no repetitions, there are 360 worlds possible for the code-breaker.</p><p>Relations in a Kripke Model are the accessibilities and possibilities of different worlds (states) of the system, from the perspective of an agent. In simpler terms, if a system is in a state <em>S1</em>, all the states which an agent <em>i </em>considers possible are connected from <em>S1</em> via an accessibility relation for agent <em>i</em>. The complete set of such accessibility relations for all the states and for all the agents, constitute the relations for the given model. In our system,</p><ul><li>Code-maker possesses reflexive relations on all the worlds. This is because, whatever is the world, code-maker knows about it, and is sure that it is the only world possible. Thus, it does not have an accessibility relation to any other world. We can conclude that in the beginning, code-maker has 360 relations, one for each world.</li><li>Regardless of the system state, code-breaker considers all worlds possible. Thus, it has accessibility relations from every world to every other world. This also includes reflexive relations. Thus, code-breaker has 360x360 = 129600 relations in the beginning of the game.</li></ul><p>Further, we borrow the tools of Higher Order Knowledge from the <a href="https://en.wikipedia.org/wiki/Dynamic_epistemic_logic">Dynamic Epistemic Logic</a> to maintain the game state, and define the code-breaker strategy. Let us walk through them in Layman’s terms.</p><p>When the game proceeds, code-breaker makes guesses and code-maker provides feedback by analysing them with respect to the secret code. Accounting this in terms of public announcement logic,</p><blockquote>The feedback is a truthful public announcement.</blockquote><p>It implies that firstly, feedback is bound to truthfully hold, i.e., code-maker cannot lie. And secondly, this information is announced publicly to all the agents, and becomes <a href="https://en.wikipedia.org/wiki/Common_knowledge_(logic)">common knowledge</a> henceforth. It means whatever insight about the secret code is gained from every feedback, is announced publicly to both agents. For example, if state <em>S1</em> is no more possible, both agents know that <em>S1</em> is no more possible, and they know that the other player knows about this. Thus, going forward, code-breaker can make use of this knowledge to narrow down the possible worlds and make a viable next guess.</p><p>Let us understand the whole scenario with an example. Suppose, we have the following 6 colours available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*NmLKnAoYs2_f6uy4_-2-jA.png" /><figcaption>All colours available</figcaption></figure><p>Let the secret code chosen by the code-maker be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*KD7fpRPisL8qQJOR3TrcAQ.png" /><figcaption>Secret Code</figcaption></figure><p>Now, if code-breaker makes the following guess :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*nqcBcHEjFT9g9gk8_oN-9Q.png" /><figcaption>Guess 1</figcaption></figure><p>Code-maker provides the following feedback : [0 1 1 -1]. This represents the following:</p><ul><li>First colour blue occurs in the secret code, but not at the first position.</li><li>Second colour yellow is correctly placed as in the secret code. It does not need any change.</li><li>Third colour red is correctly placed as in the secret code. It does not need any change.</li><li>Fourth colour pink is incorrect. It does not appear in the secret code, and needs to be replaced.</li></ul><p>After these announcements, the worlds in our Kripke Model get reduced as follows :</p><ul><li>Second and third colours have to be <em>yellow</em> and <em>red</em> respectively. All the worlds with other possibilities for second and third colours are eliminated. Following worlds are now possible :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5NzCobloidnmMhgE.jpg" /><figcaption>Announcement 1 : Processing feedback elements 2 and 3</figcaption></figure><ul><li><em>Blue</em> needs to be somewhere other than the first position. But since second and third position are already occupied, <em>blue</em> can only occur at fourth position. This eliminates all the worlds with any other colour on the fourth position, or <em>blue</em> colour in any other position. Following worlds are now possible :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WkXjXAaF3TdClyHU.jpg" /><figcaption>Announcement 2: Processing feedback element 1</figcaption></figure><ul><li>Only place left vacant is the first one. This position is occupied by any colour other than <em>pink</em>. Thus, all the worlds with <em>pink</em> in any place on the code are eliminated. Following worlds are finally possible :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*OYU1MGNuZYXXfOH3yzTFWQ.png" /><figcaption>Announcement 3: Processing feedback element 4</figcaption></figure><blockquote>If a world is eliminated, all the accessibility relations starting or ending at it are also eliminated. In the reduced model, relations are preserved in the same way as explained before, i.e., code-maker has reflexive relations for all worlds, and code-breaker can access any world from any other world.</blockquote><p>Both the agents are aware of this elimination process, and it becomes common knowledge in the system. Based on the derived system, code-breaker can now make a second guess. This guess need not be done via any complicated mathematical procedure. Rather, it can simply be a random selection of a world from the currently available worlds in the model. Code-maker would again analyse it and provide feedback. Similar procedure would be followed and the game continues.</p><p>Using this mechanism, we conclude that a game of Mastermind is a series of restrictions on the Kripke model until code-breaker has access to only one world and thereby knows the secret code. However, this restriction process is limited to only 3 moves. If code-breaker still is unable to make the correct guess, code-maker wins.</p><blockquote>We developed a Python <a href="https://github.com/deepshig/mastermind">implementation</a> for the same, using the <a href="https://github.com/erohkohl/mlsolver/">Modal Logic Solver</a> framework.</blockquote><p>We also compared the results of the above explained logical strategy against a few other strategies. Evidently, logical strategy proves out to be the best one available for the code-breaker to win the game. More details about the implementation and strategies are explained <a href="https://github.com/deepshig/mastermind/blob/master/docs/documentation.md"><em>here</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b93c360f2fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Coming Software Apocalypse]]></title>
            <link>https://medium.com/@deepshig/the-coming-software-apocalypse-ce8575951426?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8575951426</guid>
            <category><![CDATA[apocalypse]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[programmer]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 14:32:48 GMT</pubDate>
            <atom:updated>2020-06-30T12:24:03.077Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Detailed Analysis</h4><p><strong>*Disclaimer : Long post ahead 🙈; Read </strong><a href="https://www.theatlantic.com/technology/archive/2017/09/saving-the-world-from-code/540393/"><strong>this</strong></a><strong> article for better context.*</strong></p><p>Well recently, I read an article about <a href="https://www.theatlantic.com/technology/archive/2017/09/saving-the-world-from-code/540393/"><strong>The Coming Software Apocalypse</strong></a><strong> </strong>by James Somers on the <a href="http://www.theatlantic.com/">The Atlantic</a>. It seemed quite interesting, a pretty nuanced from the general view of software industry : one where we are enthusiastic about involving softwares in every cringe of our lives. But some of the writer’s thoughts felt to be biased from his perspective. So I just decided to come up with my own analysis of the issue.</p><p>Steve C McConnell, in his book ‘Code Complete’, says,</p><blockquote>It’s hard enough to find an error in your code when you’re looking for it; it’s even harder when you’ve assumed your code is error-free.</blockquote><p>I guess this captures the essence of the article <strong>The Coming Software Apocalypse</strong> in its precise sense, and I, for one, unreservedly agree to it. Software developers in the world today, whilst putting out creative software solutions for almost all of the world’s critical problems, are undoubtedly creating more and more lines of code with unanticipated bugs and potential disasters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*JBifAfu_uqHODelr.gif" /><figcaption>Source : giphy.com</figcaption></figure><blockquote>“Software failures are failures of understanding, and of imagination.”</blockquote><p>As stated in the article, softwares do not fail, they are designed to do the wrong thing. Programmers, to their humane capabilities, deliver the best possible version of the software. But it is an issue with their limited thinking capacity and not with their programming skills. This, as explained via multiple examples in the article, becomes more evident in complex software systems where in millions of interactions happen and thousands of commands can be issued. It becomes practically impossible for the human mind to simulate all of them and handle all the possible scenarios.</p><p>I have worked with a logistical solutions company previously. The architecture there was a conglomeration of more than a thousand micro-services, each handling its own logic. This often resulted in unforeseen scenarios. For instance, once, our bookings stopped going through because one of these micro-services had logic based on the maximum number of bookings that can be created. It took us about an hour or two to figure this out. Another time, bookings halted off because our wallet service stopped giving out the balance details for the customers, and apparently there was no default failover mechanism to cash payments if the wallet service fails.</p><p>Obviously, the impact was not as grave as that of the failure of the 911 service, but the company surely got hit for very high revenue amounting to more than a million bookings. And then there was the associated movement of customers to the competing brand, and thus a dip in the company’s brand value.</p><p>However big this loss might have been, we, the software engineers, could only relate to the program failure and system downtime. As accurately mentioned in the article,</p><blockquote>Software engineers don’t understand the problem they’re trying to solve, and don’t care to.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*bv3_cS5_vGIalpgb.gif" /><figcaption>Source : Imgur.com</figcaption></figure><p>In my opinion, this can be attributed to the sheer design of the industry where software engineers are not consulted with the business requirements of the system to be built. All they are given is the technical specification document. James Somers, in the article highlights that this is an issue with the programming methodology. He states that it is the very principle of programming which is at fault. He does give out anecdotes from influential people in the industry like Newcombe and Lamport about their attempts to move the programmers towards the use of model based designing tools and the resistance experienced therein.</p><p>Well, I don’t blame the programmers. They talk about the developers being interested only in making the code work, and in the process losing the imagination over the actual requirements.</p><p>In my opinion, according to the defined rules of the industry, it is not the job of the developer to ponder over the business requirements.</p><blockquote>I think the problem lies, not in the programming techniques, but in the roles given over to the programmers. I think we are getting confused among the <a href="https://en.wikipedia.org/wiki/Business_requirements"><strong>business requirements</strong></a> and the <a href="https://en.wikipedia.org/wiki/Specification_(technical_standard)"><strong>technical specifications</strong></a><strong> </strong>of a software here.</blockquote><p>The requirements and models James talks about all across the article, which he advocates, should be the only thing worked upon by the programmers, are not actually even dealt with by the programmers in the real world. There are product managers who devise the technical specifications from the business requirements, and thus, pass them on to the programmers. This, in my opinion, is the main reason, programmers do not sympathise with the losses incurred by the softwares to the business and the society.</p><p>To make programmers analyse the actual business requirements in terms of models, and develop tools for automated code generation, we need to revise the industry standards for the roles of the software developers.</p><blockquote>Make them responsible for the product as a whole, and not only the code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*H4lDNtNZajI2Hg5H.gif" /><figcaption>Source : giphy.com</figcaption></figure><p>May be cut off the middlemen, do away with product managers, and make the programmers analyse the product, define the requirements and then develop a solution for them. Yes, this indeed is a bigger change for it might take years to revise the job descriptions all across the IT industry, but I feel it will surely work out the way James advises it should be.</p><p>I agree that softwares can be better built when more of the human brain focuses on analysing the business requirements, and less of it ponders over converting them into a programming language. But we need to tell the programmers that it is their job to do this, and not some managers’. Once, the programmers find themselves comfortable with this idea, they would be forced to spend more time with the business. Thus, they would end up creating tools which devise business models into computer code for their own ease.</p><p>Then, we can put to the table whatever model based design tools that have been proposed in the article. I feel, it is then, that the programmers would not resist taking up formal methods and spending more time with tools like <a href="https://lamport.azurewebsites.net/tla/tla.html">TLA+</a>, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*AMY5J3P2QdIBoqBH.gif" /><figcaption>Source : giphy.com</figcaption></figure><p>Summarising it all, I feel to be in rigorous agreement with the point raised by James in this article. I agree that increasing the grasp of software over more of our critical systems is putting us into a dangerous position with unpredicted risks. I agree that the vast number of interactions the softwares today face are way beyond what the human mind can contemplate, and that it is very difficult for programmers to be able to foresee bugs or the limitations in such systems.</p><p>But what strikes me off is the direct blaming of the programmers over their hesitation to ditch their current programming techniques and take up the new proposed model-based design methodologies. In my opinion, this article is a little biased towards the business side of the argument, and does not take into account the dilemma of the programmers in the real world. As a solution, I propose that programmers’ accountability should be changed from only the software code to the software product as a whole. This is bound to lead to a revision in their thought process, thus making them revise their programming models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8575951426" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Benefits of Partitions in PostgreSQL]]></title>
            <link>https://medium.com/gojekengineering/the-benefits-of-partitions-in-postgresql-adc8d4df5e16?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc8d4df5e16</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 03:43:33 GMT</pubDate>
            <atom:updated>2019-09-30T03:45:01.741Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we use partitions in PostgreSQL, and the hiccups we faced on the way to improved system stability.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTv5w1a610UCrrvNc37Mag.jpeg" /><figcaption><a href="http://bit.ly/2mWu7xU">gojek.jobs</a></figcaption></figure><p>At Gojek, we continuously reassess, redesign, and rework our systems. One such system we recently worked upon is the one which stores and serves active bookings for customers.</p><blockquote>Why the rework? Read this post for more details:</blockquote><p><a href="https://blog.gojekengineering.com/the-data-dilemma-81faae3f7a82">The Data Dilemma</a></p><p>Our customer application uses this backend to show active bookings for a customer. If a customer initiates a booking, but <em>(due to some delay or failure in our system) </em>is not able to see it on the app, they might initiate another one. This would lead to multiple duplicate bookings, drivers being allocated to them, and a higher rate of cancellations. Thus, this system needed to be highly available and consistent.</p><p>In Gojek, over 3 million bookings are initiated in a day. A booking remains active for at most a week. This meant we needed our system to be able to handle large volumes of new bookings every day, each one ready to be served for at least a week.</p><blockquote>Agreed! Thats not much data compared to our other systems. But high availability and consistency was a crucial requirement here.</blockquote><p>Thus, we used <a href="https://www.postgresql.org/docs/10/release-10-5.html">PostgreSQL 10.5</a>. Our schema looked something like</p><pre>CREATE TABLE IF NOT EXISTS bookings (<br>booking_number PRIMARY KEY,<br>customer_id,<br>booking_details,<br>...<br>...<br>and so on<br>) CREATE INDEX ON (customer_id)</pre><ol><li>booking_number has to be the <a href="https://www.w3resource.com/PostgreSQL/primary-key-constraint.php">Primary Key</a> for there should be only one entry per booking</li><li>Index on customer_id is needed in order to fetch all the active bookings for a customer.</li></ol><p>Since a booking is no longer useful once it is completed, we needed this schema to facilitate periodic cleanups. We now had 2 options :</p><ol><li>Delete a booking from the DB as and when it is completed.</li><li>Partition the table with weekly timeframes, and delete the whole partition once all the bookings within it are completed.</li></ol><p>Option 1 did not seem very viable because tuples that are deleted are not physically removed from the table.</p><ul><li>It would lead to <a href="https://www.percona.com/blog/2018/08/06/basic-understanding-bloat-vacuum-postgresql-mvcc/">bloated table sizes because of increased dead tuples</a>. This means we would need larger amounts of disk space even with limited data.</li><li>Also, frequent <a href="https://www.postgresql.org/docs/9.5/sql-vacuum.html">vacuum</a> processes would be needed to clean these tuples. Vacuum slows down the DB response. Since active bookings are critical for customers, we could not afford this.</li></ul><blockquote>So we chose table partitioning.</blockquote><p>PostgreSQL 10 provides <a href="https://www.postgresql.org/docs/10/ddl-partitioning.html">native partitioning</a>. We put up a scheduler to create and archive weekly partitions. Our schema now looked like this :</p><pre>CREATE TABLE bookings (<br>booking_number PRIMARY KEY,<br>customer_id,<br>booking_details,<br>created_at_timestamp,<br>...<br>...<br>and so on<br>) PARTITION BY RANGE(created_at_timestamp)</pre><p>The functions to create and archive partitions were as follows :</p><pre>CREATE FUNCTION create_weekly_partition(total_weeks) RETURNS void AS $$<br>    BEGIN<br>        FOR i IN 1..total_weeks LOOP<br>            end_date = current_date + 7;<br>            EXECUTE CREATE TABLE partition_i PARTITION OF bookings<br>                        FOR VALUES FROM (start_date) TO (end_date)<br>            EXECUTE CREATE INDEX idx ON partition_i (customer_id);<br>            start_date = start_date + 7;<br>        END LOOP;<br>    END;<br>$$ LANGUAGE PLPGSQL;<br>_____________________________________________________________</pre><pre>CREATE FUNCTION archive_weekly_partition(weeks_to_be_deleted) RETURNS void as $$<br>    BEGIN<br>        FOR i IN 0..weeks_to_be_deleted LOOP<br>            EXECUTE DROP TABLE partition_i<br>        END LOOP;<br>    END;<br>$$ LANGUAGE PLPGSQL;</pre><ul><li>total_weeks : Number of weekly partition tables to be created for future. weeks_to_be_deleted : Number of weekly partitions to be archived from the past</li><li>Yes, we need to define the index independently for each partition table. We cannot define it in the parent table.</li></ul><p>This looked awesome 😎. It looked like we had cracked it. We only needed to store two of the weekly partition tables. This was a memory-efficient and reliable solution for our requirements of a consistent and available system.</p><blockquote>But there was a storm coming 😅. One fine night, our archive_weekly_partitions job got stuck.</blockquote><p>But that shouldn’t be an issue right? It would only affect the table to be archived. All other tables should be available and queries should be served fine.</p><blockquote>This is where we got it wrong.</blockquote><blockquote><strong>DROP TABLE</strong> acquires <strong>ACCESS EXCLUSIVE</strong> lock for the <strong>master</strong> table and not the individual child tables. This means it locked our whole <strong>bookings</strong> table, making all the active bookings unresponsive <em>🤦‍♀</em></blockquote><h3>The Solution</h3><p>This had to be fixed. We went through documentation and blogs again. It was discovered that we should <a href="https://blog.dbi-services.com/postgresql-partitioning-6-attaching-and-detaching-partitions/">detach a partition</a> from the master table before running any long queries. Hence, if this child table needs to acquire a lock, other children won’t be affected. Also, if needed, we can reattach it. Giving lock to the partition to be archived was fine, because we are not going to read from it anyway.</p><p>Thus, our new archive_weekly_partitions function looks like :</p><pre>CREATE FUNCTION archive_weekly_partition(weeks_to_be_deleted) RETURNS void as $$<br>    BEGIN<br>        FOR i IN 0..weeks_to_be_deleted LOOP<br>            EXECUTE ALTER TABLE orders DETACH PARTITION partition_i<br>            EXECUTE DROP TABLE partition_i<br>        END LOOP;<br>    END;<br>$$ LANGUAGE PLPGSQL;</pre><p>Problem Solved. Everything runs smoothly now 🎊</p><h3>Results:</h3><p>We are currently serving a throughput of <strong><em>120k requests per minute</em></strong> with a response time of <strong><em>0.5 milliseconds</em></strong> from Postgres. 😎</p><p>Data gets archived and new partitions are getting created periodically without any complicated app-level partitioning logic or the integration of any external library.</p><p>Hope you found some useful information in this post. To have more stories like this delivered to your inbox, <a href="https://mailchi.mp/go-jek/gojek-tech-newsletter">sign up for our newsletter!</a> 🙌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yigf1nGxRKjzV7vIC_YkYg.png" /></figure><figure><a href="http://bit.ly/2mWu7xU"><img alt="Current Job Openings at Gojek" src="https://cdn-images-1.medium.com/max/801/1*LIeXhpHbcTjVODQGUGcF7w.png" /></a><figcaption>gojek.jobs</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc8d4df5e16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/the-benefits-of-partitions-in-postgresql-adc8d4df5e16">The Benefits of Partitions in PostgreSQL</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Optimisation on Cassandra]]></title>
            <link>https://medium.com/gojekengineering/database-optimisation-on-cassandra-50d1fe635f6e?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d1fe635f6e</guid>
            <category><![CDATA[startup-lessons]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 03:57:31 GMT</pubDate>
            <atom:updated>2019-08-01T03:57:31.409Z</atom:updated>
            <content:encoded><![CDATA[<h4>An account of how running into problems helped us learn more about Cassandra and improve response times.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjeTL1yUfwpQEW5EmDI-aw.jpeg" /><figcaption><a href="http://bit.ly/2YAxhbl">gojek.jobs</a></figcaption></figure><p>We handle a lot of orders at Gojek, processing upwards of a 100 million transactions a month. In a SuperApp ecosystem of this scale, it is not unnatural that thousands of users per minute request to see all their completed/cancelled bookings over a two month period.</p><blockquote>That… is a lot of data <em>😅</em></blockquote><p>In order to deal with this load, we needed a database mechanism which would handle very high amounts of data with increased write efficiency. We could compromise a bit on read latencies<em> (because no one wants history urgently)</em>. Going by <a href="https://en.wikipedia.org/wiki/CAP_theorem">CAP Theorem</a>, high availability was more preferred — we could afford eventual consistency. With these factors in mind, we made the switch from Postgres to Cassandra.</p><p>This post is an account of how we matured our learnings about Cassandra amidst all the problems we faced.</p><h3><strong>Modelling the schema</strong></h3><p>We needed a schema to store a mapping of customer_ids or driver_ids to booking_details . Going by what we would have done if it had been a <a href="https://en.wikipedia.org/wiki/Relational_database">RDBMS</a> like Postgres, we normalised the store. This was done keeping in mind that we could serve the booking history for drivers as well as customers, without having to duplicate the booking_details column. A simplified form of our schema goes like :</p><pre><strong>Table1 : Customer_booking_mapping</strong><br>CREATE TABLE customer_booking_index (<br>    customer_id,<br>    booking_creation_time<br>    booking_number,<br>    ... <br>    ...<br>    PRIMARY KEY (customer_id, booking_creation_time)<br>) WITH CLUSTERING ORDER BY (customer_id, booking_creation_time DESC);</pre><pre><strong>Table2 : Driver_booking_mapping<br></strong>// similar table for drivers</pre><pre><strong>Table3 : Booking_details</strong><br>CREATE TABLE order_details (<br>    booking_number,<br>    booking_details,<br>    ...<br>    ...<br>    PRIMARY KEY (booking_number)<br>) WITH CLUSTERING ORDER BY (booking_number);</pre><p>To fetch the last n bookings for a customer, this schema would essentially make two DB calls <em>(</em><a href="https://www.datastax.com/2015/03/how-to-do-joins-in-apache-cassandra-and-datastax-enterprise"><em>nope, joins in Cassandra are not recommended for large tables</em></a><em>). </em>We know the customer_id, so the first call will go directly to the node where the data for that customer is. But all the booking_numbers for a customer can be in multiple nodes, leading to a scattered DB call. This would fail the purpose of a distributed data store, and give very high read latency.</p><p>So we had to denormalise the schema and duplicate the bookings data into two tables : one each for drivers and customers.</p><pre><strong>Table1 : Customer_booking_details</strong><br>CREATE TABLE customer_booking_details (<br>    customer_id,<br>    booking_creation_time,<br>    booking_number,<br>    booking_detail,<br>    ...<br>    ...<br>    PRIMARY KEY (customer_id, booking_creation_time)<br>) WITH CLUSTERING ORDER BY (booking_creation_time DESC, booking_number);</pre><pre><strong>Table2 : Driver_booking_details<br></strong>// similar table for drivers</pre><blockquote>Lesson<strong>: <em>UNLEARN RDBMS. </em></strong>Modelling a non-relational DB is completely different from a relational DB.</blockquote><h3><strong>Compaction Strategy</strong></h3><p>One important reason for us to choose Cassandra was that it provides the TTL feature, where we can configure data to be deleted after a certain period of time. But this is a soft delete, a periodical maintenance process is required to clean out the memory completely.</p><p>By default, Cassandra uses <a href="https://www.instaclustr.com/apache-cassandra-compaction/">SizeTiered Compaction Strategy</a>. This means, writes in Cassandra would happen in blocks of memory fragmented by size. Periodic maintenance tasks were required to clean these memory blocks. It had to iterate over all the data in each block, to see what needs to be deleted. The result was a tedious job that took 6–8 hours every week, with high CPU load and thus, slow response from the DB.</p><p>We went through many books and blogs, and discovered the <a href="https://thelastpickle.com/blog/2016/12/08/TWCS-part1.html">Time Window Compaction Strategy</a> would work the best for us. Here, data is fragmented in time series rather than size-based blocks. This means, all the data in a particular memory block was created in a given time frame. Since we wish to delete all the bookings based on their creation_time , we could afford deleting entire blocks at once. This meant no maintenance jobs were required. All we had to do was to configure the Time Window efficiently.</p><p>One shortcoming here was that once data is written, we could not edit it <em>(editing would create an entry in the block for the new time frame, thus complicating the deletion again.) </em>But that was fine for our use case, because a completed booking is a frozen entity.</p><p>This motivated us to look into other tweakable configs as well, like what should be our <a href="https://docs.datastax.com/en/archived/cassandra/2.0/cassandra/dml/dml_config_consistency_c.html">replication factor and consistency level</a>, how many nodes to use, how much RAM to be put in each node, etc.</p><blockquote>Lesson : Configure your DB according to your use case. <strong>Do not rely on default settings.</strong></blockquote><h3><strong>Adding Features</strong></h3><p>As we optimised things, there came a new feature request — to integrate driver feedback with this service. This required us to serve unrated bookings, fetch driver ratings for a booking from customer, and show these ratings along with the booking history. We could redesign the schema again to incorporate this, but now our booking would not be a frozen entity. It would require an update with driver rating.</p><p>With all the load testing and spikes, we eventually discovered that although every write query in Cassandra is an UPSERT , updating selective columns is more expensive than inserting new rows <em>(or updating the whole row)</em>. This was mainly because it is a column-oriented store. This meant, all the columns for a primary key are not stored directly against it. To update a column for a given combination of primary key, it has to go through large amounts of data — leading to lock in the table.</p><p>We could not afford our main bookings table to be locked for long durations. It would be fine if we were to rewrite the whole row again, but updating only some columns was not viable. This is so because new rows <em>(or full row updates)</em> directly store a new row in the DB, and wait for maintenance job to clean out the old row.</p><p>And thus, we had to create an entirely new table to store feedback.</p><pre><strong>Table3 : Customer_feedback_details</strong><br>CREATE TABLE customer_feedback_details (<br>    customer_id,<br>    feedback_creation_time,<br>    booking_number,<br>    feedback_detail,<br>    ...<br>    ...<br>    PRIMARY KEY (customer_id, feedback_creation_time, booking_number)<br>) WITH CLUSTERING ORDER BY (feedback_creation_time DESC, booking_number);</pre><pre><strong>Table4 : Driver_feedback_details<br></strong>// similar table for drivers</pre><blockquote>Lesson : Try to have as few update queries as possible. <strong>Cassandra is more suitable for frozen DB entries, or updates where the whole row is replaced.</strong></blockquote><h3><strong>Results</strong></h3><p>Although it was a roller coaster ride, it was all worth it. Yes, we had to redo the schema multiple times, yes we had to embrace denormalisation and data duplication, but what we finally achieved was a stable system with awesome performance. Our current system now serves <strong>writes within</strong> <strong>1ms</strong> and <strong>reads within 10ms</strong>. It did require multiple iterations of tuning the system, but we can now serve much higher amounts of data <em>(4 months of completed bookings)</em> with very low response time.</p><p>Oh and one more thing, because Cassandra uses a distributed architecture, it is very easy to add a node or tackle a failing node in times of need.</p><p>That’s all for this post. We’ll be sharing more insights as we continue to build and learn, so keep watching this space for more. Or better yet, <a href="https://mailchi.mp/go-jek/gojek-tech-newsletter">sign up for our newsletter</a> to get our latest updates beamed straight to your inbox.</p><figure><a href="http://bit.ly/2YAxhbl"><img alt="See our open positions" src="https://cdn-images-1.medium.com/max/800/1*f6cqYRiQI3nniFGklRFl0A.png" /></a><figcaption>gojek.jobs</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d1fe635f6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/database-optimisation-on-cassandra-50d1fe635f6e">Database Optimisation on Cassandra</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Data Dilemma]]></title>
            <link>https://medium.com/gojekengineering/the-data-dilemma-81faae3f7a82?source=rss-f324b341a551------2</link>
            <guid isPermaLink="false">https://medium.com/p/81faae3f7a82</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Deepshi Garg]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 03:36:56 GMT</pubDate>
            <atom:updated>2019-07-09T03:36:56.010Z</atom:updated>
            <content:encoded><![CDATA[<h4>How GOJEK’s booking data management went from being unorganised and chaotic to relying on a single source of truth.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQj-7fcwYRcHuhObM_87Mg.jpeg" /><figcaption><a href="http://bit.ly/2xA33WU">gojek.jobs</a></figcaption></figure><p>As GOJEK has scaled over the past few years, our booking management system has seen a few revisions. There used to be a time when we stored multiple copies of the same data to serve different features. It was a confusingly scattered implementation.</p><p>But, don’t take my word for it. See for yourself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99uJVfxsNPASLY52we43dQ.png" /><figcaption>P.S. Some of the services were rewritten, but the task of migration was left halfway</figcaption></figure><p>All these services maintained their own copy of booking data, and used it to serve their respective features. Any failure or delay in consumption of a booking event by a consumer would lead to inconsistency of data across systems.</p><p>This post will explain how we moved from multiple, scattered data stores to a single source of truth.</p><h3>Early days, problems galore</h3><ol><li>Data inconsistency : Let’s assume a booking is created, and is available with the Older Active Booking service, but a delay occurs in the Old Booking History Service consumer. This would mean that the driver would see the booking, but the customer will get only a red badge indicator on the home screen without any specifications of the ongoing order. Or, if there is a delay in Standardised Bookings Events bus, the customer will see the booking, but won’t be able to make a complaint about it, because the customer support portal will not get this booking.</li><li>We faced issues with scalability as well. Scaling multiple databases with the same data came to be seen as a pointless. For example, if we wanted to serve booking history of a longer duration, we would have to scale Driver Booking History, Older Booking History Service, and Rewritten Booking History Service.</li><li>Adding a new feature to this system became a pain. We had many long and eventually futile discussions about which service should serve the feature. For instance, fetching and validating orders for driver to customer chat was a confusing decision in itself. Adding the feature for the customer to be able to get unrated bookings and then submit driver ratings for them led to the creation of whole new service</li></ol><blockquote>We realised it was time for a refactor towards a <strong>Single Source of Truth</strong> for bookings data.</blockquote><p>Thus, we came up with a clear categorised plan. All the data should be divided into two major categories : <strong>Active Bookings and Completed Bookings</strong>, and should essentially be stored in only two databases.</p><blockquote>We could have created a truly singular source and stored both active and completed bookings in a single database, and served them both from a single service. However, that would create a single point of failure for the bookings management system across both driver and customer applications. Active bookings are more critical than completed bookings, and thus needed to be made more available and reliable. Also, again, scaling might be an issue.</blockquote><h3>Finding answers</h3><p>We spent some time working this out, and tackled the problems individually:</p><ol><li>The problem of <em>Data inconsistency </em>was handled by having only one service each to manage for active bookings and completed bookings. We eliminated an extra layer of potential delay by including the logic for standardisation of various booking events of multiple products in these services themselves. This logic now resides as an internal library available for use, rather than a new series of events entirely.</li><li><em>Scalability </em>was ensured differently for active and completed bookings. Active bookings are a crucial requirement for customer, and the number of queries for these is very high <em>(around </em><strong><em>100k rpm</em></strong><em> in peak hours)</em>. Also, we don’t need to store data beyond a week or two for this. Thus, it was scaled for high throughput but comparatively less data <em>(response time ~ </em><strong><em>3ms</em></strong><em>)</em>. However, completed bookings are not as critical <em>(i.e., can afford a slower response) </em>with lesser throughput<em> (around </em><strong><em>50k rpm</em></strong><em> in peak hours)</em>, but it needs to store data for upto 4 months of user bookings. Thus, it was scaled for high amounts of data but comparatively fewer queries <em>(response time ~</em><strong><em>15 ms</em></strong><em>).</em> How exactly are these two systems scaled, is a story for another time 😛</li><li>For all the upcoming features, we now clearly segregate whether they need active bookings or completed bookings, and thus use the appropriate service to handle them. For example, now all the unrated bookings for a customer (which are essentially completed bookings) are getting served by the Booking History Service. Driver Feedback Service now only receives the driver ratings, calculates the average rating for a driver and serves it to the driver app.</li></ol><p>Finally the following architecture was arrived at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5-q3JLQjJjyez3JqvSFpw.png" /><figcaption>P.S. Driver Active Bookings are still getting served from a synchronous system for the fear of reallocating an already allocated driver in times of incidental delays in the event bus</figcaption></figure><p>Ha!! This looks better. 😅</p><p>We tried to bring down the number of services as much as possible, by clubbing together the essence of features they served.</p><p>The Backend For Frontend is up for elimination too. Our older apps made a single backend call on order history screen to fetch both active and completed bookings for a customer. Once the app moves to different API calls, we can get rid of this proxy as well.</p><p>For the chat service, we allowed it to consume the booking events directly. We decided to skip the authentication of a driver or a customer for a given order, and rely on this event bus for this purpose.</p><p>Examining this ecosystem thoroughly also helped us to perform certain side tasks as a part of this migration. Firstly, we also moved all the products out of <em>stan-marsh</em>. This means we now have a log of all the bookings across multiple order management systems in the same event bus. Secondly, we managed to reduce the payload on the order history screen as well.</p><blockquote>Earlier, the API on the order history screen returned about 120 keys for every order. We brought it down to about 40 keys per order.</blockquote><h3><strong>Results</strong></h3><p>Our new system ensures consistency of data across the both the driver and customer applications. It is much more scalable, and for now, we have only two databases to manage. If we are to add a new feature, we have clear visibility as to which service should take it up.</p><p>As an added benefit, all our products now push events to the same event bus, thus creating uniformity across the GOJEK ecosystem. Also, reduced payload for the order history screen led to reduced complexity of logic on both backend and frontend.</p><p>So that’s the story of how we went from a messy system with multiple copies of data to a more streamlined one. Thanks for reading! ✌️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UMfKMvm9-j9lEu3mVUezmg.jpeg" /></figure><p>Scaling a Super App, that’s no easy task. Thankfully we have a lot of great teams that make it look easier than it actually is. We’re also looking to expand these teams. So if you’ve got the skills, we’ve got the challenges. Head over to <a href="http://bit.ly/2xA33WU">gojek.jobs</a> to see our open positions. Let’s make things official. 👍</p><figure><a href="http://bit.ly/2xA33WU"><img alt="" src="https://cdn-images-1.medium.com/max/892/1*PdKKvtpvxTQcbMlDvIlFzQ.png" /></a><figcaption>gojek.jobs</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81faae3f7a82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/the-data-dilemma-81faae3f7a82">The Data Dilemma</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>