<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Tamerlan Gudabayev - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Tamerlan Gudabayev - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 15 May 2026 22:29:39 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/tamerlan-dev/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Set Up Application Performance Monitoring for Node.js Applications Using Elastic ]]>
                </title>
                <description>
                    <![CDATA[ Building features is half the equation of creating a successful product.  The other half is making something scalable and maintainable. One aspect of that is the ability to monitor your services.  This is what we will learn today using the help of so... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-monitoring-for-nodejs-applications-using-elastic/</link>
                <guid isPermaLink="false">66bb8c952108ff2ab9af167e</guid>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tamerlan Gudabayev ]]>
                </dc:creator>
                <pubDate>Mon, 07 Aug 2023 20:57:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/pexels-taras-makarenko-593172.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building features is half the equation of creating a successful product. </p>
<p>The other half is making something scalable and maintainable. One aspect of that is the ability to monitor your services. </p>
<p>This is what we will learn today using the help of software provided by Elastic. This is the company that originally made <a target="_blank" href="https://www.elastic.co/">ElasticSearch</a>, but which now provides a suite of different tools for search, observability, logging and much more. </p>
<p>For this article, we will specifically use the <a target="_blank" href="https://www.elastic.co/observability/application-performance-monitoring">Elastic Application Performance Monitoring</a> (APM) tool. </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-why-should-you-monitor-your-services">Why Should you Monitor Your Services?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-elastic-application-performance-monitoring">What is Elastic Application Performance Monitoring?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-up-apm">How to set up APM</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This article is strictly about Elastic APM. So, I assume you just want to connect it to your Node.js application. </p>
<p>I also assume you have Docker and Docker Compose installed locally and know how to use them. </p>
<p>You can find the code for this article <a target="_blank" href="https://github.com/TamerlanG/node-elastic-demo">here</a>. </p>
<h2 id="heading-why-should-you-monitor-your-services">Why Should you Monitor Your Services?</h2>
<p>If your software is successful (meaning you have users), then you may want to monitor your services for a few reasons.</p>
<p>Let's go over them in the following sections.</p>
<h3 id="heading-you-want-to-know-the-status-of-your-services">You want to know the status of your services</h3>
<p>If your services are down, you want to know about it first. You don't want your users to be the ones to notify you. </p>
<p>To help with that, you can add alerts based on some criteria, such as:</p>
<ul>
<li>If there are more than 10 status code 500 errors in the last 5 minutes. </li>
<li>If the latency of your services goes above some threshold (such as 1 second). </li>
</ul>
<h3 id="heading-you-cant-improve-something-you-dont-measure">You can't improve something you don't measure.</h3>
<p>If you want to optimize something, then you first have to measure it. </p>
<p>Find the hotspots and fix them. But to be able to find these, you must first monitor your services. </p>
<p>This will benefit you in two ways:</p>
<p>The first way is that you can define your SLOs (Service Level Objectives), which are goals that you would want to have for your services. </p>
<p>For example:</p>
<ul>
<li><strong>Uptime Objectives</strong> – I want my services to be up 99.9% of the time. </li>
<li><strong>Latency Objectives</strong> – I want the P99 (99th percentile) of my requests to be completed in less than 1 second. </li>
</ul>
<p>SLOs then help you define your SLAs (Service Level Agreements) which are promises you make to your customer. These promises increase the value that you provide to them. </p>
<p>Examples of SLAs include:</p>
<ul>
<li><strong>Uptime Guarantee</strong> – Our services will be up 99.9% of the time. If not, then we would refund you (Every company has their own refunding model – for example, AWS will give credits back for all the time affected, while other companies will simply reimburse you).</li>
<li><strong>Latency Guarantee</strong> – Our P99 is lower than 200ms. If not, then there will be repercussions. </li>
</ul>
<p>On to our final point. </p>
<h3 id="heading-metrics-dont-always-have-to-be-technical">Metrics don't always have to be technical</h3>
<p>We can measure user behavior. </p>
<p>Things such as how long they stay on a specific page or some domain level things which are special for the business. </p>
<p>These metrics allows us to make data driven decisions. </p>
<p>For example, if you see your users not completing some sort of form, then you would decide that there is something wrong with it and fix it. </p>
<p>Another example would be that if your landing page isn't making a lot of sales then you would decide to do something about it. </p>
<h2 id="heading-what-is-elastic-application-performance-monitoring">What is Elastic Application Performance Monitoring?</h2>
<p>Elastic Application Performance Monitoring  (APM) is a tool that is used to monitor your application built on top of the Elastic Stack. </p>
<p>Here are some of its features:</p>
<ul>
<li><strong>Real Time Monitoring</strong> – APM collects metrics on the fly, so you can see the status of your services in real-time. </li>
<li><strong>Detailed Monitoring</strong> – APM collects detailed information about requests such as response time, database queries, calls to caches, external HTTP requests, and more. </li>
<li><strong>System Metrics</strong> – APM automatically picks up basic host level metrics and agent specific metrics, like .NET metrics from the .NET agent. It also collects metrics such as CPU usage and more. </li>
<li><strong>Collects Errors</strong> – APM automatically collects unhandled errors and exceptions. They are grouped based on the stack trace, so you can identify new errors as they appear. </li>
<li><strong>Tracing</strong> – APM allows you to trace requests across microservices that have APM set up. </li>
<li><strong>Support</strong> – APM supports almost all popular programming languages and frameworks. </li>
</ul>
<h2 id="heading-how-to-set-up-apm">How to Set Up APM</h2>
<p>Now that we know what APM is and how it works, let's set it up with a Node agent locally. For this we need to go through two steps.</p>
<h3 id="heading-step-1-set-up-elk-locally">Step 1: Set Up ELK Locally</h3>
<p>Setting up the Elastic Stack (ELK) locally can be a pain. There are so many different services and you have to configure them all to work together. </p>
<p>Thankfully, other people have noticed this problem and created pre-configured Docker setup for ELK. </p>
<p>For the most up to date information, follow the guide <a target="_blank" href="https://github.com/sherifabdlnaby/elastdocker">here</a>. </p>
<p>Here's a TLDR version:</p>
<ol>
<li><code>git clone https://github.com/sherifabdlnaby/elastdocker.git</code></li>
<li><code>cd elastdocker</code></li>
<li><code>make setup</code></li>
<li><code>make all</code></li>
</ol>
<p>At this point, you should have all the required services up and running. Most notably the three most important ones are:</p>
<ul>
<li>ElasticSearch which is the heart of all of this is running at port 9200. </li>
<li>Kibana which is our dashboard running at port 5601. </li>
<li>APM server which picks up the metrics running at port 8200. </li>
</ul>
<p>If you want to login to Kibana, here are the credentials:</p>
<ul>
<li>Username: <code>elastic</code></li>
<li>Password: <code>changeme</code></li>
</ul>
<h3 id="heading-step-2-set-up-node-agent">Step 2: Set Up Node Agent</h3>
<p>Okay, now that we have ELK set up, let's set things up from the client side. </p>
<p>The first step is to add the APM node agent package. Install that using the following command:</p>
<p><code>npm install elastic-apm-node --save</code></p>
<p>Here's an important note. <strong>The agent must be started before all your other modules.</strong> </p>
<p>So, most likely you would have to start it in your application main file (usually <code>index.js</code>, <code>server.js</code> or <code>app.js</code>) at the top. </p>
<p>Here's an example for an Express application: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> apm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'elastic-apm-node'</span>).start({
  <span class="hljs-attr">serviceName</span>: <span class="hljs-string">'node-application'</span>,
  <span class="hljs-attr">secretToken</span>: <span class="hljs-string">'secrettokengoeshere'</span>,
  <span class="hljs-attr">verifyServerCert</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">serverUrl</span>: <span class="hljs-string">'https://127.0.0.1:8200'</span>,
})

<span class="hljs-keyword">const</span> app = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)()

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'Hello World!'</span>)
})

app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>Let's break down the configuration:</p>
<ul>
<li><code>serviceName</code>: name of your application.</li>
<li><code>secretToken</code>: token required to authenticate the application to APM server. (The default token that is preconfigured from our docker-compose files is <code>secrettokengoeshere</code>)</li>
<li><code>verifyServerCert</code>: as we are running this locally, we don't want to verify certificates. </li>
<li><code>serverUrl</code>: URL of our APM server. </li>
</ul>
<p>All that's left now is to run your application and play around with it a little for it to send some metrics. </p>
<p>Then go to Kibana at <a target="_blank" href="https://localhost:5601/">https://localhost:5601/</a>. </p>
<p>Under Observability, click on APM. </p>
<p>You will find your application and it will look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-8.png" alt="Image" width="600" height="400" loading="lazy">
<em>Elastic APM Dashboard</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary: creating features is half the battle – the other half is monitoring and maintaining them. </p>
<p>You can use Elastic's out the box solution Application Performance Monitoring tool to monitor your application. </p>
<p>I hope you learned something today and if you have any questions feel free to ask me on Twitter (or X) <a target="_blank" href="https://twitter.com/tamerlan_dev">@tamerlan_dev</a>. </p>
<p>Thanks for reading. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Teach Yourself Computer Science – Key CS Concepts You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Software development may feel like a bit of a race to keep up with new technologies. There's always a new frontend framework to learn, or a new database or language that's a variation of another language. It's never ending and feels like you always h... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-every-software-engineer-should-know/</link>
                <guid isPermaLink="false">66bb8c9aa5fd14123a8b4a10</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fundamentals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tamerlan Gudabayev ]]>
                </dc:creator>
                <pubDate>Thu, 22 Jun 2023 22:06:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/pexels-christina-morillo-1181298--2-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Software development may feel like a bit of a race to keep up with new technologies.</p>
