<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Turki alqahtani on Medium]]></title>
        <description><![CDATA[Stories by Turki alqahtani on Medium]]></description>
        <link>https://medium.com/@turkialqahtani400?source=rss-a36ebe7e3812------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mWBm3BNU64r98kqIj7YV-A.jpeg</url>
            <title>Stories by Turki alqahtani on Medium</title>
            <link>https://medium.com/@turkialqahtani400?source=rss-a36ebe7e3812------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:52:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@turkialqahtani400/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Art of System Design: Building Scalable Solutions]]></title>
            <link>https://medium.com/@turkialqahtani400/the-art-of-system-design-building-scalable-solutions-ab7972a485be?source=rss-a36ebe7e3812------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab7972a485be</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[software-reliability]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Turki alqahtani]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 18:05:16 GMT</pubDate>
            <atom:updated>2024-07-19T18:05:16.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw3vsfGIQyG2oHR1-SxLnw.png" /></figure><p>In a data-driven world, the ability to efficiently process and analyze vast amounts of information is crucial for businesses and organizations. From financial institutions handling sensitive documents to healthcare providers managing patient records, the need for a robust and scalable file management platform has never been more critical. This platform must seamlessly handle large file uploads, process diverse data formats, and deliver actionable insights in real-time.</p><p>In this article, we delve into the <strong>intricacies of designing a state-of-the-art file management platform</strong>. Our system allows users to upload files in a chunked stream manner, ensuring the seamless transfer of large data sets. These files then pass through a sophisticated processing pipeline comprising several key services: extraction, translation, Optical Character Recognition <strong>(OCR), mapping</strong>, and conversion. Each service plays a vital role in transforming raw data into structured, meaningful information.</p><p>We will explore the architecture and components that make up this platform, emphasizing scalability, performance, and security. By the end of this article, you will have a comprehensive understanding of how to build a robust <strong>file management platform</strong> capable of handling the most demanding data processing tasks. Whether you’re a seasoned system architect or an aspiring backend developer, this guide will equip you with the knowledge and insights needed to create a cutting-edge file analysis platform.</p><h3>System Requirements</h3><h4>File Upload</h4><ul><li>The user should be able to upload files of any type, including zip, pdf, docx, ppt, images, video, etc.</li><li>The system should handle a large number of files in a single upload, particularly when in zip format.</li><li>The system should extract zip files, maintaining the exact order of the file hierarchy.</li></ul><h4><strong>Data Processing</strong></h4><ul><li>The system should perform object character recognition (OCR) on the files.</li><li>The system should allow for full-text search functionality within the files.</li><li>The system should perform document summarization to provide concise overviews of the content.</li></ul><h4><strong>File Management</strong>:</h4><ul><li>The user should be able to map files together based on common features or attributes.</li><li>The system should generate reports based on the user’s request.</li></ul><h3>System Design Architecture</h3><p>The way we will tackle this problem is that we are going to take each requirement at a time and design for it. But from the looks of it we only need around<strong> 4 services.</strong></p><p>These are the 4 services that will help us implement the <strong>functional requirements</strong> of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oADr6kUOSfpsTn60r-xhDQ.png" /></figure><h3>Data Model</h3><p>One of the key concept while designing a system is the shape of the data and how can we insure scalable communication between our data models.</p><p>the following <strong>ERD </strong>will give us a simple example of how we want our data to look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpnhShiJLym58NIBVIuYWQ.png" /></figure><h3>Where is the OCR stored ?</h3><p>We have stated that the system should have text-search feature so the user can search throw files based on text inside them. while database like MongoDB and Postgres support text-search features its not <strong>recommended at scale.</strong></p><h4>Using Elasticsearch for OCR</h4><p>To store and search OCR text efficiently, we can utilize <strong>Elasticsearch</strong>. <strong>Elasticsearch </strong>is a powerful search and analytics engine that can index and search large volumes of text quickly and efficiently.</p><blockquote><strong>I will go in depth about how we can achieve that in the file-service section</strong></blockquote><h3>Authentication and Authorization In Microservices</h3><p>In microservices architecture, handling authentication and authorization efficiently and securely is crucial. There are two primary approaches to consider: a centralized auth service approach and a distributed validation approach. Each has its own advantages and disadvantages, which we’ll explore below.</p><h4>Centralized Auth Approach</h4><p>In this approach, an auth service handles all authentication and authorization tasks. When a user logs in, they receive an access token and a refresh token. For every subsequent request to other microservices, the request is forwarded to the auth service, <strong>which validates the token and checks user permissions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP9ZmmUPoYAx4M5WAyBiLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_a3-hN4IdOKokyBt88dYmQ.png" /></figure><p><strong>Advantages</strong>:</p><ol><li><strong>Centralized Control</strong>: Centralized management of authentication and authorization ensures that any changes in user roles or permissions are immediately reflected across all services.</li><li><strong>Simpler Microservices</strong>: Individual microservices do not need to handle the complexities of token validation, reducing their responsibility and potential for <strong>security </strong>issues.</li></ol><p><strong>Disadvantages</strong>:</p><ol><li><strong>Latency</strong>: Every request involves a network call to the auth service, which can introduce latency and potentially slow down the system.</li><li><strong>Scalability</strong>: The auth service becomes a critical point of failure and a potential bottleneck if it cannot handle the volume of validation requests efficiently. It requires careful scaling and robust infrastructure.</li></ol><blockquote><strong>Keycloak</strong> is a popular open-source Identity and Access Management (IAM) solution that offers a wide range of features to handle authentication and authorization for applications and services. It simplifies security implementation by providing out-of-the-box functionalities that can be integrated with various platforms and protocols. and we can use it to be our auth service.</blockquote><h4>Distributed Auth Validation Approach</h4><p>In this approach, when a user logs in, they receive a JWT (JSON Web Token) containing user information and permissions. This token is then included in the Authorization header of subsequent requests to other microservices. Each microservice independently validates the token using a shared <strong>secret or public key</strong>.</p><p>We can implement Distributed JWT with a common module and inject it in our services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*steHEEvuB7wYPlUlAHLxvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1b477oYKF3waLfVdPUU2w.png" /></figure><p><strong>Advantages</strong>:</p><ol><li><strong>Scalability</strong>: Microservices can validate tokens independently without relying on a central auth service, reducing the risk of bottlenecks.</li><li><strong>Performance</strong>: Token validation is a quick operation that can be performed locally within each microservice, minimizing latency.</li><li><strong>Decoupling</strong>: Microservices are decoupled from the auth service, enhancing the system’s fault tolerance and flexibility.</li></ol><p><strong>Disadvantages</strong>:</p><ol><li><strong>Token Management</strong>: Managing JWTs, including expiration and revocation, can be complex. If a user’s permissions change, the token must be invalidated or updated.</li><li><strong>Security</strong>: Proper implementation is crucial to ensure token security. Inadequate validation can lead to security vulnerabilities.</li></ol><h3>Which Approach</h3><p>We will be choosing to implement the<strong> centralized</strong> solution. This approach provides centralized control over authentication and authorization, ensuring that any changes in user roles or permissions are immediately reflected across all services. Although it introduces some latency and scalability challenges, I believe that with careful optimization and robust infrastructure, these can be effectively managed. The benefits of real-time validation and simplified microservice implementation outweigh the potential drawbacks, making the centralized auth service approach the best fit for our needs.</p><h3>File Service</h3><p>In this section, we will outline the steps to create a File Service as part of a microservices architecture. This service will be responsible for handling various file operations, including uploading files in chunks, performing OCR (Optical Character Recognition) on files, summarizing OCR results, converting any file to PDF for web viewing and extracting compressed files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUJtklSTQjeBHNQsLFFz9Q.png" /></figure><p>The user selects a file to upload through the system, which can be of various types such as PDF, DOCX, PPTX, XLSX, JPEG, TXT, video, ZIP, and more. As illustrated in the figure above, the client breaks down the file into smaller chunks of fixed size and attempts to send each chunk through the network. If the server returns a status code of 200 for a chunk, the client proceeds to send the next chunk. However, if the server returns a status code of 500, the client will retry sending the same chunk up to three times. If the issue persists after three attempts, the file upload process will be considered failed.</p><h4>What is Ceph Storage ?</h4><p>Ceph is an open-source storage platform designed to provide scalable, high-performance, and reliable storage solutions. It unifies object storage, block storage, and file storage into a single platform, making it a versatile choice for various storage needs. and it is best suited for Kubernetes environment.</p><blockquote>I prefer <strong>Ceph </strong>over <strong>MinIO </strong>because we require file system storage to maintain the hierarchy of compressed files uploaded by users. This ensures that the directory structure is preserved without any data loss.</blockquote><p>As soon as the file gets saved inside the database( Document table ) we will preform OCR on the file buy using “Tesseract Open Source OCR Engine”. Then will index the text inside elastic search with the file id generated from the database.</p><p>The file text model in elastic will look something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OFYCeTYk2sOdIdLNetx2g.jpeg" /></figure><p>We will also make a post request to a summarization model that will return more smaller conscience summarization of our OCR. We can use <strong>Microsoft Azure Text Summarization</strong>,<strong> Assembly Ai&#39;s Summarization Models</strong> or any text summarization model. After getting the summarized text we will inject it back to our file record inside the database.</p><blockquote>Note both requests from the Tesseract OCR part to elastic search &amp; Summarization model are not sequential but parallel .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWp0XMnXxw5O1oGnumvEAA.png" /></figure><p>The file Converter stage will take the file path as input and will produce a pdf version of the file. If the uploaded file is <strong>pptx </strong>then we will have <strong>pdf </strong>version of it. We have this stage to allow users to <strong>view files on the browser</strong> instead of downloading the origin file.</p><h4>What about compressed files ?</h4><p>As specified in the requirements, the system should handle <strong>compressed </strong>files. This process will occur in a sub-stage between the Ceph file system storage and the file converter. When a user uploads a <strong>ZIP file</strong>, the client will stream it in chunks to our file service, which will then write each chunk into the file system.<strong> Once all chunks are written</strong>, verified by comparing the <strong>chunk index with the total index for the given file</strong>, we check the file extension. If the file extension indicates a compressed file, we proceed with the following steps:</p><ul><li>Extract file into the specified directory</li><li>Delete the origin file (after extraction)</li><li>look for nested compressed files</li><li>repeat</li></ul><p>Basic implementation can be seen below:</p><pre> public async Task ExtractZipFile(string source, string destination, string fileName)<br>        {<br>            Directory.CreateDirectory(destination);<br><br>            string uniqueFolderName = GetUniqueName(destination, fileName);<br><br>            var destinationPath = Path.Combine(destination, uniqueFolderName);<br>            ZipFile.ExtractToDirectory(source, destinationPath);<br>            File.Delete(source);<br><br>            var macosxDirectory = Path.Combine(destinationPath, &quot;__MACOSX&quot;);<br>            if (Directory.Exists(macosxDirectory))<br>            {<br>                Directory.Delete(macosxDirectory, true);<br>            }<br><br>            await ExtractNestedZipFiles(destinationPath);<br>        }<br><br>        private async Task ExtractNestedZipFiles(string destination)<br>        {<br>            var zipFiles = Directory.GetFiles(destination, &quot;*.zip&quot;, SearchOption.AllDirectories);<br>            foreach (var zipFile in zipFiles)<br>            {<br>                <br>                    var zipFileName = Path.GetFileName(zipFile);<br>                    var zipFileDirectory = Path.GetDirectoryName(zipFile);<br><br>                    string uniqueFolderName = GetUniqueName(zipFileDirectory, zipFileName.Replace(&quot;.zip&quot;, &quot;&quot;));<br>                    var zipFileDestination = Path.Combine(zipFileDirectory, uniqueFolderName);<br><br>                    ZipFile.ExtractToDirectory(zipFile, zipFileDestination);<br>                    File.Delete(zipFile);<br>                    await ExtractNestedZipFiles(zipFileDestination);<br>            }<br>        }</pre><h3>Why not use Message Broker?</h3><h4>Better question: is our communication going to be asynchronous or synchronous?</h4><p>I have not discussed the use of a message broker thus far because it isn’t necessary in this context. Message brokers like RabbitMQ are ideal for environments with a large number of microservices requiring complete decoupling. This is just my perspective, and it could change in the future.</p><p>Introducing a message broker signifies that our service communication is asynchronous, operating on a “send and forget” model, unlike the standard REST API where you send a request and wait for a response.</p><h4>Let’s redesign some components to see how we can implement RabbitMQ.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX7g7tBRCp_usmjVXXCb9Q.png" /></figure><p>As illustrated in the figure above, I have deconstructed the file-service into several sub-services that communicate via a RabbitMQ server. While this approach can be effective for teams with 20+ backend engineers, it might be deemed as “over-engineering” for smaller teams.</p><h3>Search Service</h3><p>A critical component of system is the ability to efficiently <strong>search through large volumes of data</strong>. This involves using OCR to extract text from files and indexing this text into Elasticsearch for<strong> full-text search capabilities</strong>. Optimizing the search functionality ensures quick and relevant search results, even as the dataset grows.</p><p>A Sequence Diagram can help display the workflow of the search request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrgXYM33_cXoBkbYzH-2AQ.png" /></figure><blockquote>One Important Note is that if you go back to the <strong>elastic search model</strong> displayed above you will see the model has <strong>3 fields: id, textContent and fileName</strong>. But the user wants to see a <strong>lot more than that </strong>and more importantly the user does not want to see the <strong>textContent </strong>of the file on each get request so we will have to query the File service to Map our objects and<strong> filter to only have the important parts</strong>.</blockquote><h3>Report Service</h3><p>The Report Service is a critical component of our microservice architecture, specifically designed to handle the generation and distribution of <strong>PDF reports</strong>. This service leverages data from <strong>multiple microservices</strong>, ensuring comprehensive and up-to-date information is provided in a user-friendly format.</p><h4>what does the report help us with ?</h4><p>well it depends on the type of the institution, but without the input of external factors and solely focusing on system we can have the following points to include in our report:</p><p><strong>Title and Summarized Text</strong>: Reports can aggregate files with common titles or summarized text, allowing the company to identify trends and patterns. For example, files related to specific projects or topics can be grouped together, providing insights into the volume and nature of work being done in those areas. <strong>This can help in project management</strong>, <strong>resource allocation, and identifying areas that require more focus or support</strong>.</p><p><strong>File Access and Usage Metrics:</strong> By tracking which users access which files, the company can understand employee engagement and usage patterns. This data can be used to improve internal processes, ensure compliance with security policies, and identify training needs. Additionally, it can <strong>highlight which documents are most critical to business operations</strong>.</p><p><strong>System Performance:</strong> Reports on the performance of <strong>various microservices</strong>, including response times, error rates, and processing times, can help in identifying bottlenecks and areas for optimization. This data is crucial for maintaining a high-performing and reliable system.</p><h3>Conclusion</h3><p>Building a scalable file management system is like assembling a puzzle with way too many pieces but it’s totally worth it when you see the big picture. By managing how you store, process, and search your files, you can keep things running smoothly, even when your data grows faster than your <strong>coffee consumption during crunch time</strong>. Remember, good caching strategies can be a lifesaver. Keep it scalable, keep it efficient, and don’t forget: there are <strong>10 types</strong> of people in the world — those who understand <strong>binary </strong>and those who <strong>don’t</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab7972a485be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Cloud to Code: A Full Stack Journey with AWS, GitHub Actions, and ArgoCD]]></title>
            <link>https://medium.com/@turkialqahtani400/from-cloud-to-code-a-full-stack-journey-with-aws-github-actions-and-argocd-51846e18291b?source=rss-a36ebe7e3812------2</link>
            <guid isPermaLink="false">https://medium.com/p/51846e18291b</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Turki alqahtani]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 00:39:31 GMT</pubDate>
            <atom:updated>2024-04-16T00:39:31.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S34XhSy2hvydBY9Mijnmhg.png" /></figure><p>In a fast-paced industry where uniqueness and creative problem solving are keys to success, one cannot simply stand still and not evolve with knowledge and improvements. As we embrace new technologies and methodologies, it becomes vital to share these experiences to foster learning and growth. This blog post serves as a guide through the process of building a modern software infrastructure using AWS, deploying a CI/CD pipeline with <strong>GitHub</strong> Actions and <strong>ArgoCD</strong>, and developing a full-stack application with <strong>ReactJS </strong>and<strong> .NET 7</strong>.</p><h3>Architecture And Design</h3><p>A C<strong>lient</strong> application will query the B<strong>ackend</strong> server using a <strong>Get</strong> request on the route”/_health” and the server will <strong>return 200 status</strong> if it’s healthy and <strong>500 status if its not</strong>. Very simple right ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtNkqCTMxjYmylFN4Wiswg.png" /></figure><h3>How can we make this as complex as possible ?</h3><p>Our aim is to tackle a simple problem using a <strong>complex solution</strong>. This approach provides a clear introduction to the implementation of large, scalable systems, which is the primary focus of this post.</p><p>The source code of this project is a variable, the tools that we are going to use are also variables even the cloud provider. Technologies are exchangeable but the approach is not.</p><p>We will implement the following :</p><ul><li>Frontend &amp; Backend source code implementation</li><li>Building the Frontend &amp; Backend using Docker files</li><li>Separate <strong>Github</strong> repositories for the source codes and the K8s artifacts</li><li>CI/CD with Github</li><li>Environment variables settings</li><li>IAM Roles/Polices on AWS</li><li>VPC (Subnets, Internet Gateway, Route Table) on AWS</li><li>Elastic Kubernetes Cluster(Auto Scaling Groups) on AWS</li><li>ArgoCD configurations</li></ul><h4>Frontend &amp; Backend source code implementation</h4><p>I will assume you have nodeJS &amp; .NET CLIs installed if not you can reference the installation methods <a href="https://nodejs.org/en">Node</a>JS .<a href="https://dotnet.microsoft.com/en-us/">NET</a>.</p><p>Run the following command to scaffold a Reactjs app.</p><pre>$ npm create vite@latest</pre><p>The frontend code is very simple, a button will appear in the middle of the screen with a on click event that will call the backend health check api once the user clicks it.</p><pre>import { useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const [loading, setLoading] = useState(false);<br>  const [response, setResponse] = useState(&quot;&quot;);<br><br>  const handleButtonClick = async () =&gt; {<br>    setLoading(true);<br>    try {<br>      const result = await fetch(`${import.meta.env.BACKEND_URL}/_health`);<br>      if (result.status === 200) {<br>        setResponse(&quot;Backend is working&quot;);<br>      } else {<br>        setResponse(&quot;Backend is not working&quot;);<br>      }<br>    } catch (error) {<br>      setResponse(&quot;Failed to fetch data&quot;);<br>    }<br>    setLoading(false);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={handleButtonClick}&gt;<br>        {loading ? &quot;Loading...&quot; : &quot;Check if Backend is working&quot;}<br>      &lt;/button&gt;<br>      {response &amp;&amp; &lt;p&gt;{response}&lt;/p&gt;}<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>I want you to take a close look again on the line where the actual request being made with the<strong> fetch object</strong> and notice the <strong>environment</strong> variable called <strong>BACKEND_URL</strong> this is important as we will come back to it later with <strong>ci/cd</strong> stage but for now you can create a <strong>.env</strong> file in the root folder of the frontend application and give it the value for the specified url that the backend server will be listening on naturally in this stage it will be localhost.</p><pre>BACKEND_URL=http://localhost:5104</pre><p>Run the following command that will spin up a .NET web api template with any name you wish.</p><pre>dotnet new webapi -o NameOfTheProject</pre><p>Now the backend code is also very simple its really only two lines of code and these are configurations to allow for the health check endpoint installed. Inside the program.cs add these two lines.</p><pre>builder.Services.AddHealthChecks();</pre><pre>app.MapHealthChecks(&quot;_health&quot;);</pre><p>Now one last configuration to allow all origins on the backend server. Now this is only for testing purposes it is extremely wrong for production workflows</p><pre>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAll&quot;, builder =&gt;<br>    {<br>        builder.AllowAnyOrigin()<br>               .AllowAnyMethod()<br>               .AllowAnyHeader();<br>    });<br>});<br><br>var app = builder.Build();<br>app.UseCors(&quot;AllowAll&quot;);</pre><p>The whole program.cs file should look like this.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>Console.WriteLine(&quot;Hello&quot;);<br><br><br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br>builder.Services.AddHealthChecks();<br><br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAll&quot;, builder =&gt;<br>    {<br>        builder.AllowAnyOrigin()<br>               .AllowAnyMethod()<br>               .AllowAnyHeader();<br>    });<br>});<br><br>var app = builder.Build();<br>app.UseCors(&quot;AllowAll&quot;);<br><br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br><br>app.MapControllers();<br>app.MapHealthChecks(&quot;_health&quot;);<br><br>app.Run();</pre><p>We are set, the source code for both of the Frontend and the Backend is complete.</p><h3>Dockerize Frontend And Backend</h3><p>You probably have guessed it by now, we are running on a containerization environment so we need to have a <strong>container run time</strong> and we are going to use Docker for that. If you don’t have Docker installed you can refrence the installation process here <a href="https://www.docker.com/">Docker</a>.</p><h4>What happens when you run <strong>NPM Dev vs NPM Build?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goCbcoHIfi-ec08Otz8tog.png" /></figure><p>npm run dev is typically used to start a local development server with features like hot reloading, verbose logging, and source maps to facilitate easy debugging and development without minifying the code.</p><p>npm run build prepares your application for production by performing tasks like minification, bundling, optimization, and setting environment variables for performance and efficiency, resulting in optimized <strong>static files</strong> ready for deployment.</p><p>The build command prepare static files which means these static files need a server to run on, that is why our build for the react app will need a server image known as <strong>Nginx </strong>to host these static files and let them accessible through the browser.</p><p>Frontend Dockerfile:</p><pre># Stage 1: Build the React application<br>FROM node:latest as build-stage<br><br># Set the working directory in the Docker container<br>WORKDIR /app<br><br># Copy package.json and package-lock.json/yarn.lock to the Docker image<br>COPY package*.json ./<br><br># Install project dependencies<br>RUN npm install<br><br># Copy the rest of the application&#39;s code<br>COPY . .<br><br># Accept the backend URL as a build argument<br>ARG BACKEND_URL<br><br># Set it as an environment variable that React can access<br>ENV REACT_APP_BACKEND_URL=$BACKEND_URL<br><br># Build the application<br>RUN npm run build<br><br># Stage 2: Serve the app with Nginx<br>FROM nginx:alpine<br><br># Remove the default Nginx configuration file<br>RUN rm /etc/nginx/conf.d/default.conf<br><br># Copy the Nginx configuration file<br>COPY nginx/default.conf /etc/nginx/conf.d/<br><br># Copy the build output to replace the default nginx contents.<br>COPY --from=build-stage /app/dist /usr/share/nginx/html<br><br><br># Expose port 3000<br>EXPOSE 3000<br><br># Start Nginx and keep it running<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>We will have to edit some of the default configuration of Nginx, so add a folder called n<strong>ginx</strong> and inside it create a file called <strong>default.conf</strong> and add the following server object.</p><pre>server {<br>  listen 3000;<br><br>  location / {<br>    root /usr/share/nginx/html;<br>    index index.html index.htm;<br>    try_files $uri $uri/ /index.html;<br>  }<br>}</pre><p>Backend Dockerfile:</p><p>This is how the Backend Dockerfile should look like. Notice that we are exposing two ports 80 and 442 for http https requests.</p><pre>FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base<br>WORKDIR /app<br>EXPOSE 80<br>EXPOSE 443<br><br># .NET 7 SDK image to build the application<br>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br>WORKDIR /src<br>COPY [&quot;Backend.csproj&quot;, &quot;./&quot;]<br>RUN dotnet restore &quot;./Backend.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/.&quot;<br>RUN dotnet build &quot;Backend.csproj&quot; -c Release -o /app/build<br><br># Publish the application<br>FROM build AS publish<br>RUN dotnet publish &quot;Backend.csproj&quot; -c Release -o /app/publish<br><br># Build the runtime image using the base stage<br>FROM base AS final<br>WORKDIR /app<br><br># Copy the published application and the static directories into the final image<br>COPY --from=publish /app/publish .<br><br>ENTRYPOINT [&quot;dotnet&quot;, &quot;Backend.dll&quot;]</pre><h3>Github Repository Setup</h3><p>We will first create the repo which will hold all the source code for the Frontend and the Backend, in a later stage we will talk about a different repo which will hold the <strong>kubernetes</strong> cluster manifest files.</p><p>Don’t worry about the folder called .github as I will discuss about it in the next section.</p><p>The repo should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTwJFB2C5j34RhrCUxsN_w.png" /></figure><p>Next go to settings → secrets and variables → action and add two secrets called DOCKER_USERNAME and DOCKER_PASSWORD and fill them with your actual docker username and docker password on docker hub. This will be crucial for our <strong>CI/CD.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9jvVcIENlZEUdPi3X-JWQ.png" /></figure><p>This will wrap up our GitHub repo setup.</p><h3>CI/CD setup</h3><p>Continuous Integration and Continuous Delivery are critical for build large and scalable systems as it streamlines the process of taking the source code written by the developer and shipping it to end users. In this section we will create a simple CI/CD pipeline using GitHub Actions and it will implement the following :</p><p>1- Setup virtual environment for both NodeJs and .NET</p><p>2- Build both dockerize images from the previous section</p><p>3- run those images and run the test commands</p><p>4– deploy the images into a remote registry on dockerhub</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTaYL-RRv_E4EuN8b2Qs6Q.png" /></figure><p>First create a .github folder at the root directory of our project. Inside it create another folder called workflows and inside the workflows folder create a ci-cd.yaml file.</p><p>The pipeline is triggered whenever changes are pushed to the Dev branch. This ensures that every code change is automatically processed, tested, and prepared for deployment without manual intervention.</p><p>The pipeline is composed of a single job: build-and-test, which performs multiple steps to ensure the application is built and tested correctly on an Ubuntu virtual environment.</p><p>Initially, the pipeline checks out the latest code from the repository, ensuring the most recent changes are used throughout the pipeline.</p><p>The pipeline sets up Node.js environment, specifically version 18. This is crucial for projects that depend on specific Node.js versions for compatibility.</p><p>Similarly, it sets up a .NET environment with version 7.0.x, aligning with our backend technology requirements.</p><p>In the Frontend directory, dependencies are installed using npm install, followed by running tests with npm test. This ensures that the frontend of our application behaves as expected.</p><p>For the backend, dependencies are restored using dotnet restore for the .NET project located in the Backend directory. Tests are then executed with dotnet test, validating the backend logic.</p><p>The pipeline logs into Docker using credentials stored in GitHub secrets, ensuring security and privacy.</p><p>Docker images for both frontend and backend are built and pushed to a Docker registry. Each component’s image is tagged with both the specific commit SHA and ‘dev-latest’ to allow for clear versioning and rollback capabilities. This step uses environment-specific arguments (like the backend URL) injected during the build process.</p><p>ci-cd.yaml :</p><pre>name: CI/CD Pipeline<br><br>on:<br>  push:<br>    branches:<br>      - Dev # Run this workflow on push events to the dev branch<br><br>jobs:<br>  build-and-test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3 # Check out the repository code<br><br>      # Setup Node.js<br>      - name: Setup Node.js<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: &quot;18&quot;<br><br>      # Install and Test Frontend<br>      - name: Install Frontend Dependencies<br>        run: npm install<br>        working-directory: ./Frontend<br><br>      - name: Run Frontend Tests<br>        run: npm test<br>        working-directory: ./Frontend<br><br>      # Setup .NET<br>      - name: Setup .NET<br>        uses: actions/setup-dotnet@v2<br>        with:<br>          dotnet-version: &quot;7.0.x&quot;<br><br>      # Install and Test Backend<br>      - name: Install Backend Dependencies<br>        run: dotnet restore ./Backend<br><br>      - name: Run Backend Tests<br>        run: dotnet test ./Backend<br><br>      # Docker Actions (Simplified)<br>      - name: Docker Login<br>        run: echo &quot;${{ secrets.DOCKER_PASSWORD }}&quot; | docker login -u &quot;${{ secrets.DOCKER_USERNAME }}&quot; --password-stdin<br><br>      - name: Build and Push Frontend Docker Image<br>        run: |<br>          docker build --build-arg BACKEND_URL=${{ secrets.BACKEND_URL }} -t ${{ secrets.DOCKER_USERNAME }}/booklibrary-frontend:dev-${{ github.sha }} ./Frontend<br>          docker push ${{ secrets.DOCKER_USERNAME }}/booklibrary-frontend:dev-${{ github.sha }}<br>          docker build -t ${{ secrets.DOCKER_USERNAME }}/booklibrary-frontend:dev-latest ./Frontend<br>          docker push ${{ secrets.DOCKER_USERNAME }}/booklibrary-frontend:dev-latest<br><br>      - name: Build and Push Backend Docker Image<br>        run: |<br>          docker build -t ${{ secrets.DOCKER_USERNAME }}/booklibrary-backend:dev-${{ github.sha }} ./Backend<br>          docker push ${{ secrets.DOCKER_USERNAME }}/booklibrary-backend:dev-${{ github.sha }}<br>          docker build -t ${{ secrets.DOCKER_USERNAME }}/booklibrary-backend:dev-latest ./Backend<br>          docker push ${{ secrets.DOCKER_USERNAME }}/booklibrary-backend:dev-latest</pre><p>Now any time a push event made by a developer the pipeline will fire off and start executing the steps. You can view you pipelines by clicking on the <strong>Actions</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EywPXD7_k4_hOCEf3Jlpw.png" /></figure><p>Inspect the pipeline by clicking on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niip8EvIozzFmaUWvPJ3Rg.png" /></figure><p>You can double check if the docker binaries are in fact inside your dockerhub repositories by going to dockerhub → repositories.</p><h3>AWS Infrastructure</h3><p>We will construct our infrastructure on AWS, beginning with the setup of our Virtual Private Cloud (VPC) that encompasses subnets across multiple availability zones, along with internet gateways. Next, we will establish roles and policies that are essential for creating our Kubernetes cluster and ensuring the worker nodes have the necessary access to operate effectively. Following this, we will proceed to build our cluster and, finally, establish a connection to it. An Image is worth a thousands words, a visual representation can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*de5AVxzf8NiVn9l5OrDSDw.png" /></figure><p>Note: in the world of kubernetes a server is called node.</p><h4>How does our Infrastructure fit into the work that we have done so far ?</h4><p>We can view our infra as the final destination where we want our source code to be its where the end users will connect and work with our application. all the <strong>steps before are just so we can automatically move our code into our infra. </strong>Below you will find the complete system design for our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S34XhSy2hvydBY9Mijnmhg.png" /></figure><h4>VPC Configuration</h4><blockquote>before start with our VPC configuration, what is a VPC?</blockquote><blockquote>A Virtual Private Cloud (VPC) is a secure, isolated private cloud hosted within a public cloud environment. Essentially, a VPC is a portion of a cloud computing environment where you can define and control a virtual network that closely resembles a traditional network that you’d operate in your own data center, with the benefits of using scalable infrastructure of public clouds like AWS, Google Cloud, or Microsoft Azure.</blockquote><p>Go to AWS console → VPC → create VPC . You will be promoted with this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bg4oOj8IdGyZfBrDgYFCwA.png" /></figure><p>It’s important to note that VPC is not a global service which means you will have to choose which region you will host your VPC from the top right navigation bar. I will be choosing us-east-1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwYQKLrfo4RNPoI_HL80NQ.png" /></figure><p>For the IPv4 CIDR block i will be using the following format will provide a total of 65,536 IP addresses, with 65,534 of those being usable for hosts within a private network. Keep the rest of the options as default then hit Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbPhCLjVoxS4JetZ3nAJBw.png" /></figure><p>You can view your newly created VPC from the side bar “Your VPCs’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZRy_zrrFzbe6BoHxiNEeQ.png" /></figure><h4>Internet Gateway</h4><p>Tab into the Internet Gateways tab then create an Internet gateway and attach it to the VPC we have just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfdKVyQNxuc3fCGJtJYlLA.png" /></figure><h4>Subnets</h4><blockquote>But wait why do we need Subnets ? we already created our VPC.</blockquote><blockquote>well subnets, or subnetworks, are used within a larger network to partition the network into smaller, more manageable segments. This allows for improved network performance and security, helps prevent address depletion by more efficiently using the address space, and can segregate network traffic to improve control and organization.We will be creating two subnets on two Availability zones.</blockquote><p>Tab into the Subnets from the sidebar and click on Create subnet you will be taken into this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwQaGvfAB4zQd-D_qMAKLQ.png" /></figure><ul><li>Select the VPC that we have just created and then choose your subnet name.</li><li>Select the Availability zone as well as the IPv4 subnet CIDR block.</li><li>Create the subnet</li><li>Repeat the process one more time but with a different AZ &amp; Subnet CIDR block</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7mrUEWpF5AOrHjonHhlqA.png" /></figure><p>You can view your subnets attached to the VPC by clicking subnets on the sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qx9euToidsQ1Rbgb7d5RA.png" /></figure><p>One Last thing we need to enable auto-assign public ipv4 for both of out newly created subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ld1ua_PEGRCjLOoNbpakJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfteQU1Aw2OHI5lRSXKMBg.png" /></figure><p>The last configuration will be Route-Table which will be responsible for direction the traffic between our two subnets.</p><p>Use the default options but make sure to edit routes rules and add the following public route rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5brPy4EVwibr2PSV3RfYQ.png" /></figure><h4>IAM Roles</h4><p>By default we will have to create two IAM roles.</p><ul><li>One for Creating the kubernetes cluster</li><li>One for managing the worker nodes inside the cluster</li></ul><blockquote>For the Cluster creation role you can create a role with any name and attach the <strong>AmaonEKSClusterPolicy</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku5nsRvprHkoYVp8XVSmfg.png" /></figure><blockquote>For the worker nodes role you can also use any name for the role but make sure you have the following polices attached to that role.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5g3p2Fg2bv2Sof1TSoBgQ.png" /></figure><h4>EKS setup</h4><p>Finally we are going to tie everything we have created on AWS together by making our Kuberntes cluster using <strong>Elastic Kubernetes Service</strong>.</p><p>Find the EKS service and click on create cluster.</p><ul><li>give a name to the cluster</li><li>the cluster service role should be the IAM role that we have just created for cluster creation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJXodxrfUyREyyfFwfW63g.png" /></figure><ul><li>Now for the network section select the VPC that we have just created and the subnets will auto fill.</li><li>Create a security group that allows all protocols &amp; ports into the cluster and attach it into the cluster</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtrM1oCGT-5261A0Iurwkg.png" /></figure><p>Next turn on “Configure Kubernetes service IP address range” and select range that does not overlap with our CIDR range i will be going with “10.10.0.0/16”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRT4DNvhlka7bnDplLeIQA.png" /></figure><p>and for the rest of the configuration you can keep them as the defaults values.</p><blockquote>Note that it takes from 5–15 minutes until your cluster gets ready</blockquote><p>Finally your cluster status should be Active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYOIBCWplXn3RTRwbDIn4Q.png" /></figure><p>One last thing is left for us and that is to specify our Node-groups.</p><blockquote>click on you active cluster → compute → add node group</blockquote><p>After that you will be taken to this page where you need to fill the information related to you “Nodes” also known as servers or EC2s. make sure to apply the node management role that we have created in our IAM section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4n-X_wijFqyBYspCoAb6zQ.png" /></figure><p>Thats it we are done all that is left is for us to connect to our cluster!</p><h4>Cluster Connection</h4><ul><li>Open Terminal</li><li>install AWS CLI</li><li>type “AWS configure” and fill out you user access keys and secret keys which can be optioned from IAM service.</li><li>make sure to select the region where your cluster is from</li><li>type the following command</li></ul><pre>aws eks --region &lt;Region-name&gt; update-kubeconfig --name &lt;Cluster-name&gt;</pre><p>After that you shoud be ready to work with your cluster.</p><p>lets start to play around with it type the following command:</p><pre>kubectl get nodes</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu53ebwogMieplhvMPPgJg.png" /></figure><p>Congrats you have set up a Kubernetes cluster but wait, where is my Frontend and Backend code ?</p><h3>Enter ArgoCD</h3><p>ArgoCD is a declarative, GitOps continuous delivery tool for Kubernetes. It allows you to define and manage the infrastructure and applications you run in Kubernetes using git repositories as the source of truth.</p><p>I have mentioned earlier that we are going to have another Github Repo which will hold our kubernetes manifest files. That repo will be our source of truth for our cluster artifacts which will include (Pods,Deployments,Service,Ingress..etc) in a yaml format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJUK18XPHN0f_48-YqXxlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YKYNBmaivpObELGXq6n2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlWz6nGgLLJEChxX3MPguQ.png" /></figure><blockquote>If you ever worked with kuberntes you will know that its all about yaml files. so what about our docker images on dockerhub how do we get them into our cluster? create a yaml file.</blockquote><p>Backend-Deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: backend-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: backend<br>  template:<br>    metadata:<br>      labels:<br>        app: backend<br>    spec:<br>      containers:<br>        - name: backend<br>          image: &lt;your-image-name&gt;<br>          ports:<br>            - containerPort: 80<br>            - containerPort: 443<br>      imagePullSecrets:<br>        - name: my-docker-creds<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: backend-service<br>spec:<br>  selector:<br>    app: backend<br>  ports:<br>    - name: http<br>      protocol: TCP<br>      port: 80<br>      targetPort: 80<br>    - name: https<br>      protocol: TCP<br>      port: 443<br>      targetPort: 443<br>  type: ClusterIP</pre><p>Frontend-Deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: frontend-deployment<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: frontend<br>  template:<br>    metadata:<br>      labels:<br>        app: frontend<br>    spec:<br>      containers:<br>        - name: frontend<br>          image: &lt;your-image-name&gt;<br>          ports:<br>            - containerPort: 3000<br>      imagePullSecrets:<br>        - name: my-docker-creds<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: frontend-service<br>spec:<br>  type: NodePort<br>  selector:<br>    app: frontend <br>  ports:<br>    - port: 80<br>      targetPort: 3000 <br>      nodePort: 30080</pre><h4>Install ArgoCD inside the cluster</h4><p>following these steps to run ArgoCD inside our cluster.</p><pre>kubectl create namespace argocd<br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><pre>kubectl patch svc argocd-server -n argocd -p &#39;{&quot;spec&quot;: {&quot;type&quot;: &quot;LoadBalancer&quot;}}&#39;</pre><p>The last command makes a load-balancer service for ArgoCD interface for you to access through the browser. you can find the IP of that load-balancer by running the following command</p><pre>kubectl get svc -n argocd</pre><p>Look for service called Load-balancer and use the external-ip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxIV_9B6L-y6MDf6YFIiAA.png" /></figure><p>ArgoCD default username is admin and for the password you can run the following command to get it:</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p>After you login you will promoted to a page like this. keep in mind i already have created a new app. You will have to create a new app by clicking New app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfNuR6-SB2984kePaU1EeA.png" /></figure><p>I will be creating a new App using yaml format because it is easier but you can choose whatever way you like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fs1jPR8ytLxW1QHps-7K0g.png" /></figure><p>Save and run the application and you should see something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9aETu_lol5d_MNo1i2sgA.png" /></figure><p>Finally lets test our app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQOEc3AT8maJXKu72loRPg.png" /></figure><p>In conclusion, the journey of building a full-stack application with cutting-edge technologies has been both challenging and immensely rewarding. By stepping through each phase of the infrastructure setup and application development, we’ve not only explored the technical depths but also demonstrated the importance of continuous learning and adaptation in software engineering. The solutions detailed in this article are designed to inspire and guide you through your own projects, emphasizing that in our rapidly evolving industry, the most powerful tool at our disposal is knowledge. Whether you are building your first cloud-native application or looking to refine your existing systems, remember that the path to innovation is paved with perseverance and collaborative learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51846e18291b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>