<?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 Abdullah jaffer on Medium]]></title>
        <description><![CDATA[Stories by Abdullah jaffer on Medium]]></description>
        <link>https://medium.com/@abdullahjaffer96?source=rss-7f7a54778b72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ls3FoG21phRb8ed4Ziqo9w.jpeg</url>
            <title>Stories by Abdullah jaffer on Medium</title>
            <link>https://medium.com/@abdullahjaffer96?source=rss-7f7a54778b72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:45:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullahjaffer96/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[Deploying a Spring Boot Application to an EKS cluster with ECR]]></title>
            <link>https://medium.com/@abdullahjaffer96/deploying-a-spring-boot-application-to-an-eks-cluster-with-ecr-e9ced8707825?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ced8707825</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[ecr]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 00:17:52 GMT</pubDate>
            <atom:updated>2024-02-06T00:17:52.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*leKJn58Aif06s7Hk" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the name implies we will deploy a very simple Spring Boot app to EKS by doing everything from scratch.</p><p><strong>Prerequisites</strong></p><ol><li>Java 17</li><li>Maven</li><li>Docker</li><li><a href="https://eksctl.io/installation/">ekctl</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html?tag=buylocal0e8-20">kubectl</a></li><li>AWS CLI</li><li>An AWS account that you can connect to through the AWS CLI using a profile, here is a helpful <a href="https://dev.to/hmintoh/how-to-use-multiple-aws-accounts-with-the-aws-cli-3lge#:~:text=To%20switch%20between%20different%20AWS,variable%20to%20a%20different%20value">tutorial</a> to help you get started</li></ol><h3>Table of contents</h3><ol><li>Creating the Spring Boot App</li><li>Creating a container image from the Spring Boot Application</li><li>Uploading a custom image to ECR</li><li>Creating an EKS cluster</li><li>Deploying our ECR image to our EKS cluster</li><li>Cleanup</li><li>Summary</li></ol><h3>Creating the Spring Boot App</h3><p>Intialize a Spring application with <a href="https://start.spring.io/">https://start.spring.io/</a>, I choose JDK 17 with Spring Web as a dependency to define a Rest Controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AemR5D_K73DV8uxkMoeOg.png" /><figcaption>Image by author</figcaption></figure><p>Then we create a simple Rest controller to test out the application externally.</p><pre><br>package com.example.demo;<br><br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br><br>@org.springframework.web.bind.annotation.RestController<br>@RequestMapping<br>public class RestController {<br><br> @GetMapping(&quot;/hello&quot;)<br> public String ping() {<br> return &quot;Hello World&quot;;<br> }<br>}</pre><p>Run the application using the following command, then go to localhost:8080 to see it in action.</p><pre>mvn spring-boot:run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLvXGgFDq7uMTsaT13sN-A.png" /><figcaption>Image by author</figcaption></figure><h3>Creating a container image from the Spring Boot Application</h3><p>Now since Kubernetes requires containerised images, let’s do that.</p><p>First let’s create a Jar file from our project using the following command.</p><pre>./mvnw clean install</pre><p>This will create a Jar file in the <strong>target</strong> package after execution.</p><p>Let’s create a file named <strong>Dockerfile</strong> in the root of our project with the following content:</p><pre>FROM — platform=linux/amd64 eclipse-temurin:17-jdk-alpine<br>VOLUME /tmp<br>COPY target/*.jar app.jar<br>ENTRYPOINT [“java”,”-jar”,”/app.jar”]</pre><p>Now let’s run these commands at the root of the project.</p><pre>docker build -t myapp .<br>docker run -p 8080:8080 myapp</pre><p>and we see that the project still runs on <strong>localhost8080/hello</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6U2JkaYtSlg8uI87Ncfzyg.png" /><figcaption>Image by author</figcaption></figure><h3>Uploading a custom image to ECR</h3><p>We’ve prepped the image up and tested it works locally now we can move onto uploading it to ECR.</p><p>Let’s create an ECR repository, just go to <a href="https://console.aws.amazon.com/ecr/repositories">https://console.aws.amazon.com/ecr/repositories</a>.</p><p>Click the<strong> Create repository</strong> button, it will change the UI to a form that requires additional details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvuRh7aX-Ye2E3PTZPcQ_A.png" /></figure><p>Give your repository any name, I gave it <strong>main</strong>, keep your repository <strong>Private</strong> for the sake of this tutorial<strong> </strong>and then click <strong>Create repository</strong> with the default options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Fi8Op1WDeygbkCbkJpGnNg.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGsQgFVOBGkMubKjPDG-0w.png" /><figcaption>Image by author</figcaption></figure><p>Now we login to this private repository using the following command ( change the region and account id based on your own setup ).</p><pre><br> aws ecr get-login-password — region us-east-1 | docker login — username AWS — password-stdin your_account_id.dkr.ecr.us-east-1.amazonaws.com/main</pre><p>Now we change the tag of our local image by the following command:</p><pre>docker tag 3471b50cd9c9 your_account_id.dkr.ecr.us-east-1.amazonaws.com/main:version-1</pre><p><strong>3471b50cd9c9</strong> represents the local Image tag, you can find it using <strong>docker images</strong> command.</p><p>Finally we can use push this image using the following command, you can use any tag instead of <strong>version-1</strong>:</p><pre> docker push your_account_id.dkr.ecr.us-east1.amazonaws.com/main:version-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG4sLhu2j-5AwHEGDeufPQ.png" /><figcaption>Image by author</figcaption></figure><h3>Creating an EKS cluster</h3><p>Now the stage is set to create an EKS cluster and use this image.</p><p>Run the following command:</p><pre>eksctl create cluster — name personal — region us-east-1</pre><p>It will take a few minutes to create an EKS cluster, but in the End you should see the message<strong> EKS cluster “personal” in “us-east-1” region is ready.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A1l7_AHwDP1R1iid5J70A.png" /><figcaption>Image by author</figcaption></figure><p>Now let’s create a namespace.</p><pre>kubectl create namespace eks-demo-app</pre><h3><strong>Deploying our ECR image to our EKS cluster</strong></h3><p>Perfect, it’s time to add a Kubernetes resource. For this part we will use two simple files:</p><ol><li>A deployment file which points to our ECR image</li><li>A service of type LoadBalancer and network load balancer that .automatically creates a AWS application load balancer for us, we will point to port 8080 because that’s where our application runs</li></ol><p>Here are the files:</p><p><strong>demo-deployment.yaml</strong>, notice how we added the tag of our ECR image in <strong>spec.spec.containers.image.</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: demo<br>  namespace: eks-demo-app<br>  labels:<br>    app: demo<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: demo<br>  template:<br>    metadata:<br>      labels:<br>        app: demo<br>    spec:<br>      containers:<br>        - name: demo<br>          image: your_account_id.dkr.ecr.us-east-1.amazonaws.com/main:version-1<br>          ports:<br>            - containerPort: 80</pre><p><strong>demo-service.yaml</strong>, notice that we port forwarded port 80 to 8080 internally since this is where our application runs, we kept the service type load balancer and load balancer type network load balancer. This automacially provisions a AWS Network load balancer for us.</p><pre>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: demo<br>  namespace: eks-demo-app<br>  annotations:<br>    service.beta.kubernetes.io/aws-load-balancer-type: nlb<br>    service.beta.kubernetes.io/aws-load-balancer-internal: &quot;false&quot;<br>    service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: &quot;true&quot;<br>spec:<br>  type: LoadBalancer<br>  ports:<br>    - name: web<br>      port: 80<br>      targetPort: 8080<br>  selector:<br>    app: demo</pre><p>If you’ve successfully created these files, apply the following commands in your cluster:</p><pre>kubectl apply -f demo-deployment.yaml<br>kubectl apply -f demo-service.yaml</pre><p>Now use the following command to check status:</p><pre>kubectl get pods -n eks-demo-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*X6ylZ8L3Cw0JdN7p6j8nZw.png" /><figcaption>Image by author</figcaption></figure><p>If done correctly, the pods should be in the Running state.</p><p>Now use the following command to get the external IP:</p><pre>kubectl get svc -n eks-demo-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-TE3K0vDysVQSUixzzHGQ.png" /></figure><p>Now use that external IP in your browser to hit your API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_mfRONcp8fKgQDzFC2zag.png" /><figcaption>Image by author</figcaption></figure><p>We successfully got a response!</p><h3>Cleanup</h3><p>To avoid a 10,000 USD bill overnight run the following command to delete the EKS cluster:</p><pre>eksctl delete cluster --name  personal --region us-east-1</pre><p>Also delete the ECR repository.</p><h3>Summary</h3><p>This was a very bear brunt way to deploy a custom application to EKS and make it publicly accessible but it is enough for learning purposes I guess.</p><ol><li>We created a Spring Boot Rest API</li><li>Packaged it into a container and pushed to our private ECR repository</li><li>Created an EKS cluster, then created some Kubernetes resources that utilized our image to deploy our application</li></ol><p>Link for all the code examples and Spring Boot project: <a href="https://github.com/abdullah-jaffer/spring-eks-demo">https://github.com/abdullah-jaffer/spring-eks-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ced8707825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Spring Boot, Node with Express, and Django using Locust]]></title>
            <link>https://medium.com/@abdullahjaffer96/benchmarking-spring-boot-node-with-express-and-django-using-locust-3ca879a7738a?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca879a7738a</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 03:31:04 GMT</pubDate>
            <atom:updated>2023-01-14T03:52:09.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I88tlqO0oOFukSU3" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>When working with any product that is expected to scale, it is important to know if the underlying technology that will be used can handle the level of traffic which is expected from the product in the long run. To do that we need to set up a realistic environment that simulates the expected traffic.</p><p>This is commonly known as load testing. Here, we want to find out how the underlying web servers of these frameworks perform under different types of loads, we will do that using an open-source load-testing tool known as <a href="https://locust.io/">locust</a></p><h4>Web server</h4><p>A web server is a type of server that takes an HTTP request, processes it, and returns the HTTP response. One important distinction is that Frameworks are not web servers, Web servers pass requests to web frame frameworks for business processing but passing it over the network is their responsibility. What we are trying to test is the webserver + the framework base time to process the request.</p><h4>Load testing</h4><p>Load testing is a testing technique to test the performance of software applications when multiple concurrent users are using the application.</p><p>It is a non-functional testing technique but is also used to select appropriate technologies based on business needs.</p><h4>Locust</h4><p>Locust is a powerful open-source load testing tool that makes testing quite convenient by using simple python to simulate testing scenarios.</p><h4>Our Application</h4><p>As we are just testing how the web servers will perform, we will simply be creating a book entity and sending it as a response in the get request so the only overhead for the servers from the web frameworks is to parse the response object and send it back. Following is our entity:</p><pre>Book:<br>   title: title of book<br>   IBAN: iban number<br>   pages: pages in book</pre><h3>Setup</h3><h4>Spring Boot</h4><p><strong><em>Default Web Server:</em></strong> Apache Tomcat.</p><p>We initialized a basic spring boot app using the spring initializer with the spring-boot-start-web dependency which comes with the Tomcat server built in.</p><p>Following is the book class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c5da4d30d3d9373dad1a229e79acc17/href">https://medium.com/media/8c5da4d30d3d9373dad1a229e79acc17/href</a></iframe><p>Then we create and send a book object and on the controller we specified the book/ (GET) path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f98ff705cdd2b9299e479744e93d8894/href">https://medium.com/media/f98ff705cdd2b9299e479744e93d8894/href</a></iframe><h4>NodeJS and Express</h4><p><strong><em>Default Web Server:</em></strong> NodeJS is not a web server but rather a runtime environment that can be used to create a web server, and express is a backend web application framework. So in a way, we will be creating our own web server.</p><p>Here we imported express and started listening on port 8081, and sending a book object on the url: /book/ (GET)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b21e81529d908350f7cc69a25648ecf0/href">https://medium.com/media/b21e81529d908350f7cc69a25648ecf0/href</a></iframe><h4>Django</h4><p><strong><em>Default Web Server:</em></strong> Django has an unnamed default web server which is not for production as it is not tested and is just meant for development work, a fairer comparison would be to set up a production server but for now we will just test out the default web server and see how it does.</p><p>We’ve created a simple class for a book that also has a function to serialize into JSON.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2540b59cb38aa788e57d22bf69a4b3/href">https://medium.com/media/3f2540b59cb38aa788e57d22bf69a4b3/href</a></iframe><p>Here we create a book object and simply send it after serializing to json.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa6afeb2408266a082a1b19e9c55af4/href">https://medium.com/media/4fa6afeb2408266a082a1b19e9c55af4/href</a></iframe><p>In Django, URLS definitions are decoupled from views/controllers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/049f221e7c6020f764881c2e0e016ae2/href">https://medium.com/media/049f221e7c6020f764881c2e0e016ae2/href</a></iframe><h3>Setting up locust</h3><p>Locust is straightforward to setup, we run the following command to install locust</p><pre>pip install locust</pre><p>Then we will define a simple task that will call the book endpoint, locust is a lot more configurable with a lot of scenarios we can define against multiple tasks but for the scope of this article, this is enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a5c00a0cb16c8c95a1302b9c156c12f/href">https://medium.com/media/9a5c00a0cb16c8c95a1302b9c156c12f/href</a></iframe><p>Run the following command in the directory where you saved the locust.py file</p><pre>locust</pre><p>Then we should get this nice looking UI on localhost:8089</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YET-Nmcfl1X2mS9Lbsqs3w.png" /><figcaption>our base setting( Image by author )</figcaption></figure><p>In locust we can specify a lot of settings, I will briefly explain each setting</p><p><strong><em>Number of users</em></strong> is the peak number of concurrent users we want in our system<br><strong><em>Spawn Rate</em></strong> is the number of new users that will be spawned until we reach the peak concurrency.<br><strong><em>Host</em></strong> is the base URL.<br><strong><em>Run time</em></strong> specifies how long we want this test to run, if not set, the test will not stop until you explicitly reset.</p><p>In the coming sections, we will only be changing the base URL</p><h3>Load testing with 100 concurrent users</h3><h4>Spring boot results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO0QSgflZ83t8FumB295aQ.png" /><figcaption>Image by author</figcaption></figure><p>This shows a lot of different stats, the important ones being the Current RPS(Request per second) and the 99% percentile request latencies. This essentially means that on traffic of 200 concurrent users, the 99% percentile latency is 620 seconds which is quite good for a single server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giLHgCac8RBgTuKZheD6jQ.png" /><figcaption>Image by author</figcaption></figure><p>Request per second stayed at an average of 300 per second, the important thing to note is that a single user can make more than one requests per second so the number of users != requests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyrSVjadGIKOnYMb63F48A.png" /><figcaption>Image by author</figcaption></figure><p>Median response time was fairly good at 310 ms and 95% was slightly behind with 100 ms. There is also an odd spike of 95% in a specific interval.</p><h4>NodeJS and Express Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qXPvP1S1T2WAyL2R_70wA.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7UV59h3Ze5A5HvUjaFjGA.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xsV4MHu7pquHgun3Fj-TA.png" /><figcaption>Image by author</figcaption></figure><p>99% for Node was better than Spring boot for json based parsing at least most likely due to a spike on the Spring boot side.</p><h4>Django Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDmsH9oUiOAShzQJhOcEAg.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-k-XMGU1LWDfcipdG79IuQ.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ALG8hA893nzkdMT5K2gaw.png" /><figcaption>Image by author</figcaption></figure><p>Django seemed too far the worst with 740 ms 99% percentile latency and relatively high response time but it is expected as this is a nonproduction-ready web server.</p><h3>Which web server will degrade first?</h3><p>Apache Tomcat can support up to 200 concurrent users, our custom nodejs should be close to this, maybe even better. Let’s test this out. Let us ask a question:<br>How many concurrent users does it take for the webserver to degrade to 1000 ms latency? 1000 ms –1100 ms is the type of latency up for optimization when it is found in web servers so let’s test how many users trigger this for each stack.</p><h4>Spring Boot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFpVE0_1ce88WRY2cjGL_Q.png" /><figcaption>Image by author</figcaption></figure><h4><strong>NodeJS and Express</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZw3xooagYT0EhdeIsdnhw.png" /><figcaption>Image by author</figcaption></figure><h4>Django</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3SpSfEoVi76gF67MrRDIA.png" /><figcaption>Image by author</figcaption></figure><p>Spring boot reached a Median response time of 1100 ms at 355 users. It took 365 concurrent users for a node to do it and surprisingly Django is not far behind with 340 users.</p><p><strong><em>Node takes less time to degrade in terms of median, Even 10 more concurrent users per second can translate to 20 RPS which means 1200 RPM more which is a big number for early-stage products. But the median is not an accurate representation of growth.</em></strong></p><p><strong><em>If you notice, Spring boot won when it came to the 95% percentile latency which was 1400 ms compared to nodes&#39; 1600 ms. And the 95% percentile is a much better indicator of performance.</em></strong></p><h3>Conclusion</h3><p>In a real production environment, there are a lot more factors that come into play, especially the database.</p><p>This was just a light tool to test out the base load each framework could support and to introduce a neat little testing framework.</p><p>What matters most is that we take these numbers and proactively identify bottlenecks and limitations.</p><h4>Links and References</h4><ol><li>Code: <a href="https://github.com/abdullah-jaffer/load-testing-webservers">https://github.com/abdullah-jaffer/load-testing-webservers</a></li><li><a href="https://locust.io/">https://locust.io/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca879a7738a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Evolution Part 2: Ways to evolve schema to handle scale]]></title>
            <link>https://medium.com/bazaar-tech/schema-evolution-part-ii-ways-to-evolve-tables-to-handle-scale-2cc0b8ccd26a?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc0b8ccd26a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 09:30:09 GMT</pubDate>
            <atom:updated>2022-07-13T09:11:21.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*kFDfTOXb8zS3cZZuCO05kg.png" /><figcaption>Image<a href="https://phoenixnap.com/kb/database-denormalization"> source</a></figcaption></figure><p>A while back at Bazaar we ran into an interesting problem, we needed to introduce a new level of granularity to our existing database schema to support a new feature, what this usually translates to is adding another table and introducing a one-to-many relationship to support the new layer of granularity.</p><p>But it was not so simple at the scale we were at, we already had a lot of tables and joins on tables required to perform lookups for this specific use case, adding another table onto that existing schema might become a bottleneck, especially when we were already stretched in terms of latency for the APIs that will use this new feature.</p><p>In this article, I’ll explain how we evaluated different approaches and what approach we decided to go with. Read part 1 of this series to find out how to evolve indexes in your schema along with change requests</p><p><a href="https://medium.com/bazaar-tech/database-evolution-part-1-evolving-indexes-72b469e7785f">Database Evolution Part 1: Evolving indexes</a></p><h3>Scope</h3><p>While discussing these approaches we were only considering them from the lens of the database layer which was a relational database in our case, so the solutions presented here are within that scope only.</p><h3>Context and Current Structure</h3><p>First I will explain the schema which we needed to navigate around. This is not the actual schema for confidentiality reasons but it has a very similar context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*pK0UizPo5daNS-cP6_Q1AQ.png" /><figcaption>Image by Author, made with <a href="https://app.diagrams.net/">draw.io</a></figcaption></figure><p><strong>Product<br></strong>Represents global product attributes such as title, size, type of product, etc.</p><p><strong>Category<br></strong>The category of the product, products for a specific category are fetched</p><p><strong>Batch</strong><br>The batch here represents properties such as batch age, and quantity</p><p><strong>Batch_City<br></strong>Represents city-level batch properties, such as pricing</p><p>The parent table in this relationship is the<em> Product</em> while the most granular table here is <em>Batch_City. Batch_City</em> represents the properties of the product batch on a city level.</p><p><strong>Batch_City Schema</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUpJhDLWagLokn_emrO5AQ.png" /><figcaption>Image By Author</figcaption></figure><h3>Behavior required</h3><ol><li>We need another further level of segregation called <strong><em>customer_cohort.</em></strong></li><li>Each batch can be in multiple <strong><em>customer_cohort</em></strong>.</li><li>Each batch can have different <em>price_actual</em> and <em>price_discounted</em> based on <strong><em>customer_cohort</em></strong> and city.</li></ol><h3>Approach 1: Split Batch_City into two tables</h3><h4>Updated Batch_City table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FasRTZluOVjb8ONsIpFfMg.png" /><figcaption>Image By Author</figcaption></figure><h4>New Batch_City_Price table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*z5jZkgJxsdz0cLxA0XHGAA.png" /><figcaption>Image By Author</figcaption></figure><h4>Positives of this approach</h4><ol><li>Easily Searchable, filterable</li></ol><h4>Side-effects of this approach</h4><ol><li>Requires joins every time we need to get prices and cohorts for a product batch.</li><li>On top of adding an additional join, this style of scaling is not ideal as any new type of segregation will require adding another table with joins whenever filters are required on that level.</li></ol><h3>Approach 2: Put Customer_Cohort level information in a JSON field</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvcTfk5z-dMDfFFzgPEBpw.png" /><figcaption>Image By Author</figcaption></figure><h4>Positives of this approach</h4><ol><li>Can avoid extra join.</li><li>By having different JSON fields for customer_cohorts and pricing we can do less JSON parsing and lookup if we only need available cohorts for a batch.</li></ol><h4>Side-effects of this approach</h4><ol><li>Difficult to search and index since indexes on JSON are not supported out of the box in the database we were using, <em>MySQL</em>.</li><li>We have to parse JSON for every product to get its cohorts and prices on each lookup.</li></ol><h3>Approach 3: Denormalisation</h3><p>Some of you might have predicted this as a possible approach, since it’s in the title, and this is what we went with. The idea was to denormalize the <em>batch_city</em> and for every batch, city combo, there would be a new row for a <em>cutomer_cohort</em> that is added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X32NR4bnlmxzChQx5pVRXg.png" /><figcaption>Image by author</figcaption></figure><h4>Positives of this approach</h4><ol><li>No joins.</li><li>Can keep on adding further segregation levels without much effect on latency as that can keep catered with composite indexes( Increasing space requirements ).</li><li>Ability to <em>rollback</em> in case a segregation level is not required. For example, choose a source of truth <em>customer_cohort</em>, like GENERIC, delete rows for all other cohorts, then delete column <em>customer_cohort.</em></li></ol><h4>Side-effects of this approach</h4><ol><li>Exponentially growing vertical table as new customer cohort or another filtering column for a product is added and thus increasing storage requirements.</li><li>Increased complexity in application code since all updates and insertions in denormalized tables must be catered to differently.</li></ol><h3>Approach 3.1: Division into data and filtering tables</h3><p>Dividing the denormalized <em>batch_city</em> table into a filtering table called <em>batch_city_search</em> and a data table called<em> batch_city_data</em> table, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBOLToPoz_4_DmuZblmlng.png" /><figcaption>Image by Author, table 1 is <em>batch_city_search </em>and table 2 is <em>batch_city_data</em></figcaption></figure><h4>Positives of this approach</h4><ol><li>Only one-to-one joins</li><li>Easy to add a new <em>batch_city_data </em>row and a new column in the <em>batch_city</em>_<em>search</em> table</li><li>Reusable data rows</li><li>By vertically slicing some columns and then compressing them(through reuse) we can mitigate storage requirements somewhat.</li></ol><h4>Side-effects of this approach</h4><ol><li>Exponentially growing vertical table as a new filtering column for a product is added, this would still remain a concern.</li></ol><h3>Approach 3.2: Opus Magnum, single columns</h3><p>By converting our data table columns into random strings by passing them through a hash and storing the hash string of these columns as a single column we save up space even further.</p><p><em>encode(batch_city_data_fields) = hash_result</em></p><h4>Positives of this approach</h4><p>Further mitigates storage issues by having only one column</p><h4>Side-effects of this approach</h4><p>Complex application code.</p><h3>Final Approach</h3><p>In the end, we decided to go for approach 3, not including 3.1 or 3.2, since storage was not that much of a concern for us at the time, so we put off storage optimizations to a later time if storage constraints become a legitimate issue.</p><h3>Disclaimer:</h3><p><a href="https://www.bazaartech.com/"><strong>Bazaar Technologies</strong></a> believes in sharing knowledge and freedom of expression, and it encourages it’s colleagues and friends to share knowledge, experiences and opinions in written form on it’s <a href="https://medium.com/bazaar-tech">medium publication</a>, in a hope that some people across the globe might find the content helpful. However the content shared in this post and other posts on this medium publication mostly describe and highlight the opinions of the authors, which might or might not be the actual and official perspective of Bazaar Technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc0b8ccd26a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bazaar-tech/schema-evolution-part-ii-ways-to-evolve-tables-to-handle-scale-2cc0b8ccd26a">Database Evolution Part 2: Ways to evolve schema to handle scale</a> was originally published in <a href="https://medium.com/bazaar-tech">Bazaar Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Evolution Part 1: Evolving indexes]]></title>
            <link>https://medium.com/bazaar-tech/database-evolution-part-1-evolving-indexes-72b469e7785f?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b469e7785f</guid>
            <category><![CDATA[index]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[evolution]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Mon, 09 May 2022 05:04:03 GMT</pubDate>
            <atom:updated>2022-05-12T05:16:23.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_91hTE4UJL_ZvV-c" /><figcaption>Photo by <a href="https://unsplash.com/@bamin?utm_source=medium&amp;utm_medium=referral">Pierre Bamin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A significant thing to keep in mind when creating scalable software is that your database schema is your bread and butter, a system can only scale as much as the schema and storage engine allows it. This applies to indexes as well, an index created a long time ago based on a particular usage pattern might not be useful if the usage pattern and field cardinality has changed.</p><p>Indexes are our first and primary line of defense against scalability issues. So it is important to understand how to evolve them with your schema. Because indexes can always evolve, just like database schemas or software architecture.</p><h4>A brief summary of indexes and their need</h4><p>An index is a data structure used to reduce disk seeks when querying some records from a database, the trade-off is that they require extra storage and may increase write transaction latency.</p><p>The need for indexes is simple, as a business scales, data increases, and table lookups to access that data take longer, this is not scalable, we need a way to avoid disk accesses as much as possible and indexes are a very prominent and surefire way to accomplish this goal.</p><h4>A car sales use case</h4><p>Imagine you work for a company that advertises cars for sale. So far, the utmost priority for your business has been giving potential customers the ability to search cars by name and year, and compare the prices to make their bet. A schema for a table <em>car_make</em> would look something like this:</p><pre>+---------+---------------------+--------------+-------+<br>| make_no |        name         | release_year | price |<br>+---------+---------------------+--------------+-------+<br>|      11 | Audi R8             |         2008 | 20000 |<br>|      12 | Volkswagen Scirocco |         2018 | 10000 |<br>+---------+---------------------+--------------+-------+</pre><p>Following is the query most used to lookup car makes:</p><pre>SELECT name, release_year, price FROM car_make WHERE release_year = :year:</pre><p>We have an index on <em>release_year</em> and this has served us well so far.</p><p>Let’s assume the requirements have slightly changed and the business now wants support for a color filter as well, giving the users ability to search on both year and color at the same time:</p><pre>+---------+---------------------+--------------+-------+-------+<br>| make_no |        name         | release_year | color | price |<br>+---------+---------------------+--------------+-------+-------+<br>|      11 | Audi R8             |         2008 | white | 20000 |<br>|      12 | Volkswagen Scirocco |         2018 | black | 10000 |<br>+---------+---------------------+--------------+-------+-------+</pre><p>Now our query will look something like this:</p><pre>SELECT name, release_year, color, price FROM car_make WHERE release_year = :year: and color = :color:</pre><h4>The problem</h4><p>If we look at this query, now we have two filtering fields: release_year and <em>color</em>. This implies something about our data, now we can have <strong><em>multiple colors against a single release_year. </em></strong>This will decrease the lookup time of our index since the <a href="https://brilliant.org/wiki/cardinality/#:~:text=The%20cardinality%20of%20a%20set,elements%20that%20are%20in%20it."><strong><em>cardinality</em></strong></a> for <em>release_year</em> will drop.</p><h4>Composite indexes to the rescue</h4><p>A composite index is an index made as a combination of two or more fields. We get the following benefits when using a composite index.</p><ul><li>Fewer I/O operations than single index because of increased selectivity of the index.</li><li>Lower data retrieval latency.</li><li>Ability to index multiple fields instead of individual fields so the query optimizer does not have to choose which index to use(will expand on this below)</li></ul><h4>Proof of concept</h4><p>Let’s apply the index to our data using the below query:</p><pre>CREATE INDEX release_year_color ON TABLE car_make (release_year, color)</pre><p>Let’s test out this index on some sample data and analyze the query using the EXPLAIN keyword.</p><p>So these are our current indexes, as you can see we have the new composite index <em>release_year_color</em> added</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9lkg_QgWRo1s_Y2c-FORg.png" /><figcaption>image by author</figcaption></figure><p>Right now we only have two car makes, each with a unique year and color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wD1d8TBzStz8OlP3XVwaCg.png" /><figcaption>image by author</figcaption></figure><p>Let’s try out the query and analyze which index is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SjGLmXspFz0tyYFY9KkGw.png" /><figcaption>image by author</figcaption></figure><p>What’s this? the old <em>release_year</em> index was used, but why is that?</p><h4>Enter the query optimizer</h4><p>As SQL is a declarative language, we only provide the database engine with the set of instructions on what we need, and the execution plan is decided by the query optimizer, this involves several choices, but let’s focus on the ones relevant to our use case:</p><ul><li>Whether to use table scan or index scan.</li><li>Which index to use.</li></ul><p>So it’s apparent that the query optimizer decided that the <em>release_year</em> index is a better choice for this query, why is that?</p><p>This comes back to cardinality, if we look at our current data, we have<strong> 2 rows</strong> and cardinality for <strong>release_year = 2</strong>, this is as high as cardinality as we can get given the current data so the query optimizer felt no need to use the composite index as it would not provide any significant performance gains over the <em>release_year</em> index.</p><p>Remember our prediction that the <em>release_year</em> column will likely be repeated for new colors, in that case, the composite index will be used. Let’s test that out. This is our new sample data as per the predicted evolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suhCSh0XPtSoWx9DHGZSfA.png" /><figcaption>image by author</figcaption></figure><p>We just have a new car_make entry for each car but with a new color and same year. Let’s run the same query on this dataset and analyze it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6Aq5qNxSKNe0ErzHQWnhw.png" /><figcaption>image by author</figcaption></figure><p>It seems now the optimizer decided to go with our new index.</p><h4>Takeaway</h4><p>When you first introduce a new index, and it is not being used, you should question if the data will evolve to use the new index. If you’re certain, you can remove the old indexes or wait for the natural adoption of the new index.</p><h4>When NOT to use a composite index</h4><ul><li>Composite indexes significantly increase write latencies, so let’s say you have a logs table that has significantly more write operations than reads, indexing might not be a good option, It is better to have two versions of the log datastore, one optimized for writes and one for reads.</li><li>If the query using the composite index has very low usage frequency and you have to decide between another single field index with higher usage, then better to opt for a single field index. This comes down to usage patterns.</li></ul><h4>Composite index performance</h4><p>Let’s increase the data somewhat and check the difference between performances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOSJkOfs5Yk28mjIJdO-_w.png" /><figcaption>image by author</figcaption></figure><p>Using the <em>release_year</em> index we get 1.8 ms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_fzptVgFpitDhd9KSEGlQ.png" /><figcaption>image by author</figcaption></figure><p>Using the <em>release_year_color</em> composite index we get 1.6 ms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf_RXdeo3DZH6XsmHe4C5A.png" /><figcaption>image by author</figcaption></figure><p>Not much difference since this is a fairly small dataset, but even in such a small dataset, seeing any performance difference at all is a good indication.</p><h4>In conclusion</h4><ul><li>We discussed the importance of scalable schema design and how indexes can help achieve that.</li><li>We analyzed a car sale use case and understood when to go for a composite index.</li><li>We observed how the query optimizer decides which type of index to use based on cardinality.</li><li>We tested this out by customizing our data in a way that the optimizer would pick up our new index.</li><li>We contemplated when not to go for a composite index.</li><li>We tested out performance gains on a dataset that conforms to ur expected usage pattern.</li></ul><h3>Disclaimer:</h3><p><a href="https://www.bazaartech.com/"><strong>Bazaar Technologies</strong></a> believes in sharing knowledge and freedom of expression, and it encourages it’s colleagues and friends to share knowledge, experiences and opinions in written form on it’s <a href="https://medium.com/bazaar-tech">medium publication</a>, in a hope that some people across the globe might find the content helpful. However the content shared in this post and other posts on this medium publication mostly describe and highlight the opinions of the author, which might or might not be the actual and official perspective of Bazaar Technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b469e7785f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bazaar-tech/database-evolution-part-1-evolving-indexes-72b469e7785f">Database Evolution Part 1: Evolving indexes</a> was originally published in <a href="https://medium.com/bazaar-tech">Bazaar Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-Level Data Design Part 4: Stream Processing]]></title>
            <link>https://medium.com/@abdullahjaffer96/low-level-data-design-part-4-stream-processing-b613be855743?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/b613be855743</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 16:13:57 GMT</pubDate>
            <atom:updated>2022-01-08T16:18:03.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfOAISRNx-z6bqPe" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Stream processing was, still kind of is, a very mysterious topic for me. My experience was mostly in building web services and ETL pipelines. Good stuff but not as cool as real-time streams ( IMO ).</p><p>I had built applications that had some real-time events like social media post real-time updates and notifications count updating but I didn’t really understand how that worked.</p><p>There was so much I did not know related to the streaming world, events, pub/sub, message queues, brokers, log-based queues.</p><blockquote><em>I picked up a book that changed everything called</em> Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems by Martin Kleppmann</blockquote><p>A mouthful of a name, I know, but the book is really good! This went really into the low-level nitty-gritty of a lot of topics including streaming. I’ll share a very watered-down version of what was in the book.</p><p>Hopefully, after this read, you have a better understanding of stream processing and aren’t afraid of it anymore ( Like me :D ).</p><blockquote>Generally speaking, there are three types of systems that we can build.</blockquote><h4>1. Services</h4><ul><li>Returns a response on request from some client.</li><li>Main performance metric: response time.</li><li>Return a specific small subset of information based on request query.</li><li>Combination of one or more services used to serve an OLTP system.</li></ul><h4>2. Batch Processing Systems</h4><ul><li>Takes an input such as files and performs some job on them.</li><li>Main performance metric: throughput ( Time taken to process a fixed file size )</li><li>Can take anywhere from some hours to weeks, results not expected immediately.</li><li>Recommendation systems, Web indexing are good examples of batch processing use cases.</li></ul><h4>3. Stream processing systems</h4><ul><li>Near real-time systems.</li><li>Main performance metric: throughput (Byte rate, record rate for arbitrary time, etc)</li><li>Works like batch jobs but operates on events as soon as they happen and produces output to be consumed by something?</li><li>Very low latency.</li></ul><h4>What’s an event?</h4><p>Events are like the basic building block of streams, a small immutable object which can be a string, JSON object, or bytecode.</p><p>A stream is a collection of events, moreover, we have topics that are subsets of streams. An event can be viewing a page, pressing the like button ( Facebook ), sharing a post, sensor values, CPU utilization, etc</p><blockquote>Okay, How do we stream events?</blockquote><h4>Polling</h4><p>Polling is the middle child between traditional OLTP services and streaming. Because we take ideas from both types of systems and combine them. Here’s how it works:</p><ul><li>Store events in a datastore like normal records.</li><li>Have a consumer periodically check the data store for new records.</li></ul><h4>Issues with Polling</h4><p>The main problem with polling is that as soon as we go towards low delays between polls, as in moving towards <em>real-time streaming, </em><strong>the overhead becomes larger since the number of records you get is less but the compute cost for each poll call is the same.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Qk-jX2zpMdpTF8x86Sp_OA.gif" /><figcaption>Grandpa Simpson finds no events. <a href="https://knowyourmeme.com/memes/grandpa-simpson-walking-in-and-out">Credit</a></figcaption></figure><p>Imagine polling in during low usage with little or no events in the datastore, that’s wasteful overhead.</p><h4>Implementation</h4><p>Any database to store events like Postgres, MongoDB, and AWS Lambda, or GCP Cloud functions as triggers to consume events.</p><h4>Message Queues</h4><p>Now let’s talk about some closer to real-time streaming techniques. As we’ve discussed, polling for new events is inefficient, wouldn’t it be better if “consumers” could consume an event produced by a “producer” as soon as it happens by using some middleware in between? Kind of like a Pub/Sub system. It is possible and we can do it using a message queue.</p><ul><li>One or more producers adds events to a broker/queue.</li><li>These events can be filtered by topic.</li><li>Consumers consume these events asynchronously as soon as they are added to the queue.</li><li>This is great because we delegate the responsibility to add and remove events as soon as they are consumed to the broker, taking the burden of other services not meant to handle this, thus we can decrease the latency between event consumption by a lot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*CowZouL64RsUXn7Nv2GNyw.gif" /><figcaption>Gif by Author</figcaption></figure><ul><li>This streaming mechanism is based on the<a href="https://docs.oracle.com/cd/E19957-01/816-5904-10/816-5904-10.pdf"> JMS</a> and <a href="https://www.amqp.org/">AMQP</a> standards, these are implemented by <a href="https://www.rabbitmq.com/">RabbitMQ</a>,<a href="https://cloud.google.com/pubsub/docs/overview"> Google Cloud Pub/Sub</a>, <a href="https://azure.microsoft.com/en-us/services/service-bus/?&amp;ef_id=CjwKCAiA5t-OBhByEiwAhR-hm3Q0itOEAZPETtYARhnLpEUvlIaM2JYeKZHpolS4kgwqSMwfvp0-RxoCg-gQAvD_BwE:G:s&amp;OCID=AID2200233_SEM_CjwKCAiA5t-OBhByEiwAhR-hm3Q0itOEAZPETtYARhnLpEUvlIaM2JYeKZHpolS4kgwqSMwfvp0-RxoCg-gQAvD_BwE:G:s&amp;gclid=CjwKCAiA5t-OBhByEiwAhR-hm3Q0itOEAZPETtYARhnLpEUvlIaM2JYeKZHpolS4kgwqSMwfvp0-RxoCg-gQAvD_BwE">Azure Service Bus</a>, and a ton more.</li><li><strong>One bottleneck to keep in mind is that a message queue is not persistent and has limited capacity. </strong>We need to think about some throttling or rate-limiting mechanism in case producers give out messages faster than the consumers can handle.</li></ul><h4>Log Based Message Brokers</h4><blockquote>JMS/AMQP type brokers aren’t enough</blockquote><p>It seems like with JMS/AMQP type brokers, there is a tradeoff between latency and persistence. If we want to persist events, then we need to use a database but we will lose out on the streaming capability of Message brokers. This is quite a dilemma, what if we want to:</p><ul><li><em>Use old events to generate some derived data?</em></li><li><em>Add another consumer but consume older nonexisting events?</em></li></ul><blockquote>Luckily we have a solution with Log Based Message brokers.</blockquote><ul><li>A log is an append-only file.</li><li>Producers add events to logs and consumers consume these logs from the end.</li><li>We can add new consumers anytime have them consume old events.</li><li>We can even replicate and partition the logs into several machines for availability and performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*8f7rRYH4gabj4gcXXEYUeA.png" /><figcaption>Partioned logs based on topics. <a href="https://ebrary.net/64948/computer_science/using_logs_message_storage">Credit</a></figcaption></figure><ul><li><a href="https://kafka.apache.org/">Apache Kafka</a>, <a href="https://aws.amazon.com/kinesis/">Amazon Kinesis Streams</a>, and Twitter’s DistributedLog are log based message brokers.</li></ul><h4>Streams as a means to connect a product ecosystem</h4><p>Modern data products are not a monolith. They are distributed partitioned systems, that have many connected parts such as the main software application, several helping services, and Elastic cache for search, Redis cache, a recommendation system, payment services, analytics systems, in order for such a diverse ecosystem to communicate we need some real-time, persistent means to pass new information around. Streaming is a great means to accomplish this.</p><blockquote><a href="https://kafka.apache.org/">Apache Kafka is used by 80% of Fortune 100 companies</a></blockquote><h4>Ending notes</h4><p>After reading Martin Kleppmanns’ great book I realized these hard-to-understand streaming technologies are not as otherwordly as they seem and it’s just the lack of research and information that makes them intimidating. Hopefully you also now have the basic idea of how streaming works under the hood, next step would be choosing the appropriate technology that implements the streaming method you need and deep-diving into its utility for your business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b613be855743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-Level Data Design Part 3: Transactions and Isolation Levels]]></title>
            <link>https://medium.com/@abdullahjaffer96/low-level-data-design-part-3-transactions-and-isolation-levels-101b55321840?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/101b55321840</guid>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 20:01:55 GMT</pubDate>
            <atom:updated>2022-01-06T20:14:33.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mG0PBTDTYGhFvtnhJ_SjeQ.jpeg" /><figcaption>Image source: <a href="https://venturebeat.com/2021/01/25/what-is-database-as-a-service/">https://venturebeat.com/2021/01/25/what-is-database-as-a-service/</a></figcaption></figure><p>In this age where time is limited and the need to churn out useful products fast is growing, we need to delegate some responsibility of quality to already available tools so we can focus on the actual business problem at hand.</p><p>Building reliable software is hard, since there is no all-encompassing formula for success, engineers need to go back to the drawing board again and again. As such, it is important to be aware of the toolkit already provided in the technologies we use to churn out new features.</p><p>In this post, we will look at <strong>database transactions and isolation levels</strong>. A very famous backend topic that people are aware of at a theoretical level but seldom understand enough to realize its use cases in database systems.</p><p>Before we do that, we will look at issues data systems face that are hard to deal with to get a better sense of why we need to understand Low-Level Design in general.</p><h3>Issues faced by data systems</h3><p>There are several things that can go haywire in a software application:</p><ul><li>Hardware faults</li><li>Race conditions</li><li>Incomplete or partial data</li><li>Loss of data due to network failures</li><li>And many other issues</li></ul><p>We need some sort of mechanism to protect against such issues and maintain data quality to churn out reliable systems. Here’s where transactions come in.</p><h3>Transactions</h3><p><em>“A transaction is way to group several reads and writes into a logical unit. Conceptually, all the reads and writes in a transaction are executed as one operation: either the entire transaction succeeds (commit) or it fails (abort, rollback). If it fails, the application can safely retry. With transactions, error handling becomes much simpler for an application, because it doesn’t need to worry about partial failure transactions were created to simplify the programming model for database read and writes.” [1]</em></p><p>Transactions are a common mechanism to protect against the problems mentioned above and maintain data integrity in systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*5gVuYP1BFD4isubnW4cdng.png" /><figcaption>Image by Author, tool: <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>The <strong>commit</strong> in this sample query executes everything as one transaction before the previous<strong> commit </strong>or <strong>rollback</strong> command. [2]</p><p>Almost all databases implement transactions based on the style implemented by IBM system R, the first SQL database. [3]</p><h3>Transactions through the ACID rabbit hole</h3><p>The best way to look at the security guarantees promised by transactions is through the lens of ACID principles, ACID is an acronym for atomicity, consistency, isolation, and durability.</p><h4>Atomicity</h4><p>Atomicity means an operation that is in its smallest unit form and cannot be broken down.</p><p>In the context of transactions, it means an operation should be treated as a single logical unit <strong>even if it can be broken down conceptually</strong>.</p><p>This is implemented by allowing a complex operation such as a bank payment to be rolled back as if it is a single operation even though a payment involves many logical steps such as debiting, amount from user 1, crediting the amount to user 2, applying transfer tax, auditing, etc.</p><h4>Consistency</h4><p>In terms of transactions, consistency means there are some rules about your data that are invariant.</p><p>For a banking system, this means that accounts should always be balanced. This is up to each individual business to define what should be invariant in their case.</p><h4>Isolation</h4><p>Isolation is when several users accessing the database at the same time are reading/writing the same data but are unaffected by each other. That is that that the operation performed by one user does not affect some other. In programming terms, this means avoiding race conditions.</p><p>Lack of isolation results in a lot of the aforementioned issues related to consistency and atomicity.</p><h4>Durability</h4><p>Durability in the terms of transactions is that after a transaction is completed, its changes are safely stored in permanent storage. Perfect durability does not really exist because physical devices are not 100% reliable.</p><h3>Race conditions in transactions</h3><p>If the same data is accessed and modified at the same time, that can result in race conditions and concurrency issues.</p><p>One solution is to have<a href="https://www.tutorialcup.com/dbms/transaction-serializability.htm#:~:text=A%20transaction%20is%20said%20to,is%20equivalent%20to%20serial%20schedule.&amp;text=We%20can%20see%20that%20irrespective,hence%20these%20transactions%20are%20Serializable."> serializable transactions</a>, but this can have a performance cost that most databases do not want to pay. Thus most databases implement weaker forms of isolation that guarantee protection against some concurrency issues but not all.</p><p>It’s important to note that <strong>weaker isolation levels only make it seem like transactions are serial.</strong> We will look into some of them in detail.</p><h3>1. Read committed Isolation</h3><p>Read committed isolation in transactions means that the database guarantees two things, no dirty reads, and no dirty writes.</p><h4>1. Dirty reads</h4><p>If a transaction has written something in the database but has not yet been committed and other transactions can still view this uncommitted data, it is called a dirty read.</p><h4>2. Dirty write</h4><p>If transaction A changes a value in the database and it has not yet been committed but a transaction B modifies the same value but with the changes of transaction A included(even though it has not been committed) it is called a dirty write.</p><h4>Example of a dirty write</h4><p><strong>Context<br></strong>Assume we have a counter stored in the database about unread notifications in a message thread, the counter increments every time someone posts a message in the thread and tags User A. User A currently is being shown 10 notifications (10 new messages in the thread).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*MdzKoRlFDbneqa8gL_glIQ.png" /><figcaption>Image by Author</figcaption></figure><ul><li>User B sends a message to user A, message entry is saved and the counter for notifications is incremented but not committed.</li><li>Since the previous value was 10 notifications, the counter is incremented to 11.</li><li>User C sends a message to user A at the same time, the notification counter is incremented from 11 to 12.</li><li>Because the last counter increment was by user B but it was not committed this is a dirty write.</li><li>The actual increment should have visibly been 11 even if ultimately it would be 12.</li></ul><h3>2. Snapshot isolation</h3><p>For the most part, read committed handles most transaction issues a database may face.</p><ul><li>We can abort transactions(Atomicity)</li><li>Prevents reading incomplete transaction results.</li><li>Isolates concurrent writes.</li></ul><h4>Nonrepeatable read or read skew</h4><p>Read committed isolation does not protect against read skews, which is a one-time concurrency anomaly. For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZIE6bxjGtAbeoNAe3LNVA.png" /><figcaption>Image by Author</figcaption></figure><ul><li>User A has two accounts, with a balance of 500 each.</li><li>She transfers an amount of 100 from account 1 to account 2.</li><li>She views both accounts(two select queries executed for accounts 1 and 2 separately) while the transaction is taking place.</li><li>She sees 400 in account 1 and 500 in account 2 even though account 2 should have 600, this is because the transaction is still taking place.</li><li>This is a one-time anomaly since after a short while she will see 600 in account 2.</li></ul><h4>Why this is not a dirty read</h4><p>Assuming she reads account 2 while the transaction is taking place, read committed will show her 500, and then assuming she reads account 1 moments after the transaction takes place she will see a net negative amount of 400(even though the read operation began execution during the transaction). To user A, she just lost 100 dollars and this is acceptable in read committed.</p><p>Snapshot isolation solves this by reading from a consistent snapshot. It takes a snapshot of the database right when a transaction executes. Let’s assume a scenario to better understand this.</p><ul><li>User A has two accounts, with a balance of 500 each.</li><li>She transfers an amount of 100 from account 1 to account 2.</li><li><strong>A snapshot is taken as the transaction executes.</strong></li><li>She views both accounts(two select queries executed for accounts 1 and 2 separately) while the transaction is taking place.</li><li>Since the transfer transaction is still executing She sees 500 in account 1 and account 2 from the snapshot.</li><li>After a while, if she queries both accounts again, she will see 400 in account 1 and 600 in account 2.</li></ul><p>Snapshot isolation has completely removed the chance of a read skew.</p><h4>Snapshot isolation features</h4><ul><li>Snapshot isolation supported by Postgres, MySQL, Oracle, and SQL Server.</li><li>A key principle of snapshot isolation is readers never block writers, and writers never block readers.</li><li>Snapshot isolation uses multi-version concurrency control(MVCC) to have different ids for transactions(always increasing) to make sure everything is synced.</li></ul><p>There are some other interesting transaction issues out of the scope of this article but worth being aware of as an application developer.</p><ul><li>Write skews(happens on the application code side).</li><li>Lost Updates and phantoms.</li></ul><h3>References</h3><p>[1] <a href="https://www.amazon.com/Designing-Data-Intensive-Applications-Reliable-Maintainable/dp/1449373321">Designing Data Intensive applications by Martin Kleppmann</a><br>(Article based on Chapter 7 of the book)<br>[2] <a href="https://www.geeksforgeeks.org/sql-transactions/">https://www.geeksforgeeks.org/sql-transactions/</a><br>[3] <a href="https://en.wikipedia.org/wiki/IBM_System_R">https://en.wikipedia.org/wiki/IBM_System_R</a><br>[4] <a href="https://stackoverflow.com/questions/2741016/read-committed-snapshot-vs-snapshot-isolation-level">https://stackoverflow.com/questions/2741016/read-committed-snapshot-vs-snapshot-isolation-level</a><br>[5] <a href="https://stackoverflow.com/questions/11043712/what-is-the-difference-between-non-repeatable-read-and-phantom-read">https://stackoverflow.com/questions/11043712/what-is-the-difference-between-non-repeatable-read-and-phantom-read</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101b55321840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-Level Data Design Part 2: Database replication]]></title>
            <link>https://medium.com/@abdullahjaffer96/low-level-data-design-part-2-database-replication-6bdc78377546?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bdc78377546</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 14:06:41 GMT</pubDate>
            <atom:updated>2021-12-26T18:40:01.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSLsUZ3P_57wj8JYEYdPgA.png" /></figure><h3>What is database replication?</h3><p>Database replication is the act of having multiple copies of the same database on different machines communicating over a network.</p><p>Database replication is an important technique used by many popular database management systems. It is an important concept to prepare for System Design interviews as well.</p><p>Replication can serve many purposes such as:</p><ul><li>Having data geologically close to users ( High latency ).</li><li>Robustness against failure if one or two machines fail ( High availability ).</li><li>For scalability purposes, most notably increased read operations ( High write throughput ).</li></ul><h3>Replication schemes</h3><p>The main challenge in replicating the database across multiple nodes is figuring out how to propagate change across nodes. Replication usually involves leaders ( nodes that handle writes ) and followers ( nodes that copy from leaders ).</p><p>Based on the different strategies to handle change there are three schemes to design our replication schemes.</p><ul><li>Leader Based</li><li>Multi Leader Based</li><li>Leaderless</li></ul><h3>Leader Based Replication</h3><p>In this scheme, we have a single leader node also called master or primary node. The rest of the nodes are followers or slaves.</p><p>The reason we have a single leader node is that; if all the nodes started accepting write operations it would be difficult to keep them all consistent and up to date with the latest changes.</p><p>This means that certain users might receive obsolete information. On the other hand, users can read information from any follower granted the information is up to date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdK_wdioP_0kLSdXEr_prg.png" /><figcaption>Figure 1: An Async leader replication scheme for tweet posting</figcaption></figure><p>Thus it is critical that copying changes from leader to follower is handled correctly, there are two ways to propagate changes from leader to followers:</p><h4>Synchronous and Asynchronous replication</h4><p>In synchronous replication, the leader node waits for the information to be replicated in all the followers before sending back a successful acknowledgment to the user.</p><p>This guarantees that information is properly replicated in all followers but it is slow and not really practical to make users wait if we have many followers that need to read the information.</p><p>In asynchronous replication, as shown in Figure 1, the leader does not wait for changes to be reflected in followers. This means that some users might read information from a follower that has not yet reflected all the changes on the other hand this is much faster than synchronous replication since the Leader is not waiting for any followers.</p><h4>Benefits of single leader replication</h4><ul><li>Single leader replication is great for a system with a lot of reads but relatively few writes, like Google Maps.</li><li>Even if one of the followers crashes users are not affected and the failed follower can be restarted and synced with the leader using<a href="https://mesos.apache.org/documentation/latest/replicated-log-internals/#:~:text=What%20is%20the%20replicated%20log,fault%20tolerance%20and%20high%20availability."> replication logs</a>.</li></ul><h4>Issues in single leader replication</h4><ul><li>Dealing with failover in a single leader replication scheme is tricky. Failover is when the leader goes offline due to a crash or high bottleneck traffic, during this time, one has to decide the next leader from one of the followers which is a complex process to automate.</li><li>A failover can introduce a lot of problems such as split-brain whereas two followers think they are the new leader. This can cause hard to resolve conflicts as both nodes start accepting writes.</li></ul><h3>Multi Leader Replication</h3><p>A major issue in single leader replication is that in case of failover or unavailability of the leader node we can’t perform any write operations and have to wait for the new leader to be decided or the original leader to come back online.</p><p>This is not a major problem if we have a single data center where all are replicated database instances sit. This is because the lag to determine the new leader is not extensive enough to become an issue.</p><p>However, in a multi-datacenter environment having a single leader becomes a hindrance since we need a network to communicate the changes from the leader in one datacenter to followers in another datacenter.<strong> In that case, we can have a leader in each data center</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MbXj2DvoeE7yxw93MjWlg.png" /><figcaption>Figure 2: Multi Leader Data Center</figcaption></figure><h4>Benefits of multi-leader replication</h4><ul><li>Better performance since data centers can handle writes themselves sung their own leader.</li><li>Better tolerance for failover since even if a leader fails we have other leaders actively handling writes.</li></ul><h4>Issues in multi-leader replication</h4><ul><li>If the same data is modified in two leaders this can cause write conflicts which is not a problem that occurs in single leader replication.</li></ul><h3>Leaderless replication</h3><p>As the name implies, the leaderless scheme of replication does not have a leader.</p><p>It instead allows writes to any node. Initially used by data systems but forgotten after the explosive popularity of relational databases, it resurfaced in a <a href="https://www.dynamodbguide.com/the-dynamo-paper/">paper</a> by Amazon engineers about their in-house scalable key-value store Dynamo, afterward, it inspired many leaderless databases such as <a href="https://riak.com/">Riak</a>, <a href="https://cassandra.apache.org/_/index.html">Cassandra</a>, <a href="https://www.project-voldemort.com/voldemort/">VoldemortDB</a>.</p><h4>How does it keep replicas consistent?</h4><p>Instead of writing to dedicated leaders, a leaderless scheme writes to multiple nodes which are a subset of the total nodes. We can then read from a subset of the total nodes and return the information of the node <strong>that was most recently modified</strong>. While reading the information, we can determine which nodes have stale data and update them or a background process can run to check for stale nodes and do the same.</p><h4>How do we make sure our subset of read nodes are not stale?</h4><p>It is quite possible that the subset of read nodes <strong>r</strong> are not the same as the subset of write nodes <strong>w</strong>, this would mean that users would get old information that might not have yet been updated.</p><p>We can use the <strong>Quorum read and writes</strong>. Assuming we have <strong>n</strong> total nodes, <strong>w</strong> write nodes and <strong>r</strong> read nodes if we make sure <strong>w + r &gt; n</strong> we can mak sure at least one read node has the latest changes.Let’s visualize this through an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acypG_gn2PsDD46jIKNXXw.png" /><figcaption>Figure 3: Leaderless replication</figcaption></figure><p>let’s assume n = 3, w = r = 2, which satisfies our constraint that<strong> </strong>w + r &gt; n, in this case, even if we pick any 2 nodes, we can be certain that at least one of them has the latest data because we performed the write on 2 nodes and we have a total of 3 nodes.</p><p>The quorum setting is usually configurable in databases and a rule of thumb is to keep the n an odd number, make sure w = r = ( n + 1 ) / 2.</p><h4>Benefits of Leaderless replication</h4><ul><li>Leaderless replication does not have any failover.</li><li>Writes are not focused on one spot better write performance while not sacrificing read performance too much.</li></ul><h4>Issues in Leaderless replication</h4><ul><li>Deciding on Quoram value can be tricky and is hard to automate.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bdc78377546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-Level Data Design Part 1: Data Models]]></title>
            <link>https://medium.com/@abdullahjaffer96/low-level-data-design-part-1-data-models-f4a0a3c819ea?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a0a3c819ea</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dáta]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 19:35:17 GMT</pubDate>
            <atom:updated>2021-12-14T01:49:13.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*BVfELHUXHQkgF0QZzp7N9A.png" /></figure><h3>Need for understanding Low-level Data Design</h3><p>Low-level data design or <strong>LLDD</strong> is not something most engineers worry about since we have third-party tools that already have a well-tested implementation for most LLDD.</p><p>For example, we have popular storage systems like Postgres, MySQL, MongoDB, etc which have robust implementations for most core LLDD but it is important to understand that just like any design or architecture, each LLDD has its own advantages and disadvantages and different problems require different LLDD hence it is important to be able to evaluate the pros and cons of each of these options and choose the appropriate tool that implements them.</p><p>In the first of this 4 part series, we will look at LLDD from different angles starting from Data models.</p><h3>Data Model</h3><p>A data model is an abstract organization of data and standardization of how they relate to each other and real life.</p><h3>Significance of Data models</h3><p>When building any application or service, choosing a datastore with the data model that fits your needs is critical. Not only is our solutions constraints dependant on that but it influences <strong>how we think about the problem at hand.</strong></p><p>We will look at 3 of the most used data models types listed below and evaluate the situation in which they are most appropriate.</p><ul><li>Relational Model</li><li>Document Data Model</li><li>Graph Like Data Models</li></ul><h3>Relational Model</h3><p>As the model behind relational databases, the relational model was created to model business processes and transactions. First described by Edgar F. Codd in 1969 it has found its uses in many other domains such as social media, Saas products, and healthcare. It has become one of the most commonly used data models in software engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1I2jE13Kd9s-_LVZf7J6GQ.png" /><figcaption>Figure 1: <a href="https://www.holistics.io/blog/top-5-free-database-diagram-design-tools/">https://www.holistics.io/blog/top-5-free-database-diagram-design-tools/</a></figcaption></figure><p>Figure 1 showcases a relational model-based datastore in which we model relationships between different entities such as products orders and users. Data is stored in a collection of records(tuples) called tables. There is no nesting</p><h4>Pros</h4><ul><li>Hides a lot of the inner complexities of storing and retrieving data.</li><li>Uses SQL, a declarative query language that is intuitive and easy to understand.</li><li>Great support for joins, many-to-one, and many-to-many relationships.</li><li>Since SQL is a declarative language, it uses the most optimized way to access the required data automatically using whatever index is appropriate.</li></ul><h4>Cons</h4><ul><li>There is an <strong>Object-relational mismatch </strong>about<strong> </strong>how data is represented in code paradigms like OOP and the database which can be confusing and requires a complete ORM to properly translate information between application code and the database.</li><li>Due to the relational models&#39; preference to shred a collection of entities into tables and normalize data, we need to use database joins which is not very performant in cases where data in our system is really interconnected and requires more complex code to perform CRUD operations.</li><li>The relational model imposes a strict schema and is not very flexible which is great for business transactions but not for less restrictive use cases.</li></ul><h4>Technologies</h4><p>Postgres, MySQL, SQL Server, Amazon Aurora, Redshift</p><h3>Document Model(NoSQL)</h3><p>The document model arose due to a need for more flexibility and the popularity of open-source software. It stores data in JSON-like objects that can be nested.</p><p>A NoSQL representation of a Linkedin profile in a JSON document would look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*xMk2MS40H5FaZuRVFlg2gQ.png" /></figure><p>For things like Linkedln profiles that have strong locality, the relational model is not suitable as it would impose shredding all this information into separate tables and combining them using JOINS every time some loads a profile.</p><p>NoSQL model is a much better model for this use-case due to nesting capabilities.</p><h4>Pros</h4><ul><li>Data locality(And hence performance) and flexible schema.</li><li>Easy to translate from code to schema and vice versa due to JSON structure hence reduction of impedance mismatch.</li><li>Better write throughput</li></ul><h4>Cons</h4><ul><li>Many-to-One and Many-to-Many relationships are not easy to implement in NoSQL data models.</li><li>Poor Joins support.</li><li>Cannot refer directly to a nested object in a NoSQL database, rather we need to refer to the parent document to get to the nested information, this becomes an overhead if we have deep nesting.</li></ul><h4>Technologies</h4><p>MongoDB, DynamoDB, DocumentDB, Couchbase, Cassandra, RavenDB</p><h3>Graph Like Data Models</h3><p>Many-to-one and Many-to-many relationships are good distinguishing factors between data models. Document models do not handle many-to-many relationships very well, the relational models can implement simple use cases of many-to-many relationships very well but graph-based data models are a good use case for handling this case, these types of models are used by Facebook(friends group), Google(Maps), Uber(Tracking), and many other companies.</p><p>A graph consists of edges(Nodes, Objects) and vertices(relationships). Good uses cases for graph models would be social graphs, ride-hailing, and rail networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IcOEY5-NeRTIieeaySRPw.png" /><figcaption>Figure 3: Represents an arrangement of psychology research and conferences in a graph like model</figcaption></figure><h4>Pros</h4><ul><li>Great for mapping many to many relationships and when everything is potentially related to everything else.</li><li>Can make relationships weighted for computational purposes.</li><li>Lots of searching algorithms exist to explore and fully utilize a graph model.</li></ul><h4>Cons</h4><ul><li>Very specific use case.</li></ul><h4>Examples of specific graph models</h4><p>1. Property Graph<br>2. Triple Store model</p><h4>Technologies</h4><p>AWS Neptune, Neo4J, IBM Graph, FaunaDB</p><h3>Reference</h3><p>Inspired by <a href="https://www.oreilly.com/library/view/designing-data-intensive-applications/9781491903063/">Designing Data-Intensive Applications</a>, chapter 2</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a0a3c819ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technicians vs Engineers: What do tech companies want more?]]></title>
            <link>https://medium.com/@abdullahjaffer96/technicians-vs-engineers-what-do-tech-companies-want-more-d79bee1e7444?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79bee1e7444</guid>
            <category><![CDATA[technical-excellence]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 23:32:19 GMT</pubDate>
            <atom:updated>2021-10-24T23:35:39.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7mOtUNj8G9mSrgb" /><figcaption>Photo by <a href="https://unsplash.com/@lorenzoherrera?utm_source=medium&amp;utm_medium=referral">Lorenzo Herrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The observation</h4><p>A few months ago I was watching a live interview of some industry leaders in the tech industry. During that session, one of the tech leaders on the panel lamented the lack of ‘engineers’ in their organization, they highlighted how most engineers tend to become hyper experts in a specific tech stack rather than being all-rounded software engineers, and it seems that opinion resonated with a lot of the other industry leaders in that interview.</p><p>This is an interesting topic, that I did not much pay attention to. Let’s dissect what this means and how an engineer falls into one of these buckets.</p><p><strong>The software engineer</strong></p><p>After some Googling I found this definition of a software engineer:</p><p>“A <strong>software engineer</strong> is a person who applies the principles of software engineering to design, develop, maintain, test, and evaluate computer software.”</p><p>There key takeaway in this definition is that software engineers apply the principles of software engineering in various levels of their work.</p><p>What are these software principles? Analyzing these principles individually is out of the scope of this article but to describe it very briefly, software engineers apply very formal processes to each of their activities and validate their results. They take huge considerations in designing software and consider all trade-offs of their chosen technique and then choose the tech that is best for the job.</p><p>Coding is essentially only a small part of what they do. Software engineers are definitely not <a href="https://en.wikipedia.org/wiki/Code_monkey">code monkeys</a>.</p><p><strong>Generalists != Software Engineers</strong></p><p>Generalists are usually people that do not stick with one tech for a long time and are continuously shifting. This does not make them a technician but this also doesn’t automatically put them in the software engineer bucket either. They might still not be properly following any formal software engineering principles or making novel design decisions.</p><p><strong>The Technician</strong></p><p>There’s no formal definition for the type of technician I am about to define. If you do search up a “Software technician” you will find that it most commonly refers to an IT specialist, which is not exactly what we’re talking about so we’ll stick with just “technicians”.</p><p>A technician in the context of this article is someone that is extremely well versed in the tech stack they work in, this might be React, Django, Laravel, or some other framework. All their design decisions are grounded within the limitation of the tech they excel at. This can be great because tech-specific implementations are usually well tested, for the most part, it can, however, be a bottleneck if the technology is not the best fit for the task at hand.</p><p><strong>Crashcourse to becoming a technician</strong></p><p>Let’s say you’re fresh out of college, you learned several seemingly important topics in computer science such as software engineering, data structures, algorithms, functional and, object-oriented programming, database concepts.</p><p>You start your job, you find frameworks like Angular are really great because they’ve already imposed a certain set of rules on you that conform to some architecture you studied about, like MVC, it saves you from coding out the entire flow from scratch.</p><p>You’re spending more time learning about core Javascript and advanced Angular. It’s been a while since you’ve solved a coding problem or implemented a design pattern, most of that stuff has already been implemented by other great engineers. Your job is just importing it and making it work.</p><p>You recently implemented a complex data query feature. You did not find any package or Angular based implementation for that specific use case so you quickly coded up a brute force solution since you were low on time and you couldn’t think of a better way to do it, but it should be fine. it worked on staging.</p><p>Some trouble just happened, that feature completely crashed on production, turns out it didn’t scale well to deal with a very large number of concurrent repeated read requests to the database. Turns out you needed to implement some caching mechanism to make that feature scale. Oh well.</p><p>Ever since you’ve shifted to a senior position this has been happening more frequently. People ask you for specific high-level design feedback, it’s been a while since you’ve brushed up on any theoretical knowledge. You didn’t think about it much, but due to time pressure you needed to focus on the work at hand, now it’s becoming a problem at this stage of your career, you’re unable to give advice about anything outside of Javascript and Angular, but alas this is what you’re good at. This is who you are now.</p><p><strong>Why you shouldn’t “just” be a technician</strong></p><ol><li>Being good at specific tech confines your analytical thinking within a box defined by that stack</li><li>It makes it difficult to transfer skills from one tech to another.</li><li>You stop evaluating design and architecture from a high-level perspective hindering your growth.</li><li>You lose out on growth opportunities in the long run.</li></ol><p><strong>Why you might still become a technician</strong></p><ol><li>It makes you more productive short term.</li><li>Companies hire primarily based on your experience in a specific stack. So it leads to more opportunities early to mid-career.</li><li>Most of the work in tech organizations can be done by technicians.</li></ol><p><strong>How tech companies can attract more engineers</strong></p><p>People are usually reactive, devs are no different, we do what we need to do so that we land our dream jobs. When jobs require experience in very specific stacks, devs will spend more time becoming technicians to meet those requirements. Opening up more positions for generalists with a focus on core data structures and system design in interviews might be a good way to attract software engineers that spend a good chunk of their time contemplating the design and architecture of their solution independently of the technologies they use. FAANG companies have a good approach to this.</p><p><strong>What do tech companies want more?</strong></p><p>Well, let me just state that this article and my upcoming opinions are based solely on my limited observation within a very short career of 1.5 years in the industry with no data to back it up so read on your own violation.</p><p>I think based on what I’ve written already you’ve already inferred my opinion, companies want engineers a lot more than technicians. Although based on job posts it might seem like they want hardcore technical experts. Some companies have softened this requirement and allow you to apply as long as you are also a great technical expert in one of the multiple tech stacks of their choice so there’s that, At least you have that option.</p><p>There are also some companies that really don’t care about your tech expertise as long as you’re a great engineer but those are rare and their criteria to identify great engineers is a bit ambiguous at best.</p><p><strong>Final advice</strong></p><p>Aim to be a “T shaped’ engineer, be good at at least one tech stack to get relevant job opportunities but don’t go too in-depth in any other tech stack if it takes away from your time from learning other useful but late-blooming skills like design patterns, system design, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79bee1e7444" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning UseContext, UseReducer, and Custom hooks in ReactJS by Building a Dark Mode Toggle]]></title>
            <link>https://medium.com/@abdullahjaffer96/learning-usecontext-usereducer-and-custom-hooks-in-reactjs-by-building-a-dark-mode-toggle-39c7e211d9ab?source=rss-7f7a54778b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c7e211d9ab</guid>
            <category><![CDATA[dark-mode]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Abdullah jaffer]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 20:23:13 GMT</pubDate>
            <atom:updated>2021-08-15T20:23:13.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c96m8y-q4qU8FSw-" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I was a beginner in ReactJS and even well into my first few months as a professional frontend engineer, the only things I thought I needed to use were:<br> 1. Two hooks: UseState for component level state management and UseEffect for side effects. <br>2. Redux for global state management</p><p>Both these hooks and redux are versatile tools that can be used in almost all development situations but I quickly noticed that relying solely on these lead to messy and over-engineered code, I was managing several states related to a single component independently and it felt like using Redux for a simple login validation flow was becoming overkill.</p><p>After a while, I realized that this was because I was unaware of the different built-in tools/hooks in ReactJS that could help mitigate this problem, primarily UseReducer, UseContext, and the ability to create custom hooks. So I wanted to create this short article to demonstrate the usage of all these things through a common web use case to give a better idea of how they can be used together and really save you write easily maintainable code and avoid over-engineered solutions.</p><h3>UseReducer</h3><p>useReducer is an alternative to useState which is very similar to Redux. According to the official docs, useReducer is best used when you have a complex set of interconnected states that depend on each other.</p><p>It helps you keep complex states organized and keeps your code maintainable.</p><p>For simplicities sake, we will not be using multiple states in our reducer, instead, it will mostly be used as a demonstration on how to combine it with the UseContext Hook.</p><h3>UseReducer in our DarkMode Feature</h3><p>First, let’s define an initial state for our reducer. Think of it as the default state for a useState hook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQFxZ14rz5_cGWCnlvlppw.png" /></figure><p>Notice the export keyword, we’ll be keeping this in a separate constants folder so we need to export it, our initial state is set to the light mode</p><p>Next, we’ll define a reducer, which encapsulates how our reducer state is determined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3wV-nK1VhRkzVYdk-gvZw.png" /></figure><p>So when we receive an action, we decide the current theme accordingly.</p><p>And this is how we’re going to use this reducer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39lHD_-iqCyM5w4n1iERIQ.png" /></figure><p>Now we have access to our current state and we can use dispatch to ‘dispatch’ any changes to our reducer state. We will be using this state in our next hook called UseContext</p><h3>UseContext</h3><p>The UseContext hook is first and foremost, not a replacement for Redux, Redux is a global state management tool, UseContext is simply used to drill down props to child components without having to manually pass the props from parents to child components, all you need to do is just import the context and use it in your components.</p><h3>UseContext in our DarkMode feature</h3><p>First, we need to create a context instance for our Theme using the createContext method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_k0kQGaha_wRTkDzVwarA.png" /></figure><p>Great, we have a context object, and we have a reducer to manage our theme state, but how do we connect them?</p><p>First of all, it’s important to understand that the createContext is used to <strong>read the value of the context from the closest matching “provider” from the element tree above it.</strong></p><p>What is a provider? Well, we haven’t defined it yet but according to the React docs, “Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.”</p><p>This provider component also has a <strong>value</strong> prop, that is where we will pass our reducer state and dispatch. To make this all work, we’ll make a separate component to define our Theme context provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4phyWF_Da7gIS_ZZC6g2Q.png" /></figure><p>Let’s look at this code, we essentially:<br>1. Created a ThemProvider that initializes our reducer<br>2. Returns a Provider for the ThemeContext that we created.<br>3. Have added a value props for the Provider which will be used to pass our theme state and dispatch to the Context Hook</p><p>Let’s complete this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNxyYWOKO09dHnWpQaCzlg.png" /></figure><p>We have passed the state and dispatch function so that we can use and modify the state of the Theme reducer in child components for our dark mode trigger.</p><p>Notice the props.children as well, this is because we want the ThemeProvider to act as a parent component so it has to accept components as children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCw6u5xxV0H0CfE8LEfyfg.png" /></figure><p>We will make this ThemeProvider the parent of the main App component in our index.js file because we want the context to be available in all of our child components.</p><h3>Making a Custom Hook to Toggle Dark Mode</h3><p>Now that we have this all set up, we can just as easily use this to enable dark mode in our app but I want to go one step beyond, you see, accessing and updating the dark mode toggle is it’s on action that has to be triggered every time want to toggle state, instead of passing this logic to a button and duplicate that code in different components I want to make a custom hook to do this of us and just use that hook in different components.</p><p>Let’s define a very simple custom hook that simply has the useState hook to manage the theme state and takes a default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACDEu3jtPxqWC8US1bFfOg.png" /></figure><p>Looks simple but this isn’t connected to ur Theme Context, so let’s import our theme context</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhG0TsoeWkSsaTU_f8zzSQ.png" /></figure><p>Looks simple enough, but now we need to define the logic dispatch the change in state when our darkMode state is toggled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufWo1ZzngPW01p1JnXO74w.png" /></figure><p>Now we have the logic to dispatch the mode we want based on whether darkMode is true or false, now we can successfully read and update the dark mode toggle, but there’s still something missing.</p><p>How will we detect when the darkMode state changes? Of course, it’s using the setDarkMode method we pass to the components, they can simply use it to toggle state change but how will we actually detect the function call?</p><p>Well, that’s using the last piece of our puzzle, the useEffect hook, we will use the useEffect hook to detect changes in the darkMode state and dispatch the appropriate action accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxFVtOqEVeamSD2KdukBTQ.png" /></figure><p>Now our hook is ready to use!</p><h3>Our Theme Hook in Action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q92rxP83gR91rAUrWDuEYg.png" /></figure><p>Now we can simply call our custom hook in any component and use it to decide what styling we need to display, and can also use the setDarkMode button to trigger a mode switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Yg_5xjADHyqRBK0VYzEM7w.gif" /></figure><h4>Some tips on how to structure the code</h4><ol><li>Create a separate folder for constants and keep the initial reducer state there.</li><li>Separate the ThemeProvider and UseContext implementations into their own folders</li><li>Separate folder for the reducer and custom hooks respectively as well</li></ol><p>Here is the repository with all the code used in this tutorial:</p><p><a href="https://github.com/abdullah-jaffer/Dark-mode-hook-for-ReactJS">GitHub - abdullah-jaffer/Dark-mode-hook-for-ReactJS: A dark mode implementation for my article using a custom hook, useContext and, useReducer</a></p><h3>References</h3><ol><li>First and foremost, this article hugely paraphrases the context and reducer section from this article: <a href="https://www.section.io/engineering-education/dark-mode-for-react-app-using-context-api-and-hooks/">https://www.section.io/engineering-education/dark-mode-for-react-app-using-context-api-and-hooks/</a>, so please give them a read as they’ve done a really good job of explaining the concepts.</li><li><a href="https://reactjs.org/docs/context.html#contextprovider">https://reactjs.org/docs/context.html#contextprovider</a></li><li><a href="https://reactjs.org/docs/hooks-custom.html">https://reactjs.org/docs/hooks-custom.html</a></li><li><a href="https://reactjs.org/docs/hooks-reference.html">https://reactjs.org/docs/hooks-reference.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c7e211d9ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>