<p>There's always a new frontend framework to learn, or a new database or language that's a variation of another language. It's never ending and feels like you always have to keep up.</p>
<p>But it doesn't have to be this way. </p>
<h2 id="heading-everything-is-built-from-the-fundamentals">Everything is Built From the Fundamentals</h2>
<p>If you learn the fundamentals, then everything else will become easier. </p>
<p>For example, if you <a target="_blank" href="https://www.freecodecamp.org/news/what-is-tcp-ip-layers-and-protocols-explained/">learn how the TCP/IP protocol works</a>, then from that you can easily learn all the other protocols that are built on top of it. </p>
<p>You're essentially having to cover less ground. The more fundamentals you know, the less you will struggle learning new things.</p>
<p>I believe there are 10 core subjects which, if you learn them, will give you a solid foundation. </p>
<h2 id="heading-why-should-you-learn-these-key-concepts">Why Should You Learn These Key Concepts?</h2>
<p>Learning the fundamentals will really put you in the top 5% of all programmers.</p>
<p>If we look at it from a different perspective, here's a great quote from Ras Bodik.</p>
<blockquote>
<p>Don’t be a boilerplate programmer. Instead, build tools for users and other programmers. Take historical note of textile and steel industries: do you want to build machines and tools, or do you want to operate those machines?</p>
</blockquote>
<h2 id="heading-but-there-are-a-million-different-courses-to-choose-from">But There are a Million Different Courses to Choose From</h2>
<p>Well, look no further. </p>
<p>Below, I've compiled a bunch of helpful resources on each subject – with some alternatives, of course. So you can focus on learning and not on mindlessly researching which books/videos/courses are the best. </p>
<h3 id="heading-a-few-notes">A few notes</h3>
<p>This article is well-suited for self-taught developers or developers who don't feel quite comfortable with certain computer science concepts. </p>
<p>If you are learning to program for the first time, I would recommend <a target="_blank" href="https://www.reddit.com/r/learnprogramming/">r/learnprogramming</a> community on Reddit. </p>
<p>This article was heavily inspired by <a target="_blank" href="https://twitter.com/oznova_">Oz Nova</a> and <a target="_blank" href="https://twitter.com/quackingduck">Myles Byrne</a> who authored the site <a target="_blank" href="https://teachyourselfcs.com/">teachyourselfcs.com</a>. If you enjoy this article, feel free to check out and share their site. </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-programming">Programming</a></li>
<li><a class="post-section-overview" href="#heading-computer-architecture">Computer Architecture</a></li>
<li><a class="post-section-overview" href="#algorithms-and-data-structures">Algorithms and Data Structures</a></li>
<li><a class="post-section-overview" href="#heading-math-for-computer-science">Math for Computer Science</a></li>
<li><a class="post-section-overview" href="#heading-operating-systems">Operating Systems</a></li>
<li><a class="post-section-overview" href="#heading-computer-networking">Computer Networking</a> </li>
<li><a class="post-section-overview" href="#heading-databases">Databases</a></li>
<li><a class="post-section-overview" href="#language-and-compilers">Languages and Compilers</a></li>
<li><a class="post-section-overview" href="#heading-distributed-systems">Distributed Systems</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/dfc9104e-85e4-4749-88dc-1859e6c643b9/web-security">Web Security</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/dfc9104e-85e4-4749-88dc-1859e6c643b9/conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-programming">Programming</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-84.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://dabeaz.com/sicp.html">Source</a></em></p>
<p>I'm not talking about syntax here. But actually programming or problem solving. Things such as abstraction, functions as data, recursion, and the different kinds of programming paradigms (object-oriented, functional, and declarative). </p>
<p>The book I recommend to learn programming is <a target="_blank" href="https://sarabander.github.io/sicp/html/index.xhtml">Structures and Interpretations of Computer Programs</a> (SICP) (It's also known as the wizard book). </p>
<p>The book is free and has a set of <a target="_blank" href="https://ocw.mit.edu/courses/6-001-structure-and-interpretation-of-computer-programs-spring-2005/video_galleries/video-lectures/">MIT lectures</a>. But the MIT lectures are a bit hard to watch due to the poor quality of that time (2005). So I recommend <a target="_blank" href="https://archive.org/details/ucberkeley-webcast-PL3E89002AA9B9879E?sort=titleSorter">Brian Harvey’s SICP lectures</a> (for the 61A course at Berkeley) instead.</p>
<h3 id="heading-why-this-book">Why this book?</h3>
<p>Because this book focuses on the big picture. </p>
<p>It doesn't care about the programming language. It uses a variation of Lisp called Scheme. Scheme is very easy to learn (you can probably learn it in less than an hour), so it let's you focus on ideas not syntax. </p>
<p>Because of its simplicity, it makes it possible to examine different programming paradigms. It's a functional first approach, but you can implement your own OOP. </p>
<p>Scheme is a great language for teaching because it takes the focus away from the language and puts it on the big ideas. </p>
<p>If you're worried about it not being used in the industry, it's ok – you can always learn a more commonly-used programming languages after you grasp these high-level concepts.</p>
<h3 id="heading-but-what-if-i-really-dont-want-to-learn-scheme">But what if I REALLY don't want to learn Scheme?</h3>
<p>Okay, you can follow the new version of the book which uses Python. The book is called <a target="_blank" href="http://composingprograms.com/">Composing Programs</a>. It also has its own <a target="_blank" href="https://cs61a.org/">set of lectures</a>. </p>
<p>But, I highly recommend at least trying to do the Scheme version. It's just magical once you get it. </p>
<h3 id="heading-okay-ive-tried-it-but-its-really-hard">Okay, I've tried it but it's really hard</h3>
<p>Yes, I understand. </p>
<p>Some of you will find SICP a bit too hard. It's not meant for purely beginner programmers. </p>
<p>If that's the case, then I would recommend <a target="_blank" href="https://htdp.org/">How to Design Programs (HTDP)</a>. It uses a language very similar to Scheme and is generally more slower paced. You can use this book and its <a target="_blank" href="https://www.edx.org/course/how-to-code-simple-data">course on edX</a>.</p>
<h3 id="heading-tips-on-studying">Tips on Studying</h3>
<p>Don't read these books like a story. </p>
<p>It's not meant to be read cover to cover. Instead, <strong>focus on the exercises</strong>. You don't have to do them all, but just make sure you know how to solve most of them. </p>
<p>The lectures are optional and only needed if they help. It's really up to you. </p>
<h3 id="heading-additional-resources">Additional Resources</h3>
<ul>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PLVFrD1dmDdvdvWFK8brOVNL7bKHpE-9w0">Virtual meetups that talk about SICP</a> </li>
<li><a class="post-section-overview" href="#https://racket-lang.org/">Racket</a> (IDE for Scheme) (<a target="_blank" href="https://stackoverflow.com/a/25096066">Checkout this StackOverFlow answer for Scheme setup</a>)</li>
</ul>
<h2 id="heading-computer-architecture">Computer Architecture</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-128.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://github.com/ahmeducf/computer-systems-CS-APP3e">Source</a></em></p>
<p>You wrote some code and it magically runs. </p>
<p>How does that work? Well, this is what you will learn with computer architecture. This is by far the most neglected subject by most self taught engineers. </p>
<p>As engineers, we don't believe in magic. We have to unravel the magic behind computers. You will also learn some useful stuff such as:</p>
<ul>
<li>What is the L1, L2 cache? </li>
<li>Why does cyberpunk lag?</li>
</ul>
<p>The book I recommend here is <em><a target="_blank" href="http://csapp.cs.cmu.edu/3e/home.html">Computer Systems: A Programmer's Perspective</a></em>. I would also recommend an <a target="_blank" href="https://www.cs.cmu.edu/afs/cs/academic/class/15213-f16/www/schedule.html">introductory course</a> that will cover chapters 1-6 of the book (That was made by the authors of the book). </p>
<h3 id="heading-but-theres-a-catch">But there's a catch</h3>
<p><strong>This book is not meant to be read cover to cover</strong>. It has a lot of content, that may not well be presented in the optimal order.</p>
<p>So I recommend that you follow the course and do the labs. </p>
<h3 id="heading-what-if-i-find-it-too-hard">What if I find it too hard?</h3>
<p>A lot of people will find the content a bit heavy, so to ease into it, I would recommend doing the following:</p>
<ul>
<li>Read <a target="_blank" href="https://www.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319">Code: The Hidden Language of Computer Hardware and Software</a>\</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-software-architecture-patterns/">Read this handbook on Software Architecture</a></li>
<li>Watch all 4 videos of <a target="_blank" href="https://www.youtube.com/playlist?list=PLFt_AvWsXl0dPhqVsKt1Ni_46ARyiCGSq">Exploring How Computers Work</a></li>
<li>Watch all 41 videos of <a target="_blank" href="https://www.youtube.com/playlist?list=PLH2l6uzC4UEW0s7-KewFLBC1D0l6XRfye">Crash Course: Computer Science</a></li>
<li>Take the course <a target="_blank" href="https://www.coursera.org/learn/build-a-computer">NAnd2Tetris</a> </li>
<li>Learn a bit of C by reading the book: <a target="_blank" href="https://www.amazon.com/C-Programming-Modern-Approach-2nd/dp/0393979504">C Programming a Modern Approach</a></li>
</ul>
<p>Once you finish that you can then come back to Computer Systems: A Programmers Perspective. </p>
<h2 id="heading-data-structures-and-algorithms">Data Structures and Algorithms</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-131.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://twitter.com/StevenSkiena/status/1336050368875290629">Source</a></em></p>
<p>Everyone wants to work at a FAANG company, but no one wants to learn Data Structures and Algorithms. </p>
<p>Nevertheless, I don't want you to learn these just because of technical interviews. Data structures and algorithms are important because they help build your problem solving skills. </p>
<p>There are many great books and courses on Data Structures and Algorithms but the one I would recommend is a book named <em><a target="_blank" href="https://www.amazon.com/Algorithm-Design-Manual-Steven-Skiena/dp/1849967202">The Algorithm Design Manual</a></em> by Steven Skiena. You can also check out his course <a target="_blank" href="https://www3.cs.stonybrook.edu/~skiena/373/videos/">here</a>. </p>
<h3 id="heading-dont-forget-to-practice">Don't forget to practice</h3>
<p>Same rules apply here. Don't just learn about data structures, but create them in whatever language you want. Don't just memorize algorithms but implement them and see where and how you can use them. </p>
<p>A good tip is solving some <a target="_blank" href="https://leetcode.com/">Leetcode</a> problems while going through the book/course. </p>
<h3 id="heading-what-if-i-find-it-too-hard-1">What if I find it too hard?</h3>
<p>If you find the material a bit heavy, then I would recommend the following resources:</p>
<ul>
<li>Read the book: <a target="_blank" href="https://www.amazon.com/Grokking-Algorithms-illustrated-programmers-curious/dp/1617292230">Grokking Algorithms</a> </li>
<li>Read the book: <a target="_blank" href="https://www.amazon.com/How-Solve-Mathematical-Princeton-Science/dp/069111966X#:~:text=Polya%2C%20How%20to%20Solve%20It,winning%20a%20game%20of%20anagrams.">How to Solve It: A New Aspect of Mathematical Method</a></li>
</ul>
<p>In general there are many different books/courses that teach Data Structures and Algorithms – Here are some other great resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/algorithms-and-data-structures-free-treehouse-course/">Data Structures and Algorithms course on freeCodeCamp</a></li>
<li><a target="_blank" href="https://algorithmsilluminated.org/">Algorithms Illuminated</a> </li>
<li><a target="_blank" href="https://www.coursera.org/learn/algorithms-part1">Princeton Algorithms Course</a> </li>
<li><a target="_blank" href="https://frontendmasters.com/courses/algorithms/">ThePrimegeans Data Structures and Algorithms Course</a></li>
<li><a target="_blank" href="https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011/">MIT Introduction to Algorithms</a> </li>
</ul>
<h2 id="heading-math-for-computer-science">Math for Computer Science</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-144.png" alt="Image" width="600" height="400" loading="lazy">
<em>Don't worry, this is some random math photo found <a target="_blank" href="https://unsplash.com/photos/h3kuhYUCE9A">here</a></em></p>
<p>Many new developers skip this. </p>
<p>But, hear me out – computer science is essentially a branch of mathematics. Learning it will make you a better developer by honing your problem solving skills. </p>
<h3 id="heading-the-most-relevant-area-for-cs-is-discrete-mathematics">The most relevant area for CS is Discrete Mathematics</h3>
<p>Discrete mathematics is the branch of mathematics that deals with countable or finite numbers. </p>
<p>The topics in discrete mathematics are many, but the ones which are relevant for CS are:</p>
<ul>
<li>Logic </li>
<li>Combinatorics </li>
<li>Discrete Probability </li>
<li>Set Theory </li>
<li>Graph Theory</li>
<li>Number Theory </li>
</ul>
<h3 id="heading-how-to-study-discrete-mathematics">How to Study Discrete Mathematics</h3>
<p>I would suggest starting with a set of <a target="_blank" href="https://cims.nyu.edu/~regev/teaching/discrete_math_fall_2005/dmbook.pdf">lecture notes by László Lovász</a>. </p>
<p>Professor Lovász notes are easier to digest than formal texts and are just generally fun. He starts of with a problem and solves it using discrete mathematics. </p>
<p>After that, you can take an MIT book called <em><a target="_blank" href="https://courses.csail.mit.edu/6.042/spring17/mcs.pdf">Mathematics for Computer Science</a>.</em> The book comes with video lectures that are <a target="_blank" href="https://ocw.mit.edu/courses/6-042j-mathematics-for-computer-science-fall-2010/video_galleries/video-lectures/">freely available</a>. </p>
<h3 id="heading-what-if-its-too-hard">What if it's too hard?</h3>
<p>Don't worry – sometimes you just have to accept that <strong>you won't always get it right away</strong>. </p>
<p>It's fine. </p>
<p>But if you feel like you're missing some fundamental knowledge, then it's a different story. The fundamental prerequisite subjects for discrete mathematics are:</p>
<ul>
<li>Algebra</li>
<li>Geometry</li>
<li>Calculas</li>
</ul>
<p>There are many free resources, but the ones I would recommend are:</p>
<ul>
<li><a target="_blank" href="https://www.khanacademy.org/">Khan Academy</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/college-algebra-course-with-python-code/">College Algebra course</a> </li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-college-calculus-in-free-course/">Calculus 1 course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-calculus-2-in-this-free-7-hour-course/">Calculus 2 course</a></li>
</ul>
<h2 id="heading-operating-systems">Operating Systems</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-228.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://pages.cs.wisc.edu/~remzi/OSTEP/">Source</a></em></p>
<p>Remember when I told you that we as developers want to remove the magic in computing?</p>
<p>Same thing applies here – operating systems seem like some sort of magical black box. But they're not – it's just a lot of clever engineering. </p>
<p>If you know how these operating systems are built and work, then you will definitely be in a league of your own. </p>
<p>It's somewhat difficult to find good resources online for operating systems but the most recommend book is <a target="_blank" href="https://pages.cs.wisc.edu/~remzi/OSTEP/">Operating Systems: Three Easy Pieces (OSTEP).</a> There isn't any official video lecture online that fully covers the book but I found this <a target="_blank" href="https://www.youtube.com/playlist?list=PLhtZD20ADU45ADsAIxlNpFowP3iYvGXvJ">playlist on YouTube</a>. </p>
<h3 id="heading-recommend-prerequisites">Recommend Prerequisites</h3>
<p>I would suggest learning computer architecture first and a little bit about C before embarking on the operating systems journey. </p>
<h3 id="heading-optional-resources">Optional Resources</h3>
<p>Now, I recommend finishing OSTEP first and then checking out the other recommend resources. They are all optional. </p>
<ul>
<li>Want to build your own Linux system? Check out <a target="_blank" href="https://www.linuxfromscratch.org/">Linux from Scratch</a>. </li>
<li>Want an in-depth overview of Linux, MacOS, and Windows? <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-operating-systems/">Here's a handbook for you</a>.</li>
<li>Want to build your own OS? Check out <a target="_blank" href="https://wiki.osdev.org/Introduction">OSDEV</a></li>
<li>Want to build your own Sockets? Check out <a target="_blank" href="https://beej.us/guide/bgnet/">Beej's Guide to Network Programming</a> </li>
</ul>
<h2 id="heading-computer-networking">Computer Networking</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-237.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://github.com/topics/top-down-approach">Source</a></em></p>
<p>Since the dawn of the internet, computer networking has been one the most important subjects for software engineers. </p>
<p>If you don't know things like IP, TCP, UDP, HTTP, TLS, DNS, SMTP, and so on — then you should learn about computer networking (especially if you are a backend engineer).</p>
<p>The recommended book here is <a target="_blank" href="https://gaia.cs.umass.edu/kurose_ross/wireshark.php">Computer Networking: A Top-Down Approach</a>. You can also check out the <a target="_blank" href="https://www.youtube.com/playlist?list=PLByK_3hwzY3Tysh-SY9MKZhMm9wIfNOas">video lectures</a> from the author of the book himself. </p>
<p>But before beginning that I would recommend to check out this <a target="_blank" href="https://www.youtube.com/playlist?list=PLowKtXNTBypH19whXTVoG3oKSuOcw_XeW">video crash course on computer networking</a> from a bottom up approach. And <a target="_blank" href="https://www.freecodecamp.org/news/computer-networking-how-applications-talk-over-the-internet/">here's a helpful tutorial</a> that covers the basics well.</p>
<h2 id="heading-databases">Databases</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-229.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.astera.com/type/blog/a-quick-overview-of-different-types-of-databases/">Source</a></em></p>
<p>Databases are somewhat new – they came around the 1970s and have since become integral parts of many applications.</p>
<p>I highly recommend the below courses from the <a target="_blank" href="https://www.youtube.com/@CMUDatabaseGroup/featured">CMU Database Group</a>. They're all freely available on YouTube. I would recommend going through at least the first one. </p>
<ol>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PLSE8ODhjZXjaKScG3l0nuOiDTTqpfnWFf">Introduction To Databases</a></li>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PLSE8ODhjZXjZKp-oX_75aBnznulk7nubu">Database Seminars</a></li>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PLSE8ODhjZXjYzlLMbX3cR0sxWnRM7CLFn">Advanced Databases</a></li>
</ol>
<p>Also, <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">here's a great collection of resources</a> to help you learn about SQL databases. And <a target="_blank" href="https://www.freecodecamp.org/news/learn-nosql-in-3-hours/">here's a free course on NoSQL databases</a>.</p>
<h2 id="heading-languages-and-compilers">Languages and Compilers</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-230.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://chidiwilliams.com/post/crafting-interpreters-a-review/">Source</a></em></p>
<p>You may know how to code in one or more programming languages. </p>
<p>But do you know how to create or design one? That's what you will learn by studying programming languages and compilers.</p>
<p>The recommended introductory book is called <a target="_blank" href="https://craftinginterpreters.com/contents.html">Crafting Interpreters</a>. </p>
<p>After that you can move on to <em><a target="_blank" href="https://smile.amazon.com/Compilers-Principles-Techniques-Tools-2nd/dp/0321486811">Compilers: Principles, Techniques &amp; Tools</a></em>, also called “the Dragon Book”. The book is covers a lot of topics so I highly recommend taking a course with it. The one I recommend is from <a target="_blank" href="https://www.edx.org/course/compilers">Alex Aiken on edX</a>.</p>
<p>And <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-compiler-in-c/">here's a helpful beginner-friendly tutorial</a> on how the compiler works in C programming.</p>
<h2 id="heading-distributed-systems">Distributed Systems</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-231.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://vvsevolodovich.dev/designing-data-intensive-applications-by-martin-kleppmann/">Source</a></em></p>
<p>If you choose to study only one subject from the list, make it distributed systems. It's the holy grail for tech companies, and if you want to get a developer job, you should be proficient about distributed systems. </p>
<p>My recommend path in learning the subject is:</p>
<ol>
<li>Read the book: <a target="_blank" href="https://www.amazon.com/gp/product/1838430202/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=utsavized0d-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=1838430202&amp;linkId=8f3007bbed9b958980492f5c0bb1105f">Understanding Distributed Systems</a> </li>
<li>Read the book: <a target="_blank" href="https://www.amazon.com/Designing-Data-Intensive-Applications-Reliable-Maintainable/dp/1449373321">Designing Data Intensive Applications</a> also known as the "red book"</li>
<li>While reading the "red book", take its accompanying <a target="_blank" href="https://www.youtube.com/@6.824/videos">MIT course on YouTube</a>. </li>
<li>Read the book: <a target="_blank" href="https://www.amazon.com/dp/1492086894?psc=1&amp;linkCode=sl1&amp;tag=utsavized0d-20&amp;linkId=64e15d236bb8c1015661423e5be849ac&amp;language=en_US&amp;ref_=as_li_ss_tl">Software Architecture: The Hard Parts</a> (Optional) </li>
<li>You can also <a target="_blank" href="https://www.freecodecamp.org/news/design-patterns-for-distributed-systems/">check out my handbook about design patterns for distributed systems</a>.</li>
</ol>
<h2 id="heading-web-security">Web Security</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-232.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.ifourtechnolab.com/blog/principles-of-web-security">Source</a></em></p>
<p>There have been a lot of security breaches in the last 2-3 years. </p>
<p>It's getting dangerous out there – and as a software engineer, knowing some fundamentals of web security will give you an edge. </p>
<p>The course I recommend first is <a target="_blank" href="https://web.stanford.edu/class/cs253/">CS253 Web Security by Stanford</a>. It gives a comprehensive overview of web security. So expect topics like web app vulnerabilities, injection, denial-of-service, and many more. </p>
<p>You can also <a target="_blank" href="https://www.freecodecamp.org/news/technical-dive-into-owasp/">review these common vulnerabilities</a> and learn how to prevent attacks that take advantage of them.</p>
<p>Later on, if you want, you could learn how to hack using <a target="_blank" href="https://pwn.college/">pwn.college</a>. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Learning all these subjects will take you a while, and will require consistent effort. But if you like what you do and are interested in the subject, then it should feel like play and not a chore. </p>
<p>Regardless of the subjects you choose to study. The most important tip I can give you is...</p>
<h3 id="heading-dont-be-a-passive-learner">Don't be a passive learner</h3>
<p>Don't just watch videos – do the exercises as well. Build the projects along with the tutorials. </p>
<p>Don't just read books but engage in the book by asking questions and doing your own research. </p>
<p>You want the information to stick, so you don't forget it. And to make it stick you have to actively engage in the subject. </p>
<p>I sincerely hope that I encouraged you to study some of these subjects. As always I want to end it of by thanking you for reading this article. </p>
<p>I wish you all the best. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Design Patterns for Distributed Systems Handbook – Key Concepts Every Developer Should Know ]]>
                </title>
                <description>
                    <![CDATA[ When I first started my career as a backend engineer, I always worked with monolithic systems. The work was good but I always had this thought in the back of my mind: "Man, I want to work on big systems such as ones for Google, Netflix, etc..." I w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/design-patterns-for-distributed-systems/</link>
                <guid isPermaLink="false">66bb8c92a5fd14123a8b4a0e</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ distributed systems ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tamerlan Gudabayev ]]>
                </dc:creator>
                <pubDate>Mon, 05 Jun 2023 20:49:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/sigmund-HsTnjCVQ798-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I first started my career as a backend engineer, I always worked with monolithic systems.</p>
