<?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 - on Medium]]></title>
        <description><![CDATA[Stories by - on Medium]]></description>
        <link>https://medium.com/@cheahwen1997?source=rss-62025a437ee2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by - on Medium</title>
            <link>https://medium.com/@cheahwen1997?source=rss-62025a437ee2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:43:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cheahwen1997/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[A Practical Guide to Networking Best Practices in AWS (VPC)]]></title>
            <link>https://medium.com/@cheahwen1997/a-practical-guide-to-networking-best-practices-in-aws-vpc-05ce5bf008dd?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/05ce5bf008dd</guid>
            <category><![CDATA[network-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 08:15:14 GMT</pubDate>
            <atom:updated>2025-09-15T14:57:24.757Z</atom:updated>
            <content:encoded><![CDATA[<p>When deploying an application on AWS, having a secure and standardized networking setup is crucial to prevent your application from being compromised. Sometimes we just simply deploy everything in the public subnet with default VPC to save our time. While this may seem fine at first, since you can rely on security groups and access key verification but in the long run it can become risky. As your application grows in complexity, a single misconfiguration could expose sensitive information to the public. In this article, I’ll walk you through a step-by-step guide on how to properly set up networking in AWS and place your application in the correct subnet.</p><h3>Network Architecture</h3><p>We will organize the subnets as follows:</p><ul><li><strong>INT (Private Subnet):</strong> For application servers such as EC2 or ECS.</li><li><strong>SEC (Private Subnet):</strong> For database and caching services such as RDS and ElastiCache.</li><li><strong>DMZ (Public Subnet):</strong> For public-facing resources such as Load Balancers.</li></ul><p><strong>Traffic Flow Example 1: </strong>Users -&gt; ALB (DMZ) -&gt; EC2 (INT) -&gt; RDS/Elasticache (SEC)</p><p><strong>Traffic Flow Example 2:</strong> Developer -&gt; SSH Bastion EC2 (DMZ) -&gt; RDS/Elasticache (SEC)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiGizOejnKcIUgOw_soBvg.png" /><figcaption>Network Design</figcaption></figure><p>In this setup, I am using the <strong>ap-northeast-1 (Tokyo) region</strong>, which currently provides <strong>three Availability Zones: A, C, and D</strong>. Each subnet type will be distributed across these AZs to ensure high availability and fault tolerance.</p><h4>Virtual Private Cloud (VPC)</h4><p>VPC is the AWS virtual network and the first thing that we need to configure to define how our subnets should be placed. Here I put IPv4 CIDR to 10.1.0.0/16 which will contain 65,536 total IPv4 addresses distributed to subnets (private &amp; public).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8aAJYNyKZRp2YPdSIKl6Hg.png" /><figcaption>VPC Creation</figcaption></figure><p>Next, we need to <strong>enable DNS hostnames</strong> in the VPC settings. This allows public EC2 instances (Bastion/etc) launched in the <strong>public subnet</strong> to be assigned a <strong>public DNS hostname</strong>, making them accessible from the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig4V2Dd6DhltWY_kX0FQrQ.png" /><figcaption>Edit VPC to Enable DNS hostnames</figcaption></figure><h4>Subnets</h4><p>Subnets are range of IP addresses in VPC. When you create AWS resources such as EC2/RDS, this is where the subnet placement have to be defined.</p><p>We need to do some math to calculate range of IPv4 subnet CIDR block to avoid subnet overlapping. Please visit <a href="https://www.calculator.net/ip-subnet-calculator.html">https://www.calculator.net/ip-subnet-calculator.html</a> to find out the respective range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*NYGeR4KdYJ_TgPRUu39UZw.png" /><figcaption>IP Address range</figcaption></figure><p>For each subnet, we will allocate a <strong>/24 CIDR block</strong>, which provides <strong>256 IP addresses</strong> in total. Out of these, <strong>251 are usable</strong>, since AWS reserves 5 IP addresses in every subnet.</p><p>INT Subnet (AZ A): 10.1.0.4 to 10.1.0.254</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyF9FrYCEAjVdgTJMe83zQ.png" /><figcaption>demo-int-subnet-a</figcaption></figure><p>INT Subnet (AZ C): 10.1.1.4 to 10.1.1.254</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZXsyUeHByagadh_yxQWDg.png" /><figcaption>demo-int-subnet-c</figcaption></figure><p>INT Subnet (AZ D): 10.1.3.4 to 10.1.3.254</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_EQOzUh2Q-Y6Sf46xes5w.png" /><figcaption>demo-int-subnet-d</figcaption></figure><p>Repeat the same step as above for SEC subnet (A, C, D) and DMZ subnet (A, C, D) with the subsequence IPv4 CIDR block. Your final configuration should look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TebPU1PM8Y8SHUIsipTcyw.png" /><figcaption>Subnet Configuration</figcaption></figure><p>Next, we need to create another <strong>public subnet</strong> (demo-dmz-subnet-nat) to host the NAT Gateway. Once the NAT Gateway is in place, our applications running in the <strong>INT (private subnet)</strong> will be able to make outbound calls to the internet securely. Later, we will associate all the private subnets in route table to send traffic to 0.0.0.0/0 (public internet) through NAT Gateway.</p><p>DMZ NAT: 10.1.255.244 to 10.1.255.254</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLjLP3IyOwT1nHD5i2amYg.png" /><figcaption>Nat Subnet</figcaption></figure><h4>Internet Gateway (IGW)</h4><p>When our application needs to connect to the public internet, or when public users send requests to our backend services through the internet, we must configure an <strong>Internet Gateway (IGW)</strong> to route the traffic to and from our subnets. Typically, only the <strong>public subnet</strong> is allowed to communicate directly with the internet, while private subnets remain isolated for security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrK3ifuK2JxQEFGZ_FAZTw.png" /><figcaption>demo-dmz-igw</figcaption></figure><p>After the IGW created, you will see the state is in “Detached”, please attach it to the VPC created just now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8VZ-42xIG7ZmWLYC5DR6A.png" /></figure><h4>NAT Gateway (NGW)</h4><p>For resources that sit in a private subnet but still need to access the public internet (for example, to download updates or fetch external data) without being accessible from the internet, we need to configure a <strong>NAT Gateway (NGW)</strong>. Make sure the connectivity type is set to <strong>Public</strong>, so the NAT Gateway can communicate with the public internet. Elastic IP (EIP) is needed to provide a static, public IP address for private EC2 instances to communicate with the internet, ensuring that the public IP doesn’t change even if the NAT Gateway restarts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urKjUYAAJ1U-XvbzfWSUeA.png" /><figcaption>demo-dmz-ngw</figcaption></figure><p>Please wait a few minutes for the NGW to finish deploying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wcx3E9xre8JW4qssluvTuQ.png" /><figcaption>NGW Status</figcaption></figure><h4>Route Tables</h4><p>Route tables in a VPC act as controllers that define how traffic is routed between your subnets and other networks (such as the internet, other VPCs, or on-premises networks).</p><ul><li>Create INT Route Table:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKHpVYGs2XOhhlyopcSnpQ.png" /><figcaption>demo-int-rt</figcaption></figure><p>Select tab “Routes” and click “Edit routes” and configure 0.0.0.0/0 as destination and source as the NGW we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hpuB2up2786o0TbAskbuQ.png" /><figcaption>Route NAT to public internet</figcaption></figure><p>Next, select “Subnet associations” to associate all the private subnets (INT).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_TSeZj47jz9MM6WabNC_w.png" /><figcaption>Explicit associate other private subnets (INT)</figcaption></figure><ul><li>Create SEC Route Table:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysl3hvKl_N7hgUMt1o7ujg.png" /><figcaption>demo-sec-rt</figcaption></figure><p>Select “Subnet associations” to associate all the private subnets (SEC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FW85Q2KaSHxwpTHOvtg7g.png" /><figcaption>Explicit associate other private subnets (SEC)</figcaption></figure><ul><li>Reuse main route table for DMZ Route Table:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB5QBOcdEeIppPprx_oZ1w.png" /><figcaption>demo-dmz-rt</figcaption></figure><p>Select tab “Routes” and click “Edit routes” and configure 0.0.0.0/0 as destination and source as the IGW we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rI3MpQVGqO6n2ADF7CGU8w.png" /><figcaption>Route IGW to public internet</figcaption></figure><p>Select “Subnet associations” to associate all the public subnets (DMZ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBpK_iPE1fBq_gbVQBv5Fw.png" /><figcaption>Explicit associate other public subnets (DMZ)</figcaption></figure><h3>Network Overview &amp; Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeciWZBbK1xgy8zgqTbKmg.png" /><figcaption>VPC Resource Map</figcaption></figure><p>After completing the networking setup, we can proceed to deploy our application components by placing the <strong>EC2 servers</strong> in the <strong>INT subnet</strong>, the <strong>RDS database</strong> in the <strong>SEC subnet</strong>, and the <strong>Application Load Balancer (ALB)</strong> in the <strong>DMZ subnet</strong>. However, since this full setup might take some time, I will just create an EC2 in the <strong>public subnet (DMZ)</strong> to quickly verify that it can connect to the internet. Make sure your IP address is whitelisted in <strong>Security Group</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QENrtwzdci1LG3KKjcmPyA.png" /><figcaption>Network Setting</figcaption></figure><p>After the EC2 created, we can SSH into it.</p><pre>ssh -i ec2-test-rsa.pem ec2-user@52.199.214.225</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ly5M6UFQNKt8qBha5iXVHQ.png" /><figcaption>Trying to curl google.com in Bastion Host</figcaption></figure><h3>Summary</h3><p>That’s all for this article! By now, you should have a clearer understanding of how to design and implement a secure networking setup in AWS. We’ve walked through how to separate your resources into proper subnets, configure route tables, and use Internet Gateways and NAT Gateways effectively.</p><p>The key takeaway is this: <strong>not everything belongs in the public subnet</strong>. By following best practices — placing application servers and databases in private subnets, exposing only necessary endpoints through the DMZ, and using NAT Gateways for outbound internet access — you’ll greatly reduce the risk of accidental exposure and misconfiguration.</p><p>Networking might seem intimidating at first, but once you understand the building blocks, it becomes a powerful tool to keep your applications secure, scalable, and resilient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05ce5bf008dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elastic Search in NestJS with Supabase Integration]]></title>
            <link>https://medium.com/@cheahwen1997/elastic-search-in-nestjs-with-supabase-integration-564768a521b9?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/564768a521b9</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[edge-ngram]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 09:21:14 GMT</pubDate>
            <atom:updated>2025-04-05T03:48:50.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*mqiiOo0_uxTrPndhZUnwBA.png" /><figcaption>Searching in Github</figcaption></figure><p>When dealing with large datasets, filtering relevant results efficiently can be a challenging task. Writing complex SQL queries to retrieve data often becomes cumbersome, especially when multiple conditions and matching criteria are involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2H9yEU6ndfqOqddIZnIGCw.png" /><figcaption>Scary SQL query🤯</figcaption></figure><p>This is where Elasticsearch comes in — a powerful search engine designed for lightning-fast searches and advanced filtering capabilities. Instead of relying solely on SQL queries, I wanted to explore how Elasticsearch could streamline search operations in a NestJS project.</p><h4>Step 1: Project Setup</h4><pre>git clone https://gitlab.com/medium3171129/nestjs-elastic-search.git<br>npm i</pre><h4>Step 2: Supabase Setup &amp; Env Vars</h4><p>Go to Supabase website, create a new project and get the supabase url and supabase key. Create a file named .env.local, put the supabase url and key respectively. Create a table called ‘users’.</p><pre>SUPABASE_URL=&lt;YOUR_SUPABASE_URL&gt;<br>SUPABASE_KEY=&lt;YOUR_SUPABASE_KEY&gt;<br>ELASTICSEARCH_NODE=http://elastic:admin1234@localhost:9200</pre><h4>Step 3: Setup Docker Container for Elastic Search</h4><pre>npm run setup:docker</pre><h4>Setup 4: Run the project</h4><p>Run the project and running on PORT 8888. Access it through <a href="http://localhost:8888/">http://localhost:8888</a></p><pre>npm run start:local</pre><h3>Process Flow</h3><p>There are 5 endpoints:</p><ul><li>&lt;GET&gt; /users/list (Retrieved from Elastic Search)</li><li>&lt;GET&gt; /users/:id (Retrieved from Elastic Search, if not then Supabase)</li><li>&lt;POST&gt; /users/:id (Insert into Elastic Search &amp; Supabase)</li><li>&lt;PATCH&gt; /users/:id (Replace into Elastic Search &amp; Supabase)</li><li>&lt;DELETE&gt; /users/:id (Delete from Elastic Search &amp; Supabase)</li></ul><p>When we first run our app, elastic search index called ‘users’ will be created (with tokenization strategy) if no existed. Then, we will sync the existing data from supabase into Elastic Search. Hence,<strong> Supabase will act as a backup for us to resync back our data</strong> when Elastic Search data gone or migrated.</p><h4>Supabase Setting</h4><p>Create a table named users in supabase with id, created_atand name fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*va37TMKuaEh95dnrdg7xZw.png" /><figcaption>Supabase data structure</figcaption></figure><h4>Elastic Search Tokenization Setting</h4><p>In <a href="https://gitlab.com/medium3171129/nestjs-elastic-search/-/blob/main/src/users/users.service.ts?ref_type=heads#L12">UsersService</a> constructor, we create our Elastic Search setting. It defines an edge_ngram_tokenizer that generates token substrings from the beginning of words, supporting letters and digits with token lengths between 1 and 25. A custom edge_ngram_analyzer is configured to use this tokenizer, optimizing search suggestions and autocomplete. The index mappings specify a name field of type text, utilizing the edge_ngram_analyzer to improve partial word matching and prefix-based searches.</p><p>In <strong>Edge N-grams</strong> (used for autocomplete and prefix search in Elasticsearch), min_gram and max_gram define the <strong>range of token lengths</strong> generated from a word or phrase.</p><p>If you have the word <strong>“search”</strong>, and set:</p><ul><li><strong>min_gram: 2</strong>, <strong>max_gram: 4</strong>, it generates: &quot;se&quot;, &quot;sea&quot;, &quot;sear&quot;</li><li><strong>min_gram: 1</strong>, <strong>max_gram: 6</strong>, it generates: &quot;s&quot;, &quot;se&quot;, &quot;sea&quot;, &quot;sear&quot;, &quot;searc&quot;, &quot;search&quot;</li></ul><pre>this.elasticsearchService.indices.create({<br>    index: TABLE_NAME,<br>    body: {<br>      settings: {<br>        analysis: {<br>          tokenizer: {<br>            edge_ngram_tokenizer: {<br>              type: &#39;edge_ngram&#39;,<br>              min_gram: 1,<br>              max_gram: 25,<br>              token_chars: [&#39;letter&#39;, &#39;digit&#39;],<br>            },<br>          },<br>          analyzer: {<br>            edge_ngram_analyzer: {<br>              type: &#39;custom&#39;,<br>              tokenizer: &#39;edge_ngram_tokenizer&#39;,<br>            },<br>          },<br>        },<br>      },<br>      mappings: {<br>        properties: {<br>          name: {<br>            type: &#39;text&#39;,<br>            analyzer: &#39;edge_ngram_analyzer&#39;,<br>          },<br>        },<br>      },<br>    },<br>  });</pre><h4>Querying Elastic Search</h4><ul><li>Through web browser HTTP request</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRvVALH7eAbOILl5yA414g.png" /><figcaption>Direct access Elastic Search from browser</figcaption></figure><ul><li>Kibana</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeKC9UwpeAFcZoKJjDTELg.png" /><figcaption>Access Elastic Search from Kibana</figcaption></figure><h3>Mock Data</h3><ul><li>Download Postman and import the collection collection. (Download: <a href="https://gitlab.com/medium3171129/nestjs-elastic-search/-/blob/main/Nest%20Elastic%20Search.postman_collection.json?ref_type=heads">https://gitlab.com/medium3171129/nestjs-elastic-search/-/blob/main/Nest%20Elastic%20Search.postman_collection.json?ref_type=heads</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*3kCBblZA1_WyC7grDJiCAQ.png" /><figcaption>Postman Collection</figcaption></figure><ul><li>Then click the 3 dots, select “Run Collection”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*KYTKcqeDx2vqmvrIKEMTqA.png" /><figcaption>Run collection option</figcaption></figure><ul><li>Then, select “Create One User” request, set the Iterations to 1000 to generate 1000 users with random name. There is a prescript setup to retrieve random users from <a href="https://randomuser.me/api/">https://randomuser.me/api/</a>, here we will just take the name field and assigned it into the payload.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBKX3mtZ2KP5GXBq8cvcbQ.png" /><figcaption>Random User API in PreScript Postman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXxIKYbtkLrIN79FWZVkxQ.png" /><figcaption>Mock up 1000 users</figcaption></figure><p>Let’s run the iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrpJgAL-x9C4ZnWu7fsZxg.png" /><figcaption>Creating 1000 users in Supabase and Elastic Search</figcaption></figure><h3>Testing Elastic Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NmunJZBKMCxHF5Vdo51uQ.png" /><figcaption>Search Query: Anthony</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5JtORsjgHoICNkbiiSa_g.png" /><figcaption>Search Query: Jayden</figcaption></figure><p>From the response, there is relevancy_score from elastic search response “_score”. This list will be sorted from higher score to the lower.</p><p>Let’s say we want to get the top 1 result from the API, we could defined the pageSize to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3q16As0V1ggu5GIuD3a58w.png" /><figcaption>Single result from search (currentPage: 1, pageSize: 1)</figcaption></figure><p>That’s it for the demo of implementing Elastic Search in NestJS. We could further adding more fields like email/metadata, then perform more advanced search between these fields to get better and relevant result set.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564768a521b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitrise App Deployment Guide]]></title>
            <link>https://medium.com/@cheahwen1997/visual-studio-app-center-retire-soon-bitrise-integration-800e57510c1a?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/800e57510c1a</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[mobile-app-deployment]]></category>
            <category><![CDATA[automated-deployment]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <category><![CDATA[bitrise]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 16:02:32 GMT</pubDate>
            <atom:updated>2025-10-21T09:34:23.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AkK5Hz3ucM_nihepR2ugg.png" /><figcaption>Visual Studio App Center</figcaption></figure><p>It’s unfortunate to hear that Visual Studio App Center will be retiring on March 31, 2025. As one of the top app distribution platforms for internal applications, it has been widely used for B2B mobile apps in many companies.</p><p>Recently, I’ve been working on the transition from App Center to Bitrise. Bitrise is an advanced CI/CD platform that streamlines the build, test, and deployment processes for iOS, Android, and cross-platform apps. Renowned for its user-friendly interface and vast integration options, it’s an ideal solution for mobile app development.</p><h4>Step 1: Register Bitrise</h4><p>Go to <a href="https://app.bitrise.io/users/sign_in">https://app.bitrise.io/users/sign_in</a> and register an account. Once you register, then it will start the free trial for 30 days. You can later subscribe to “Hobby” plan where you will have 300 credits/month for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZ7FtxR-esGhFoKxeQ4edg.png" /><figcaption>Bitrise Pricing</figcaption></figure><h4>Step 2: Create a New Project</h4><p>Go to “Bitrise CI” menu, go create a new project. Connect you repository (Github, Gitlab, Bitbucket, etc) and authorize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPM1WRLjJE_b-Q_VcS32AA.png" /><figcaption>Create new Project in Bitrise</figcaption></figure><p>Here I am choosing one of my React Native git repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7LKzcSAPvrADiS2EqS01A.png" /><figcaption>Select Repo</figcaption></figure><p>Then, we will need to add SSH key for bitrise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4sSOhW5a3PZWj-VtwVsDg.png" /><figcaption>SSH Key for bitrise</figcaption></figure><p>Then select you default branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5LzT8Qz3WWX7T-Qgsq_bw.png" /><figcaption>Choose branch</figcaption></figure><p>Then, select the stack and machine type as defaulted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*993z5PSkIAEQIkQKaID9SQ.png" /><figcaption>Stack &amp; Machine Type</figcaption></figure><p>For Webhook Setup, you can opt to register the webhook as we can configure trigger_map in bitrise to lookup commit message and auto run the workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXuZiJ3x3IlhFKoCuxYlBA.png" /><figcaption>Webhook Setup</figcaption></figure><p>Note: After project is created with webhook, you can check the Integrations where the incoming webhooks (automatic webhook) should be connected.</p><h4>Step 3: Define our workflow</h4><p>Click “Edit Workflow”, and you should be able to see there are 2 workflows: primary, deploy.</p><p>Let’s create workflow called “dev” and duplicated from “primary” workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKPG0fiAXBVnykIJ94iIZg.png" /><figcaption>Create Workflow</figcaption></figure><p>Hover on the top of the first step in workflow, there will be a “+” icon appear, click on that button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqbpNMYUbNUeKXsSKIVV1g.png" /><figcaption>Add step</figcaption></figure><p>Search for “nvm”. Move the step below “Git Clone Repository”. At the configuration, enter the Node Version to be 20.11.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeW5iRB0AuQiYaxmcz_oNA.png" /><figcaption>Node Version Config</figcaption></figure><p>Search for “Change Working Directory”. Move the step below “Run npm command”. At the configuration, enter the Node Version to be 20.11.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVuIMmLEdHs2PF5aEsw5TQ.png" /><figcaption>Change Working Directory</figcaption></figure><p>Remove “Run npm command” on top of “Change Working Directory” as I just want to deploy it only without test.</p><p>Here we just focus on Android deployment. Search for “Android Build”. Move the step below “Change Working Directory”. Module is set to “app” and variant is set to “release”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eG2kOx4D-6-RDTjD0cER6w.png" /><figcaption>Android build</figcaption></figure><p>Oh ya, I’ve forgotten that the project is running on Expo. There is not android/ios folder in root directory. Hence, I need to run “npx expo prebuild” to generate android/ios folder. Search for “Script” and add the command “npx expo prebuild” before “Change Working Directory”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmeYOhMvdoM3sKMJUftzug.png" /><figcaption>Script: npx expo prebuild</figcaption></figure><h4>Step 4: Testing Workflow</h4><p>Click the play button to run “dev” workflow and on “main” branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyeY5CzRUMS3lgZ6cVTVbw.png" /><figcaption>Run dev workflow</figcaption></figure><p>After waiting for few minutes, the build is success and will be notified through your email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UAZyTSekrjEC-z6d5u1yA.png" /><figcaption>Build Status</figcaption></figure><h4>Step 5: Release Management</h4><p>Now, in order to send the download notification to our QA, PM or designer, we need to add an app in Release Management.</p><p>Create “New App” and select our existing project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s4nnc0JRN2UdcPAkE16VQ.png" /><figcaption>Create an app in Release Management</figcaption></figure><p>Give the title and OS to be Android, package name will be based on your Android’s package name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bgs0CRyVLmPnyj-0WgbCVg.png" /><figcaption>Define title, OS, package name</figcaption></figure><p>Go to your project and click “Testers group” and click “New Group”. Here we will add the group “Developers” and “QA” with send notification automatically enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibSt6xz7pO-arR0sidQ_6Q.png" /><figcaption>Tester groups</figcaption></figure><p>Then click the vertical ellipsis button, click “Manage testers”. Click button “Add testers” to add the respective collaborators into the respective group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jfk-MZNxaoQ6bZG-TTTg4g.png" /><figcaption>Add Testers</figcaption></figure><h4>Step 6: Automate Trigger Workflow</h4><p>In case you want to automate the deployment using commit message, we can do so in Bitrise. Remember that previously when we create the project, there is webhook registration, you should be able to see “Automatic webhook” being connected as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5_62e1goGEdYfkhSvOu1Q.png" /><figcaption>Automatic Webhook</figcaption></figure><p>Let’s go to the “Triggers” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcdPz89wZfm5O-KH_7TSkA.png" /><figcaption>Triggers</figcaption></figure><p>Please remove the 2 triggers on “dev” as we will use the legacy triggers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ushB-mmI8zkPYwqF3e5khg.png" /><figcaption>Clean up triggers</figcaption></figure><p>Under legacy triggers, click “Add push trigger”. Insert “Release v\d+\.\d+\.\d+” in commit message and enable “Use regex pattern”. This will notify that the incoming commit webhook will check against the commit message (E.g: Release v0.1.0) and trigger the target workflow “dev”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLVA6cEzex_QmRZBR7OaFQ.png" /><figcaption>Add push trigger (Conditions)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gx1G5mmYfeJ_Oq-b13PrCA.png" /><figcaption>Add push trigger (Target)</figcaption></figure><p>Let’s test the trigger. Go to your project and make some changes, then commit message with “Release v1.0.0”.</p><pre>git commit -m &quot;Release v1.0.0&quot;</pre><p>We shall see the “dev” workflow is triggered, but then the “primary” workflow also be triggered as there is trigger on push commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymG5rBJAmNepBi_DrptlyQ.png" /><figcaption>Workflow triggers</figcaption></figure><h4>Step 7: Clean up unneccessary workflow “primary” and “deploy”</h4><p>Go to “Configuration YAML” tab, we shall see our defined workflows and trigger_map. In YAML, remove “workflows.deploy” and “workflows.primary”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6x2PlVkSA7KjQpLoygngQ.png" /><figcaption>Configuration YAML</figcaption></figure><p>The final YAML should look like this.</p><pre>---<br>format_version: &#39;13&#39;<br>default_step_lib_source: https://github.com/bitrise-io/bitrise-steplib.git<br>project_type: react-native<br>workflows:<br>  dev:<br>    description: |<br>      Runs tests.<br><br>      Next steps:<br>      - Check out [Getting started with Expo apps](https://devcenter.bitrise.io/en/getting-started/getting-started-with-expo-apps.html).<br>    steps:<br>    - activate-ssh-key@4: {}<br>    - git-clone@8: {}<br>    - nvm@1:<br>        inputs:<br>        - node_version: 20.11.1<br>    - restore-npm-cache@1: {}<br>    - npm@1:<br>        inputs:<br>        - command: install<br>    - script@1:<br>        inputs:<br>        - content: |-<br>            #!/bin/bash<br>            npx expo prebuild<br>    - change-workdir@1:<br>        inputs:<br>        - path: android<br>    - android-build@1:<br>        inputs:<br>        - module: app<br>        - variant: release<br>    - save-npm-cache@1: {}<br>    - deploy-to-bitrise-io@2: {}<br>    triggers:<br>      push: []<br>      pull_request: []<br>meta:<br>  bitrise.io:<br>    stack: osx-xcode-16.0.x<br>    machine_type_id: g2-m1.4core<br>app:<br>  envs:<br>  - PLATFORM: all<br>    opts:<br>      is_expand: false<br>trigger_map:<br>- push_branch: &quot;*&quot;<br>  commit_message:<br>    regex: Release v\d+\.\d+\.\d+<br>  type: push<br>  workflow: dev</pre><p>Once done, click “Save changes”.</p><p>Actually you could also create your workflows and triggers here if you are comfortable with the yaml configuration instead of using the low-code technique.</p><p>Then we shall see there is only “dev” workflow and everything work fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMu_H30iTKkIS59zXYGfMA.png" /><figcaption>Final Workflows</figcaption></figure><h4>Step 7: Trigger Bitrise workflow locally using API call</h4><p>Somehow your team want to trigger the workflow locally. We could do this as well by just API call to Bitrise.</p><p>Go to Settings &gt; Security and add a new token for manager role and admin permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nErf8qpISkCUuvNJZIDeaw.png" /><figcaption>Bitrise token</figcaption></figure><p>Copy the token and export it in your console.</p><pre>export BITRISE_TOKEN=???</pre><p>Get the App Slug from your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*dVZ1AyM4P4y-uVZqQeWHRA.png" /><figcaption>Bitrise App Slug</figcaption></figure><pre>export BITRISE_APP_SLUG=???</pre><p>Call the bitrise API.</p><pre> curl -X POST \<br>        -H &quot;Content-Type: application/json&quot; \<br>        -H &quot;Authorization: $BITRISE_TOKEN&quot; \<br>        -d &#39;{&quot;hook_info&quot;:{&quot;type&quot;:&quot;bitrise&quot;,&quot;api_token&quot;:&quot;$BITRISE_TOKEN&quot;},&quot;build_params&quot;:{&quot;workflow_id&quot;:&quot;dev&quot;}}&#39; \<br>        https://api.bitrise.io/v0.1/apps/$BITRISE_APP_SLUG/builds</pre><p>Yeah, we have trigger the Bitrise workflow successfully in local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*TxTe-4iQHDIziSCvMSh14w.png" /><figcaption>Local trigger Bitrise Workflow</figcaption></figure><h4>Step 8: Trigger Bitrise workflow from Gitlab pipeline using API call</h4><p>We could move the curl command from step 7 and integrated into our Gitlab pipeline.</p><p>Add the Bitrise Token and App Slug in the Gitlab settings, we can mask and hide them if we don’t want to expose it to other team members.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcS_PbjnjjMaFZ91mvdmBg.png" /><figcaption>Go to Gitlab Settings &gt; CICD &gt; Variables (BITRISE_TOKEN)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oV4bnQ8YCag1L8ONGgAwPA.png" /><figcaption>Go to Gitlab Settings &gt; CICD &gt; Variables (BITRISE_APP_SLUG)</figcaption></figure><p>Here is the pipeline config in .gitlab-ci.yaml.</p><pre>stages:<br>  - deploy<br><br>trigger_bitrise:<br>  stage: deploy<br>  script:<br>    - |<br>      curl -X POST \<br>        -H &quot;Content-Type: application/json&quot; \<br>        -H &quot;Authorization: $BITRISE_TOKEN&quot; \<br>        -d &#39;{&quot;hook_info&quot;:{&quot;type&quot;:&quot;bitrise&quot;,&quot;api_token&quot;:&quot;$BITRISE_TOKEN&quot;},&quot;build_params&quot;:{&quot;workflow_id&quot;:&quot;dev&quot;}}&#39; \<br>        https://api.bitrise.io/v0.1/apps/$BITRISE_APP_SLUG/builds</pre><p>Yeah, we have triggered Bitrise workflow successfully through Gitlab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zry2Aald4udEY5hYlBFPFQ.png" /><figcaption>Gitlab Pipeline Trigger Bitrise</figcaption></figure><p>That concludes the demo on using Bitrise workflows in our CI pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800e57510c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part V: Kubernetes Deployment with Minikube For A Full Stack Application (React + NodeJS + GraphQL)]]></title>
            <link>https://medium.com/@cheahwen1997/part-v-kubernetes-deployment-with-minikube-for-a-full-stack-application-react-nodejs-82406b325b50?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/82406b325b50</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 12:07:02 GMT</pubDate>
            <atom:updated>2025-03-13T07:52:54.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Previous deployment is using serverless with Netlify which is quite straightforward, this time I’ll try to do kubernetes deployment using kubectl in minikube cluster.</p><p><strong>Previous episodes:</strong></p><p><strong>Part I:</strong> <a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-i-2d16f32cfe47">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-i-2d16f32cfe47</a></p><p><strong>Part II: </strong><a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-ii-4854639ee4c7">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-ii-4854639ee4c7</a></p><p><strong>Part III:</strong> <a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-iii-4ed3ffc49479">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-iii-4ed3ffc49479</a></p><p><strong>Part IV: </strong><a href="https://medium.com/@cheahwen1997/implement-a-face-recognition-attendance-system-with-face-api-js-946a1615236d">https://medium.com/@cheahwen1997/implement-a-face-recognition-attendance-system-with-face-api-js-946a1615236d</a></p><p><strong>Frontend Stack: </strong>React, Ant Design</p><p><strong>Backend Stack: </strong>NodeJS, GraphQL, MongoDB</p><h3>Step 1: Installation</h3><p><strong>Docker:</strong> <a href="https://docs.docker.com/engine/install/">https://docs.docker.com/engine/install/</a></p><p><strong>kubectl: </strong><a href="https://kubernetes.io/docs/tasks/tools/">https://kubernetes.io/docs/tasks/tools/</a></p><p><strong>minikube:</strong> <a href="https://minikube.sigs.k8s.io/docs/start/">https://kubernetes.io/docs/tasks/tools/</a></p><h3>Step 2: Run Minikube</h3><p>To run Kubernetes locally, we can using Minikube (local cluster) to test the deployment before deployed to the Cloud Kubernetes (EKS, OKE, GKE, etc).</p><pre>minikube start<br>minikube dashboard # Access dashboard in browser <br><br># Check current context: minikube, config stored in ~/.kube/config or C:/Users/&lt;USER&gt;/.kube/config<br>kubectl config current-context<br><br># Switch to minikube if current context is not minikube, but no likely because `minikube start` already did so<br># kubectl config set-context minikube<br><br><br># Port forward all Kube Load Balancer services to host machine<br>minikube tunnel</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3e8svRLZZkuP5yeOQo9yrQ.png" /><figcaption>Minikube dashboard</figcaption></figure><h3>Step 3: Frontend Deployment</h3><p>Before we can run our app in Kubernetes, we first need to build a Docker image and push it to any docker registry (DockerHub, ECR, OCR, etc). Here I will use DockerHub.</p><h4>Create Docker Image + Push to DockerHub</h4><ul><li><strong>client/Dockerfile</strong></li></ul><pre>FROM node:16-alpine as build<br><br>RUN mkdir -p /home/node/app/node_modules &amp;&amp; chown -R node:node /home/node/app<br><br>WORKDIR /home/node/app<br><br>COPY --chown=node:node package*.json ./<br><br>USER node<br><br>RUN npm install --legacy-peer-deps<br><br>COPY --chown=node:node . .<br><br>EXPOSE 3000<br><br>ENV CI=true<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><ul><li>Run below command to build &amp; push to DockerHub</li></ul><pre>docker login -u &lt;DOCKERHUB USERNAME&gt;<br>docker build -t &lt;DOCKERHUB USERNAME&gt;/attendlytical-client .<br>docker push &lt;DOCKERHUB USERNAME&gt;/attendlytical-client</pre><h4>Create Kubernetes Config Files</h4><ul><li><strong>client/kube/namespace.yml</strong>: The project namespace</li></ul><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: attendlytical</pre><ul><li><strong>client/kube/config.yml</strong>: Store a list of env variables.</li></ul><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: client-config<br>  namespace: attendlytical<br>data:<br>  base-url: http://localhost:4000/graphql  # API Endpoint</pre><ul><li><strong>client/kube/attendlytical-client.yml</strong>: A deployment for the image pushed to DockerHub. From here, when the service listen port: 3000, it will forward the request to targetPort:3000, and the deployment matchLabel “client” will receive the request from containerPort:3000.</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: client-deployment<br>  namespace: attendlytical<br>  labels:<br>    app: client<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: client<br>  template:<br>    metadata:<br>      labels:<br>        app: client<br>    spec:<br>      containers:<br>      - name: client<br>        image: cheahwen/attendlytical-client:latest<br>        imagePullPolicy: Always # Change to Never if using local Docker image<br>        ports:<br>        - containerPort: 3000 #  Need to be same as target port in service<br>        env:<br>        - name: REACT_APP_BASE_URL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: client-config<br>              key: base-url<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: client-service<br>  namespace: attendlytical<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: client<br>  ports:<br>    - protocol: TCP<br>      port: 3000  # Service running port (minikube tunnel will proxy this port)<br>      targetPort: 3000 # Need to be same as container port in deployment</pre><ul><li>Run command below to apply the kubernetes resources.</li></ul><pre>kubectl apply -f kube/namespace.yml<br>kubectl apply -f kube/config.yml<br>kubectl apply -f kube/attendlytical-client.yml</pre><ul><li>Open your browser -&gt; <a href="http://localhost,/">http://localhost:3000,</a> should see the app running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*xYbaTl8FpulQbhLVGYn6Eg.png" /><figcaption>Frontend App Running</figcaption></figure><h3>Step 4: Backend Deployment</h3><p>Same with the frontend deployment, we first need to create a Docker image of our backend app and push it to DockerHub.</p><h4>Create Docker Image + Push to DockerHub</h4><ul><li><strong>server/Dockerfile</strong></li></ul><pre>FROM node:16-alpine<br><br>RUN mkdir -p /home/node/app/node_modules &amp;&amp; chown -R node:node /home/node/app<br><br>WORKDIR /home/node/app<br><br>COPY --chown=node:node package*.json ./<br><br>USER node<br><br>RUN npm install --legacy-peer-deps<br><br>COPY --chown=node:node . .<br><br>EXPOSE 4000<br><br>CMD [ &quot;node&quot;, &quot;index.js&quot; ]</pre><ul><li>Run below command to build &amp; push to DockerHub</li></ul><pre>docker login -u &lt;DOCKERHUB USERNAME&gt;<br>docker build -t &lt;DOCKERHUB USERNAME&gt;/attendlytical-server .<br>docker push &lt;DOCKERHUB USERNAME&gt;/attendlytical-server</pre><h4>Create Kubernetes Config Files</h4><p>We will deploy the database locally with PersistanceVolumeClaim (to retain the data if pod restarted), mapping the mongo service to our backend app.</p><ul><li><strong>server/kube/namespace.yml</strong>: The project namespace</li></ul><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: attendlytical</pre><ul><li><strong>server/kube/mongo-config.yml</strong>: Config Map for MongoDB</li></ul><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: mongo-config<br>  namespace: attendlytical<br>data:<br>  mongo-url: mongo-service<br>  mongo-db-name: Attendlytical</pre><ul><li><strong>server/kube/mongo-secret.yml</strong>: Secret For MongoDB (Note: Please provide base64 encoded values)</li></ul><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: mongo-secret<br>  namespace: attendlytical<br>type: Opaque<br>data:<br>  mongo-user: bW9uZ291c2Vy<br>  mongo-password: bW9uZ29wYXNzd29yZA==</pre><ul><li><strong>server/kube/mongo-pv.yml</strong>: Persistence Volume (PV) config to bound</li></ul><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: mongo-data-pv<br>  namespace: attendlytical<br>spec:<br>  accessModes:<br>  - ReadWriteOnce<br>  capacity:<br>    storage: 1000Mi<br>  hostPath:<br>    path: /data/standard/default/mongo-data-pv<br>    type: &quot;&quot;<br>  persistentVolumeReclaimPolicy: Retain<br>  storageClassName: standard<br>  volumeMode: Filesystem<br>  claimRef:<br>    namespace: attendlytical  # Bound to specified PVC<br>    name: mongo-data-pvc</pre><ul><li><strong>server/kube/mongo-pvc.yml</strong>: Persistence Volume Claim (PVC) config from PV</li></ul><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: mongo-data-pvc<br>  namespace: attendlytical<br>spec:<br>  storageClassName: standard<br>  accessModes:<br>  - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 1000Mi</pre><ul><li><strong>server/kube/mongo.yml</strong>: MongoDB deployment and service, here we specify the PVC and admin username password. Sometime may need to use different db port, can specify running port (e.g: 27018) in service.</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mongo-deployment<br>  namespace: attendlytical<br>  labels:<br>    app: mongo<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mongo<br>  template:<br>    metadata:<br>      labels:<br>        app: mongo<br>    spec:<br>      containers:<br>      - name: mongodb<br>        image: mongo:5.0<br>        ports:<br>        - containerPort: 27017<br>        volumeMounts:<br>        - mountPath: /data/db<br>          name: mongo-data<br>        env:<br>        - name: MONGO_INITDB_ROOT_USERNAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: mongo-secret<br>              key: mongo-user<br>        - name: MONGO_INITDB_ROOT_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: mongo-secret<br>              key: mongo-password<br>      volumes:<br>      - name: mongo-data<br>        persistentVolumeClaim:<br>          claimName: mongo-data-pvc<br>      restartPolicy: Always<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mongo-service<br>  namespace: attendlytical<br>spec:<br>  selector:<br>    app: mongo<br>  type: LoadBalancer  # Use ClusterIP if dont want to expose external<br>  ports:<br>    - protocol: TCP<br>      port: 27018  # Testing different port, will be using this port to access db<br>      targetPort: 27017</pre><ul><li><strong>server/kube/cloudinary-secret.yml</strong>: Cloudinary secret config (Note: Please provide base64 encoded values)</li></ul><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: cloudinary-secret<br>  namespace: attendlytical<br>type: Opaque<br>data:<br>  cloudinary-name: YXR0ZW5lZGxsdd5dGljYWw=<br>  cloudinary-api-key: NzMyODQ0OTfsac5OTMzMjQ4<br>  cloudinary-api-secret: cmlTQVF6sddbEMwUnJFNHNJQVdBcGlRbUxjdnBF</pre><ul><li><strong>server/kube/attendlytical-server.yml</strong>: A deployment for the image pushed to DockerHub. From here, when the service listen port: 4000, it will forward the request to targetPort:4000, and the deployment matchLabel “server” will receive the request from containerPort:4000. <strong>For MONGO_URI env variable, we need to combine DB username and password env variables in connection string, specify port to be 27018 as defined server/kube/mongo.yml</strong></li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: server-deployment<br>  namespace: attendlytical<br>  labels:<br>    app: server<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: server<br>  template:<br>    metadata:<br>      labels:<br>        app: server<br>    spec:<br>      containers:<br>      - name: server<br>        image: cheahwen/attendlytical-server:latest<br>        imagePullPolicy: Always # Change to Never if using local Docker image<br>        ports:<br>        - containerPort: 4000 #  Need to be same as target port in service<br>        env:<br>        - name: MONGO_USER_NAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: mongo-secret<br>              key: mongo-user<br>        - name: MONGO_USER_PWD<br>          valueFrom:<br>            secretKeyRef:<br>              name: mongo-secret<br>              key: mongo-password <br>        - name: MONGO_PORT<br>          valueFrom:<br>            configMapKeyRef:<br>              name: mongo-config<br>              key: mongo-port <br>        - name: MONGO_URL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: mongo-config<br>              key: mongo-url<br>        - name: MONGO_URI<br>          value: &quot;mongodb://$(MONGO_USER_NAME):$(MONGO_USER_PWD)@$(MONGO_URL).attendlytical.svc.cluster.local:$(MONGO_PORT)&quot; # Check mongo.yml to see db service running port 27018<br>        - name: SECRET_KEY<br>          value: sfssdfsdfsdfsdf<br>        - name: CLOUDINARY_NAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: cloudinary-secret<br>              key: cloudinary-name<br>        - name: CLOUDINARY_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: cloudinary-secret<br>              key: cloudinary-api-key<br>        - name: CLOUDINARY_API_SECRET<br>          valueFrom:<br>            secretKeyRef:<br>              name: cloudinary-secret<br>              key: cloudinary-api-secret<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: server-service<br>  namespace: attendlytical<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: server<br>  ports:<br>    - protocol: TCP<br>      port: 4000 # Service running port (minikube tunnel will proxy this port)<br>      targetPort: 4000 #  Need to be same as container port in deployment</pre><ul><li>Run command below to apply the kubernetes resources.</li></ul><pre>kubectl apply -f kube/namespace.yml <br>kubectl apply -f kube/mongo-config.yml<br>kubectl apply -f kube/mongo-secret.yml<br>kubectl apply -f kube/mongo-pv.yml<br>kubectl apply -f kube/mongo-pvc.yml<br>kubectl apply -f kube/mongo.yml<br>kubectl apply -f kube/mongo-express.yml<br>kubectl apply -f kube/cloudinary-secret.yml<br>kubectl apply -f kube/attendlytical-server.yml</pre><ul><li>Open your browser -&gt; <a href="http://localhost,/">http://localhost:4000/graphql,</a> should see the app running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmSWU8mqRkmrf6A9DldEHw.png" /><figcaption>Backend App Running</figcaption></figure><ul><li>Open your browser -&gt; <a href="http://localhost,/">http://localhost:8081,</a> should see the mongo express running. Enter “admin” for username, “pass” for mongo express.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yTUp76GnMhtkEoxD_Y1Qg.png" /><figcaption>Mongo Express Running</figcaption></figure><h4>Connect with MongoDB Compass</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jkjECwvj0MnnLv126YCuQ.png" /><figcaption>MongoDB Compass</figcaption></figure><h3>Step 5: Testing Persistency</h3><ul><li>Have some records in our database.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HEto70jaW6UDCL_LA77lw.png" /><figcaption>DB record</figcaption></figure><ul><li>Restart minikube, check if the data retain or not.</li></ul><pre>minikube stop<br>minikube start</pre><p>That’s all about the development with Kubernetes in Minikube cluster. The same config can also be applied to the other Kubernetes provider like (EKS, OKE, etc) with minor modification.</p><p>Buy me a coffee: <a href="https://buymeacoffee.com/cheahwen">https://buymeacoffee.com/cheahwen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82406b325b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SCP Deployment From Local Machine to Remote Windows Server]]></title>
            <link>https://medium.com/@cheahwen1997/scp-deployment-from-local-machine-to-remote-windows-server-0b996ccdd538?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b996ccdd538</guid>
            <category><![CDATA[windows-server]]></category>
            <category><![CDATA[ssh-to-windows-server]]></category>
            <category><![CDATA[cicd-automation]]></category>
            <category><![CDATA[scp-deployment]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 08:00:51 GMT</pubDate>
            <atom:updated>2024-01-28T07:18:07.688Z</atom:updated>
            <content:encoded><![CDATA[<p>When doing deployment to a Remote Windows Server, we usually build our project locally and move the output build folder to the specific remote path. However, if we adopted the source control (Git) with CICD pipeline to automate the task of copying and updating files upon detected changes in specific branch, it will be partial automate since moving the files are done manually through Sftp client like WinSCP. Hence, the action to moving the files to the server has to be converted to single line command. Secure copy protocol (SCP) is a network protocol to transfer files between hosts on the network via Secure Shell (SSH).</p><p>Let’s see the basic command. Below show example to move a folder to remote server.</p><pre>scp -r C:/app/MyProject/build TARGET_USER@TARGET_IP:~/build</pre><h3>Step 1: Startup OpenSSH Service in Windows Server</h3><ul><li>Make sure OpenSSH Service is started on Windows server. If the Status is disabled, go to Properties &gt; Log On &gt; Log on as &gt; Local System account. We will use the existing users available in the Remote Window Server for auth.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu-YOkY__YmtYVJbcrT50Q.png" /><figcaption>Open SSH Service</figcaption></figure><h3>Step 2: Generate SSH Key Pairs</h3><ul><li>At your host machine, run command below</li></ul><pre># Key Type: RSA<br># Number of bit for RSA Key: 2048 bit<br># Generated key pairs path: $HOME/ssh_keys/windows-server-rsa<br># Passphare: &quot;&quot;<br>ssh-keygen -t rsa -b 2048 -f $HOME/ssh_keys/windows-server-rsa  -q -N &quot;&quot;</pre><ul><li>Make sure private key to be not too open.</li></ul><pre>chmod 600 $HOME/ssh_keys/windows-server-rsa</pre><ul><li>Copy the value in the windows-server-rsa.pub and prepare to paste the value to the Windows Server in the next step.</li></ul><h3>Step 3: Paste the Public Key in .ssh/authorized_keys</h3><ul><li>Go to the target logon user folder in C drive of Window C:/Users/${REMOTE_LOGON_USER}, and navigate to .ssh folder and paste the public key to authorized_keys file.</li></ul><pre># Create .ssh folder if no exist<br>mkdir -p C:/Users/${REMOTE_LOGON_USER}/.ssh<br><br># Paste the ssh public key to the file<br>echo ssh-rsa AAAAB3NzaC1yc2EAAA... &gt;&gt; C:/Users/${REMOTE_LOGON_USER}/.ssh/authorized_keys</pre><h3>Step 4: Create SSH Config</h3><ul><li>In your local machine, go to the SSH Config file. And add a new Host config.</li></ul><pre># Mac/Linux<br>cd ~/.ssh <br>vi config<br><br># Windows<br>cd C:/Users/${YOUR_LOCAL_USER}/.ssh<br># Make sure have bash in Windows<br>bash -c &quot;vi config&quot;</pre><ul><li>Add your Windows Server Host</li></ul><pre>Host windows-server<br>  HostName xxx.xxx.xxx.xxx #Remote Server Public IP Address<br>  User REMOTE_LOGON_USER #Remote User <br>  IdentityFile $HOME/ssh_keys/windows-server-rsa #Path of the generated private key just now</pre><h3>Step 5: Testing SSH Connection</h3><pre># If command work, scp should also be fine<br>ssh windows-server<br><br># If dont want to use SSH config, provide full command<br>ssh -i PRIVATE_KEY_PATH USER@xxx.xxx.xxx.xxx</pre><h3>Step 6: SCP Deployment</h3><ul><li>In your remote Windows server, go to your project path. Make sure to give full permission of target folder to your logon user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*OkyiT3JRX2sn8_oEON1PHw.png" /><figcaption>Folder access right to full control</figcaption></figure><ul><li>If everything look good, try to run SCP command</li></ul><pre>scp -r ~/build windows-server:C:/MY_PROJECT_PATH/build</pre><ul><li>After success copy the files to the server, you might need to run some command in the Window server. SSH provide RemoteCommand option for running command after logon to the server.</li></ul><pre>ssh windows-server -oRemoteCommand=&quot;cd C:/MY_PROJECT_PATH &amp;&amp; git pull origin main &amp;&amp; cmd -l&quot;<br><br># add --login/-l to maintain the connection after the command. Remove it if no necessary</pre><ul><li>Combine together scp and ssh command above. If you are running NodeJS project, we can add “deploy” and “postdeploy” script to the package.json.</li></ul><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;deploy&quot;: scp -r ~/build windows-server:C:/MY_PROJECT_PATH/build &amp;&amp; ssh windows-server -oRemoteCommand=&quot;cd C:/MY_PROJECT_PATH &amp;&amp; git pull origin main&quot;<br>    &quot;postdeploy&quot;: pm2 restart my-project // will run after npm run deploy<br>  }<br>}</pre><p>That’s all for the deployment to Windows server via SCP.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b996ccdd538" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Deployment with Netlify Lambda (ReactJS FE + GraphQL BE)]]></title>
            <link>https://medium.com/@cheahwen1997/implement-a-face-recognition-attendance-system-with-face-api-js-946a1615236d?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/946a1615236d</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[netlify]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 03:20:56 GMT</pubDate>
            <atom:updated>2024-05-03T11:51:53.000Z</atom:updated>
            <content:encoded><![CDATA[<p>This is about the serverless deployment process using Netlify CLI and Lambda.</p><p><strong>Previous episodes:</strong></p><p><strong>Part I:</strong> <a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-i-2d16f32cfe47">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-i-2d16f32cfe47</a></p><p><strong>Part II: </strong><a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-ii-4854639ee4c7">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-ii-4854639ee4c7</a></p><p><strong>Part III:</strong> <a href="https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-iii-4ed3ffc49479">https://medium.com/analytics-vidhya/implement-a-face-recognition-attendance-system-with-face-api-js-part-iii-4ed3ffc49479</a></p><p>Netlify is a Paas for application development without the need to create and maintain the server ourselves. It is good for fast deployment and hobby projects that we could use for both Frontend and Backend deployment. For this project, the tech stack used are below.</p><p><strong>Frontend Stack: </strong>React, Ant Design</p><p><strong>Backend Stack: </strong>NodeJS, GraphQL, MongoDB</p><h3>Step 1: Prerequisite</h3><h4><strong>Download project:</strong></h4><ol><li>git clone <a href="https://github.com/CodeShareCW/Attendlytical.git">https://github.com/CodeShareCW/Attendlytical.git</a></li><li>cd Attendlytical &amp;&amp; git fetch origin main &amp;&amp; git checkout main</li></ol><h4>Node Version</h4><ol><li>Download and install nvm library: <a href="https://github.com/nvm-sh/nvm/releases/tag/v0.39.7">https://github.com/nvm-sh/nvm/releases/tag/v0.39.7</a></li><li>Run nvm install v16.20.2</li></ol><h4>Netlify CLI</h4><ol><li>Install netlify-cli: nvm use v16.20.2 &amp;&amp; npm i -g netlify-cli</li></ol><h3>Step 2: Frontend Deployment</h3><p>The deployment of frontend is very straight-forward. First we need to create the netlify.toml (Netlify config file).</p><p>In project directory, run cd client &amp;&amp; touch netlify.toml . Paste the following script in the file.</p><pre>[[redirects]]<br>  from = &quot;/*&quot;<br>  to = &quot;/index.html&quot;<br>  status = 200<br>  force = false<br><br>[build]<br>  command = &quot;npm run build&quot;<br>  publish = &quot;build&quot; # create-react-app builds to this folder, Netlify should serve all these files statically</pre><ul><li>[[redirect]] will tell Netlify to redirect all path to index.html, as the route configured with React Router (SPA).</li><li>[build] will tell be called when we run command netlify build</li></ul><p>Initialize netlify app, run command netlify init , login to your account and create an app name to deploy.</p><p>Then, there are 2 commands in package.json &gt; scripts</p><pre>    &quot;deploy:netlify:preview&quot;: &quot;netlify build &amp;&amp; netlify deploy&quot;,<br>    &quot;deploy:netlify&quot;: &quot;netlify build &amp;&amp; netlify deploy --prod&quot;</pre><p>Finally run the command npm run deploy:netlify:preview.Open the preview page printed in console. If everything good, run npm run deploy:netlify</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mYEb-Oza_ay0BLlmKCfeQ.png" /></figure><h3>Step 3: Backend Deployment</h3><p>In my previous backend deployment, I was using Heroku but unfortunately they had already remove the free tier plan and resources are not accessible, which cause the API failure in website: <a href="https://attendlytical.netlify.app/">https://attendlytical.netlify.app</a>. I tried to search around any other option instead of Heroku such as Railway, Vercel, etc. Then I found an interesting way to use same Paas (Netlify) for deployment. Netlify introduce functions which is the same as AWS serverless lambda: <a href="https://www.netlify.com/blog/intro-to-serverless-functions/">https://www.netlify.com/blog/intro-to-serverless-functions/</a>.</p><p>To build the code to serverless, install netlify-lambda with npm: npm i -D netlify-lambda . Our stack in backend using Graphql, hence there will only be 1 POST endpoint as 1 handler function. Then, I make a folder called lambdas . In the lambdas folder, created a file call graphql.js, following the code as in index.js, but apollo-server need to be replaced with apollo-server-lambda.</p><pre>require(&#39;dotenv&#39;).config();<br><br>const { ApolloServer } = require(&#39;apollo-server-lambda&#39;);<br>const typeDefs = require(&#39;../graphql/typeDefs&#39;);<br>const resolvers = require(&#39;../graphql/resolvers&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br><br>let conn = null<br>const getHandler = async (event, context) =&gt; {<br>    context.callbackWaitsForEmptyEventLoop = false<br><br>    if (!conn) {<br>        conn = await mongoose<br>            .connect(process.env.MONGO_URI, {<br>                useNewUrlParser: true,<br>                useUnifiedTopology: true,<br>                useCreateIndex: true,<br>                useFindAndModify: false<br>            });<br><br>        console.log(&quot;Mongodb connected!&quot;)<br>    }<br><br>    const server = new ApolloServer({<br>        typeDefs,<br>        resolvers,<br>        debug: true,<br>        context: () =&gt; ({ ...context, req: event }),<br>    });<br>    const graphqlHandler = server.createHandler({<br>        expressGetMiddlewareOptions: {<br>            cors: {<br>                origin: &#39;*&#39;,<br>                methods: [&quot;POST&quot;],<br>                allowedHeaders: &quot;*&quot;,<br>                credentials: true<br>            }<br>        }<br>    });<br>    if (!event.requestContext) {<br>        event.requestContext = context;<br>    }<br>    return graphqlHandler(event, context);<br>}<br><br>exports.handler = getHandler;</pre><p>Then in package.json , there are command start , build with will use netlify-lambda to generate serverless functions.</p><p>Create netlify.toml and paste the following in the file.</p><pre>[[redirects]]<br>  from = &quot;/*&quot;<br>  to = &quot;/.netlify/functions/graphql&quot;<br>  status = 200<br>  force = true<br>  <br>[functions]<br>  node_bundler = &quot;esbuild&quot; # To resolve encoding MODULE_NOT_FOUND error<br><br>[build]<br>  command = &quot;npm run build&quot;<br>  functions = &quot;build&quot; # netlify-lambda build artifacts<br>  publish = &quot;build&quot; # netlify deploy folder</pre><ul><li>[[redirect]] we specified the redirect rule to point from any path to the graphql endpoint</li><li>[functions] Just to resolve some package error during build</li><li>[build] Runnetlify buildwill run npm run build , which will trigger netlify-lambda build lambdas</li></ul><h4>Running Locally</h4><p>Run npm start , then open <a href="http://localhost:9000/graphql">http://localhost:9000/graphql</a>. You will see the screen as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IidMjOYdC2q2OOw5ynUdOg.png" /><figcaption>Sample Screen</figcaption></figure><h4>Testing API with Frontend</h4><p>Go to client/src/ApolloProvider.js , replace the endpoint to <a href="http://localhost:9000/graphql">http://localhost:9000/graphql</a> for local server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9vSIzNMWKjdXdy6pK9H9A.png" /><figcaption>Endpoint change</figcaption></figure><h4>Environment Variables</h4><p>Go to <a href="https://app.netlify.com/sites/%7B%7BYOUR_PROJECT%7D%7D/configuration/env">https://app.netlify.com/sites/{{YOUR_PROJECT}}/configuration/env</a>, and set the respective compulsory environment variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDBbolp3lF8Vp0qtEsgk2A.png" /></figure><ul><li><strong>MONGO_URI</strong>: MongoDB Connection String</li><li><strong>CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET, CLOUDINARY_NAME</strong>: Cloudinary Config</li><li><strong>SECRET_KEY</strong>: any random string for JWT Sign Key</li></ul><h4>Build and Deployment with Netlify Lambda</h4><p>Initialize netlify project, run command netlify init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EL_KREPo4tMeJj10TaOwCA.png" /></figure><p>Then, there are 2 commands in package.json &gt; scripts</p><pre>    &quot;deploy:preview&quot;: &quot;netlify build &amp;&amp; netlify deploy&quot;,<br>    &quot;deploy&quot;: &quot;netlify build &amp;&amp; netlify deploy --prod&quot;</pre><p>Finally run the command npm run deploy:preview.Open the preview page printed in console. There is a zip file generated after netlify build , it will be deployed during netlify deploy .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*cedHU7V_CUpAlniRb1AMIA.png" /></figure><p>If everything good, run npm run deploy</p><h3>Step 4: Testing</h3><p>Go to your deployed site: <a href="https://attendlytical.netlify.app/">https://attendlytical.netlify.app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yD6595GF5zRuk38XgnthyQ.png" /><figcaption>Attendance History</figcaption></figure><p>That’s all about the development with Netlify in serverless way.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946a1615236d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Simple App with AWS Lambda and Paypal Integration]]></title>
            <link>https://aws.plainenglish.io/building-simple-app-with-aws-lambda-and-paypal-integration-c98197216d96?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98197216d96</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-pricing-calculator]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[paypal]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 12:26:38 GMT</pubDate>
            <atom:updated>2024-01-26T07:55:08.968Z</atom:updated>
            <content:encoded><![CDATA[<p>In legacy systems, normally we build the app and rented racks of instances purchased from the cloud provider/on-premises. As the application grows, most resources such as RAM, storage, CPU are needed to offload the workload, resulting a higher cost per hour. Although the instance is in idle state whereby no request/processing happen in a period of time, we are still be charged for what resources we are using. Nowadays, more organizations would prefer to go for serverless such as Lambda to reduce operational overhead and cost saving. In serverless, the job of allocating resources will be managed by the cloud provider, hence reduce human intervention on configuration and enjoy zero downtime.</p><h3>Cost Comparison (EC2 vs Lambda)</h3><p>Suppose we are using EC2 of type t3.medium (2vCPUs and 4GiB RAM), we need to pay 37.96USD per month on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVMksfjQo8MoXsTC18CvoQ.png" /><figcaption>AWS Cost Estimator (EC2)</figcaption></figure><p>On the other hand, if using lambda (4 GiB RAM equivalent to around 3vCPUs), it is 0.48USD if number of calls near 100k per month with 1 second response time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLghATq6RZdWKl_y2X2tPw.png" /></figure><p>In lambda, we configure the RAM of functions which represent certain number of vCPUs. The default RAM is 128MB, you can increase the RAM to reduce the response processing time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*EfDEcM21LP4fw6BYoBPneg.png" /><figcaption>Lambda Memory corresponded vCPUs</figcaption></figure><p>As from the above, whether or not one should use lambda is based on your application workload. If your application is always idle and below 100k request per month, it is worthy to use lambda. But please note that lambda should not be used for long running job such as image processing as such because the timeout is 15 minutes at max (30 seconds for API gateway proxy). Also, the longer response time would result higher billed duration.</p><p>Before start building lambda functions, let’s look at the limitation of lambda.</p><h3>Lambda Limitations</h3><ol><li>Execution concurrency is 1000 <strong>at account level </strong>(Request AWS Support if need more than 1000). This means that no more than 1000 lambda execution in your AWS account running concurrently. If such case happen, throttling will occur that the incoming requests are on hold until some of the existing requests are completed.</li><li>Memory allocation is 128MB to 10GB per function. It is recommended to keep at 128MB since lambda will autoscale horizontally, meaning the requests are load balanced to more instances.</li><li>Deployment package size is 50MB for zipped and 250MB unzipped including lambda layer size.</li><li>Lambda layers is 5 at max per function. Lambda layer is a piece of dependency to your function which is excluded during deployment.</li><li>Environment variables is 4KB at max.</li><li>Payload size 6MB (req &amp; res) for one off and 20MB for streamed in synchronous. 256KB for asynchronous.</li></ol><p>Above are the common limitations should be borne in mind. For more limitations, please visit <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html">https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html</a></p><h3><strong>Lambda Function</strong></h3><p>A lambda is a small function as an API endpoint. The lambda call the handler (a piece of logic to solve the query), just like NodeJS Express app.</p><pre>// In express app<br>const appRouter = async (req, res, next) =&gt; res.status(200).json({message: &quot;ok&quot;})<br><br>// In serverless app, always return string for body<br>const handler = async (event, context) =&gt; ({statusCode: 200, body: JSON.stringify({ message: &quot;ok&quot; })})<br><br>// In express app return html<br>const appRouter = async (req, res, next) =&gt; {<br>    res.set(&#39;Content-Type&#39;, &#39;text/html&#39;)<br>    res.send(&quot;&lt;h1&gt;Hello world&lt;/h1&gt;&quot;)<br>}<br><br>// In serverless app return html<br>const handler = async (event, context) =&gt; ({<br>    statusCode: 200,<br>    body: &quot;&lt;h1&gt;Hello World&lt;/h1&gt;&quot;,<br>    headers: {<br>        &#39;Content-Type&#39;: &#39;text/html&#39;,<br>    }<br>})</pre><p>Please always return string for lambda response body as shown above (using JSON.stringify).</p><h3><strong>Lambda Context</strong></h3><ol><li>A context is basically the object provides methods and properties that provide information about the invocation, function, and execution environment.</li><li>For a singleton like DB class, you will export a global static object and pass around in the project. We can just pass it to the context using <a href="https://www.npmjs.com/package/@middy/core">Middy</a> library then destructure the context to get the DB object.</li><li><a href="https://www.npmjs.com/package/@middy/core">Middy</a> is a handy tools because it has before ,after, onError function allowing us to reformat request and response without writing too many duplicated code with similar format.</li></ol><h3>API Gateway</h3><p>After building the lambda functions, they can be proxy integrated with API Gateway. API Gateway provides some features which can be used to enhance the performance and security such as Usage Plan with API Key to control traffic, environment stage, caching behaviour and rate limiting.</p><h3>Section A: Application Design &amp; Configuration</h3><p>Let’s get started. We are going to build a simple Exam Purchase App with AWS Lambda and Paypal integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yYckN9zkPul8bwS3Z7rwgg.gif" /><figcaption>Application Demo</figcaption></figure><p>The app is pretty simple, user just select their desired exam and checkout with Paypal.</p><h4>Step 1: Download &amp; Installation</h4><ol><li>Download the source code</li></ol><pre>git clone https://gitlab.com/medium3171129/paypal-app-lambda.git</pre><p>2. Install AWSCLI v2 if havent done.</p><pre># Linux command<br><br>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>unzip awscliv2.zip<br>sudo ./aws/install</pre><p>3. Install NVM &amp; Serverless if havent done.</p><pre>nvm install 18<br>nvm use 18<br>npm i -g serverless</pre><p>4. Install node_modules</p><pre>cd client &amp;&amp; npm i &amp;&amp; cd ../server &amp;&amp; npm i</pre><p>5. Run client and server locally</p><pre>cd client &amp;&amp; npm start &amp;&amp; cd ../server &amp;&amp; npm run dev</pre><h4>Step 2: Understand Architectural Flow</h4><p>Below show the basic architectural flow of the application. In order to call the API, client need to pass x-api-key: 0deb71fb-da6b-4b6a-9b2c-e471ad48b4f8configured at our serverless backend in the request headers.</p><p>At first, client will call GET /paypal/clientid,load the paypal script with the clientId and render the Paypal button. Catalogs are retrieved GET /catalogs and displayed on the left. When users selected the items and click the Paypal button, an createOrder event will be called, passing the selected item ids to via AWS API Gateway associated with respective Lambda function: paypal-intent.handler. The Lambda handler will filter the catalogs by the selected ids, then pass the payload of the calculated total amount and item breakdown to the Paypal API to create a payment intent. Once done, an orderId will be created by Paypal and sent back to the client.</p><p>After the payment completed, a webhook CHECKOUT.ORDER.APPROVED from Paypal will callback to POST /paypal-order-approved-webhook , payload pushed to AWS SQS: paypal-order-approved-webhook-sqs to be processed by a lambda handler to update our internal DB payment status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsbAI9qBhut3FvOOYpKidA.png" /><figcaption>Architectual Flow</figcaption></figure><h4>Step 3: Setup Paypal</h4><p>Let’s go to <a href="https://developer.paypal.com/">https://developer.paypal.com/</a> and create an App call Exam App Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6iUShyE5Eevz-mK1dq55Q.png" /><figcaption>Create App in Paypal</figcaption></figure><p>Copy the client id and client secret, then paste it in server/env.dev.yml and server/env.sit.yml (If you prefer different Paypalaccount for each environment (dev/sit/uat), create respective Paypal app, then pass the credentials accordingly)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*Y4EqWqIBW3MxjHWyzkrrSA.png" /><figcaption>Client Id and Secret in Paypal App</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H63tYZl76aIVzwydnCcJdQ.png" /><figcaption>server/env.sit.yml</figcaption></figure><p>Next, you will need to add the webhook for order approved. This need to be done after you have done Lambda deployment. To do this, scroll to the end and you will see “Sandbox Webhooks”, click “Add Webhook” button. Paste the SQS endpoint: <a href="https://1pi78jq69c.execute-api.us-west-1.amazonaws.com/sit/paypal-order-approved-webhook">https://1pi78jq69c.execute-api.us-west-1.amazonaws.com/sit/paypal-order-approved-webhook</a> (Everyone will be different hostname, please change accordingly).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjgr-7-k_86Nj4jJ_9rLTQ.png" /><figcaption>Paypal Webhooks Setup</figcaption></figure><h4>Step 4: Understand common variables in Serverless YAML configuration</h4><p>Let’s open server/serverless.ymlfile, it might take some time to understand but the more you see it will be familiar.</p><ol><li>self: Similar to “this”</li></ol><pre>provider:<br>  stage: ${self:myCustomVariables.myStage}<br>  region: ${self:myCustomVariables.myRegion}<br>myCustomVariables:<br>  myStage: dev<br>  myRegion: &quot;ap-southeast-1&quot;<br><br># Equivalent to <br>provider:<br>  stage: dev<br>  region: &quot;ap-southeast-1&quot;<br>myCustomVariables:<br>  myStage: dev<br>  myRegion: &quot;ap-southeast-1&quot;</pre><p>2. file : Refer file content, much like “fs.readFile”</p><pre># In src/module1/serverless-module1.yml<br>func1:<br>  handler: src/module1/lambdas/func1.handler # path of func1 handler script<br>  event:<br>    ...</pre><pre># In serverless.yml<br>functions:<br>  func1: ${file(src/module1/serverless-module1.yml):func1}<br><br># Equivalent to below<br>functions:<br>  func1: <br>    handler: src/module1/lambdas/func1.handler # path of func1 handler script<br>      event:<br>        ...</pre><p>3. env : Environment variables</p><pre>provider:<br>  environment:<br>    DOMAIN_NAME: google.com</pre><pre>// we can access the environment in our code<br>function getEnv(key){<br>    return process.env[key]<br>}<br><br>getEnv(&quot;DOMAIN_NAME&quot;)  // we will get &quot;google.com&quot;</pre><p>4. opt:{{ARGS}} : Named arguments pass after command. Can have default value by appending for second argument.</p><pre># Example in serverless.yml<br>provider:<br>  stage: ${opt:stage, &#39;dev&#39;}</pre><pre>sls offline --stage AnyStageZZZ<br>## will translate as below in serverless.yml<br># provider:<br>#  stage: AnyStageZZZ<br><br>sls offline<br>## will translate as below in serverless.yml<br># provider:<br>#  stage: dev</pre><p>5. sls: Serverless core variables</p><pre># Running: sls offline --stage myStage<br><br>provider:<br>  environment:<br>    STAGE: ${sls:stage}  # myStage<br><br># Equivalent to<br>provider:<br>  environment:<br>    STAGE: ${opt:stage, self:provider.stage, &quot;dev&quot;}   # myStage</pre><p>6. param : Parameter in AWS Console lambda/yaml file.</p><pre>provider:<br>  environment:<br>    STAGE: ${params:stage}  # test<br><br>params:<br>  stage: test</pre><pre># Running: sls offline --param &quot;stage=test&quot;<br>provider:<br>  environment:<br>    STAGE: ${params:stage}  # test</pre><p>7. ssm : AWS Parameter Store variables.</p><pre>iamRoleStatements:<br>  - Effect: Allow<br>    Action:<br>      - ssm:GetParameters<br>      - ssm:GetParameter<br>    Resource: &quot;arn:aws:ssm:*:*:parameter/${opt:stage, self:provider.stage}/*&quot;<br>  - Effect: Allow<br>    Action:<br>      - ssm:DescribeParameters<br>    Resource: &quot;*&quot;<br>provider:<br>    environment:    <br>        PASS: ${ssm:/path/to/service/PASS}</pre><p>Sometimes, it is hard to see all the configuration mixed with variables. You can run sls print to show full details with values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*I99d3Fo4VRDy-Ji46GoRuA.png" /><figcaption>sls print</figcaption></figure><h4>Step 5: Understand Serverless Plugins</h4><p>In some cases, there are lack of functionality or complex setup by serverless library, we need to use some plugins to simplify and achieve certain result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*o25PtlFTL_nCEHQzKguAcQ.png" /><figcaption>Serverless Plugins</figcaption></figure><p>For example, serverless-plugin-apigateway-service-proxy allow us to make SQS/SNS/etc to be endpoint proxied with API Gateway, then the plugin will look for custom.apiGatewaServiceProxy to associate the endpoints. In this case, we do not have to manually create API and map to AWS services by ourselves, everything is done by the plugin in serverless.ymland configured properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*sj3v6d8TqG-B_oR_5Jdu-Q.png" /><figcaption>custom.apiGatewaServiceProxy</figcaption></figure><p>serverless-offline allow us to run our lambda function locally with sls offline command.</p><h4>Step 6: API Gateway API Key</h4><p>There is some cases you want to limit the API usage to control the traffic/rate limiting/quota or do not want to allow our API Gateway without providing a key.</p><p>In this project, a plugin call serverless-add-api-key is used and specified in custom.apiKeys . This is much convenient because it will automatically detect and associate api key to different stages (dev/sit/uat).</p><h4>Step 7: Setup Custom Domain with Route53</h4><p>In case you want to map API Gateway endpoint to Route53, you can use a plugin call serverless-domain-manager . Or alternatively, you can map it manually in AWS console. But it will be better to put every configuration in serverless.yml because it use Cloud Formation, thus in case we want to remove the lambda, we do not need to check 1 by 1 what have been done and manually delete accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNKulfrpc9yMb1jrUWiwWg.png" /><figcaption>custom.customDomain</figcaption></figure><h3>Section B: Code Customization</h3><h4>Client</h4><p>React and Ant Design are used to create the application.</p><ul><li><strong>Paypal: </strong>paypaljs is a library to be used, it have have several function but the important one are createOrder and onApprove. Make sure always capture the order in onApproveevent after user completed the payment, otherwise the payment is considered incomplete.</li></ul><pre>  useEffect(() =&gt; {<br>    if (!paypalClientId) return;<br>    (async () =&gt; {<br>      const paypal = await loadPaypal({<br>        clientId: paypalClientId,<br>        disableFunding: &quot;credit,card&quot;,<br>        currency: &quot;USD&quot;,<br>      });<br><br>      await paypal<br>        .Buttons({<br>          style: {<br>            disableMaxWidth: true,<br>          },<br><br>          onClick: function (data) {<br>            console.log(data);<br>            if (items.length &lt;= 0) {<br>              message.error(`You haven&#39;t selected an item`);<br>              // dont proceed createOrder when no selected an item<br>              return false;<br>            }<br>            return true;<br>          },<br>          createOrder: async function () {<br>            const intentOrderId = await fetch(<br>              `${process.env.REACT_APP_API_HOST}/paypal/intent`,<br>              {<br>                method: &quot;POST&quot;,<br>                body: JSON.stringify({<br>                  ids: items.map((i) =&gt; i.id),<br>                }),<br>                headers: {<br>                  &quot;x-api-key&quot;: process.env.REACT_APP_API_KEY,<br>                },<br>              }<br>            )<br>              .then((res) =&gt; {<br>                if (res.ok) {<br>                  return res.json();<br>                }<br>                throw res;<br>              })<br>              .then((jsonData) =&gt; jsonData.data.orderId)<br>              .catch(() =&gt; {});<br><br>            if (intentOrderId) {<br>              return intentOrderId;<br>            }<br>          },<br>          onApprove: async function (data, actions) {<br>            if (actions?.order)<br>              // Capture the funds from the transaction<br>              await actions.order.capture();<br>          },<br>          onError: function (error) {<br>            message.error(error.message);<br>          },<br>          onCancel: () =&gt; {<br>            message.warning(`Order Cancelled`);<br>          },<br>        })<br><br>        .render(paypalDivRef.current);<br>    })();<br>    return () =&gt; {<br>      if (paypalDivRef.current) {<br>        paypalDivRef.current.innerHTML = &quot;&quot;;<br>      }<br>    };<br>  }, [paypalClientId, items]);</pre><ul><li><strong>API Host: </strong>Go to client/.env and change REACT_APP_API_HOST to be your endpoint or localhost</li><li><strong>API Key:</strong> Go to client/.env and change REACT_APP_API_KEY to be your server API Key specified in server/env.{{STAGE}}.yml</li></ul><h4>Server</h4><p>All handler functions are in the server/src/functions</p><ul><li><strong>API Key: </strong>It is up to you on whatever API key you want, just remember to modify the value in client/.env after you change the API key in env.{{STAGE}}.yml file</li><li><strong>Response format: </strong>Navigate to server/middlewares/injectResponseHandler.ts , the format will be consistent for all API. Then for each handler script, you will just need to pass the core payload, to be wrapped into data field in aftermiddy function. Any error will go to middy onError function.</li></ul><pre>// sample<br>{<br>  statusCode: 200,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>    &#39;Access-Control-Allow-Headers&#39;: &#39;*&#39;,<br>    &#39;Access-Control-Allow-Methods&#39;: &#39;OPTIONS,DELETE,GET,HEAD,PATCH,POST,PUT&#39;,<br>  },<br>  body: JSON.stringify({<br>    success: true,<br>    data: handler.response || &#39;empty response&#39;,<br>    meta: null,<br>  }),<br>}</pre><ul><li><strong>Cors</strong>: If you observe carefully, there are 2 places we need to configure CORS. One at server/serverless.yml and another in server/middlewares/injectResponseHandler.ts. The first one is allowing cors from API Gateway. After the API Gateway passed, the request will be forwarded to the Lambda function and responded with the allow origin &amp; headers. So, CORS need to enabled on both side to work properly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*XUX5A6LScVwuUKM94-8ntA.png" /><figcaption>CORS (API Gateway)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*942a6cz8_pfLuDU5_cL7uw.png" /><figcaption>CORS (Lambda)</figcaption></figure><ul><li><strong>AWS Profiles for Deployments: </strong>Most of the case, organization use different AWS account for staging and production. You can configure different AWS account in ~/users/.aws/credentials and modify custom.profiles.{{STAGE}} in server/serverless.yml .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*42J1nC3YV5ifOjPi320QhA.png" /><figcaption>AWS Profile Setup for different stages</figcaption></figure><h3>Section C: Deployment</h3><h4>Client</h4><p>We can deploy in AWS S3 with Cloudfront. Please refer this article: <a href="https://medium.com/@cheahwen1997/continuous-deployment-of-react-app-in-aws-cloudfront-with-gitlab-pipeline-1fb4cfd73722">https://medium.com/@cheahwen1997/continuous-deployment-of-react-app-in-aws-cloudfront-with-gitlab-pipeline-1fb4cfd73722</a></p><h4>Server</h4><p>Run command below will deploy to API gateway in SIT environment.</p><pre>cd server &amp;&amp; npm run deploy:sit</pre><p>In case you want to remove, run the command below without manually delete all the associated resources in AWS console.</p><pre>cd server &amp;&amp; npm run remove:sit</pre><h3>Section D: Cloudwatch Monitoring</h3><p>AWS Lambda will use Cloudwatch to log the application. In case something go wrong, you can go to your AWS Cloudwatch and track the error to debug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cl28YXCpHkiwkQYEkHY8DQ.png" /><figcaption>AWS Cloudwatch</figcaption></figure><p>Just simple console.log or you can use <a href="https://www.npmjs.com/package/@aws-lambda-powertools/logger">@aws-lambda-powertools/logger</a> with log level, basically just inject Logger during the middy before function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*uenk4CfKP-gpacDDXyDbGg.png" /><figcaption>Inject Logger in Middy before function</figcaption></figure><p>That’s all for the demo of how to build simple app with AWS Lambda. Thank you for reading.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98197216d96" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/building-simple-app-with-aws-lambda-and-paypal-integration-c98197216d96">Building Simple App with AWS Lambda and Paypal Integration</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Deployment of React App in AWS Cloudfront with Gitlab Pipeline]]></title>
            <link>https://aws.plainenglish.io/continuous-deployment-of-react-app-in-aws-cloudfront-with-gitlab-pipeline-1fb4cfd73722?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb4cfd73722</guid>
            <category><![CDATA[gitlab-pipeline]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gitlab-runner]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 04:35:50 GMT</pubDate>
            <atom:updated>2024-01-26T07:53:20.185Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AWS Cloudfront </strong>is a content delivery network (CDN) operated by Amazon Web Services. If your customer live in different regions and they experience a very a high latency of your website deployed in AWS S3, that’s due to AWS S3 is a regional service whereby the data are retrieved from a single region which causes uncertain latency from each region. To solve the regional issue, you will need to place your website to different region using a CDN. AWS Cloudfront will help to deploy your application to different location so-called <strong>edge location</strong>, hence it find the nearest origin to retrieve data based on your customer location. Whenever the data is fetched at the first time, the content are cached in edge location for faster retrieval by next customer. Due to this, we will need to <strong>invalidate Cloudfront</strong> whenever we have update our content.</p><p><strong>Continuous Deployment (CD)</strong> is a strategy in software development whereby the code will be automatically deployed to production environment when detected changes happens in certain branch (master).</p><p>Let’s get started.</p><h3>Create AWS S3 Bucket</h3><ol><li>Go to S3: <a href="https://s3.console.aws.amazon.com/s3/home?region=us-east-1#">https://s3.console.aws.amazon.com/s3/home?region=us-east-1#</a></li><li>Then create a new bucket called: aws-cloudfront-react-antd. We will set ACLs enabled so that other account can use the bucket.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJLcMF9JWEwRxTMh9ss33w.png" /></figure><p>3. Then create a new bucket called: aws-cloudfront-react-antd. We will set <strong>ACLs enabled </strong>so that other account can use the bucket.</p><p>4. Make the bucket public accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0ZaFizXcBj2p_g_wNDxfA.png" /></figure><p>5. Leave the rest of the setting and click “Create bucket”</p><p>6.<em> (Optional since already have cloudfront)</em> Select the bucket you created, click “Properties” tab, we need to enable “Static website hosting”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-9dUjrjTc-kB3Rs5lIEhQ.png" /></figure><p>7.<strong> </strong><em>(Optional since already have cloudfront) </em><strong>[IMPORTANT!] Make sure to enter “index.html” in both index document and error document.</strong> Otherwise, you will hit “Access Denied” error, usually breaking React Router if error document no point back to entry page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*CO3Yb_rqpfYPc1JBIxMe_w.png" /></figure><h3>Create AWS Cloudfront Distribution</h3><ol><li>Go to cloudfront: <a href="https://us-east-1.console.aws.amazon.com/cloudfront/v4/home?region=us-east-1#/distributions">https://us-east-1.console.aws.amazon.com/cloudfront/v4/home?region=us-east-1#/distributions</a></li><li>In Origin domain, select the bucket you created just now.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCD27qyE9UGIFH9GaoNpLw.png" /></figure><p>3. At default cache behavior, select “Redirect HTTP to HTTPS” in viewer protocol policy and “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE” in Allowed HTTP methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*h0E37QnWI7rXUUI-NWLzhg.png" /></figure><p>4. Leave the rest as default, then create distributions.</p><p>5. Then you will see a domain url is created for you which will be used to access the cloudfront. Alternatively, you can make it as CName mapped to route53 if you have a custom domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMClMuVn8o5x9FFdEy1Wjw.png" /></figure><p>6. <strong>[IMPORTANT!] </strong>We need to create custom error response. This is the same when we add index.html in error document in S3 static website setting. We need to point 403 error back to 200</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbJae1EVQMxvwlMRWGUxUQ.png" /></figure><p>7. <strong>[IMPORTANT!] </strong>We need to point 403 error page to /index.html with response 200 since we already have our internal error page built inside React app to handle that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Y4unWgGbKmwAdkOpDabDDw.png" /></figure><h3>Setup Gitlab Pipeline</h3><ol><li>Download the repository here: <a href="https://gitlab.com/medium3171129/aws-cloudfront-react-antd">https://gitlab.com/medium3171129/aws-cloudfront-react-antd</a></li><li>Go to Build &gt; Pipelines editor, then configure the pipelines</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*gfPdbXca9AUjijdF_S0pIQ.png" /></figure><p>3. Just click “Commit Changes” first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k33mX9TGbnKl5SRw3a9MCA.png" /></figure><p>4. Then go to Settings &gt; CICD&gt; Variables, we add to provide AWS Credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7E-On2pkbxvGS-y5UFuCg.png" /></figure><p>5. There are 5 variables which are:</p><ul><li>AWS_ACCESS_KEY_ID: {{YOUR IAM ACCESS ID}}</li><li>AWS_DEFAULT_REGION: {{AWS REGION}}</li><li>AWS_SECRET_ACCESS_KEY: {{YOUR IAM ACCESS SECRET}}</li><li>CLOUDFRONT_DIST_ID: {{YOUR CLOUDFRONT DIST ID}}</li><li>S3_BUCKET: aws-cloudfront-react-antd</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnrhK_k_kVqtEGHeeQ6uZg.png" /></figure><p>5. Go back to Build &gt; Pipelines editor, modify the job script as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KIGMFGA2OJmpPxAXzsVRQ.png" /></figure><ul><li>We have 2 job: build &amp; deploy.</li><li>During the build, installation of npm packages will be executed first, then npm run build. We need the keep the artifact in artifacts fields so that the “build” folder can be referenced by the next stage.</li><li>During deploy stage, we will specify awscli image “banst/awscli” to use the aws command line. In the scripts, we do S3 upload &amp; revalidate and cloudfront invalidation. <strong>(Notes: Quote are important!)</strong></li><li>Both of the jobs will be triggered when detected changes in main branch.</li></ul><h3>Test Cloudfront and Gitlab Pipeline</h3><p>Let open the Cloudfront Url: <a href="https://d2kb3eivzneuy7.cloudfront.net/">https://d2kb3eivzneuy7.cloudfront.net/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKaJTRClTHA7KCG1hA2xHQ.png" /></figure><p>Let’s edit and push our code to main branch. I will modify the “Muse Dashboard” to “AWS Cloudfront”.</p><p>Lets go back to Gitlab &gt; Build &gt; Jobs. We could see the job is triggered automatically.</p><p>Let’s wait for gitlab pipeline finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGnUxR0JCJdYQHvG7ck1oA.png" /></figure><p>Let’s wait for cloudfront invalidation finish. If still cannot see the changes it cloudfront, perhap you are missing quote in the command. Check this: <a href="https://stackoverflow.com/questions/62172836/aws-cloudfront-invalidation-not-working-as-expected">https://stackoverflow.com/questions/62172836/aws-cloudfront-invalidation-not-working-as-expected</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTi2uSrZhmYcI1Su0bHo7Q.png" /></figure><p>Check again the our Cloudfront url: <a href="https://d2kb3eivzneuy7.cloudfront.net/">https://d2kb3eivzneuy7.cloudfront.net/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGx_pxlxpiUyMiHZW9eWIQ.png" /></figure><p>Yeah, it works.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb4cfd73722" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/continuous-deployment-of-react-app-in-aws-cloudfront-with-gitlab-pipeline-1fb4cfd73722">Continuous Deployment of React App in AWS Cloudfront with Gitlab Pipeline</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing search selection with lazy loading in ReactJS MUI]]></title>
            <link>https://medium.com/@cheahwen1997/debouncing-search-selection-with-lazy-loading-in-reactjs-mui-c725d4e3e1bc?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c725d4e3e1bc</guid>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[lodash]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mui]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 08:29:09 GMT</pubDate>
            <atom:updated>2024-01-26T07:57:56.239Z</atom:updated>
            <content:encoded><![CDATA[<p>When typing to search something in Google, you will notice that we are sending too much query API to the backend and some of the APIs are aborted eventually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_nEQ_IiGptva8l-hoxRYg.png" /></figure><p>In general, the user do not interested in the result until they finish typing their context, thus this will waste lots of traffic and load to the server if we just send the request without waiting the user to finish their typing.</p><p>Hence, to avoid too many request sent to our server, we need something call “debounce” to reduce the API trigger. We will pass the event every time new changes are detected to the debounce function. There is a timer control in debounce which will basically check when the typing is stop/ongoing in order to trigger the action.</p><p>To demonstrate, I will use React with MUI with the Autocomplete (Select dropdown) with lazy loading feature and lodash debounce function to control the API trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*_Xs-4RHXA7LukMxCrzpe2Q.gif" /></figure><h3><strong>Step 1: Download Repo</strong></h3><p>Please clone the repo here: <a href="https://gitlab.com/medium3171129/react-mui-debounce-search">https://gitlab.com/medium3171129/react-mui-debounce-search</a></p><p>The api used: <a href="https://dummyjson.com/users">https://dummyjson.com/users</a></p><h3>Step 2: Debounce Overview</h3><p>We will use the lodash provided debounce function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*BWW1XJC9vyqqSdpysiquQw.png" /></figure><p>We will just pass the debounce function in the onChange event. Then we will update the searchQuery if user stop typing (interval to determine stop typing is 1 second) and fetch the API every time searchQuery changed.</p><p><a href="https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/App.js#L114-125">https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/App.js#L114-125</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*QJBIhEg9zpIewDz_FBkqrw.png" /><figcaption>onChange pass in debounce function</figcaption></figure><p><a href="https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/App.js#L34-46">https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/App.js#L34-46</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*0teuUWSL-aimFrWl2M8G_w.png" /><figcaption>Fetch API when seachQuery changed</figcaption></figure><h3>Step 3: Lazy Loading</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*CS1AG0Qa7iO5B2SB4K8wNw.png" /></figure><p>The logic of lazy loading is that we will instead of fetching all the record once time, we will just fetch the record by specifying a limit. This is to reduce the API throughtput and timeout chance which will impact both our FE and BE. Imagine fetch 100,000 records from database, how easily it will crash your database and make the UI slow and lagging. You don’t want to waste your money on these unwanted outbound traffic to cloud services!</p><p>Below the code snippet will check if the last item in the list shown in the viewport, it will trigger fetch more function. We will pass in a ref to the last item in the list and detect using <strong>IntersectionObserver.</strong></p><p><a href="https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/components/DebouncedAutocomplete.js#L50-58">https://gitlab.com/medium3171129/react-mui-debounce-search/-/blob/8511b8f4e771c16bbf6955a4fbdb269eb40f629c/src/components/DebouncedAutocomplete.js#L50-58</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Cl6tCNF2M_dse8HtQ5DbWg.png" /><figcaption>Detect last item in the list scroll into viewport</figcaption></figure><p>That’s all for the demo. Hope this give you some idea on how to make your search function properly and reduce the API workload efficiently.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c725d4e3e1bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decouple background task (Gmail) with API call with Redis Bull Queue]]></title>
            <link>https://medium.com/@cheahwen1997/decouple-background-task-gmail-with-api-call-with-redis-bull-queue-a338d946bda1?source=rss-62025a437ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a338d946bda1</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[bull-queues]]></category>
            <category><![CDATA[api-throttling]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[-]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 04:13:36 GMT</pubDate>
            <atom:updated>2024-01-26T07:58:27.906Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometime it is difficult to just make the API and process it directly and return the response in millisecond latency. Imagine if you have thousand of API call at the same time, each response time from API take about 1 minute to finish. Your server will become very busy and there might be throttle issue or timeout to concurrently process all the requests.</p><p>Hence, we need to decouple the API with the processing task in a separated environment (worker) whereby the API will act as a task receiver and worker will pull the task from the API to process the task. <a href="https://github.com/OptimalBits/bull">Redis bull queue</a> is a queue service like AWS SQS, ActiveMq, MQTT. In this demo, we will implement a NodeJS app with Typescript integrated with Redis bull queue, there will be 2 environment created which are API and worker running separately.</p><h4>Step 1: Enable Gmail API (Skip if know)</h4><ol><li>Go to GCP, create a new project: bull-queue-gmail-demo</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*bbWk3XBJcXDyjTznWzK0Tg.png" /><figcaption>GCP Project</figcaption></figure><p>2. Then at the side menu, select <strong>APIs and services &gt; Enable APIs and services</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*idMg7xhxf0cEf4_WNyxCdQ.png" /><figcaption>Enable APIs and services</figcaption></figure><p>3. Then press “Enable APIs and Services”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vnyf_uaLq6Ts73SFtsNUoQ.png" /></figure><p>4. Search “gmail api”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvZF8d1l1-ZZ-24HslhG4A.png" /></figure><p>5. Enable gmail API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZJHtZkS3iAwS2xaGIg2tw.png" /></figure><h4>Step 2: Create Oauth Credentials (Skip if know)</h4><ol><li>Go to <strong>APIs and services &gt; Credentials</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*9FAVqb1Xe6e1pkOJP4T2RQ.png" /></figure><p>2. Create <strong>OAuth client ID</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdckvCm_zHsH0nluA63PPA.png" /><figcaption>Oauth Client ID</figcaption></figure><p>3. Click “Configure Consent Screen”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9o8RoCvGSlU7dkPWihLJA.png" /></figure><p>4. Click “External”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFiJf6Z9aS3FqToPvRfVlw.png" /></figure><p>5. Enter app registration: “Bull Queue Demo”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s2ZMzLg7U5ZTfimY8jdZw.png" /></figure><p>6. Click “Publish App”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH9JQfQ-VhM1BiNhKYeB2g.png" /></figure><p>7. Go back to Credential Tab. Create OAuth client ID for application type “Desktop app”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrOc-od3IX-kFP4SfbLP4w.png" /></figure><p>8. Create name: “Gmail”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vC1WduxsGlRkYdCkN1AjMw.png" /></figure><p>9. Then click “Download JSON”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OMXlYMxEJoXWsetDaWEMQ.png" /></figure><p>10. Rename the downloaded file as “oauthMailKey.json”.</p><h4>Step 2: Download Git Repo</h4><ol><li>Go to my gitlab repo: <a href="https://gitlab.com/medium3171129/bull-queue">https://gitlab.com/medium3171129/bull-queue</a></li><li>Create a folder “.gcp” and place “oauthMailKey.json” inside the folder.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*1Dz1pdGc_5xBlg05N3yczQ.png" /></figure><p>3. <em>npm run genOauthToken</em>: generating the refreshToken based on the client id and client secret, then a file named “oauthMailToken.json” will be generated in .gcp folder.</p><p>4. The permission screen will be popped out and just click “Advanced” then “Go to Bull Queue (unsafe)”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8jjb1VtUenV4NUiPlD8dQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_m_hbAuoBvABmC0oXGa3A.png" /></figure><p>5. Read the installation and setup in README.md</p><p>6. To make the code more versatile, we will pass in “x-channel-id” in the request headers to identify.</p><p>7. See the sample api call in “examples/testApi.ts”.</p><p>8. Run the test case, npm run api: test. You should be getting a JobId.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*Zred8Sam37rSbAISv28NIg.png" /><figcaption>Redis Bull Queue JobId</figcaption></figure><p>9. Check the Redis Commander, you will see whether the job is processed, failed, attempts made</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*CrFNp2QZttFQwznWLsKuBQ.png" /><figcaption>Redis Commander</figcaption></figure><p>10. Please check your email</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkJdvZ7Vryg1s8iWzESY4w.png" /><figcaption>Email</figcaption></figure><h4>Step 3: Architecture Overview</h4><ol><li>Client will send the request payload via the api endpoint. [POST]: <a href="http://localhost:8080/api/mail">http://localhost:8080/api/mail</a></li><li>Server received the request, will push the payload in the queue.</li><li>The worker detected the item in the queue, will process it in FIFO pattern. Exponentially retry until attempt made to 3 if the queue item is failed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*xWluQ12R3mrXatMkIDKdGQ.png" /><figcaption>Queue configuration</figcaption></figure><p>4. Below is the basic overview of the decoupled architecture design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*itKnMoiPJgKi5nFAuKrUYw.png" /></figure><p>That’s a basic of how we do decouple job to avoid API bottleneck, remember to follow me and stay tuned.</p><h3>Support &amp; Appreciation</h3><p>Big thanks for being awesome and diving into my blog posts! If you’ve enjoyed the content and want to see more, consider supporting the blog financially. Your contributions help keep the virtual ink flowing and ensure more quality posts in the future. Every bit counts, and I appreciate your support in making this blogging journey even more exciting!</p><p>Support me here: <a href="https://www.buymeacoffee.com/cheahwen">https://www.buymeacoffee.com/cheahwen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a338d946bda1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>