<p>The work was good but I always had this thought in the back of my mind:</p>
<blockquote>
<p>"Man, I want to work on big systems such as ones for Google, Netflix, etc..."</p>
</blockquote>
<p>I was 19 and a junior developer, so cut me some slack here.</p>
<p>I didn't even know the term distributed systems until one of my colleagues started talking about it. </p>
<p>Then I researched it – I researched a lot. It seemed very complicated, and I felt very stupid. </p>
<p>But I was excited. </p>
<p>I studied this concept of distributed systems for a while, but didn't fully understand it until I saw it all in action a few years later.</p>
<p>Now that I have some experience, I would like to share with you what I know about distributed systems.  </p>
<h2 id="heading-prerequisite-knowledge">Prerequisite Knowledge</h2>
<p>The topics I'll be discussing here may be a bit advanced for beginner programmers. To help you be prepared, here's what I assume you know:</p>
<ul>
<li>Mid Level Programming (any language will work)</li>
<li>Basic Computer Networking (TCP/IP, network protocols, and so on)</li>
<li>Basic Data Structures and Algorithms (Big O notation, search, sort, and so on)</li>
<li>Databases (Relational, NoSQL, and so on)</li>
</ul>
<p>If that sounds like a lot, don't feel discouraged. </p>
<p>Here are some resources that can help you brush up on some of these more specific topics:</p>
<ol>
<li>Learn how computer networks work <a target="_blank" href="https://www.freecodecamp.org/news/free-computer-networking-course/">in this free course</a></li>
<li>Learn about data structures and algorithms <a target="_blank" href="https://www.freecodecamp.org/news/algorithms-and-data-structures-free-treehouse-course/">in this free course</a></li>
<li>Learn about <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">relational databases here</a>, and about <a target="_blank" href="https://www.freecodecamp.org/news/learn-nosql-in-3-hours/">NoSQL databases here</a>.</li>
</ol>
<h2 id="heading-heres-what-well-cover">Here's What We'll Cover:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-are-distributed-systems">What are Distributed Systems?</a></li>
<li><a class="post-section-overview" href="#heading-common-challenges-in-distributed-systems">Common Challenges in Distributed Systems</a></li>
<li><a class="post-section-overview" href="#heading-command-and-query-responsibility-segregation-cqrs-pattern">Command and Query Responsibility Segregation (CQRS) Pattern</a></li>
<li><a class="post-section-overview" href="#heading-two-phase-commit-2pc-pattern">Two-Phase Commit (2PC) Pattern</a></li>
<li><a class="post-section-overview" href="#heading-saga-pattern">Saga Pattern</a></li>
<li><a class="post-section-overview" href="#heading-replicated-load-balanced-services-rlbs-pattern">Replicated Load-Balanced Services (RLBS) Pattern</a></li>
<li><a class="post-section-overview" href="#heading-sharded-services-pattern">Sharded Services Pattern</a></li>
<li><a class="post-section-overview" href="#heading-sidecar-pattern">Sidecar Pattern</a></li>
<li><a class="post-section-overview" href="#write-ahead-log-pattern">Write-Ahead Log Technique</a></li>
<li><a class="post-section-overview" href="#heading-split-brain-pattern">Split-Brain Pattern</a></li>
<li><a class="post-section-overview" href="#heading-hinted-handoff-pattern">Hinted Handoff Pattern</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/62b41b39-6b8e-4e9b-a541-1071140ffb3a/read-repair-pattern">Read Repair Pattern</a></li>
<li><a class="post-section-overview" href="#heading-service-registry-pattern">Service Registry Pattern</a></li>
<li><a class="post-section-overview" href="#heading-circuit-breaker-pattern">Circuit Breaker Pattern</a></li>
<li><a class="post-section-overview" href="#heading-leader-election-pattern">Leader Election Pattern</a></li>
<li><a class="post-section-overview" href="#heading-bulk-head-pattern">Bulk Head Pattern</a></li>
<li><a class="post-section-overview" href="#heading-retry-pattern">Retry Pattern</a></li>
<li><a class="post-section-overview" href="#heading-scatter-gather-pattern">Scatter Gather Pattern</a></li>
<li><a class="post-section-overview" href="#bloom-filters-pattern">Bloom Filters Data Structure</a> </li>
</ol>
<h2 id="heading-what-are-distributed-systems">What are Distributed Systems?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-110.png" alt="Image" width="600" height="400" loading="lazy">
<em>Netflix Architecture. <a target="_blank" href="https://www.geeksforgeeks.org/system-design-netflix-a-complete-architecture/">Source</a></em></p>
<p>When I started my career, I worked as a front-end developer for an agency.</p>
<p>We used to get requests from clients and then we'd just build their site.</p>
<p>Back then I didn't fully understand the architecture and infrastructure behind the stuff I was building. </p>
<p>Thinking back about it now, it wasn't complicated at all. </p>
<p>We had one backend service written in PHP and Yii2 (PHP Framework) and a frontend written in JavaScript and React.</p>
<p>All of this was deployed to one server hosted in <a target="_blank" href="https://www.ps.kz/">ps.kz</a> (Kazakhstan Hosting Provider) and exposed to the internet using NGINX as a web server. </p>
<p>This architecture works for most projects. But once your application becomes more complex and popular, the cracks begin to show. </p>
<p>You get problems such as:</p>
<ul>
<li><strong>Complexity</strong> – Codebase is too large and too complex for one person to mentally handle. It's also hard to create new features and maintain old ones. </li>
<li><strong>Performance Issues</strong> – The popularity of your app caused it to have a lot of network traffic and it has proven to be too much for your single server. Because of that, the application has started to face performance issues. </li>
<li><strong>Inflexibility</strong> – Having a single codebase means that you are stuck with the technology stack that you began with. If you want to change it, then you will either have to rewrite the whole thing in another language or break up the app. </li>
<li><strong>Fragile System</strong> –  Code being highly coupled together means that if any of the functionality breaks then the whole application will break. This leads to more downtime which will lose the business more money. </li>
</ul>
<p>There are many ways to optimize a monolithic application, and it can go very far. Many big tech companies such as Netflix, Google, and Facebook (Meta) started off as monolithic applications because they're easier to launch.   </p>
<p>But they all began facing problems with monoliths at scale and had to find a way to fix it. </p>
<p>What did they do? They restructured their architectures. So instead of having a single super service that contained all the features of their business, they now had multiple independent services that talk to each other. </p>
<p>This is the basis of distributed systems. </p>
<p>Some people mistake distributed systems for microservices. And it's true – microservices are a distributed system. But distributed systems do not always follow the microservice architecture. </p>
<p>So with that in mind, let's come up with a proper definition for distributed systems:</p>
<blockquote>
<p>A distributed system is a computing environment in which various components are spread across multiple computers (or other computing devices) on a network.</p>
</blockquote>
<h2 id="heading-common-challenges-in-distributed-systems">Common Challenges in Distributed Systems</h2>
<p>Distributed systems are by far much more complex than monolithic ones. </p>
<p>That's why before migrating or starting a new project, you should ask the question:</p>
<blockquote>
<p>Do I really need it? </p>
</blockquote>
<p>If you decide that you do need a distributed system, then there are some common challenges you will face:</p>
<ul>
<li><strong>Heterogeneity</strong> – Distributed systems allow us to use a wide range of different technologies. The problem lies in how we keep consistent communication between all the different services. Thus it is important to have common standards agreed upon and adopted to streamline the process.</li>
<li><strong>Scalability</strong> – Scaling is no easy task. There are many factors to keep in mind such as size, geography, and administration. There are many edge cases, each with their own pros and cons. </li>
<li><strong>Openness</strong> – Distributed systems are considered open if they can be extended and redeveloped.</li>
<li><strong>Transparency</strong> – Transparency refers to the distributed system's ability to conceal its complexity and give off the appearance of a single system. </li>
<li><strong>Concurrency</strong> – Distributed systems allow multiple services to use shared resources. Problems may arise when multiple services attempt to access the same resources at the same time. We use concurrency control to ensure that the system remains in a stable state. </li>
<li><strong>Security</strong> – Security is comprised of three key components: availability, integrity, and confidentiality. </li>
<li><strong>Failure Handling</strong> – There are many reasons for errors in a distributed system (for example, software, network, hardware, and so on...). The most important thing is how we handle those errors in a graceful way so that the system can self-heal. </li>
</ul>
<p>Yea, designing robust and scalable distributed systems is not easy. </p>
<p>But you are not alone. Other smart people have faced similar problems and offer common solutions which are called design patterns. </p>
<p>Let's cover the most popular ones. </p>
<p><em>PS. We won't only cover patterns, but anything that helps in distributed systems. This may include data structures, algorithms, common scenarios, etc...</em> </p>
<h2 id="heading-command-and-query-responsibility-segregation-cqrs-pattern">Command and Query Responsibility Segregation (CQRS) Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-109.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://dev.to/karanpratapsingh/system-design-command-and-query-responsibility-segregation-cqrs-1kl1">Source</a></em></p>
<p>Imagine that you have an application with millions of users. You have multiple services that handle the backend, but as a single database. </p>
<p>The problem arises when you do reads and writes on this same database. Writes are a lot more expensive to compute than reads, and the system starts to suffer. </p>
<p>This is what the CQRS pattern solves.</p>
<p>It states that writes (commands) and reads (queries) should be separated. By separating writes and reads, we can allow developers to optimize each task separately. </p>
<p>For example, you might choose a high-performance database for write operations and a cache or search engine for read operations.</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><strong>Code Simplification</strong> – Reduces system complexity by separating writes and reads. </li>
<li><strong>Resource Optimizations</strong> – Optimizes resource usage by having a separate database for writes and reads.</li>
<li><strong>Scalability</strong> – Improves scalability for reads as you can simply add more database replicas. </li>
<li><strong>Reduce Number of Errors</strong> – By limiting the entities that can modify shared data, we can reduce the chances of unexpected modifications of data.</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><strong>Code Complexity</strong> – Adds code complexity by requiring developers to manage reads and writes separately. </li>
<li><strong>Increased Development Time</strong> – This can increase development time and cost (in the beginning only).</li>
<li><strong>Additional Infrastructure</strong> – This may require additional infrastructure to support separate read and write models. </li>
<li><strong>Increased Latency</strong> – It can cause increased latency when sending high-throughput queries.</li>
</ul>
<h3 id="heading-use-cases">Use Cases</h3>
<p>CQRS is best used when an application's writes and reads have different performance requirements. But it is not always the best approach, and developers should carefully consider the pros and cons before adopting the pattern.</p>
<p>Here are some use cases that utilize the CQRS pattern:</p>
<ul>
<li><strong>E-Commerce</strong> –  Separate read models for product catalogs and recommendations, while the write side handles order processing and inventory management.</li>
<li><strong>Banks</strong> – Optimize read models for balance inquiries and reporting, while the write side handles transactions and calculations.</li>
<li><strong>Healthcare</strong> –  CQRS can be used to optimize the reads for patient searches, medical record retrieval, and generating reports, while the write side manages data updates, scheduling, and treatment plans.</li>
<li><strong>Social Media</strong> –By applying CQRS, the read models can efficiently handle feed generation, personalized content recommendations, and user profile queries, while the write side handles content creation, updates, and engagement tracking.</li>
</ul>
<h2 id="heading-two-phase-commit-2pc-pattern">Two-Phase Commit (2PC) Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/image-83.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://www.researchgate.net/figure/The-basic-two-phase-commit-protocol_fig3_2276629">Source</a>_</p>
<p>2PC solves the problem of data consistency. When you have multiple services talking to a relational database, it's hard to keep the data consistent as one service can create a transaction while the other aborts it. </p>
<p>2PC is a protocol that ensures that all services commit or abort a transaction before it is completed.</p>
<p>It works in two phases. The first phase is the Prepare phase in which the transaction coordinator tells the service to prepare the data. Then comes the Commit phase, which signals the service to send the prepared data, and the transaction gets committed.</p>
<p>2PC systems make sure that all services are locked by default. This means that they can't just write to the database. </p>
<p>While locked, the services complete the Prepare stage to get their data ready. Then the transaction coordinator checks each service one-by-one to see if they have any prepared data. </p>
<p>If they do, then the service gets unlocked and the data gets committed. If not, then the transaction coordinator moves on to another service.</p>
<p>2PC ensures that only one service can operate at a time, which makes the process more resistant and consistent than CQRS.</p>
<h3 id="heading-pros-1">Pros</h3>
<ul>
<li><strong>Data Consistency</strong> – Ensures data consistency in a distributed transaction environment.</li>
<li><strong>Fault Tolerance</strong> – Provides a mechanism to handle transaction failures and rollbacks.</li>
</ul>
<h3 id="heading-cons-1">Cons</h3>
<ul>
<li><strong>Blocking</strong> – The protocol can introduce delays or blocking in the system, as it may have to wait for unresponsive participants or resolve network issues before proceeding with the transaction.</li>
<li><strong>Single point of failure</strong> – Reliance on a single coordinator introduces a potential point of failure. If the coordinator fails, the protocol may be disrupted, leading to transaction failures or delays.</li>
<li><strong>Performance overhead</strong> – The additional communication rounds and coordination steps in the protocol introduce overhead, which can impact the overall performance, especially in scenarios with many participants or high network latency.</li>
<li><strong>Lack of scalability</strong> – As the number of participants increases, the coordination and communication overhead also increase, potentially limiting the scalability of the protocol.</li>
<li><strong>Blocking during recovery</strong> – The protocol may introduce blocking during recovery until the failed participant is back online, impacting system availability and responsiveness.</li>
</ul>
<h3 id="heading-use-cases-1">Use Cases</h3>
<p>2PC is best used for systems that deal with important transaction operations that must be accurate. </p>
<p>Here are some use cases where the 2PC pattern would be beneficial:</p>
<ul>
<li><strong>Distributed Databases</strong> – Coordinating transaction commits or aborts across multiple databases in a distributed database system.</li>
<li><strong>Financial Systems</strong> – Ensuring atomic and consistent transaction processing across banks, payment gateways, and financial institutions.</li>
<li><strong>E-commerce Platforms</strong> – Coordinating services like inventory management, payment processing, and order fulfillment for reliable and consistent transaction processing.</li>
<li><strong>Reservation Systems</strong> – Coordinating distributed resources and participants in reservation processes for consistency and atomicity.</li>
<li><strong>Distributed File Systems</strong> – Coordinating file operations across multiple nodes or servers in distributed file systems to maintain consistency.</li>
</ul>
<h2 id="heading-saga-pattern">Saga Pattern</h2>
<p>So let's imagine that you have an e-commerce app that has three services, each with its own database.</p>
<p>You have an API for your merchants which is called <code>/products</code> to which you can add a product with all its information. </p>
<p>Whenever you create a product, you also have to create its price and meta-data. All three are managed in different services with different databases.</p>
<p>So, you implement the simple approach of:</p>
<blockquote>
<p>Create product -&gt; create price -&gt; create meta-data</p>
</blockquote>
<p>But what if you created a product but failed to create a price? How can one service know that there was a failed transaction of another service?</p>
<p>The saga pattern solves this problem.</p>
<p>There are two ways to implement sagas: orchestration and choreography.</p>
<h3 id="heading-orchestration">Orchestration</h3>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-3.png" alt="Image" width="679" height="288" loading="lazy">
<em><a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga">Source</a></em></p>
<p>The first method is called Orchestration. </p>
<p>You have a central service that calls all the different services in the right order. </p>
<p>The central service makes sure that if there is a failure, it will know how to compensate for that by reverting transactions or logging the errors.</p>
<h4 id="heading-pros-2">Pros</h4>
<ul>
<li>Suitable for complex transactions that involve multiple services or new services added over time. </li>
<li>Suitable when there is control over every participant in the process and control over the flow of activities.</li>
<li>Doesn't introduce cyclical dependencies, because the orchestrator unilaterally depends on the saga participants.</li>
<li>Services don't need to know about commands for other services. There is a clear separation of concerns which reduces complexity. </li>
</ul>
<h4 id="heading-cons-2">Cons</h4>
<ul>
<li>Additional design complexity requires you to implement a coordination logic.</li>
<li>If the orchestrator fails then the whole system fails.</li>
</ul>
<h4 id="heading-when-to-use-orchestration">When to Use Orchestration?</h4>
<p>You should consider using this pattern:</p>
<ul>
<li>If you need a centralized service that coordinates of the workflow.</li>
<li>If you want a clear and centralized view of the workflow which makes it easier to understand and manage the overall system behavior.</li>
<li>If you have complex and dynamic workflows that require a high degree of coordination and centralized control.</li>
</ul>
<h3 id="heading-choreography">Choreography</h3>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-2.png" alt="Image" width="656" height="349" loading="lazy">
<em><a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga">Source</a></em></p>
<p>On the other hand, the Choreography method doesn't use a central service. Instead, all communication between servers happens by events. </p>
<p>Services will react to events and will know what to do in case of success or failure. </p>
<p>So for our example above, when the user creates a product it will:</p>
<ol>
<li>Create an event called <code>product-created-successfully</code></li>
<li>Then the price service will react to the event by creating a price for the product and it will then create another event called <code>price-created-successfully</code></li>
<li>The same logic applies to the meta-data service.</li>
</ol>
<h4 id="heading-pros-3">Pros</h4>
<ul>
<li>Suitable for simple workflows that don't require complex coordination logic. </li>
<li>Simple to implement because it doesn't require additional service implementation and maintenance.</li>
<li>There is no single point of failure as responsibilities are distributed between the services.  </li>
</ul>
<h4 id="heading-cons-3">Cons</h4>
<ul>
<li>Difficult to debug because it's difficult to track which saga services listen to which commands.</li>
<li>There's a risk of cyclic dependency between Saga services because they have to consume each other's commands.</li>
<li>Integration testing is difficult because all services must be running to simulate a transaction.</li>
</ul>
<h4 id="heading-when-to-use-choreography">When to Use Choreography:</h4>
<p>You should consider using this pattern if:</p>
<ul>
<li>The application needs to maintain data consistency across multiple microservices without tight coupling.</li>
<li>There are long-lived transactions and you don’t want other microservices to be blocked if one microservice runs for a long time.</li>
<li>You need to be able to roll back if an operation fails in the sequence.</li>
</ul>
<h2 id="heading-replicated-load-balanced-services-rlbs-pattern">Replicated Load-Balanced Services (RLBS) Pattern</h2>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-4.png" alt="Image" width="380" height="237" loading="lazy">
<em><a target="_blank" href="https://vladsukhachev.wordpress.com/2019/11/02/replicated-load-balanced-service-in-kubernetes/">Source</a></em></p>
<p>This is essentially a load balancer – I don't know why they made it sound so intimidating. </p>
<p>A load balancer is software or hardware that distributes network traffic equally between a set of resources. </p>
<p>But that's not always the case – it can also route different routes to different services. </p>
<p>So for example:</p>
<ul>
<li><code>/frontend</code> goes to the front-end service. </li>
<li><code>/api</code> goes to the backend service.</li>
</ul>
<h4 id="heading-pros-4">Pros</h4>
<ul>
<li><strong>Performance</strong> – Load balancing distributes the workload evenly across multiple resources, preventing any single resource from becoming overloaded. This leads to improved response times, reduced latency, and better overall performance for users or clients accessing the system.</li>
<li><strong>Scalability</strong> – Load balancing allows you to scale horizontally, meaning that instead of getting more powerful servers, you can get more servers.</li>
<li><strong>High availability</strong> – As said above, load balancing allows us to vertically scale which means we have multiple servers. If one server fails then the load balancer will detect that and traffic can be redirected to other working servers.</li>
<li><strong>Better resource utilization</strong> – Load balancing helps to optimize resource utilization by distributing traffic evenly across multiple servers or resources. This ensures that each server or resource is used efficiently, helping to reduce costs and maximize performance.</li>
</ul>
<h4 id="heading-cons-4">Cons</h4>
<ul>
<li><strong>Complexity</strong> – Implementing and configuring load balancing can be complicated especially for large scale systems.</li>
<li><strong>Single Point of Failure</strong> – While load balancers enhance system availability, they can also become a single point of failure. If the load balancer itself fails, it can cause a disruption in service for all resources behind it.</li>
<li><strong>Increased Overhead</strong> –Load balancers computations are not free, if they are not controlled then they can become a bottleneck to the entire system.</li>
<li><strong>Session Handling Challenges</strong> – Load balancing stateful applications is a bit tricky as you need to maintain sessions. It requires additional mechanisms such as sticky sessions or session synchronization, which adds complexity.</li>
</ul>
<h4 id="heading-when-to-use-load-balancing">When to use load balancing</h4>
<p>A load balancer is mainly used when:</p>
<ul>
<li>You have a high traffic website and you want to spread the load so that your servers don't fry. </li>
<li>You have users from all over the world and want to serve them data from their closest location. You could have a server in Asia and another in Europe. The load balancer would then route all users from Asia to the Asian server and European users to the Europe server. </li>
<li>You have a service orientated architecture with API's corresponding to different services. Load balancing can be used as a simple API gateway. </li>
</ul>
<p>I've written a bunch of articles on load balancing, so feel free to check them out.</p>
<ul>
<li><a target="_blank" href="https://tamerlan.dev/how-to-set-up-nginx-load-balancing-a-step-by-step-guide/">How to set up NGINX load balancing: a step-by-step guide</a></li>
<li><a target="_blank" href="https://tamerlan.dev/load-balancing-in-kubernetes-a-step-by-step-guide/">Load balancing in Kubernetes: a step-by-step guide</a></li>
<li><a target="_blank" href="https://tamerlan.dev/load-balancing-101-how-it-works-and-why-it-matters-for-your-platform/">Load balancing 101: How it works and why it matters for your platform</a></li>
</ul>
<h2 id="heading-sharded-services-pattern">Sharded Services Pattern</h2>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-5.png" alt="Image" width="979" height="325" loading="lazy">
<em><a target="_blank" href="https://medium.com/@bindubc/sharded-services-68db32e03d80">Source</a></em></p>
<p>In the previous section, we talked about replicated services. Any request can be processed by any of the services. This is because they are replicas of one another. </p>
<p>This is good for stateless services. But what if you have a stateful service? Then a sharded approach would be more appropriate. </p>
<p>Sharded service only accepts certain kinds of requests. </p>
<p>For example, you may have one shard service accept all caching requests while another shard service accepts high-priority requests. </p>
<h3 id="heading-but-how-do-we-implement-this">But, how do we implement this?</h3>
<p>Well, if we are strictly talking about application services then you could go with the service oriented architecture approach. You could have multiple services developed and deployed independently.  </p>
<p>Then you could use a load balancer to route requests by URL path to the appropriate service.</p>
<p><em>PS. Sharding is not only used for application services but can be used for databases, caches, CDNs, etc...</em> </p>
<h3 id="heading-pros-5">Pros:</h3>
<ul>
<li><strong>Scalability</strong> – Sharding allows you to distribute load across multiple nodes or servers, thus enabling horizontal scaling. As your workload increases, you can just add more shards. </li>
<li><strong>Performance</strong> – A single node doesn't have to handle all requests especially if it is computationally heavy. Each node can take in a subset of requests, improving the systems performance.</li>
<li><strong>Cost-effectiveness</strong> – Sharding can be a cost-effective solution for scaling your system. Instead of investing in a single, high-capacity server, you can use commodity hardware and distribute the workload across multiple, less expensive servers. </li>
<li><strong>Fault isolation</strong> – Sharding provides a level of fault isolation. If one shard or node fails, the remaining shards can continue serving requests.</li>
</ul>
<h3 id="heading-cons-5">Cons:</h3>
<ul>
<li><strong>Complexity</strong> –  Sharding is not easy to implement. It requires careful planning and design to handle data distribution, consistency, and query coordination.</li>
<li><strong>Operational overhead</strong> –  Managing a sharded system involves additional operational tasks such as monitoring, maintenance, and backup, which can require more resources and expertise.</li>
</ul>
<h3 id="heading-use-cases-2">Use Cases</h3>
<p>The Sharded Services Pattern is typically used in the following scenarios:</p>
<ul>
<li><strong>Performance Requirements</strong> – If your system is dealing with large data volumes or high read/write workloads that a single server cannot handle, sharding can distribute the workload across multiple shards. This enables parallel processing and improving overall performance.</li>
<li><strong>Scalability requirements</strong> –  When you anticipate the need for horizontal scalability in the future, sharding can be implemented from the beginning to provide the flexibility to add more shards and scale the system as the workload grows.</li>
<li><strong>Cost considerations</strong> –  If vertical scaling (upgrading to more powerful hardware) becomes cost-prohibitive, sharding offers a cost-effective alternative by distributing the workload across multiple, less expensive servers or nodes.</li>
<li><strong>Geographical distribution</strong> –  Sharding can be beneficial when you need to distribute data across different geographical locations or data centers, allowing for improved performance and reduced latency for users in different regions.</li>
</ul>
<p>But keep in mind that there must be careful considerations when sharding your services as it is very complex and expensive to implement and revert. </p>
<h2 id="heading-sidecar-pattern">Sidecar Pattern</h2>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-6.png" alt="Image" width="994" height="502" loading="lazy">
<em><a target="_blank" href="https://medium.com/nerd-for-tech/microservice-design-pattern-sidecar-sidekick-pattern-dbcea9bed783">Source</a></em></p>
<p>In a service-oriented architecture, you might have a lot of common functionalities – things such as error handling, logging, monitoring, and configuration.</p>
<p>In the past, there were two ways to solve this problem:</p>
<h3 id="heading-implement-common-functionalities-within-the-service">Implement common functionalities within the service</h3>
<p>The problem with this approach is that the utilities are tightly linked and run within the same process by making efficient use of the shared resources. This makes the components interdependent. </p>
<p>If one functionality fails then this can lead to another functionality failing or the whole service failing.</p>
<h3 id="heading-implement-common-functionalities-in-a-separate-service">Implement common functionalities in a separate service</h3>
<p>This may seem a good approach because the utilities can be implemented in any language and it does not share resources with other services. </p>
<p>The downsides are that it adds latency to the application when we deploy two services on different containers, and it adds complexity in terms of hosting, deployment, and management.</p>
<h3 id="heading-how-can-we-do-it-better">How can we do it better?</h3>
<p>One method is using the side-car pattern. It states that a container should only address a single concern and do it well. </p>
<p>So to do that, we have a single node (virtual or physical machine) with two containers. </p>
<p>The first is the application container which contains the business logic. The second container, usually called the sidecar, is used to extend/enhance the functionality of the application container. </p>
<p>Now you might ask, "But, how is this useful?"</p>
<p>You should keep in mind that the sidecar service runs in the same node as the application container. So they share the same resources (like filesystem, memory, network, and so on...)</p>
<h3 id="heading-an-example">An example</h3>
<p>Let's say you have a legacy application that generates logs and saves them in a volume (persisted data) and you want to extract them into an external platform such as ELK. </p>
<p>One way to do this is just extending the main application. But that's difficult due to the messy code.</p>
<p>So you decide to go with the sidecar method and develop a utility service that:</p>
<ul>
<li>Captures the logs from the volume. </li>
<li>Transfers the logs into Elastic. </li>
</ul>
<p>The architecture of the node would look something like this:</p>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-7.png" alt="Image" width="1123" height="613" loading="lazy">
<em><a target="_blank" href="https://medium.com/nerd-for-tech/microservice-design-pattern-sidecar-sidekick-pattern-dbcea9bed783">Source</a></em></p>
<p>Hooray, you haven't changed any code in the application and you extended its functionality by plugging in a sidecar. </p>
<p>Heck, you can even plug this log aggregator sidecar into other applications.  </p>
<h4 id="heading-pros-6">Pros:</h4>
<ul>
<li><strong>Modularity</strong> – Sidecar allows you to develop and maintain utility functions independently. </li>
<li><strong>Scalability</strong> – If there is too much load on the sidecar, you can easily horizontally scale it by adding more containers. </li>
<li><strong>Isolation</strong> – The sidecar is isolated from the main application, providing an additional layer of security. </li>
</ul>
<h4 id="heading-cons-6">Cons:</h4>
<ul>
<li><strong>Complexity</strong> –  It requires extra management of multiple containers and their dependencies.</li>
<li><strong>Resource overhead</strong> – Because we have an extra container, this can increase the overall resource usage of the application.</li>
<li><strong>Coordination</strong> – The sidecar must be coordinated in a way that it works correctly with the main application which increases complexity. </li>
<li><strong>Debugging</strong> – Debugging is more difficult with the sidecar pattern, as it requires tracing the interactions between the main application and the sidecar.</li>
</ul>
<h3 id="heading-use-cases-3">Use Cases</h3>
<p>The sidecar pattern is useful when you want to add additional functionality to the application without touching the core business logic code. </p>
<p>By deploying the sidecar, the core logic can remain lightweight and focus on its primary task while the sidecar can handle additional functionality.</p>
<p>If need be, you can reuse the sidecar for other applications too. </p>
<p>Now that we know when to use this pattern, let's look at some use cases where it is beneficial:</p>
<ul>
<li><strong>Logging and Monitoring</strong> – The sidecar container collects logs and metrics from the main container, providing centralized storage and real-time monitoring for improved observability.</li>
<li><strong>Caching</strong> – The sidecar container caches frequently accessed data or responses, enhancing performance by reducing the need for repeated requests to external services.</li>
<li><strong>Service Discovery and Load Balancing</strong> – The sidecar container registers the main container with a service discovery system, enabling load balancing and fault tolerance across multiple instances of the main container.</li>
<li><strong>Security and Authentication</strong> – The sidecar container handles authentication tasks, offloading responsibilities like OAuth, JWT verification, or certificate management from the main container.</li>
<li><strong>Data Transformation and Integration</strong> – The sidecar container performs data transformation and integration tasks, facilitating seamless communication and synchronization between the main container and external systems.</li>
<li><strong>Proxy and Gateway</strong> –  The sidecar container acts as a proxy or gateway, providing functionalities like rate limiting, SSL termination, or protocol translation for enhanced communication capabilities.</li>
<li><strong>Performance Optimization</strong> – The sidecar container handles CPU-intensive tasks or background processes, optimizing resource usage and improving the main container's performance.</li>
</ul>
<h2 id="heading-write-ahead-log-technique">Write-Ahead Log Technique</h2>
<p>Imagine this: you are working on a service that is connected to a database with sensitive user information. </p>
<p>One day, the server crashes. Your database crashes. All the data is gone, apart from the backups. </p>
<p>You sync the database with the backup, but the backup is not up to date. It's 1 day old. You sit and cry in the corner. </p>
<p>Well thankfully, that will most likely never happen.</p>
<p>Because most databases have something called a write-ahead log (WAL). </p>
<h3 id="heading-what-is-a-write-ahead-log">What is a write-ahead log?</h3>
<p>A write-ahead log is a popular technique used to preserve:</p>
<ul>
<li><strong>Atomicity</strong> – Every transaction is treated as a single unit. Either the entire transaction is executed, or none of it is executed. This ensures that the data does not get corrupted or lost. </li>
<li><strong>Durability</strong> –  Ensures that the data will not be lost, even in an event of a system failure. </li>
</ul>
<h3 id="heading-but-how-does-it-work">But how does it work?</h3>
<p>A WAL stores every change you made onto a file on a hard disk. </p>
<p>So for example, let's say you created your own in-memory database called KVStore. In case of system failure, you want:</p>
<ul>
<li>Data to not be lost.</li>
<li>Data to be recovered onto memory. </li>
</ul>
<p>So you decide to implement a write-ahead log. </p>
<p>Every time you do any transaction (SET or REMOVE), the command will be logged into a file on the hard disk. This allows us to recover the data in case of system failure. The memory will be flushed, but the log is still stored in the hard drive. </p>
<p>The overall architecture would look something like this:</p>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-8.png" alt="Image" width="960" height="540" loading="lazy">
<em><a target="_blank" href="https://martinfowler.com/articles/patterns-of-distributed-systems/wal.html">Source</a></em></p>
<h3 id="heading-its-not-all-sunshine-and-rainbows">It's not all sunshine and rainbows</h3>
<p>As useful as it is, WAL is not easy to implement. There are many nuances, but the most common ones are:</p>
<h4 id="heading-performance">Performance</h4>
<p>If you use standard file-handling libraries in most programming languages, you would most likely "flush" the file onto the hard disk. </p>
<p>Flushing every log will give you a strong guarantee of durability. But this severely limits performance and can quickly become a bottleneck. </p>
<p>You might ask, "why don't we delay flushing or do it asynchronously?"</p>
<p>Well, this might improve performance but at the risk of losing entries from the log if the server crashes before entries are flushed.</p>
<p>The best practice here is to implement techniques like Batching, to limit the impact of the flush operation.</p>
<h4 id="heading-data-corruption">Data Corruption</h4>
<p>The other consideration is that we have to make sure that corrupted log files are detected. </p>
<p>To handle this, save log files via CRC (Cyclic Redundancy Check) records, which validates the files when read.</p>
<h4 id="heading-storage">Storage</h4>
<p>Single Log files can be difficult to manage and can consume all the available storage. </p>
<p>To handle this issue, use techniques like:</p>
<ul>
<li><strong>Segmented Log</strong> – Split the single log into multiple segments. </li>
<li><strong>Low-Water Mark</strong> – This technique tells us which portion of the logs can be safely discarded. </li>
</ul>
<p>These two techniques are used together as they both complement each other. </p>
<h4 id="heading-duplicate-entries">Duplicate Entries</h4>
<p>WALs are append-only, meaning that you can only add data. Because of this behavior, we might have duplicate entries. So when the log is applied, it needs to make sure that the duplicates are ignored. </p>
<p>One way to solve this is to use a hashmap, where updates to the same key are idempotent. If not, then there needs to be a mechanism to mark each transaction with a unique identifier and detect duplicates. </p>
<h3 id="heading-use-cases-4">Use Cases</h3>
<p>Overall WALs are mostly used in databases but can be beneficial in other areas:</p>
<p>Write-ahead logs (WALs) are widely used in various systems and databases. Here are some common use cases for write-ahead logs:</p>
<ul>
<li><strong>File Systems</strong> – File systems can employ write-ahead logging to maintain data consistency. By logging changes before applying them to the file system, WALs allow for crash recovery and help prevent data corruption in case of system failures.</li>
<li><strong>Message Queues and Event Sourcing</strong> – Write-ahead logs are often used in message queues and event sourcing architectures. The logs serve as a reliable and ordered record of events, allowing for reliable message delivery, event replay, and system state restoration.</li>
<li><strong>Distributed Systems</strong> – Distributed systems that need to maintain consistency across multiple nodes can benefit from write-ahead logs. By coordinating log replication and replay, WALs help synchronize data updates and ensure consistency in distributed environments.</li>
</ul>
<h2 id="heading-split-brain-pattern">Split-Brain Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-113.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.alachisoft.com/resources/docs/ncache/admin-guide/split-brain.html">Source</a></em></p>
<p>That's definitely an interesting name, isn't it? It might make you think of the two halves of the brain. </p>
<p>Well, it is actually somewhat similar. </p>
<p>A split brain in distributed systems happens when nodes in a distributed system become disconnected from each other but still continue to operate. </p>
<p>Split brain? Nodes working independently when they should work together? Sound similar? I hope so. </p>
<p>Anyways, the biggest problem with this is that it causes:</p>
<ul>
<li>Data Inconsistency</li>
<li>Competing for resources</li>
</ul>
<p>This will usually shut the cluster off while developers try to fix things. This causes downtime which makes the business lose money.</p>
<h3 id="heading-whats-the-fix">What's the fix?</h3>
<p>One fix is using a generational number. Every time a leader is elected, the generation number gets incremented. </p>
<p>For example, if the old leader had a generational number of one, then the second leader will have a generational number of two.</p>
<p>The generation number is included in every request, and now clients can just trust the leader with the highest number. </p>
<p>But keep in mind that the generational number must be persisted on disk.</p>
<p>One way to do that is using a Write Ahead Log. See, things are connected to each other. </p>
<p>This solution is categorized as a leader election but there are others:</p>
<ul>
<li><strong>Quorum-based Consensus</strong> – Use algorithms like Raft or Paxos to ensure that only a majority of nodes can make decisions, preventing conflicting decisions in a split brain scenario.</li>
<li><strong>Network Partition Detection</strong> – Use monitoring techniques or distributed failure detectors to identify network partitions and take appropriate actions.</li>
<li><strong>Automatic Reconciliation</strong> – Implement mechanisms to automatically resolve conflicts and ensure data consistency once a split brain is resolved, such as merging conflicting changes or using timestamps or vector clocks.</li>
<li><strong>Application-level Solutions</strong> – Design the application to tolerate split brain scenarios by employing eventual consistency models, conflict-free data structures, or CRDTs.</li>
<li><strong>Manual Intervention</strong> –In some cases, manual intervention may be required to resolve split brain scenarios, involving human decision-making or administrative actions to determine the correct system state and perform data reconciliation.</li>
</ul>
<h3 id="heading-pros-7">Pros</h3>
<ul>
<li><strong>Data Consistency</strong> – Implementing a fix ensures that shared data remains consistent across the distributed system.</li>
<li><strong>System Stability</strong> – Resolving split brain scenarios promotes system stability by avoiding conflicting operations and maintaining coherent behavior.</li>
</ul>
<h3 id="heading-cons-7">Cons</h3>
<ul>
<li><strong>Increased Complexity</strong> – Fixing split brain scenarios adds complexity to the system due to the intricate logic and mechanisms required.</li>
<li><strong>Performance Overhead</strong> – Split brain resolution mechanisms may impact system performance and latency due to additional processing and communication requirements.</li>
<li><strong>Higher Resource Utilization</strong> – Addressing split brain scenarios may require allocating more resources, potentially increasing costs.</li>
<li><strong>Increased Failure Surface</strong> – Introducing split brain resolution mechanisms may inadvertently introduce new failure modes or vulnerabilities.</li>
<li><strong>Configuration and Tuning Complexity</strong> – Implementing a fix requires careful configuration and ongoing maintenance to ensure optimal behavior in different scenarios.</li>
</ul>
<h2 id="heading-hinted-handoff-pattern">Hinted Handoff Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-114.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://docs.datastax.com/eol/en/dse/6.0/dse-arch/datastax_enterprise/dbArch/archRepairNodesHintedHandoff.html">Source</a>_</p>
<p>The Hinted Handoff technique makes sure that you have:</p>
<ul>
<li><strong>Fault Tolerance</strong> – The ability of the system to continue working even if one or more components fail. </li>
<li><strong>Availability of Data</strong> –  Ability to access and modify the data at any given time. </li>
</ul>
<h3 id="heading-what-problem-does-it-solve">What problem does it solve?</h3>
<p>Imagine you have a bank service that communicates with a node that has three replicas. None of the nodes are leaders, so the architecture is leaderless. </p>
<p>You send a request to update the customer's balance to $100. You send this to all the replicas. </p>
<p>The request is successful for the first two replicas but the last one is down. After a few seconds, the replica that was down got back up again but it has the old data.</p>
<h3 id="heading-how-do-we-fix-this-issue">How do we fix this issue?</h3>
<p>The hinted handoff technique says that when a node for a particular data goes offline, then the other nodes of the system will temporarily store updates or modifications intended for the unavailable node. </p>
<p>Hence the name "hints". </p>
<p>So when the unavailable node comes back alive, it can retrieve the hints and apply them. </p>
<p>So the process goes like this:</p>
<ol>
<li><strong>Detection</strong> – When a node fails, other nodes detect this failure and mark that node as unavailable. </li>
<li><strong>Hint Generation</strong> – When a node receives a request to send to the unavailable node, it will store it locally, usually to a file on the disk.  </li>
<li><strong>Hint Delivery</strong> – When the available node goes back online, it sends a message to the other nodes requesting any hints that were made while it was offline. The other nodes send the hints and the node applies them.  </li>
</ol>
<p>By using this technique we ensure our data is consistent and available even when nodes fail or become temporarily unavailable.</p>
<h3 id="heading-pros-8">Pros</h3>
<ul>
<li><strong>Improved data availability</strong> – Hinted handoff ensures data remains accessible during temporary node failures by transferring responsibilities to other nodes.</li>
<li><strong>Data consistency</strong> – Hinted handoff helps maintain data consistency by synchronizing the failed node with others when it recovers.</li>
<li><strong>Reduced latency</strong> – Hinted handoff minimizes the impact of node failures on system performance, routing requests to alternative nodes and reducing latency.</li>
<li><strong>Scalability</strong> – Hinted handoff enables dynamic redistribution of data responsibilities, allowing the system to handle increased workloads and node changes.</li>
</ul>
<h3 id="heading-cons-8">Cons</h3>
<ul>
<li><strong>Increased complexity</strong> – Implementing hinted handoff adds complexity to the system, making development, debugging, and maintenance more challenging.</li>
<li><strong>Storage overhead</strong> – Hinted handoff requires storing additional metadata, incurring storage overhead to track handoff status.</li>
<li><strong>Potential data staleness</strong> – After a failure, recovered nodes may have temporarily stale data until synchronization occurs, leading to potential inconsistencies.</li>
<li><strong>Increased network traffic</strong> – Hinted handoff involves transferring data responsibilities, resulting in increased network traffic and potential impact on network performance.</li>
</ul>
<h3 id="heading-use-cases-5">Use Cases</h3>
<p>Hinted handoff is typically implemented in distributed database systems or distributed storage systems where data availability and consistency are crucial.</p>
<p>Here are some scenarios where implementing hinted handoff is beneficial:</p>
<ul>
<li><strong>Cloud storage systems</strong> – Hinted handoff enables seamless redirection of client requests to available nodes in cloud storage systems when a node becomes temporarily unavailable.</li>
<li><strong>Messaging systems</strong> – Hinted handoff allows distributed messaging systems to route messages to other active brokers when a broker node fails, ensuring message delivery and system operability.</li>
<li><strong>Distributed file systems</strong> – Hinted handoff in distributed file systems allows the temporary transfer of data responsibilities to other nodes when a data node fails, ensuring data availability and uninterrupted read/write operations.</li>
<li><strong>Content delivery networks (CDNs)</strong> – Hinted handoff in CDNs facilitates the redirection of content delivery requests to other servers in the network when a server becomes temporarily unavailable, ensuring continuous content delivery to users.</li>
</ul>
<h2 id="heading-read-repair-pattern">Read Repair Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-115.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://martinfowler.com/articles/patterns-of-distributed-systems/version-vector.html#ReadRepair">Source</a></em></p>
<p>In a distributed system, you can have data partitioned into multiple nodes. </p>
<p>This introduces a new challenge where we have to keep the data consistent in all nodes. </p>
<p>For example, if you update data on node A, the changes might not be immediately propagated to other nodes due to all sorts of reasons.</p>
<h3 id="heading-so-we-use-the-read-repair-pattern">So we use the "read repair" pattern</h3>
<p>When a client reads a piece of data from a node, that node will check if the data is the latest. If not, then it receives the latest data from another node.</p>
<p>Once it receives the latest data, it will update the node with the old data with the new data. Hence the "repair".</p>
<h3 id="heading-but-this-is-done-on-the-application-side">But this is done on the application side</h3>
<p>Doing things on the application side is pretty flexible as you can have your own custom logic per service but it increases complexity and development time. </p>
<p>Thankfully, there are three other methods of implementing read repair:</p>
<ul>
<li><strong>Write-Based Read Repair</strong> – Proactively update multiple replicas or nodes with the latest data during write operations.</li>
<li><strong>Background Repair</strong> – Schedule periodic background repair processes to scan and repair inconsistencies in the database.</li>
<li><strong>Database-Specific Read Repair</strong> – Leverage built-in read repair mechanisms or conflict resolution features provided by the database.</li>
</ul>
<h3 id="heading-pros-9">Pros</h3>
<ul>
<li><strong>Data Consistency</strong> – Read repair maintains data consistency by automatically detecting and correcting inconsistencies between replicas or nodes.</li>
<li><strong>Improved User Experience</strong> – Read repair provides reliable and accurate data, enhancing the user experience by reducing conflicting or outdated information.</li>
<li><strong>Fault Tolerance</strong> – Read repair increases system resilience by addressing data inconsistencies and reducing the risk of cascading failures.</li>
<li><strong>Performance Optimization</strong> – Read repair improves performance by minimizing the need for separate repair processes and distributing the repair workload.</li>
<li><strong>Simplified Development</strong> – Read repair automates consistency checks, simplifying application development.</li>
</ul>
<h3 id="heading-cons-9">Cons</h3>
<ul>
<li><strong>Increased Complexity</strong> – Implementing read repair adds complexity to system design, development, and maintenance efforts.</li>
<li><strong>Performance Overhead</strong> – Read repair may introduce additional latency and computational overhead, impacting overall system performance.</li>
<li><strong>Risk of Amplifying Failures</strong> – Incorrect implementation of read repair can propagate inconsistencies or amplify failures.</li>
<li><strong>Scalability Challenges</strong> – Coordinating repairs in large-scale systems can be challenging, impacting performance and scalability.</li>
<li><strong>Compatibility and Portability</strong> – Read repair mechanisms may be specific to certain databases or technologies, limiting compatibility and portability.</li>
</ul>
<h3 id="heading-use-cases-6">Use Cases</h3>
<p>Read repair can be beneficial in various scenarios where maintaining data consistency across replicas or nodes is crucial. </p>
<p>Here are some situations where you should consider using read repair:</p>
<ul>
<li><strong>Distributed Database Systems</strong> – Use read repair in distributed database systems where data is replicated across multiple nodes or replicas to ensure data consistency.</li>
<li><strong>High Data Consistency Requirements</strong> – Implement read repair when your application requires a high level of data consistency, such as in financial systems, collaborative editing platforms, or real-time analytics.</li>
<li><strong>Read-Heavy Workloads</strong> – Consider read repair for read-heavy workloads to detect and reconcile inconsistencies during read operations, improving performance by reducing the need for separate repair processes.</li>
<li><strong>Systems with Network Delays or Failures</strong> – Use read repair in environments with network delays or occasional node failures to automatically detect and correct data inconsistencies caused by these issues.</li>
</ul>
<h2 id="heading-service-registry-pattern">Service Registry Pattern</h2>
<p>When you are working with a distributed system, you will have services that have instances that can scale up or down.   </p>
<p>One service can have ten instances at one time and two at another time. </p>
<p>The IP addresses of these instances get created dynamically. Problems arise here. </p>
<p>Imagine that you have a client and it wants to talk to a service. How will it know the IP address of the service if IP addresses are dynamically created?</p>
<p>The answer is a service registry. </p>
<h3 id="heading-what-the-heck-is-that">What the heck is that?</h3>
<p>A service registry is usually a separate service that runs that keeps information about available instances and their locations. </p>
<p>But how does the service registry know all this information?</p>
<p>When we create an instance of any of our services, we register ourselves to the service registry with our name, IP address, and port number. </p>
<p>The service registry then stores this information in its data store. </p>
<p>When a client needs to connect to a service, it queries the service registry to obtain the necessary information for connecting to the service.</p>
<p>Now that we know what a service registry is, let's talk about the patterns of service discovery.  </p>
<h3 id="heading-client-side-discovery">Client Side Discovery</h3>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-9.png" alt="Image" width="1024" height="967" loading="lazy">
<em><a target="_blank" href="https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/">Source</a></em></p>
<p>The first and easiest way is for the client to call the service registry and get information about all the available instances of a service. </p>
<p>This approach works well when you want to:</p>
<ul>
<li>Have something simple and straightforward.</li>
<li>Have the client-side make the decisions about which instances to call. </li>
</ul>
<p>But the significant drawback here is that it couples the client with the service registry.</p>
<p>So you must implement client-side discovery logic for every programming language and framework that your service uses.   </p>
<h3 id="heading-server-side-discovery">Server Side Discovery</h3>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-10.png" alt="Image" width="1024" height="631" loading="lazy">
<em><a target="_blank" href="https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/">Source</a></em></p>
<p>On the other hand, the server-side discovery forces the client to make the request via a load balancer. </p>
<p>If you don't know what a load balancer is, feel free to check out my <a target="_blank" href="https://tamerlan.dev/load-balancing-101-how-it-works-and-why-it-matters-for-your-platform/">other comprehensive article on it</a>. </p>
<p>The load balancer will call the service registry and routes the request to the specific instance. </p>
<p>Server-side discovery has the following benefits:</p>
<ul>
<li>Abstracting the details of the service registry to the load balancer means that the client can simply make a request to the load balancer.   </li>
<li>It's built-in in most popular providers such as AWS ELB (Elastic Load Balancer). </li>
</ul>
<p>The only downside is that you have another component (service registry) in your infrastructure that you have to maintain.    </p>
<h2 id="heading-circuit-breaker-pattern">Circuit Breaker Pattern</h2>
<p><img src="https://tamerlan.dev/content/images/2023/05/image-13.png" alt="Image" width="1102" height="852" loading="lazy">
<em><a target="_blank" href="https://martinfowler.com/bliki/CircuitBreaker.html">Source</a></em></p>
<p>Let's say you have three services, A, B, and C. They all call each other sequentially – A calls B, which calls C. </p>
<p>All goes well as long as the services work. But what if one of the services is down Then the other services would fail. If service C is down, then B and A would be down, too. </p>
<h3 id="heading-how-do-we-fix-this">How do we fix this?</h3>
<p>We use the circuit breaker pattern which acts as a middleware between two services. </p>
<p>It monitors the state of the second service and, in case of failure or unresponsiveness, stops the requests to the service and returns a fallback response or error message to the component.</p>
<p>The middleware has three states:</p>
<ul>
<li><strong>Closed</strong> – The service can communicate with the second service normally. </li>
<li><strong>Open</strong> – When the middleware detects a certain number of consecutive failures then it transitions to the open state, and all requests to the service are immediately blocked.</li>
<li><strong>Half Open</strong> – After a certain period of time, the middleware transitions to a half-open state which allows a limited number of requests to be sent to the second service. If successful, then the middleware transitions to a closed state otherwise it will transition to an open state.</li>
</ul>
<p>Overall, the circuit breaker pattern increases resilience by providing a fallback mechanism and reducing the load on a failed service.</p>
<p>It also provides insight into the status of a service which helps us identify failures more quickly. </p>
<h3 id="heading-pros-10">Pros</h3>
<ul>
<li><strong>Fault tolerance</strong> – Circuit breakers enhance system stability by protecting against cascading failures and reducing the impact of unavailable or error-prone dependencies.</li>
<li><strong>Fail-fast mechanism</strong> – Circuit breakers quickly detect failures, allowing for faster recovery and reducing latency by avoiding waiting for failed requests to complete.</li>
<li><strong>Graceful degradation</strong> – Circuit breakers enable the system to gracefully degrade functionality by providing alternative responses or fallback mechanisms during failures.</li>
<li><strong>Load distribution</strong> – Circuit breakers can balance the load across available resources during high traffic or when a service is experiencing issues.</li>
</ul>
<h3 id="heading-cons-10">Cons</h3>
<ul>
<li><strong>Increased complexity</strong> – Implementing a circuit breaker adds complexity to the system, impacting development, testing, and maintenance efforts.</li>
<li><strong>Overhead and latency</strong> – Circuit breakers introduce processing overhead and latency as requests are intercepted and evaluated against circuit states.</li>
<li><strong>False positives</strong> – Circuit breakers can mistakenly block requests even when the dependency is available, leading to false positives and impacting system availability and performance.</li>
<li><strong>Dependency on monitoring</strong> – Circuit breakers rely on accurate monitoring and health checks, and if these are unreliable, the effectiveness of the circuit breaker may be compromised.</li>
<li><strong>Limited control over remote services</strong> – Circuit breakers provide protection but lack direct control over underlying services, requiring external intervention for resolving certain issues.</li>
</ul>
<h3 id="heading-use-cases-7">Use Cases</h3>
<p>The circuit breaker pattern is beneficial in specific scenarios where a system relies on remote services or external dependencies. </p>
<p>Here are some situations where it is recommended to use the circuit breaker pattern:</p>
<ul>
<li><strong>Distributed systems</strong> – When building distributed systems that communicate with multiple services or external APIs, the circuit breaker pattern helps improve fault tolerance and resilience by mitigating the impact of failures in those dependencies.</li>
<li><strong>Unreliable or intermittent services</strong> – If you are integrating with services or dependencies that are known to be unreliable or have intermittent availability, implementing a circuit breaker can protect your system from prolonged delays or failures caused by those dependencies.</li>
<li><strong>Microservices architecture</strong> – In a microservices architecture, where individual services have their own dependencies, implementing circuit breakers can prevent cascading failures across services and enable graceful degradation of functionality during failures.</li>
<li><strong>High-traffic scenarios</strong> – In situations where the system experiences high traffic or load, circuit breakers can help distribute the load efficiently by redirecting requests to alternative services or providing fallback responses, thereby maintaining system stability and performance.</li>
<li><strong>Resilient and responsive systems</strong> – The circuit breaker pattern is useful when you want to build systems that are resilient and responsive to failures. It allows the system to quickly detect and recover from issues, reducing the impact on users and ensuring a smoother user experience.</li>
</ul>
<h2 id="heading-leader-election-pattern">Leader Election Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-116.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://www.google.com/search?q=leader+election+pattern&amp;tbm=isch&amp;ved=2ahUKEwir3L6n3o7_AhUMwSoKHdg3BngQ2-cCegQIABAA&amp;oq=leader+election+pattern&amp;gs_lcp=CgNpbWcQAzIHCAAQGBCABDIHCAAQGBCABDoECCMQJzoFCAAQgAQ6BggAEAgQHjoHCCMQ6gIQJzoHCAAQigUQQzoGCAAQBRAeOgQIABAeUNkEWIskYJAmaAFwAHgAgAFNiAGNDJIBAjI0mAEAoAEBqgELZ3dzLXdpei1pbWewAQrAAQE&amp;sclient=img&amp;ei=1WtuZOudM4yCqwHY75jABw&amp;bih=837&amp;biw=1512#imgrc=Ppb-jyxvryxCWM">Source</a>_</p>
<p>The leader election pattern is a pattern that gives a single thing (process, node, thread, object) superpowers in a distributed system. </p>
<p>This pattern is used to ensure that a group of nodes can coordinate effectively and efficiently. </p>
<p>So when you have three or five nodes performing similar tasks such as data processing or maintaining a shared resource, you don't want them to conflict with one another (that is, contesting for resources or interfering with each other's work).</p>
<h3 id="heading-elect-one-leader-that-coordinates-everything">Elect one leader that coordinates everything</h3>
<p>The leader will be responsible for critical decisions or distributing workloads among the other processes.</p>
<p>Any node can be a leader, so we should be careful when we elect them. We don't want two leaders at the same time. </p>
<p>So we must have a good system for selecting a leader. It must be robust, which means it has to cope with network outages or node failures. </p>
<h3 id="heading-how-to-select-a-leader">How to select a leader</h3>
<p>One algorithm named Bully assigns every node with a unique identifier. The node with the highest identifier initially is considered the leader. </p>
<p>If a low-ranked node detects that the leader has failed, it sends a signal to all the other high-ranked nodes to take over. If none of them respond then the node will make itself the leader. </p>
<p>Another popular algorithm is called the Ring algorithm. Each node is arranged in a logical ring. The node with the highest identifier is initialized as a ring. </p>
<p>If a lower-ranked node detects that the ring has failed, then it will request all the other nodes to update their leader to the next highest node.</p>
<p>Both of the above algorithms assume that every node can be uniquely identified.  </p>
<h3 id="heading-pros-11">Pros</h3>
<ul>
<li><strong>Coordination</strong> –  Leader election allows for better organization and coordination in distributed systems by establishing a centralized point of control.</li>
<li><strong>Task Assignment</strong> –  The leader can efficiently allocate and distribute tasks among nodes, optimizing resource utilization and workload balancing.</li>
<li><strong>Fault Tolerance</strong> –  Leader election ensures system resilience by promptly electing a new leader if the current one fails, minimizing disruptions.</li>
<li><strong>Consistency and Order</strong> – The leader maintains consistent operations and enforces the proper order of tasks in distributed systems, ensuring coherence.</li>
</ul>
<h3 id="heading-cons-11">Cons</h3>
<ul>
<li><strong>Overhead and Complexity</strong> – Leader election introduces additional complexity and communication overhead, increasing network traffic and computational requirements.</li>
<li><strong>Single Point of Failure</strong> – Dependency on a single leader can lead to system disruptions if the leader fails or becomes unavailable.</li>
<li><strong>Election Algorithms</strong> – Implementing and selecting appropriate leader election algorithms can be challenging due to varying trade-offs in performance, fault tolerance, and scalability.</li>
<li><strong>Sensitivity to Network Conditions</strong> – Leader election algorithms can be sensitive to network conditions, potentially impacting accuracy and efficiency in cases of latency, packet loss, or network partitions.</li>
</ul>
<h3 id="heading-use-cases-8">Use Cases</h3>
<ul>
<li><strong>Distributed Computing</strong> –  In distributed computing systems, leader election is crucial for coordinating and synchronizing the activities of multiple nodes. It enables the selection of a leader responsible for distributing tasks, maintaining consistency, and ensuring efficient resource utilization.</li>
<li><strong>Consensus Algorithms</strong> – Leader election is a fundamental component of consensus algorithms such as Paxos and Raft. These algorithms rely on electing a leader to achieve agreement among distributed nodes on the state or order of operations.</li>
<li><strong>High Availability Systems</strong> – Leader election is employed in systems that require high availability and fault tolerance. By quickly electing a new leader when the current one fails, these systems can ensure uninterrupted operations and mitigate the impact of failures.</li>
<li><strong>Load Balancing</strong> – In load balancing scenarios, leader election can be used to select a leader node responsible for distributing incoming requests among multiple server nodes. This helps in optimizing resource utilization and evenly distributing the workload.</li>
<li><strong>Master-Slave Database Replication</strong> – In database replication setups, leader election is used to determine the master node responsible for accepting write operations. The elected master coordinates data synchronization with slave nodes, ensuring consistency across the replica set.</li>
<li><strong>Distributed File Systems</strong> – Leader election is often employed in distributed file systems, such as Apache Hadoop's HDFS. It helps in maintaining metadata consistency and enables efficient file access and storage management across a cluster of nodes.</li>
</ul>
<h2 id="heading-bulk-head-pattern">Bulk Head Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-117.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/patterns/bulkhead">Source</a></em></p>
<p>Things fail for all sorts of reasons in a distributed system. This is why we need to make sure our systems are resilient in case of failures. </p>
<p>One way to improve that is to use the bulkhead pattern. </p>
<p>So let's say we have two services, A and B.</p>
<p>Some requests of A depend on B. But the issue is that service B is pretty slow which makes A slow and blocks its threads. This makes all requests to A slow, even the ones which don't depend on B. </p>
<p>The bulkhead pattern solves that by allocating a specific amount of threads for requests to B. This prevents A from consuming all threads due to B. </p>
<h3 id="heading-pros-12">Pros</h3>
<ul>
<li><strong>Fault isolation</strong> – The bulkhead pattern contains failures within individual services, minimizing their impact on the overall system.</li>
<li><strong>Scalability</strong> – Services can be independently scaled, allowing allocation of resources where needed without affecting the entire system.</li>
<li><strong>Performance optimization</strong> – Specific services can receive performance optimizations independently, ensuring efficient operation.</li>
<li><strong>Development agility</strong> – Code modularity and separation of concerns facilitate parallel development efforts.</li>
</ul>
<h3 id="heading-cons-12">Cons</h3>
<ol>
<li><strong>Complexity</strong> – Implementing the bulkhead pattern adds architectural complexity to the system.</li>
<li><strong>Increased resource usage</strong> –  Duplication of resources across components may increase resource consumption.</li>
<li><strong>Integration challenges</strong> –  Coordinating and integrating the services can be challenging and introduce potential points of failure.</li>
</ol>
<h3 id="heading-use-cases-9">Use Cases</h3>
<p>Here are some common scenarios where the bulkhead pattern is beneficial:</p>
<ul>
<li><strong>Microservices architecture</strong> –  The bulkhead pattern is used to isolate individual microservices, ensuring fault tolerance and scalability in a distributed system.</li>
<li><strong>Resource-intensive applications</strong> – By partitioning the system into components, the bulkhead pattern optimizes resource allocation, enabling efficient processing of resource-intensive tasks without impacting other components.</li>
<li><strong>Concurrent processing</strong> –  The bulkhead pattern helps handle concurrent processing by assigning dedicated resources to each processing unit, preventing failures from affecting other units.</li>
<li><strong>High-traffic or high-demand systems</strong> –  In systems experiencing high traffic or demand, the bulkhead pattern distributes the load across components, preventing bottlenecks and enabling scalable handling of increased traffic.</li>
<li><strong>Modular and extensible systems</strong> –  The bulkhead pattern facilitates modular development and maintenance, allowing independent updates and deployment of specific components in a system.</li>
</ul>
<h2 id="heading-retry-pattern">Retry Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-118.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://dev.to/azure/learn-about-the-retry-pattern-in-5-minutes-fjo">Source</a></em></p>
<p>The retry pattern is used to handle temporary failures. </p>
<p>Requests fail for all sorts of reasons, from faulty connections to site reloading after a deployment.  </p>
<p>So let's say we have a client and a service. The client sends a request to the service and receives a response code 500 back. </p>
<p>There are multiple ways to handle this according to the retry pattern.</p>
<ul>
<li>If the problem is rare, then retry immediately. </li>
<li>If the problem is more common, then retry after some amount of delay (for example 50ms, 100ms, etc)</li>
<li>If the issue is not temporary (invalid credentials, and so on) then cancel the request. </li>
</ul>
<h3 id="heading-but-sometimes-the-client-thinks-that-the-request-has-failed">But sometimes, the client thinks that the request has failed</h3>
<p>Sometimes the operation was a success but the request failed to return something. This happens when requests are not stateless, meaning that they change the state of the system somehow (like CRUD operations on a database). </p>
<p>So what we do is we send a duplicate request which can cause problems in the system. </p>
<p>For that, we need some sort of tracking system. We can use the circuit breaker pattern to limit the impact of repeatedly retrying a failed/recovering service.</p>
<h3 id="heading-pros-13">Pros</h3>
<ul>
<li><strong>Resilience and Reliability</strong> – By automatically retrying failed requests, you increase the chance of the system recovering from failure (resilience) and increase a chance of a successful requests (reliability). </li>
<li><strong>Error handling</strong> – Retrying an operation transparently hides the error from the end user, making the system appear more robust.</li>
<li><strong>Simplified Implementation</strong> – The retry pattern is simple to implement. Instead of having custom error handling logic for all your requests, you can wrap them all with a <code>retry pattern class</code>. </li>
<li><strong>Performance optimization</strong> – In some cases, temporary errors may be resolved quickly, and the subsequent retries can succeed without significant delays. This can help optimize performance by avoiding unnecessary failures and reducing the impact on the end user.</li>
</ul>
<h3 id="heading-cons-13">Cons</h3>
<ul>
<li><strong>Increased latency</strong> – When retries are attempted, there is an inherent delay introduced in the system. If the retries are frequent or the operations take a long time to complete, the overall latency of the system may increase. </li>
<li><strong>Risk of infinite loops</strong> – Without proper safeguards, retries can potentially lead to infinite loops if the underlying error condition persists. </li>
<li><strong>Increased network and resource usage</strong> – Retrying failed operations can lead to additional network traffic and resource utilization. </li>
<li><strong>Potential for cascading failures</strong> – If the underlying cause of the failure is not resolved, retrying the operation may result in cascading failures throughout the system. </li>
<li><strong>Difficulty in handling idempotent operations</strong> – Retrying stateful requests can lead to unintended consequences if the request is performed multiple times. </li>
</ul>
<h3 id="heading-use-cases-10">Use Cases</h3>
<p>The applicability of the retry pattern depends on the specific requirements and characteristics of the system being developed. </p>
<p><strong>The pattern is most useful for handling temporary errors.</strong> But, you must also keep in mind for scenarios involving long delays, stateful requests, or cases where manual intervention is required.</p>
<p>Now, let's look at some use cases where retrying requests help:</p>
<ul>
<li><strong>Network communication</strong> – When working with third party services or APIs over a network, all sorts of errors can occur.</li>
<li><strong>Database operations</strong> – Databases also face the same issues due to temporary unavailability, timeouts, or deadlock situations.</li>
<li><strong>File or resource access</strong> – When accessing files, external resources, or dependencies, failures due to locks, permissions, or temporary unavailability can occur.</li>
<li><strong>Queue processing</strong> –  Systems that rely on message queues or event-driven architectures may encounter temporary issues like queue congestion, message delivery failures, or service availability fluctuations. </li>
<li><strong>Distributed transactions</strong> –  In distributed systems, performing coordinated transactions across multiple services or components can face challenges like network partitions or temporary service failures.</li>
<li><strong>Data synchronization</strong> –  When synchronizing data between different systems or databases, temporary errors can disrupt the synchronization process. </li>
</ul>
<h2 id="heading-scatter-gather-pattern">Scatter Gather Pattern</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-119.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://ssekars.wordpress.com/2015/10/16/pattern-scatter-gather/">Source</a></em></p>
<p>Let's say we have a process-heavy task like video compression. </p>
<p>We get a video and have to compress it into 5 different resolutions such as 240p, 360p, 480, 720p, and 1080p. </p>
<p>We have a single image compression service that takes in the video and processes each resolution sequentially. The problem here is that it's very slow. </p>
<p>The scatter-gather pattern advises us to run multiple of these processes simultaneously and gather all the results in one place. </p>
<p>So for our video process examples, this is how it will look:</p>
<ol>
<li>Scatter – We will divide the task into multiple nodes, so one node will take care of compressing the video into 240p, another to 360p, and so on. </li>
<li>Process – Each node will compress its video individually and simultaneously. </li>
<li>Gather – Once all the nodes have finished compressing the videos, the videos will be stored on some server and we collect the links for all the different versions. </li>
</ol>
<p>Instead of waiting for each of our videos to be compressed sequentially, now we can parallelize this whole process and increase performance significantly. </p>
<h4 id="heading-pros-14">Pros</h4>
<ul>
<li><strong>Parallel Processing</strong> – The scatter-gather pattern improves performance by enables parallel processing of subtasks. Tasks can execute concurrently across multiple nodes or processors.</li>
<li><strong>Scalability</strong> – The scatter gather pattern allows us to scale horizontally, the higher our workload, the more nodes we provision. </li>
<li><strong>Fault Tolerance</strong> – This pattern enhances fault tolerance by redistributing failed subtasks to other available nodes, ensuring the overall task can still be completed successfully.</li>
<li><strong>Resource Utilization</strong> –  The scatter-gather pattern optimizes resource utilization by efficiently leveraging available computational resources across multiple nodes or processors.</li>
</ul>
<h4 id="heading-cons-14">Cons</h4>
<ul>
<li><strong>Communication Overhead</strong> – This pattern involves communication between nodes which introduce potential latency and network congestion that may impact overall performance, especially with large data volumes.</li>
<li><strong>Load Balancing</strong> – Balancing the workload evenly across nodes can be challenging, leading to potential inefficiencies and performance bottlenecks if some nodes are idle while others are overloaded.</li>
<li><strong>Complexity</strong> – This pattern is not easy to implement and adds an aditional layer of complexity to the system. It requires careful planning and synchronization mechanisms to coordinate subtasks.</li>
<li><strong>Data Dependency</strong> – Handling dependencies among subtasks, where the output of one subtask is needed as input for another, can be more complex in the scatter-gather pattern compared to other patterns.</li>
</ul>
<h4 id="heading-use-cases-11">Use Cases</h4>
<p>The scatter-gather pattern is useful in distributed systems and parallel computing scenarios where you can divide tasks into smaller subtasks that can be performed concurrently across multiple nodes and processors. </p>
<p>Here are some use cases where the scatter-gather pattern can be used:</p>
<ul>
<li><strong>Web Crawling</strong> – You can use the scatter gather pattern to fetch and crawl multiple web pages concurrently. </li>
<li><strong>Data Analytics</strong> – Apply scatter-gather to divide large datasets into chunks for parallel processing in data analysis tasks, combining individual results for final insights.</li>
<li><strong>Image/Video Processing</strong> – Utilize scatter-gather for distributed image/video processing, such as encoding frames in parallel and gathering results for the final output.</li>
<li><strong>Distributed Search</strong> – Implement scatter-gather in distributed search systems to distribute search queries across nodes, gather and rank results for final search output.</li>
<li><strong>Machine Learning</strong> –  Apply scatter-gather in distributed machine learning for parallel model training on scattered data and combining models for final trained model.</li>
<li><strong>MapReduce –</strong>  Incorporate scatter-gather in the MapReduce model for big data processing, scattering input, parallel processing of intermediate results, and gathering for final output.</li>
</ul>
<h2 id="heading-bloom-filters-data-structure">Bloom Filters (Data Structure)</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-120.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://en.wikipedia.org/wiki/Bloom_filters_in_bioinformatics">Source</a>_</p>
<p>Bloom filters is a data structure that is designed to tell you efficiently both in memory and speed whether an item is in a set. </p>
<p>But the cost of this efficiency is that it is probabilistic. It can tell you that an item is either:</p>
<ul>
<li>Definitely not in a set.   </li>
<li>Might be in a set. </li>
</ul>
<h4 id="heading-pros-15">Pros</h4>
<ul>
<li><strong>Space Efficiency</strong> – Bloom filters usually require a smaller amount of memory to store the same number of elements compared to hash tables or other similar data structures.</li>
<li><strong>Fast Lookups</strong> – Checking whether an element is in a Bloom filter has a constant-time complexity regardless of the size of the filter or the number of elements it contains. </li>
<li><strong>No False Negatives</strong> – Bloom filters provide a definitive "no" answer if an element is not in the filter. There are no false negatives, meaning if the filter claims an element is not present, it is guaranteed to be absent.</li>
<li><strong>Parallelizable</strong> – Bloom filters can be easily parallelized, allowing for efficient implementation on multi-core systems or distributed environments.</li>
</ul>
<h4 id="heading-cons-15">Cons</h4>
<ul>
<li><strong>False Positives</strong> – Due to their probabilistic nature, there is a small probability that the filter will incorrectly claim an element is present when it is not. The probability of false positives increases as the filter becomes more crowded or the number of elements increases.</li>
<li><strong>Limited Operations</strong> – Bloom filters only support insertion and membership tests. They do not allow deletion of elements or provide a mechanism to retrieve the original elements stored in the filter. Once an element is inserted, it cannot be removed individually.</li>
<li><strong>Fixed Size</strong> – The size of the bloom filter must be determined beforehand and cannot dynamically resize. If these parameters are not estimated accurately, the filter may become ineffective or waste memory.</li>
<li><strong>Unordered Data</strong> – Bloom filters do not maintain the order or provide any information about the stored elements. They are not suitable for scenarios that require ordering or retrieval of elements based on certain criteria.</li>
</ul>
<h4 id="heading-use-cases-12">Use Cases</h4>
<p>Bloom filters are most useful in situations where approximate membership tests with a low false positive rate are acceptable and where memory efficiency is a priority. </p>
<p>Here are some scenarios where Bloom filters are particularly beneficial:</p>
<ul>
<li><strong>Caching Systems</strong> – Bloom filters can be used to quickly check if an item is likely to be present in the cache or not. By checking the bloom filter, the system can avoid the costly operation of fetching the item from the cache or underlying storage if it is not likely to be there, thereby improving overall performance. </li>
<li><strong>Content Delivery Systems</strong> – CDNs use bloom filters to handle cache invalidation. Instead of checking each edge server, we use a bloom filter to identify whether the edge server potentially has a specific resource.</li>
<li><strong>Anti-Spam Systems</strong> – Anti-spam systems check emails against common spam databases. Instead of checking against the databases which is expensive, we use bloom filters which are much more efficient. </li>
<li><strong>Distributed Data Processing</strong> – In a distributed data processing framework such as Hadoop or Spark. We use bloom filters to optimize join operations by pre-filtering data and removing unnecessary shuffles. </li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You don't need to be an expert in all of these things – I'm not. And even if you don't ever directly use or work with some of these concepts, they are still good to know. </p>
<p>Try to implement them in simple projects. It's a good idea to keep the projects simple enough so you won't get sidetracked.</p>
<p>Below, I share with you my favorite resources that I used to learn about distributed systems. </p>
<p>Thank you for reading.</p>
<h3 id="heading-recommended-resources">Recommended Resources</h3>
<ul>
<li><a target="_blank" href="https://microservices.io/index.html">Microservices.io</a></li>
<li><a target="_blank" href="https://www.goodreads.com/book/show/23463279-designing-data-intensive-applications">Designing Data Intensive Applications</a></li>
<li><a target="_blank" href="https://bytebytego.com/">System Design Interview Prep</a></li>
<li><a target="_blank" href="https://github.com/donnemartin/system-design-primer">System Design Prime</a></li>
<li><a target="_blank" href="https://www.goodreads.com/en/book/show/405614">Distributed Systems: Principles and Paradigms</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the OSI Model? Computer Networking for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn about the core concepts of the Open Systems Interconnections (OSI) model in a simple and easy way. As a developer, it's a good idea to learn how things work "under the hood". That way you understand what your code and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/osi-model-computer-networking-for-beginners/</link>
                <guid isPermaLink="false">66bb8c97d2bda3e4315491b1</guid>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tamerlan Gudabayev ]]>
                </dc:creator>
                <pubDate>Mon, 04 Oct 2021 16:27:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/banner-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn about the core concepts of the Open Systems Interconnections (OSI) model in a simple and easy way.</p>
<p>As a developer, it's a good idea to learn how things work "under the hood". That way you understand what your code and the tools you use are actually doing.</p>
<p>But it might seem easier to rely on black box abstraction and ignore the inner workings.</p>
<p>A popular black box abstraction is the internet. </p>
<p>Sure, many of us probably know the basics of what the internet is and how it works. There is a client and a server and they simply "communicate" with each other using something called HTTP or HTTPS?</p>
<p>But that's the extent of most people's knowledge.</p>
<p>I'm not saying we shouldn't use abstractions – I'm just saying that we should have some basic idea about how things work.</p>
<p>This is why I'm writing this article: to demystify this black box to help you learn how computers communicate with each other over a network. </p>
<h2 id="heading-what-is-the-osi-model">What is the OSI Model?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/osi-model-layers.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Seven Layers of OSI</em></p>
<p>The Open Systems Interconnection or OSI model is essentially a reference system that lays out how computers communicate with each other over a network.</p>
<p>It was created in 1983 by representatives of telecom companies and officially standardized in 1984 by the International Organization for Standardization (ISO).</p>
<p>It is divided into seven layers. Each layer has its own domain and receives data from the previous layer, while passing data to the next layer.</p>
<p>The seven layers are:</p>
<ol>
<li>Application Layer</li>
<li>Presentation Layer</li>
<li>Session Layer</li>
<li>Transport Layer</li>
<li>Network Layer</li>
<li>Data Link Layer</li>
<li>Physical Layer</li>
</ol>
<p>If we think of it in coding terms, each layer is a class with some core functionality, and each class communicates with only the class above or below it. </p>
<p>Keep in mind that this is a <strong>reference</strong> model, meaning that we don't actually use it in real life. There is another model which is very similar to the OSI model but it encapsulates the first three layers and the last two. </p>
<p>This "real life" model is called the TCP/IP Model which is what the internet runs on. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/osi-vs-tcpip-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>OSI vs TCP/IP Model diagram</em></p>
<p>But before we jump in and deal with each layer one by one, let's go over why should you learn the OSI model if it's not even used in real life.</p>
<h2 id="heading-why-learn-the-osi-model">Why Learn the OSI Model</h2>
<p>During the past 20 years or so, the world has dramatically changed.</p>
<p>The internet came, the "web" came, and within the web ecosystem lots of things have changed. We started with simple HTML pages, then came JavaScript, and now we have all these frameworks and it sometimes feels so overwhelming. </p>
<p>But, you gotta remember this:</p>
<blockquote>
<p>Learn the fundamentals, learn from first principles.</p>
</blockquote>
<p>Let's take the web, for example, aside from all these changes we have seen during the past 20 years. </p>
<p>How the web works hasn't actually change much. </p>
<p>We still use the HTTP protocol. </p>
<p>It's true that the HTTP protocol has been updated, but not so much.</p>
<p>Even if we break down HTTP, it's made from TCP which also hasn't changed much.</p>
<p>My point is that you should stop looking at the shiny new things and focus on the fundamentals that these shiny new things are built upon. </p>
<p>For example, I remember when web sockets was a popular thing.</p>
<p>But if we break it down, they're based on the TCP protocol. </p>
<p>If you know TCP, you can easily understand how web sockets work and don't have to rely on black box abstractions. </p>
<p>I hope I've convinced on why you should learn from first principles. This not only applies to software engineering but to many other fields, too.</p>
<p>With that done, let's go over the seven layers of the OSI model.</p>
<h2 id="heading-the-seven-layers-of-the-osi-model">The Seven Layers of the OSI Model</h2>
<h3 id="heading-application-layer">Application Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/3.png" alt="Image" width="600" height="400" loading="lazy">
<em>This is the layer where the end user exists</em></p>
<p>The application layer is where most software engineers work. And this is where your browsers lives. </p>
<p>But I'm not talking about concrete applications such as Chrome, Skype, or Outlook. </p>
<p>I'm talking more fundamental things, such as protocols.</p>
<p>For example:</p>
<ul>
<li>Your browser makes a request to a web server using the HTTP protocol. </li>
<li>Your email app uses the SMTP protocol to send and receive emails.</li>
<li>Without the DNS protocol, you would have to type 142.250.150.138 instead of google.com. </li>
</ul>
<p>In a nutshell, the application layer handles the foundation that almost all end user applications use.</p>
<h3 id="heading-presentation-layer">Presentation Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once the client makes the HTTP request, the request itself get's passed down to the presentation layer (also called syntax layer).</p>
<p>This layer handles three main functionalities:</p>
<h4 id="heading-encryption-and-decryption">Encryption and Decryption</h4>
<p>You don't want your data out in public, which is why smart people created the Transport Layer Security (TLS). It essentially encrypts your data. </p>
<p>It's also responsible for decrypting requests coming from other servers to be consumed by the application layer.</p>
<h4 id="heading-serialization-and-deserialization">Serialization and Deserialization</h4>
<p>These are some big words, but what they essentially mean is "translation".</p>
<p>We want to "translate" our data to forms that our application understands. </p>
<p>For example, simple data structures may be translated into "objects" that our JavaScript application understands.</p>
<p>On the other hand, if we want our data to pass down the layer, we would translate our object into simple data structures that could be understood in the lower layers.</p>
<h4 id="heading-compression">Compression</h4>
<p>This is a no-brainer: the fewer bits there are to send, the faster the request will be. </p>
<p>This is also one of the main functions of the presentation layer. Keep in mind this is a lossless compression meaning no information will be lost in the process.</p>
<p>Well to be fair, in the real world most of these things are done in the application layer. </p>
<p>This is why in the TCP/IP model the presentation layer is part of the application layer.</p>
<h3 id="heading-session-layer">Session Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/5-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The session layer is responsible for opening, closing and maintaining connections between client and server</em></p>
<p>This one is a bit confusing. And in fact, I couldn't find many use cases for it. </p>
<p>The primary function of the session layer is to manage connections between client and server. </p>
<p>But what does that actually mean?</p>
<p>So let's say you want to go to google.com</p>
<p>To do that you first have to establish a connection with google.com, so you say "Hey server, what's up, I want to connect to google.com".</p>
<p>The server responds back: "Yeah, sure." </p>
<p>Congratulations, you have just established a connection with google.com's server and can freely send a GET request to fetch the page. </p>
<p>Long story short, this layer is used for:</p>
<ul>
<li>Opening connections </li>
<li>Keeping connections alive</li>
<li>Closing connections.</li>
</ul>
<p>Now comes the reality check: in real life this pretty much does not exist and is part of the Transport Layer – which we'll discuss next.</p>
<h3 id="heading-transport-layer">Transport Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Transport-Layer.png" alt="Image" width="600" height="400" loading="lazy">
<em>TCP and UDP visualized</em></p>
<p>This is where the interesting stuff happens.</p>
<p>The transport layer is usually defined based on the protocol that's being used.</p>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/what-is-tcp-ip-layers-and-protocols-explained/">two most popular ones are</a>:</p>
<ul>
<li>Transmission Control Protocol (TCP)</li>
<li>User Datagram Protocol (UDP)</li>
</ul>
<p>TCP is one of the main protocols in the internet suite. It is used on top of the IP (internet protocol) to ensure reliable transmission of packets.</p>
<p>TCP fixes many issues that arise when you use IP such as lost packets, out of order packets, duplicate packets, and corrupted packets.</p>
<p>You would use TCP in applications that require all packets to be error-free such as text messaging.</p>
<p>On the other hand UDP is stateless, meaning it doesn't save any state between the client and server It is also very light making it fast. But the downside is that it's not reliable, packets can go missing, get corrupted, and so on.</p>
<p>UDP is mostly used when you don't really care if you lose a few packets here and there, such as video streaming.</p>
<p>Also keep in mind that the data in this layer are called segments.</p>
<p>Long story short, TCP is reliable but slow, while UDP is unreliable but fast.</p>
<h3 id="heading-network-layer">Network Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Network-Layer-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The network layer is responsible for sending packets from network to network</em></p>
<p>I don't really know why this is called the network layer. </p>
<p>It should be called the internet layer – because the most important protocol here is the Internet Protocol (IP)</p>
<p>What the IP basically does is it takes the segments from the transport protocol, and adds meta-data that helps identify where your client is in a local network.</p>
<p>Another function of the network layer is message forwarding, meaning that it sends your packets from network to network.</p>
<p>Data in this layer are called packets.</p>
<h3 id="heading-data-link-layer">Data-Link Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Data-Link-Layer.png" alt="Image" width="600" height="400" loading="lazy">
<em>The data link layer is made of two parts: MAC and LLC</em></p>
<p>This layer defines how data is transmitted between two systems. </p>
<p>It takes care of things such as how long two systems talk to each other, how much data can be sent, and what happens if there are any errors. All this is handled in the Data Link layer.</p>
<p>The data link layer is broken up to two sub-layers:</p>
<ul>
<li>Logical Link Layer (LLC) – This layer provides flow control, acknowledgment, and error handling in case things go wrong.</li>
<li>Media Access Control (MAC) – This layer is responsible for assigning a unique id number based on your network card called a MAC address. Meaning no two devices have the same MAC addresses.</li>
</ul>
<p>Packets are taken from the network layer, and are encapsulated with the addition of new headers for the MAC address of the client and server. </p>
<p>There is also another subset of data added at the end of the packet which is used for error detection. This is called the tail.</p>
<p>Once these meta-data are added, the data is now called a frame.</p>
<h3 id="heading-physical-layer">Physical Layer</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Physical-Layer.png" alt="Image" width="600" height="400" loading="lazy">
<em>Bits can be transferred using electricity, radio waves, or even light</em></p>
<p>Finally this is the physical layer.</p>
<p>Don't get confused with the word physical – we are not only talking about wires. </p>
<p>Data can get transferred in many different ways such as radio waves or even light. </p>
<p>Unfortunately these ways of transportation do not know "frames", they only know bits. </p>
<p>The function of this layer is to simply transform frames into bytes (8 bits) and send them over some transport method (electricity, waves, light, and so on).</p>
<p>Finally our request will get transmitted to the server, and the server will go through the same process but in reverse. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned:</p>
<ul>
<li>That the OSI Model is a reference model on how two systems talk to each other over a network.</li>
<li>We don't use this model in real life. Instead, we use another similar model called the TCP/IP model.</li>
<li>The OSI mode is made up of seven parts, each with a specific function.</li>
</ul>
<p>I hope you learned something today, and would like to thank you for reaching the end. </p>
<p>I plan to post snippets of content similar to this on Twitter, so if you're interested follow me <a target="_blank" href="https://twitter.com/tamerlan_dev">@tamerlan_dev</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a GraphQL API Using Laravel ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'll walk you through how to set up your own GraphQL API using PHP and Laravel. Two years ago, I started working professionally as a backend developer. And I was very intimidated by all the technology I didn't yet know. Words like Do... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-graphql-api-using-laravel/</link>
                <guid isPermaLink="false">66bb8c8e2108ff2ab9af167c</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Laravel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tamerlan Gudabayev ]]>
                </dc:creator>
                <pubDate>Wed, 26 May 2021 16:34:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/graphql-article-image.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'll walk you through how to set up your own GraphQL API using PHP and Laravel.</p>
<p>Two years ago, I started working professionally as a backend developer. And I was very intimidated by all the technology I didn't yet know. Words like Docker, Kubernetes, and GraphQL seemed quite scary.</p>
<p>But I mustered up the courage and started to learn them all one by one.</p>
<p>It was actually easier than I thought, so I would like to share with you what I've learned about GraphQL by creating a simple demo project together.</p>
<p>You can find the final project on GitHub <a target="_blank" href="https://github.com/TamerlanG/GraphQL-using-Laravel">here</a>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we begin, make sure to have these installed on your system:</p>
<ul>
<li>PHP 7+</li>
<li>Composer 2.0</li>
<li>Docker 20.10.6 (Any other version should be fine)</li>
<li>Docker-Compose 1.29.1 (Any other version should be fine)</li>
</ul>
<p>I also assume that you have:</p>
<ul>
<li>Basic knowledge of Laravel (Eloquent, Migrations, MVC, Routes, and so on)</li>
<li>Knowledge of PHP (Syntax, OOP, and so on)</li>
<li>Basic knowledge of GraphQL (in theory)</li>
</ul>
<h2 id="heading-what-were-going-to-build">What We're Going to Build</h2>
<p>I like RPG games like the Elder Scrolls Series or Final Fantasy, so of course our app will be about games. The project will consist of only two models called <strong>Quests</strong> and <strong>Categories</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/1-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Database Schema</em></p>
<p>By the end of this post we will create a CRUD GraphQL API for each model.</p>
<h2 id="heading-how-to-initialize-the-project">How to Initialize the Project</h2>
<p>Create a Laravel project using this command:</p>
<pre><code class="lang-bash">composer create-project laravel/laravel quest_journal
</code></pre>
<p>This will create a new project in a new directory called <code>quest_journal</code>.</p>
<p>Next let's setup sail like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Move into the project</span>
<span class="hljs-built_in">cd</span> quest_journal

<span class="hljs-comment"># Install and configure laravel sail</span>
php artisan sail:install
</code></pre>
<p>It's gonna ask you which services to install. Just press <code>enter</code> to only install MySQL.</p>
<p>If all goes well, you should now see a <code>docker-compose.yml</code> file in your project directory.</p>
<p>Let's then run the containers using sail:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Run the containers</span>
./vendor/bin/sail up -d

<span class="hljs-comment"># Check if the containers are running</span>
docker ps
</code></pre>
<p>At this point I suggest you alias <code>sail</code> to <code>./vendor/bin/sail</code>. You can do that by adding this piece of code to your <code>bashrc</code> or <code>zshrc</code>:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># in ~./zshrc or ~./bashrc</span>

<span class="hljs-built_in">alias</span> sail = <span class="hljs-string">'bash vendor/bin/sail'</span>
</code></pre>
<p>Moving on, if you go to <a target="_blank" href="http://localhost/">localhost</a> you should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Default Laravel Home Page</em></p>
<p>But before we move on, there are some packages that we need to install first:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># IDE helper for laravel, always useful to have.</span>
sail composer require --dev barryvdh/laravel-ide-helper

<span class="hljs-comment"># GraphQL library which we are going to use</span>
sail composer require rebing/graphql-laravel
</code></pre>
<p>Next we have to publish the GraphQL library like this:</p>
<pre><code class="lang-bash">sail artisan vendor:publish --provider=<span class="hljs-string">"Rebing\\GraphQL\\GraphQLServiceProvider"</span>
</code></pre>
<p>This should create a GraphQL config file that we will use in <code>config/graphql.php</code>.</p>
<h2 id="heading-how-to-create-the-migrations-and-models">How to Create the Migrations and Models</h2>
<p>This isn't a Laravel tutorial, so we'll quickly create the models with the appropriate migrations.</p>
<p>Let's start with category model:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create model with migrations</span>
sail artisan make:model -m Category
</code></pre>
<p>This will create the Category model with it's migration file.</p>
<p>Our category will consist of four fields:</p>
<ul>
<li>ID</li>
<li>Title</li>
<li>Created_At</li>
<li>Updated_At</li>
</ul>
<p>Our category migrations file should look like this:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// database/migrations/yyyy_mm_dd_hhMMss_create_categories_table.php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Migrations</span>\\<span class="hljs-title">Migration</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Schema</span>\\<span class="hljs-title">Blueprint</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">Schema</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateCategoriesTable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * Run the migrations.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::create(<span class="hljs-string">'categories'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;id();
            $table-&gt;text(<span class="hljs-string">'title'</span>);
            $table-&gt;timestamps();
        });
    }

    <span class="hljs-comment">/**
     * Reverse the migrations.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::dropIfExists(<span class="hljs-string">'categories'</span>);
    }
}
</code></pre>
<p>Next let's configure the category model class.</p>
<p>We will do two things here:</p>
<ul>
<li>Make the field <code>title</code> editable, so we will add it to our <code>$fillable</code> array.</li>
<li>Define the relationship between category model and quest model.</li>
</ul>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// App\\Models\\Category</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Factories</span>\\<span class="hljs-title">HasFactory</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Category</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasFactory</span>;

    <span class="hljs-keyword">protected</span> $fillable = [<span class="hljs-string">'title'</span>];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">quests</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;hasMany(Quest::class);
    }
}
</code></pre>
<p>You will have some errors concerning the Quest model, but no worries – we will handle that next.</p>
<p>Run the command to make a model and migration file for quest:</p>
<pre><code class="lang-bash">sail artisan make:model -m Quest
</code></pre>
<p>This will create a model named Quest and a migration file for it.</p>
<p>Our quest will have the fields:</p>
<ul>
<li>ID</li>
<li>Title</li>
<li>Description</li>
<li>Reward</li>
<li>Category_ID</li>
<li>Created_At</li>
<li>Updated_At</li>
</ul>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-comment">// database/migrations/yyyy_mm_dd_hhMMss_create_quests_table.php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Migrations</span>\\<span class="hljs-title">Migration</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Schema</span>\\<span class="hljs-title">Blueprint</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">Schema</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateQuestsTable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * Run the migrations.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::create(<span class="hljs-string">'quests'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;id();
            $table-&gt;text(<span class="hljs-string">'title'</span>);
            $table-&gt;text(<span class="hljs-string">'description'</span>);
            $table-&gt;integer(<span class="hljs-string">'reward'</span>);
            $table-&gt;foreignId(<span class="hljs-string">'category_id'</span>)-&gt;constrained();
            $table-&gt;timestamps();
        });
    }

    <span class="hljs-comment">/**
     * Reverse the migrations.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::dropIfExists(<span class="hljs-string">'quests'</span>);
    }
}
</code></pre>
<p>As you can see, we declared the <code>category_id</code> to be a <code>foreignId</code>. This way Laravel will automatically create a foreign key relationship between the tables <code>categories</code> and <code>quests</code>.</p>
<p>Next let's configure the quest model class. </p>
<p>Here we will:</p>
<ul>
<li>Make the appropriate fields editable by adding them to the <code>$fillable</code> array.</li>
<li>Define the relationship between category model and quest model.</li>
</ul>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// App\\Models\\Quest</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Factories</span>\\<span class="hljs-title">HasFactory</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Quest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasFactory</span>;

    <span class="hljs-keyword">protected</span> $fillable = [<span class="hljs-string">'title'</span>, <span class="hljs-string">'category_id'</span>, <span class="hljs-string">'description'</span>,                               <span class="hljs-string">'reward'</span>];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">category</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;belongsTo(Category::class);
    }
}
</code></pre>
<p>With both the migrations and models ready, we can apply the changes to the database.</p>
<p>Run this command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Apply migrations</span>
sail artisan migrate
</code></pre>
<p>Our database should be updated! Next we should put some data into our tables.</p>
<h2 id="heading-how-to-seed-the-database">How to Seed the Database</h2>
<p>We need data to work with, but as developers we are too lazy to manually do it. </p>
<p>This is where factories come.</p>
<p>First, we'll create the factory classes for both the quest and category model.</p>
<p>Run the following commands:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a factory class for quest model</span>
sail artisan make:factory QuestFactory --model=Quest

<span class="hljs-comment"># Create a factory class for category model</span>
sail artisan make:factory CategoryFactory --model=Category
</code></pre>
<p>This will create for us two new classes:</p>
<ul>
<li><code>QuestFactory</code> – a class that helps us generate quests.</li>
<li><code>CategoryFactory</code> – a class that helps us generate categories.</li>
</ul>
<p>Let's start with the <code>QuestFactory</code>. In our <code>definitions</code> function we will tell Laravel how each field should be generated. For the field <code>category_id</code>, we will pick a random category.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// database/factories/QuestFactory.php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Database</span>\\<span class="hljs-title">Factories</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Factories</span>\\<span class="hljs-title">Factory</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QuestFactory</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Factory</span>
</span>{
    <span class="hljs-comment">/**
     * The name of the factory's corresponding model.
     *
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">protected</span> $model = Quest::class;

    <span class="hljs-comment">/**
     * Define the model's default state.
     *
     * <span class="hljs-doctag">@return</span> array
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">definition</span>(<span class="hljs-params"></span>)
    </span>{
        $categoryIDs = Category::all()-&gt;pluck(<span class="hljs-string">'id'</span>)-&gt;toArray();

        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;faker-&gt;title(),
            <span class="hljs-string">'description'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;faker-&gt;text(),
            <span class="hljs-string">'reward'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;faker-&gt;numberBetween(<span class="hljs-number">1</span> , <span class="hljs-number">100</span>),
            <span class="hljs-string">'category_id'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;faker-&gt;randomElement($categoryIDs)
        ];
    }
}
</code></pre>
<p><code>CategoryFactory</code> is much simpler, as we simply have to generate a title.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// database/factories/CategoryFactory.php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Database</span>\\<span class="hljs-title">Factories</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Eloquent</span>\\<span class="hljs-title">Factories</span>\\<span class="hljs-title">Factory</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoryFactory</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Factory</span>
</span>{
    <span class="hljs-comment">/**
     * The name of the factory's corresponding model.
     *
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">protected</span> $model = Category::class;

    <span class="hljs-comment">/**
     * Define the model's default state.
     *
     * <span class="hljs-doctag">@return</span> array
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">definition</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;faker-&gt;title()
        ];
    }
}
</code></pre>
<p>Now instead of creating seeders, we will simply run the factory create method inside <code>DatabaseSeeder.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// database/seeders/DatabaseSeeder.php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Database</span>\\<span class="hljs-title">Seeders</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\\<span class="hljs-title">Database</span>\\<span class="hljs-title">Seeder</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseSeeder</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Seeder</span>
</span>{
    <span class="hljs-comment">/**
     * Seed the application's database.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span>(<span class="hljs-params"></span>)
    </span>{
        Category::factory(<span class="hljs-number">10</span>)-&gt;create();
        Quest::factory(<span class="hljs-number">10</span>)-&gt;create();
    }
}
</code></pre>
<p>Finally run the command to seed the database.</p>
<pre><code class="lang-php">sail artisan db:seed
</code></pre>
<h2 id="heading-folder-structure">Folder Structure</h2>
<p>At this point we are ready to create our GraphQL APIs. To do that let's first create a new folder in the <code>app</code> directory called <code>GraphQL</code>.</p>
<p>Inside the GraphQL folder, create three new folders:</p>
<ul>
<li>Mutations</li>
<li>Queries</li>
<li>Types</li>
</ul>
<p>It will look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is where the bulk of our code will be. As you might be able to tell, it's very different from REST architecture. Before we begin writing the code, let me quickly explain the purpose of each folder.</p>
<ul>
<li><strong>Mutations</strong>: This folder will contain classes that manage the insert, update, and delete operations.</li>
<li><strong>Queries</strong>: This folder will contain the classes that fetch data from the database.</li>
<li><strong>Types</strong>: You can think of this as a model, or a model resource. Basically types are objects that can be fetched from the database. For example, we are going to have a <code>QuestType</code> and a <code>CategoryType</code>.</li>
</ul>
<h2 id="heading-how-to-define-the-category-and-quest-types">How to Define the Category and Quest Types</h2>
<p>Let's first start with types. We'll create two new classes in our types folder called:</p>
<ol>
<li><code>CategoryType</code></li>
<li><code>QuestType</code></li>
</ol>
<p>Here is where we will use the <code>rebing/graphql-laravel</code> package which basically helps us create types, queries, and mutations.</p>
<p>Our types will inherit the <code>Type</code> class from <code>Rebing\\GraphQL\\Support\\Type</code>. There's also another class called <code>Type</code> in the package but it's used to declare the type of field (like string, int, and so on).</p>
<p>Let's begin with the <code>CategoryType</code> class:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/types/CategoryType </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Types</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Type</span> <span class="hljs-title">as</span> <span class="hljs-title">GraphQLType</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoryType</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">GraphQLType</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Category'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Collection of categories'</span>,
        <span class="hljs-string">'model'</span> =&gt; Category::class
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fields</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'ID of quest'</span>
            ],
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::string()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Title of the quest'</span>
            ],
            <span class="hljs-string">'quests'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::listOf(GraphQL::type(<span class="hljs-string">'Quest'</span>)),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'List of quests'</span>
            ]
        ];
    }
}
</code></pre>
<p>Let's break this down:</p>
<ul>
<li><strong>Attributes</strong>: This is your type configuration. It has core information about your type, and to which model it associates.</li>
<li><strong>Fields</strong>: This method returns the fields that your client can ask for.</li>
</ul>
<p>You may have noticed that we have a field called <code>quests</code> which is a list of <code>QuestType</code>. But we don't associate the class directly – we instead use its <code>name</code> from its attribute.</p>
<p>Next is the <code>QuestType</code> class:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/types/QuestType </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Types</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Type</span> <span class="hljs-title">as</span> <span class="hljs-title">GraphQLType</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QuestType</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">GraphQLType</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Quest'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Collection of quests with their respective category'</span>,
        <span class="hljs-string">'model'</span> =&gt; Quest::class
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fields</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'ID of quest'</span>
            ],
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::string()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Title of the quest'</span>
            ],
            <span class="hljs-string">'description'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::string()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Description of quest'</span>
            ],
            <span class="hljs-string">'reward'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Quest reward'</span>
            ],
            <span class="hljs-string">'category'</span> =&gt; [
                <span class="hljs-string">'type'</span> =&gt; GraphQL::type(<span class="hljs-string">'Category'</span>),
                <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'The category of the quest'</span>
            ]
        ];
    }
}
</code></pre>
<h2 id="heading-how-to-define-the-queries-for-your-model">How to Define the Queries for Your Model</h2>
<p>Now that we have defined our types, we can move on to queries.</p>
<p>For each model we will have two queries:</p>
<ul>
<li>A class to query a single model</li>
<li>A class to query a list of models</li>
</ul>
<p>To keep stuff organized, create two new folders in your <code>Queries</code> folder:</p>
<ul>
<li>Category</li>
<li>Quest</li>
</ul>
<p>Let's create our classes:</p>
<ul>
<li><code>QuestQuery</code></li>
<li><code>QuestsQuery</code></li>
<li><code>CategoryQuery</code></li>
<li><code>CategoriesQuery</code></li>
</ul>
<p>Your file structure should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's start with the <code>QuestQuery</code> class:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/queries/quest/QuestQuery </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Queries</span>\\<span class="hljs-title">Quest</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Query</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QuestQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Query</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'quest'</span>,
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Quest'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::int(),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'required'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        <span class="hljs-keyword">return</span> Quest::findOrFail($args[<span class="hljs-string">'id'</span>]);
    }
}
</code></pre>
<p>Let's break this down:</p>
<ul>
<li>Our query classes will inherit from <code>Rebing\\GraphQL\\Support\\Query</code></li>
<li>The <code>attributes</code> function is used as the query configuration.</li>
<li>The <code>type</code> function is used to declare what type of object this query will return.</li>
<li>The <code>args</code> function is used to declare what arguments this query will accept. In our case we only need the <code>id</code> of the quest.</li>
<li>The <code>resolve</code> function does the bulk of the work – it returns the actual object using eloquent.</li>
</ul>
<p>The rest of the classes have a similar format, so it's pretty much self explanatory.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/queries/quest/QuestsQuery </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Queries</span>\\<span class="hljs-title">Quest</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Query</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QuestsQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Query</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'quests'</span>,
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> Type::listOf(GraphQL::type(<span class="hljs-string">'Quest'</span>));
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        <span class="hljs-keyword">return</span> Quest::all();
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/queries/category/CategoryQuery </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Queries</span>\\<span class="hljs-title">Category</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Query</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoryQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Query</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'category'</span>,
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Category'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::int(),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'required'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        <span class="hljs-keyword">return</span> Category::findOrFail($args[<span class="hljs-string">'id'</span>]);
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/queries/category/CategoriesQuery </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Queries</span>\\<span class="hljs-title">Category</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Query</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoriesQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Query</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'categories'</span>,
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> Type::listOf(GraphQL::type(<span class="hljs-string">'Category'</span>));
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        <span class="hljs-keyword">return</span> Category::all();
    }
}
</code></pre>
<h2 id="heading-how-to-create-the-mutation-classes">How to Create the Mutation Classes</h2>
<p>Mutations will house our classes that control the insertion/deletion of our models. So for each model we will have three classes:</p>
<ul>
<li>A class to create a model</li>
<li>A class to update a model</li>
<li>A class to delete a model</li>
</ul>
<p>We have two models in our app, so we will have 6 mutation classes.</p>
<p>To keep things organized, create two new folders in your <code>Mutations</code> folder:</p>
<ul>
<li>Category</li>
<li>Quest</li>
</ul>
<p>Let's create our mutation classes:</p>
<ul>
<li><code>CreateCategoryMutation</code></li>
<li><code>DeleteCategoryMutation</code></li>
<li><code>UpdateCategoryMutation</code></li>
<li><code>CreateQuestMutation</code></li>
<li><code>DeleteQuestMutation</code></li>
<li><code>UpdateQuestMutation</code></li>
</ul>
<p>Your file structure should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's start with <code>CreateCategoryMutation</code>:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/category/CreateCategoryMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Category</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateCategoryMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'createCategory'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Creates a category'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Category'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'title'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $category = <span class="hljs-keyword">new</span> Category();
        $category-&gt;fill($args);
        $category-&gt;save();

        <span class="hljs-keyword">return</span> $category;
    }
}
</code></pre>
<p>As you can see, the structure is very similar to our queries.</p>
<p>Once again let's break down this class:</p>
<ul>
<li>Our mutation classes will inherit from <code>Rebing\\GraphQL\\Support\\Mutation</code></li>
<li>The <code>attributes</code> function is used as mutation configuration.</li>
<li>The <code>type</code> function is used to declare what type of object this query will return.</li>
<li>The <code>args</code> function is used to declare what arguments this mutation will accept. In our case we only need the <code>title</code> field.</li>
<li>The <code>resolve</code> function does the bulk of the work – it does the actual mutation using eloquent.</li>
</ul>
<p>The rest of the mutations have a similar format, so they should be self-explanatory.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/category/DeleteCategoryMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Category</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DeleteCategoryMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'deleteCategory'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'deletes a category'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> Type::boolean();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::int(),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'required'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $category = Category::findOrFail($args[<span class="hljs-string">'id'</span>]);

        <span class="hljs-keyword">return</span>  $category-&gt;delete() ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/category/UpdateCategoryMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Category</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Category</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UpdateCategoryMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'updateCategory'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Updates a category'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Category'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::int()),
            ],
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'title'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $category = Category::findOrFail($args[<span class="hljs-string">'id'</span>]);
        $category-&gt;fill($args);
        $category-&gt;save();

        <span class="hljs-keyword">return</span> $category;
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/quest/CreateQuestMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Quest</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateQuestMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'createQuest'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Creates a quest'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Quest'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'title'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
            <span class="hljs-string">'description'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'description'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
            <span class="hljs-string">'reward'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'reward'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
            ],
            <span class="hljs-string">'category_id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'category_id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'exists:categories,id'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $quest = <span class="hljs-keyword">new</span> Quest();
        $quest-&gt;fill($args);
        $quest-&gt;save();

        <span class="hljs-keyword">return</span> $quest;
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/quest/DeleteQuestMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Quest</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DeleteQuestMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'deleteQuest'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Deletes a quest'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> Type::boolean();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'exists:quests'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $category = Quest::findOrFail($args[<span class="hljs-string">'id'</span>]);

        <span class="hljs-keyword">return</span>  $category-&gt;delete() ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// app/graphql/mutations/quest/UpdateQuestMutation </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Mutations</span>\\<span class="hljs-title">Quest</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\\<span class="hljs-title">Models</span>\\<span class="hljs-title">Quest</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Type</span>\\<span class="hljs-title">Definition</span>\\<span class="hljs-title">Type</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Facades</span>\\<span class="hljs-title">GraphQL</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rebing</span>\\<span class="hljs-title">GraphQL</span>\\<span class="hljs-title">Support</span>\\<span class="hljs-title">Mutation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UpdateQuestMutation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mutation</span>
</span>{
    <span class="hljs-keyword">protected</span> $attributes = [
        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'updateQuest'</span>,
        <span class="hljs-string">'description'</span> =&gt; <span class="hljs-string">'Updates a quest'</span>
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">type</span>(<span class="hljs-params"></span>): <span class="hljs-title">Type</span>
    </span>{
        <span class="hljs-keyword">return</span> GraphQL::type(<span class="hljs-string">'Quest'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">args</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'id'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::int()),
            ],
            <span class="hljs-string">'title'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'title'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
            <span class="hljs-string">'description'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'description'</span>,
                <span class="hljs-string">'type'</span> =&gt;  Type::nonNull(Type::string()),
            ],
            <span class="hljs-string">'reward'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'reward'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
            ],
            <span class="hljs-string">'category_id'</span> =&gt; [
                <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'category_id'</span>,
                <span class="hljs-string">'type'</span> =&gt; Type::nonNull(Type::int()),
                <span class="hljs-string">'rules'</span> =&gt; [<span class="hljs-string">'exists:categories,id'</span>]
            ]
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">$root, $args</span>)
    </span>{
        $quest = Quest::findOrFail($args[<span class="hljs-string">'id'</span>]);
        $quest-&gt;fill($args);
        $quest-&gt;save();

        <span class="hljs-keyword">return</span> $quest;
    }
}
</code></pre>
<h2 id="heading-schemas">Schemas</h2>
<p>All the hard work is done! Now we have to put everything together.</p>
<p>We have to register our queries, mutations, and types in our <code>config/graphql</code>:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">return</span> [
    <span class="hljs-comment">// ... some code</span>

    <span class="hljs-string">'schemas'</span> =&gt; [
        <span class="hljs-string">'default'</span> =&gt; [
            <span class="hljs-string">'query'</span> =&gt; [
                <span class="hljs-string">'quest'</span> =&gt; \\App\\GraphQL\\Queries\\Quest\\QuestQuery::class,
                <span class="hljs-string">'quests'</span> =&gt; \\App\\GraphQL\\Queries\\Quest\\QuestsQuery::class,
                <span class="hljs-string">'category'</span> =&gt; \\App\\GraphQL\\Queries\\Category\\CategoryQuery::class,
                <span class="hljs-string">'categories'</span> =&gt; \\App\\GraphQL\\Queries\\Category\\CategoriesQuery::class,
            ],
            <span class="hljs-string">'mutation'</span> =&gt; [
                <span class="hljs-string">'createQuest'</span> =&gt; \\App\\GraphQL\\Mutations\\Quest\\CreateQuestMutation::class,
                <span class="hljs-string">'updateQuest'</span> =&gt; \\App\\GraphQL\\Mutations\\Quest\\UpdateQuestMutation::class,
                <span class="hljs-string">'deleteQuest'</span> =&gt; \\App\\GraphQL\\Mutations\\Quest\\DeleteQuestMutation::class,
                <span class="hljs-string">'createCategory'</span> =&gt; \\App\\GraphQL\\Mutations\\Category\\CreateCategoryMutation::class,
                <span class="hljs-string">'updateCategory'</span> =&gt; \\App\\GraphQL\\Mutations\\Category\\UpdateCategoryMutation::class,
                <span class="hljs-string">'deleteCategory'</span> =&gt; \\App\\GraphQL\\Mutations\\Category\\DeleteCategoryMutation::class,
            ],
            <span class="hljs-string">'middleware'</span> =&gt; [],
            <span class="hljs-string">'method'</span> =&gt; [<span class="hljs-string">'get'</span>, <span class="hljs-string">'post'</span>],
        ],
    ],

        <span class="hljs-string">'types'</span> =&gt; [
       <span class="hljs-string">'Quest'</span> =&gt; \\App\\GraphQL\\Types\\QuestType::class,
       <span class="hljs-string">'Category'</span> =&gt; \\App\\GraphQL\\Types\\CategoryType::class
    ],

    <span class="hljs-comment">// some code </span>
];
</code></pre>
<p>Now that all that's done, let's try out our APIs.</p>
<h2 id="heading-how-to-test-the-queries">How to Test the Queries</h2>
<p>Our GraphQL library provides us with an IDE.</p>
<p>So make sure your Docker containers are running and head into <a target="_blank" href="http://localhost/graphiql">http://localhost/graphiql</a>.</p>
<p>You should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let us test our queries:</p>
<h3 id="heading-fetch-a-single-quest">Fetch a Single Quest</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-fetch-a-list-of-quests">Fetch a List of Quests</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-insert-a-quest-into-the-database">Insert a Quest into the Database</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-update-a-quest">Update a Quest</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-delete-a-quest-from-the-database">Delete a Quest from the Database</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations, you have created your first GraphQL API.</p>
<p>In summary:</p>
<ul>
<li>A GraphQL API consists of three parts: Queries, Types, and Mutations.</li>
<li>Mutations manage your CRUD operations.</li>
<li>Queries fetch from the database.</li>
<li>Types are the model resource that gets returned to the client.</li>
</ul>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
