<?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 DinhNT on Medium]]></title>
        <description><![CDATA[Stories by DinhNT on Medium]]></description>
        <link>https://medium.com/@dinh.nt?source=rss-25b2d1e0c2ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UqQevBlZpntkpfr61eNLxA.jpeg</url>
            <title>Stories by DinhNT on Medium</title>
            <link>https://medium.com/@dinh.nt?source=rss-25b2d1e0c2ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:43:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinh.nt/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[Designing an Auction System for the iPhone 17]]></title>
            <link>https://medium.com/@dinh.nt/designing-an-auction-system-for-the-iphone-17-a4fc09b1bbc2?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fc09b1bbc2</guid>
            <category><![CDATA[bidding-platform]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 11:13:08 GMT</pubDate>
            <atom:updated>2025-09-12T23:37:31.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>System Design: Auction System for the iPhone 17</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rFT5J2qSQVuOZYH9ucB-w.png" /></figure><p>What would happen if the iPhone 17 just launched, and Apple decided to auction off the first one?</p><p>In the final 30 seconds, 100,000 people simultaneously spam the “Place Bid” button with prices jumping from $1,000 to $10,000. How would the system handle it when the database has to update the current price thousands of times per second? Who would win when 1000 people bid $9,999 in the same millisecond?</p><p>This is exactly the situation that auction platforms like eBay face on a daily basis. And this is also the problem I want to discuss in this article. We’ll go from the most basic designs of an auction system to scaling the system and handling this hot iPhone scenario.</p><h3>Introduction to the Problem</h3><h3>Requirements</h3><ul><li>Buyers can bid on products, and after the auction ends, the winner can purchase the product.</li><li>Handle multiple people bidding on the same product simultaneously.</li><li>When popular items are being auctioned, the system should respond within an acceptable time frame.</li></ul><h3>Overview of Auction Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YMDy9efLn99SKQYZ.png" /></figure><p>A basic auction flow will include several steps:</p><ul><li>After the seller posts a product and sets the auction start and end times, anyone can join the auction for that product</li><li>Each time a buyer places a bid, the system will check the current price, and if the bid is higher, it will replace the old bid.</li><li>This process continues until the auction ends.</li><li>At this point, the system determines the winner and sends them a notification to make payment.</li></ul><p>From here, we have a simple design as follows:</p><h3>Initial Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jp6t4B3Icn3LM2mz.png" /></figure><p>1. API: Of course, to handle requests from users like creating products, browsing, and placing bids</p><ul><li>Additionally, the API will take on the task of updating the current price for users and notifying when someone else bids higher than them. We can use websocket or simpler server-sent events to implement this feature.</li></ul><p>2. Database: Store information about products and orders.</p><ul><li>So which type of database should we choose? Our system must handle concurrent bidding, so ACID properties are essential for maintaining data consistency =&gt; Relational databases (like PostgreSQL, MySQL, etc.) would be suitable.</li><li>We can start with simple modeling using 2 tables: one table to store products and one table to store bidding history. Although the problem requirements don’t need to store history, to ensure transparency and prevent fraud, this data is essential in a bidding platform.</li></ul><p>3. A cronjob to handle auction endings. Since we’ve stored the auction end time, the cronjob just needs to query using this field to satisfy the requirement.</p><ul><li>SELECT … FROM AuctionProduct WHERE endBid &lt; NOW() AND status = &quot;in-auction&quot;</li><li>However, when the system scales, the number of auction products increases more and more, this approach is not yet optimized.</li></ul><p>While this basic design works for small-scale auctions, it faces significant challenges when we scale up to handle thousands of concurrent users.</p><h3>How to handle multiple people bidding on the same product simultaneously?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GaxdCH3vTMepdB0S.png" /></figure><p>Each time a user places a bid, the system will check step by step:</p><ul><li>Is the bidding time valid?</li><li>Is the bid price higher than the current price?</li></ul><p>When multiple people bid simultaneously, race conditions will inevitably occur. How can we solve this? I think we can start with using DB transaction combined with lock. The idea is that for one product, at one time, only one session can update currentPrice and add to history.</p><pre>BEGIN;<br>-- 1. Lock the auction product row<br>SELECT currentPrice, startBid, endBid<br>    FROM AuctionProduct<br>WHERE id = :auctionProductId<br>    FOR UPDATE;<br>IF (NOW() &lt; startBid OR NOW() &gt; endBid) THEN<br>    ROLLBACK;<br>END IF;<br>IF (:bidPrice &lt;= currentPrice) THEN<br>    ROLLBACK;<br>END IF;<br>INSERT INTO Bids SET userId=...,price=...,time=...<br>UPDATE AuctionProduct<br>    SET currentPrice = :bidPrice<br>WHERE id = :auctionProductId;<br>COMMIT;</pre><p>When multiple people bid simultaneously, this design approach performs poorly:</p><ul><li>If they’re bidding on the same product, the locking mechanism will cause transactions to wait for extended periods (due to having to process 2 DML commands in the transaction as well), risking hanging the entire application (due to Pool Exhaustion).</li><li>Even if users aren’t bidding on the same product, having too many transactions with 2 DML commands at one time will also exhaust database resources.</li></ul><p>Next, let’s handle the remaining issues in this design. There are several difficult problems to solve.</p><h3>Handling Scaling Issues</h3><p>Let’s examine the main bottlenecks in our initial design and explore solutions.</p><h4>1. Optimizing Auction End Processing Flow</h4><p>Instead of having to query continuously, is there a more optimized approach?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wl3tLTd4oKTRB8zT.png" /></figure><p>Every time we query, we’re checking all current auctions, so instead of checking everything, is there a way for auctions that have ended to automatically send back to the system? Like using a message queue, but messages will be sent back to the system after a certain time period?</p><p>Fortunately, such queues do exist. You can refer to <a href="https://github.com/rabbitmq/rabbitmq-delayed-message-exchange"><strong>RabbitMQ Delayed Message Plugin</strong></a> as a typical example. We can set up messages to appear in the queue only after a certain time period, and then the system processes them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6wipSSAY_NxBrBWe.png" /></figure><p>What if the seller changes the auction end time? We can delete the current message and create a new one.</p><p>This approach not only separates the two logic flows but also helps us easily change when there are new requirements, such as some platforms allowing auctions without end time, only closing after the last person bids for about 1–2 hours. Using <strong>Delay message queue</strong> is an optimized approach in this case.</p><h4>2. Optimizing When Multiple Users Bid Simultaneously</h4><p>The simple immediate approach is that we have more servers processing user requests, add cache to the system, and add a separate Push Service to handle real-time updates for the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CFzSUC6SQY9gD_tz.png" /></figure><p>Cache will help optimize the system in many aspects:</p><ul><li>Cache product information =&gt; browsing products is also faster</li><li>Cache current product price: at this point, if users bid lower than the current price, we’ll reject that request before executing a transaction to the database.</li></ul><p>However, this solution doesn’t yet handle the case where the number of users bidding suddenly increases (popular items).</p><p>The advantage of the current approach is that users will receive feedback after they place a bid. So what if we consider another direction: asynchronous processing?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hxrSpQEzFDDiieTi.png" /></figure><p>After processing at the API layer (comparing with current price in cache, eliminating if lower), instead of processing the user’s request immediately, we push that command into a queue and process it later. Next, the system will immediately respond to the user that their command has been received.</p><p>We’ll add a bunch of workers to process these commands sequentially. At this point, the system will avoid congestion from having to receive a sudden high volume of bids and will process them gradually afterward. With proper setup, I believe the system can completely handle 5–10 bids/second (400k-800k per day).</p><p>So what if on a given day, there’s a product that’s too popular, leading to 100k bids?</p><p>At this point, our system still processes slowly, 10 times/second. That means after the session ends, it takes 3 hours for us to get the winner result. Everyone participating in that auction session has to wait for server feedback, bidders are eager to purchase but don’t know if their bid price is good enough.</p><h4>3. Optimizing When There Are Popular Items</h4><p>When processing asynchronously, we already have a very large set of commands stored in the queue, so is there a way to use batching to optimize the write flow to DB? Instead of one transaction only writing 1 bid, we’ll write 1000 bids?</p><pre>BEGIN;<br>-- Start: Product 1<br>SELECT currentPrice, startBid, endBid<br>    FROM AuctionProduct<br>WHERE id = :auctionProductId<br>    FOR UPDATE;<br>IF (NOW() &lt; startBid OR NOW() &gt; endBid) THEN<br>    ROLLBACK;<br>END IF;<br>IF (:bidPrice &lt;= currentPrice) THEN<br>    ROLLBACK;<br>END IF;<br>INSERT INTO Bids SET userId=...,price=...,time=...<br>UPDATE AuctionProduct<br>    SET currentPrice = :bidPrice<br>WHERE id = :auctionProductId;<br>-- End: Product 1<br>-- Start: Product 2<br>...<br>-- End: Product 2<br>-- Start: Product 3<br>...<br>-- End: Product 3<br>COMMIT;</pre><p>The weakness of this approach is that if any product fails, the entire transaction fails.</p><p>Note that when there’s a popular item, most events in the queue will contain bidding commands for it =&gt; we’ll focus on optimizing events for one product.</p><p>So what if we check the timing of events, calculate the highest price at the API, then simultaneously write them to the database?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IQTYG5DQN_TCeqrw.png" /></figure><p>This approach optimizes the previous method, but the events are still being routed randomly to workers =&gt; multiple workers processing batching for one product =&gt; leading to transactions waiting due to locks.</p><p>To make batching more effective plus limit locks, we can set up so that one product is always routed to only one worker (can be achieved through setting up subscription/partition for the queue). At this point, the flow for processing commands will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaORyU1FI0WxuR1F.png" /></figure><p>So the transaction really has the ability to process multiple events (of one product) and is least likely to wait due to locks, performance has been optimized much more. Assuming a product really has 100k bids, then each second only needs to process 1 transaction batching 1000 events, which reduces calculation time to just 2 minutes.</p><h3>Is there really a way to eliminate locks?</h3><p>If at one point in time, for a specific product, only one thread handles updating its price, then race conditions can be avoided.</p><p>To achieve this, first we need to make sure that one product is always routed to only one worker as above. And need to make sure that the worker won’t process two threads for one product simultaneously.</p><p>This approach optimizes bidding a bit more, but requires careful attention and thorough testing. Even better, we can use <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">Optimistic Locking</a> technique (combined with retry) here, since the chance of conflicts has dropped very low (you can research more in this direction).</p><p>In summary, we have a final design as follows:</p><h3>Design When Scaling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ox2ne-6zouQHH64C.png" /></figure><p>And the flow for the bidding feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RRmO4w0e14TmfGPB.png" /></figure><p>Although there are many more ideas to expand and optimize for this system, the article is already long so I’ll list them briefly here:</p><ul><li><a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">Handle locks at the caching layer</a> to store the highest bid in Redis directly, so the system can easily respond accurately to which bids are invalid, update that product’s price in real-time, especially when there are popular items like above, immediate response will create a very good experience. However, we need to consider handling HA for Redis, and make sure that the highest price in Redis and Database don’t get out of sync.</li><li>Additionally, partition techniques to optimize write performance for the database are also a direction to optimize performance.</li></ul><h3>Summary</h3><p>Okay, so you’ve gone through this entire article about this system with me. I believe that a real auction system would have more complex requirements, more complex models, and the approaches in my article might no longer be suitable. But I believe these analyses will provide insights into how to build a system from the starting point to when scaling.</p><p>See you in the next articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fc09b1bbc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Single-Threaded with Nodejs Event Loop]]></title>
            <link>https://medium.com/@dinh.nt/beyond-single-threaded-with-nodejs-event-loop-8aec62f72655?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aec62f72655</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 14:10:53 GMT</pubDate>
            <atom:updated>2025-04-05T14:10:53.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Many developers are familiar with statements like “<strong>Node.js is single-threaded</strong>” and “<strong>it handles concurrent tasks through the event loop.</strong>” However, the detailed workings of the event loop and why <strong>Node </strong>only needs a single thread to execute <strong>JavaScript </strong>might not be widely understood. Even after studying this topic, I think many dev still struggle to explain it clearly during interviews.</p><p>That’s why I’ve researched this topic in depth to provide you with the most detailed explanation possible. Through this article, I’ll help you:</p><h3>Understanding the Event Loop Mechanism</h3><p>The Event Loop is the heart of<strong> Node.js</strong>. In reality, Node.js isn’t simply “single-threaded” as many believe. Although your JavaScript code runs on a main thread, behind the scenes, Node.js uses multiple threads to handle I/O tasks and timers.</p><p>We’ll dive deep into the Event Loop architecture, its different phases such as timers, pending callbacks, idle &amp; prepare, poll, check, and close callbacks. You’ll understand why Node.js can handle thousands of concurrent connections without creating a new thread for each connection like traditional models.</p><h3>The Role of libuv, Thread Pool, and epoll API</h3><p>Behind Node.js’s “magic” is the libuv library — a cross-platform library focused on asynchronous I/O. Libuv provides Node.js with a thread pool to handle time-consuming tasks like file reading/writing, DNS lookups, etc. Libuv also leverages the epoll API (on Linux) — a highly efficient I/O multiplexing mechanism that allows a process to monitor multiple file descriptors simultaneously.</p><h3>Let’s explore the initial phase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YxEyhOiLNCqLjjMy" /></figure><h3>Initial Phase</h3><p>This is the first phase, occurring before the event loop initialization. This phase runs exactly once.</p><p>Node executes the entire source code sequentially from top to bottom. All callbacks from I/O or timers are registered in their respective phases and won’t run immediately.</p><p>If you load modules using require(), they will be loaded synchronously in this phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*4SIjcU7UP2zzjIzW" /></figure><p>Next, the Event loop is initialized, and the main thread’s journey officially begins. The Event loop consists of 6 main phases that repeat continuously until it can stop.</p><h3>1. First Phase: Timer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rD1t7I3e37AAkVwV" /></figure><p>As its name suggests, the timer phase executes timer callbacks (<strong>setTimeout </strong>and <strong>setInterval</strong>).</p><p>Node manages timer callbacks in a separate thread. First, it arranges all timers based on the duration value, then uses a sleep-and-wake mechanism when the duration expires, marks the timer as ready, goes back to sleep, and continues this process until all timers are processed.</p><p>Meanwhile, in the main thread, each time the event loop reaches the timer phase, it checks if any timers are marked as ready. If so, it executes their callbacks. Otherwise, it moves to the next phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C10SFwy55CixeJlM" /></figure><h3>2. Pending callback:</h3><p>This phase is used to execute some low-priority callbacks from the previous loop, especially handling errors such as:</p><ul><li>TCP error callbacks</li><li>UDP error callbacks</li><li>Other error callbacks from the system</li></ul><p>Example of pending callbacks:</p><ul><li>Network operation executed in the poll phase</li><li>It fails → schedule callback for pending callback phase</li><li>When running to the next loop, the pending callback phase takes the error and processes its callback (retry, for instance).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*01mRvf7rREOsIL5a" /></figure><h3>3. Idle — Prepare Phase</h3><p>This phase allows Node to perform some of its background work and prepare for the next very important phase — the Poll phase.</p><p>This phase can be overridden with C++ Extensions. Indeed, we can write C++ extensions for Node.</p><h3>4. Poll Phase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-m_0aicoX3Stjuxb" /></figure><p><strong>The Poll phase processes callbacks for I/O operations and is a crucial phase of the event loop.</strong></p><p>The two main tasks of the poll phase include:</p><p>Polling for I/O operations:</p><ul><li>Listening for socket connections</li><li>Receiving new connections</li><li>Reading/writing files</li></ul><p>Executing callbacks when data is ready from I/O operations, for example:</p><ul><li>Successfully reading a file</li><li>Successfully connecting to a server</li><li>Successfully receiving data from a connection</li><li>(And many other tasks)</li></ul><p>Another task of the poll phase is handling dynamic imports. Imports need to read files from the system, which Node treats as I/O operations.</p><h3>Node.js I/O Operations Handling Mechanism</h3><ul><li><strong>Handling file operations</strong></li></ul><p>Under the hood, Node uses libuv to handle these operations. Libuv has a separate thread to process files, preventing the main thread from being blocked.</p><p>When this thread finishes processing a file, the callback is queued, and the main thread executes it in the poll phase.</p><p>In another case, if we create a stream to read a file, when libuv finishes processing a chunk, it queues the callback along with the chunk, which will also be executed in the poll phase.</p><ul><li><strong>Handling network operations</strong></li></ul><p>Reading and writing to network connections are essentially blocking operations. If we process them sequentially, one connection at a time, it would cause significant blocking.</p><p>This is where epoll (Linux), kqueue (macOS), and iocp (Windows) are leveraged by Node to handle asynchronous operations.</p><p>With epoll on Linux, Node registers connections through epoll_wait. If a connection has data ready, the Linux kernel notifies Node, which then executes that connection’s callback immediately.</p><p>Interestingly, epoll_wait supports timeouts. For example, we can set up that if after waiting 1 second no connection has data, Node will move to the next phase.</p><p>In reality, Node will block at the poll phase waiting for data from connections. However, it handles this as follows:</p><ul><li>If there’s a timer scheduled to execute in the timer phase, Node will wait for epoll_wait for a specific amount of time, then move to the next phase.</li><li>If there are no timers, Node will block at this phase until a connection has data, receives a new connection, etc.</li></ul><h3>Summary of poll phase operation:</h3><ul><li>It’s the phase where most tasks are executed</li><li>Executes I/O operations and callbacks</li><li>It calculates how long to wait before moving to the next phase</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MN9GFbrX6eMINHSp" /></figure><h3>5. Check Phase</h3><p>This phase always executes after the poll phase and provides a call for developers to register callbacks (setImmediate).</p><p>If you have an operation in the poll phase that’s too large and you want to break it down, you can schedule it to the check phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*buFguq-hZaEgmQQW" /></figure><h3>6. Final Phase: Close Callback</h3><p>This phase is used to execute callbacks when an I/O is closed. The main purpose is to clean up resources.</p><p>A separate phase is needed for this activity because closing connections also takes time. For example, TCP requires multiple close connection requests (FIN, FIN-ACK, FIN, ACK), which are executed in the poll phase. However, their callbacks when successfully closed are executed in the Close Callback phase.</p><p>The second reason is that close events have low priority, making them perfectly suitable for execution at the end of the event loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dbuZqCUOjARwzncu" /></figure><h3>Summary</h3><p>I hope that through this article, you now have a deeper understanding of how Node.js handles I/O operations, timers, and runs multiple tasks concurrently.</p><p>I believe there are other concepts in Node.js that you might be curious about too, such as promises, async/await, or garbage collection. I’ll address these in another article, along with their positions in the event loop.</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aec62f72655" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Terraform — Deploy a secure application: container apps, postgreSQL, and Redis]]></title>
            <link>https://medium.com/@dinh.nt/azure-terraform-deploy-a-secure-application-container-apps-postgresql-and-redis-4a5fc6cb7877?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5fc6cb7877</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[azure-networking]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 14:58:00 GMT</pubDate>
            <atom:updated>2024-12-29T08:50:58.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Terraform — Deploy a secure application: container apps, postgreSQL, and Redis</h3><p>Recently I took a task to deploy a full-fledged application securely on a virtual network in Azure cloud. I have to use IAC to reduce maintenance time later on.</p><p>This is not a easy task for me, since my knowledge of <strong>virtual network was limited</strong>. But luckily, I managed to get it done in a week, which is <strong>quite fast for what I had estimated.</strong></p><p>I will share with you everything I did in this post.</p><h3>Application Architecture</h3><p>The application will be securely contained within a virtual network and only allow traffic from internet to the container app. By that way, we minimize attack surface and secure all internal resources, while allow them to communicate over private connections</p><p>The application consists of the following components:</p><ul><li><strong>Azure Container App</strong>: Connects to other services and serves as the entry point for internet traffic.</li><li><strong>Azure Redis Cache</strong>: Accessed via a private endpoint.</li><li><strong>Azure PostgreSQL Flexible Server</strong>: Secured within a dedicated subnet.</li></ul><p>Each service resides in its own subnet, connected through a private DNS zone for seamless internal communication.</p><p>Our redis cache will be connected through a private endpoint, why ? Actually we can setup redis to sit within a virtual network directly, but that requires Redis Premium Tier which has a minimum size of 6GB and cost ~ $400/m, or more — which is very expensive for a small to medium application.</p><p>So we should go with Basic or Standard tier, and the only way to isolate it inside virtual network is through a private endpoint.</p><p>All services will be connected using a url, managed by the private DNS zone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SthGxpGboILYXtikOcaPwg.png" /><figcaption>Application Architecture in virtual network</figcaption></figure><h3>Prerequisite</h3><ul><li>Basic Terraform and IAC knowledge</li><li>Azure subscription, an available resource group and Azure cli</li><li>Terraform local setup</li></ul><h3>Setting Up Virtual Network</h3><p>Everything is bounded by a virtual network so we will start with that</p><pre>data &quot;azurerm_resource_group&quot; &quot;app_rg&quot; {<br>  name = var.resource_group_name<br>}<br>resource &quot;azurerm_virtual_network&quot; &quot;app_vnet&quot; {<br>  name                = &quot;app-virtual-network&quot;<br>  location            = data.azurerm_resource_group.app_rg.location<br>  resource_group_name = data.azurerm_resource_group.app_rg.name<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br>  tags                = local.common_tags<br>}hcl</pre><h3>Deploying PostgreSQL in a Virtual Network</h3><p>In order to have PostgreSQL in a virtual network, we need the subnet dedicated for postgreSQL DB resources, a private DNS zone for routing and the DB itself. Notice that this is the DB server, we need to define which database we want to create in the server, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJIMiQlsLg4GPxv7C7x0bQ.png" /><figcaption>Database</figcaption></figure><pre>resource &quot;azurerm_subnet&quot; &quot;postgresql_subnet&quot; {<br>  name                 = &quot;postgresql-subnet&quot;<br>  resource_group_name  = data.azurerm_resource_group.app_rg.name<br>  virtual_network_name = azurerm_virtual_network.app_vnet.name<br>  address_prefixes     = [&quot;10.0.2.0/24&quot;]<br>  service_endpoints    = [&quot;Microsoft.Storage&quot;]<br>  delegation {<br>    name = &quot;fs&quot;<br>    service_delegation {<br>      name = &quot;Microsoft.DBforPostgreSQL/flexibleServers&quot;<br>      actions = [<br>        &quot;Microsoft.Network/virtualNetworks/subnets/join/action&quot;,<br>      ]<br>    }<br>  }<br>}<br><br>resource &quot;azurerm_private_dns_zone&quot; &quot;postgres_zone&quot; {<br>  name                = &quot;private.postgres.database.azure.com&quot;<br>  resource_group_name = data.azurerm_resource_group.app_rg.name<br>}<br>resource &quot;azurerm_private_dns_zone_virtual_network_link&quot; &quot;postgres_vn_link&quot; {<br>  name                  = &quot;postgresVnetZone.com&quot;<br>  private_dns_zone_name = azurerm_private_dns_zone.postgres_zone.name<br>  virtual_network_id    = azurerm_virtual_network.app_vnet.id<br>  resource_group_name   = data.azurerm_resource_group.app_rg.name<br>}<br>resource &quot;azurerm_postgresql_flexible_server&quot; &quot;postgres_server&quot; {<br>  name                          = &quot;app-db-posgresql&quot;<br>  resource_group_name           = data.azurerm_resource_group.app_rg.name<br>  location                      = data.azurerm_resource_group.app_rg.location<br>  version                       = &quot;16&quot;<br>  delegated_subnet_id           = azurerm_subnet.postgresql_subnet.id<br>  private_dns_zone_id           = azurerm_private_dns_zone.postgres_zone.id<br>  public_network_access_enabled = false<br>  administrator_login           = var.db_admin_username<br>  administrator_password        = var.db_admin_password<br>  zone                          = &quot;1&quot;<br>  storage_mb   = var.app_config.postgresql.storage_mb<br>  storage_tier = var.app_config.postgresql.storage_tier<br>  sku_name     = var.app_config.postgresql.sku_name<br>  lifecycle {<br>    prevent_destroy = true<br>  }<br>}<br>// we will create main-database in the server<br>resource &quot;azurerm_postgresql_flexible_server_database&quot; &quot;main_database&quot; {<br>  name      = &quot;main-database&quot;<br>  server_id = azurerm_postgresql_flexible_server.postgres_server.id<br>  collation = &quot;en_US.utf8&quot;<br>  charset   = &quot;utf8&quot;<br>  lifecycle {<br>    prevent_destroy = true<br>  }<br>}</pre><h3>Setting Up Redis with private endpoint</h3><p>The next thing will be the Azure Redis Cache with the a private endpoint and a DNS zone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agsV3Upz6zD9LaWaDN3C7A.png" /><figcaption>Database and redis</figcaption></figure><pre>resource &quot;azurerm_redis_cache&quot; &quot;redis&quot; {<br>  name                          = &quot;app-redis-cache&quot;<br>  location                      = data.azurerm_resource_group.app_rg.location<br>  resource_group_name           = data.azurerm_resource_group.app_rg.name<br>  capacity                      = var.app_config.redis.capacity<br>  family                        = var.app_config.redis.family<br>  sku_name                      = var.app_config.redis.sku_name<br>  public_network_access_enabled = false<br>  non_ssl_port_enabled          = false<br>  minimum_tls_version           = &quot;1.2&quot;<br>  redis_version                 = &quot;6&quot;<br>}<br>resource &quot;azurerm_private_endpoint&quot; &quot;redis_private_endpoint&quot; {<br>  name                = &quot;redis-endpoint&quot;<br>  location            = data.azurerm_resource_group.app_rg.location<br>  resource_group_name = data.azurerm_resource_group.app_rg.name<br>  subnet_id           = azurerm_subnet.redis_cache_subnet.id<br>  custom_network_interface_name = &quot;private-redis-nic&quot;<br>  private_dns_zone_group {<br>    name                 = &quot;private.redis.cache.windows.net&quot;<br>    private_dns_zone_ids = [azurerm_private_dns_zone.private_redis_zone.id]<br>  }<br>  private_service_connection {<br>    name                           = &quot;redis-private&quot;<br>    subresource_names              = [&quot;redisCache&quot;]<br>    private_connection_resource_id = azurerm_redis_cache.redis.id<br>    is_manual_connection           = false<br>  }<br>}<br>resource &quot;azurerm_private_dns_zone&quot; &quot;private_redis_zone&quot; {<br>  name                = &quot;redis.cache.windows.net&quot; // must be redis.cache.windows.net<br>  resource_group_name = data.azurerm_resource_group.app_rg.name<br>}<br>resource &quot;azurerm_private_dns_zone_virtual_network_link&quot; &quot;private_redis_vn_link&quot; {<br>  name                  = &quot;redisVnetZone.com&quot;<br>  private_dns_zone_name = azurerm_private_dns_zone.private_redis_zone.name<br>  virtual_network_id    = azurerm_virtual_network.app_vnet.id<br>  resource_group_name   = data.azurerm_resource_group.app_rg.name<br>  registration_enabled  = false<br>}</pre><h3>Deploying Azure Container Apps</h3><p>The container app will need a registry storage, but you can choose other registry service as well. The container app is only gate accept connection from internet.</p><p>The beauty of container app is that it will handle scaling automatically based on the traffic, custom domain, and zero downtime between deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPLdmhI1Kq_0j_7EOVu_AQ.png" /></figure><pre>resource &quot;azurerm_container_app_environment&quot; &quot;container_app_environment&quot; {<br>  name                     = &quot;app-container-environment&quot;<br>  location                 = data.azurerm_resource_group.app_rg.location<br>  resource_group_name      = data.azurerm_resource_group.app_rg.name<br>  infrastructure_subnet_id = azurerm_subnet.container_apps.id<br>  workload_profile {<br>    name                  = &quot;Consumption&quot;<br>    workload_profile_type = &quot;Consumption&quot;<br>  }<br>  log_analytics_workspace_id = azurerm_log_analytics_workspace.log_analytics.id<br>}<br><br>resource &quot;azurerm_subnet&quot; &quot;container_apps&quot; {<br>  name                 = &quot;containerapps-subnet&quot;<br>  resource_group_name  = data.azurerm_resource_group.app_rg.name<br>  virtual_network_name = azurerm_virtual_network.app_vnet.name<br>  address_prefixes     = [&quot;10.0.0.0/23&quot;]<br><br>  delegation {<br>    name = &quot;Microsoft.App.environments&quot;<br>    service_delegation {<br>      name = &quot;Microsoft.App/environments&quot;<br>      actions = [<br>        &quot;Microsoft.Network/virtualNetworks/subnets/join/action&quot;,<br>      ]<br>    }<br>  }<br>}<br><br>resource &quot;azurerm_container_app&quot; &quot;container_app&quot; {<br>  name                         = &quot;container-app&quot;<br>  container_app_environment_id = azurerm_container_app_environment.container_app_environment.id<br>  resource_group_name          = data.azurerm_resource_group.app_rg.name<br>  revision_mode                = &quot;Single&quot;<br>  template {<br>    container {<br>      name   = &quot;container-app&quot;<br>      image  = &quot;...container-app:latest&quot; // your image url<br>      cpu    = &quot;0.5&quot;<br>      memory = &quot;1Gi&quot;<br>    }<br>  }<br>}</pre><h3>The last piece: Connecting the Services</h3><pre>locals {<br>  databaseUrl = &quot;postgres://${azurerm_postgresql_flexible_server.postgres_server.administrator_login}:${azurerm_postgresql_flexible_server.postgres_server.administrator_password}@${azurerm_postgresql_flexible_server.postgres_server.fqdn}:5432/${azurerm_postgresql_flexible_server_database.main_database.name}?sslmode=require&quot;<br>  redisUrl    = &quot;rediss://:${azurerm_redis_cache.redis.primary_access_key}@${azurerm_redis_cache.redis.hostname}:${azurerm_redis_cache.redis.ssl_port}&quot;<br>}<br><br>resource &quot;azurerm_container_app&quot; &quot;container_app&quot; {<br>  template {<br>    container {<br>      env {<br>        name  = &quot;DATABASE_URL&quot;<br>        value = local.databaseUrl<br>      }<br>      env {<br>        name  = &quot;REDIS_URL&quot;<br>        value = local.redisUrl<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc6ia06y_Kz9E221nfJ77A.png" /></figure><p>And your container app can start access to Redis and the db.</p><p>Hope you guys find this usefull. If you have questions or improvements, feel free to share them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5fc6cb7877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System design: Scaling WebSocket Applications]]></title>
            <link>https://medium.com/@dinh.nt/system-design-scaling-websocket-applications-c7827ec82afb?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7827ec82afb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 14:47:30 GMT</pubDate>
            <atom:updated>2024-11-22T14:47:30.440Z</atom:updated>
            <content:encoded><![CDATA[<p>Realtime applications are everywhere nowaday, it plays such a crucial job where we want to interact with people directly: <strong>chat app, online meeting, and gaming.</strong></p><p>Building a <strong>reliable real-time application is hard</strong>, but scaling it is even <strong>harder</strong>. A real-time application has to maintain persistent connections with the client, <strong>so scaling is different from scaling a normal web app</strong>. In this post, we will explore those challenges, solve them, and make a demo using Docker.</p><h3>How WebSocket application normally work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QejXrihNGXC_3iJEZGJaw.png" /></figure><p>Typically, there will be a lot of client connect to the server through websocket connection. They will interact with server in both ways, client send event to the server, and the server can send something to the client.</p><p>This server is a stateful server, because it has to keep all connection information in its memory, if it’s down, all connections will be lost.</p><h3>The problem when scaling.</h3><p>A WebSocket server can become overloaded faster than a traditional HTTP server because it must maintain all connection information. Both vertical and horizontal scaling can be applied to increase performance. While vertical scaling involves upgrading CPU and adding more RAM, <strong>I’ll focus on horizontal scaling.</strong></p><p>So, horizontal scaling, just add more servers with a load balancer, and it’s done right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYIX3Z-obyQqAk0bIAMfdQ.png" /></figure><p>This is <strong>true for HTTP server</strong>, but for WebSocket-based applications, we have some problems:</p><ul><li>Connection consistency: If client A establishes a WebSocket connection to Server 1, all subsequent messages from that client must be handled by the same server. If the load balancer routes its request to Server 2, the connection state is lost, causing errors.</li><li>Cross-client communication: if client A and client B connect to different servers, how do these 2 clients exchange messages in real-time. There is no way because each server keeps its own connections and state, isolated from the rest of the clusters.</li></ul><h3>Design to scale</h3><p>So, let’s solve the above problems:</p><h4><strong>Connection consistency</strong></h4><p>we can solve this problem quite easily by using proper balancing algorithms</p><p>What we need in here is each client must stick to their server on one session, or even better, all subsequent sessions. IP hash is a great way to solve it, since it will choose the server base on the hasing result of client IP address. So if the client IP remain consistency on the whole session (which it should), it will always connect to the same server.</p><h4><strong>Cross-client communication</strong></h4><p>So we need a way to broadcast messages from one client to the rest.</p><p>But the real problem is, that we need a way to broadcast messages from one server to the rest of the clusters.</p><p>The simplest way to solve this is to use a message queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBGc_810R6FjOqdO1egaag.png" /></figure><p>So now, if client A wants to send a message to client B, it will send it to its connected server — Server 1.</p><p>Server 1 will broadcast to the message queue and deliver to Server 2.</p><p>If Server 2 is connected to B, it will send that message to client B.</p><p>The finalized design will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Z8vCdNOkIhspjp5Mt9RoA.png" /></figure><p>The message queue service could be anything, rabbitMQ, kafka, or redis. They all support clustering for scalability.</p><h3>Demo with a chat app</h3><p>My demo infrastructures will contain 3 websocket apps, 1 Redis instance and 1 nginx server.</p><p>docker-compose.yml file</p><pre>name: socket-io-app<br>services:<br>  app-1:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: socket-io-app-1<br>    environment:<br>      - REDIS_URL=redis://redis-1:6379<br>    ports:<br>      - &quot;3000:80&quot;<br>  app-2:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: socket-io-app-2<br>    environment:<br>      - REDIS_URL=redis://redis-1:6379<br>    ports:<br>      - &quot;3001:80&quot;<br>  app-3:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: socket-io-app-3<br>    environment:<br>      - REDIS_URL=redis://redis-1:6379<br>    ports:<br>      - &quot;3002:80&quot;<br>  redis-1:<br>    image: redis:7.4<br>    container_name: redis-1<br>  nginx:<br>    image: nginx:latest<br>    container_name: nginx<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf<br>    depends_on:<br>      - app-1<br>      - app-2<br>      - app-3</pre><p>The exposed port is for testing purposes, since when sending the request locally, they will be routed to the same server.</p><p>Setup socket.io with Redis is so easy with the built-in adapter. This adapter will help <a href="https://socket.io/docs/v4/adapter/">broadcasting events to all or a subset of clients.</a></p><pre>import { Redis } from &quot;ioredis&quot;;<br>import { Server } from &quot;socket.io&quot;;<br>import { createAdapter } from &quot;@socket.io/redis-adapter&quot;;<br><br>const pubClient = new Redis(process.env.REDIS_URL!);<br>const subClient = pubClient.duplicate();<br>const io = new Server({<br>  adapter: createAdapter(pubClient, subClient),<br>});<br><br>io.listen(80);</pre><p>For example, this piece of code, let say client 1 connect to server 1 and join room 1. Then client 2 connect to server 2 and join room 1. When client 1 send message to the room 1, both client will receive it.</p><p>If there is client 3 connected to server 3, and then it tries to send a message to all, all 3 clients will receive it.</p><pre>socket.on(&quot;joinRoom&quot;, (data) =&gt; {<br>  socket.join(data.room);<br>  console.log(`Socket ${socket.id} joined room ${data.room}`);<br>});<br>socket.on(&quot;message&quot;, (data) =&gt; {<br>  console.log(<br>    `User ${data.userId} sent message to room ${data.room}: ${data.message}`<br>  );<br>  io.to(data.room).emit(&quot;message&quot;, {<br>    userId: data.userId,<br>    message: data.message,<br>  });<br>});<br>// send to all client across clusters<br>socket.on(&quot;all&quot;, (data) =&gt; {<br>  console.log(`Socket ${socket.id} sent message to all: ${data.message}`);<br>  io.emit(&quot;all&quot;, {<br>    message: data.message,<br>  });<br>});</pre><p>This is my test on postman to 3 server from 3 client, with according timeline. Seems work as expected huh?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AP64yVHqFv6qp7bRqm6GVw.png" /></figure><p>Hope you find valuable things in my post. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7827ec82afb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System design: Bottlenecks by third-party API]]></title>
            <link>https://medium.com/@dinh.nt/system-design-bottlenecks-by-third-party-api-b2dbbf2d5257?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2dbbf2d5257</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 02:16:03 GMT</pubDate>
            <atom:updated>2024-11-04T02:16:55.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Years ago I had a chance to work on a logistics project for a famous company.</p><p>The business logic was super complicated, but the main logic for the end customer, the one that generates revenue, is simple: <strong>booking a parcel and tracking its status.</strong></p><p>There is one problem that occurs in the design —<strong> bottlenecks caused by the third-party API service.</strong></p><p>In this post, I will discuss the problem and the solution in detail.</p><h3>1. The overall project design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1Cj4dIYKsS8OlJbbSU3Kg.png" /><figcaption>Overall project design</figcaption></figure><p>This is a typical microservice design system with a <strong>load balancer, multiple app services, and one database</strong>. Why one database? It is good for data <strong>consistency </strong>across all services.</p><p>Plus, Azure Cosmos DB does a good job scaling under high load. We just have to set up the<strong> proper partitionKey for splitting the logical and physical partition.</strong></p><p>So the overall design is good both consistency and scalability.</p><h3>2. Detail design</h3><h4>Booking a new parcel logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJNJPmMf1Iq7k6aF-GMGQg.png" /></figure><p><strong>How it works:</strong></p><p>The flow contains 3 main small steps:</p><ul><li>Validate the parcel data</li><li>Send to the third party delivery service, wait for the response</li><li>Store to database</li></ul><p>And return response to user.</p><p><strong>Pros/Cons:</strong></p><p>One of the biggest problem in this design is handling the third party api. Rate limiting, timeouts, budget constraints, or sometimes unknown errors can occur. Any of those problems can slow down the processing time, and eventually, limit how many booking requests we can handle — which equals limiting our revenue.</p><p>Another problem is the microservice design isn’t pure. It doesn’t make sense to handle third party delivery service in Finance and Admin app. This logic should be separated into a new service.</p><h4>Tracking parcel status logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOedPlJtrocZ-1AyCLLniw.png" /></figure><p><strong>How it works:</strong></p><p>The user will go to Tracking UI to view the status of each parcel<br>The parcel status will be updated in 3 ways:</p><ul><li>Listening to third-party delivery service</li><li>Setup a background job to query third-party delivery service</li><li>Update internally from Admin team</li></ul><p><strong>Pros/Cons:</strong></p><p>There are no problems with this design.</p><h3>2. How I improve it</h3><p>Overall, the only problem in this design is handle third party api service and separate the delivery service from the other. In my opinion, introduce event queue to the system will solve it nicely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUOJkp1kHbTazXMf8JJk3Q.png" /><figcaption>Improved design using event queue</figcaption></figure><p><strong>How it works:</strong></p><p>Now booking new parcel will be:</p><ul><li>validate the parcel data</li><li>store it in the database</li><li>fire new parcel event to event queue (Kafka)</li></ul><p>And when <strong>Kafka </strong>receives this event:</p><ul><li>Send event to delivery service</li><li>Delivery service will try making requests to third-party API, handle rate limit</li><li>If successful, store additional data to the DB</li><li>If fail, return that status to kafka and <a href="https://www.baeldung.com/spring-retry-kafka-consumer#:~:text=To%20implement%20a%20retry%20logic,unacknowledged%20messages%20to%20another%20consumer">retry it</a> later</li></ul><p><strong>Pros/Cons:</strong></p><p>From now the booking request will all be handled internally by our system, much easier for us to increase the throughput.</p><p>One problem is this setup is a bit more complicated, and needs to test carefully.</p><p>And for the UI we needs to inform user of additional status when their parcel is successfully booked by Delivery service.</p><h3>Recap</h3><p><strong>Bottlenecks in third-party API</strong> is such a common thing. But for critical operations, we should fix it as soon as possible. In this case, I solved it by decoupling from internal system, using event queues. But maybe in another case, it would not be suitable at all.</p><p>Hope you guys find my insight valuable!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2dbbf2d5257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to transform monolith to microservice architecture]]></title>
            <link>https://medium.com/@dinh.nt/how-to-transform-monolith-to-microservice-architecture-d4e555deed24?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e555deed24</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 13:59:47 GMT</pubDate>
            <atom:updated>2024-10-20T14:01:49.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yApG04VeCTXrpsk-mIkikg.png" /><figcaption>Transform monolith to microservice architecture</figcaption></figure><p>Transforming a monolithic architecture to a microservices architecture is a significant task many organizations face as they scale and modernize their applications. In this post, I will walk you through the key considerations and steps involved in this process.</p><h3>What is Monolith Architecture?</h3><p>A monolithic architecture is a traditional software design pattern where all components are organized into a single codebase and deployed as a single unit. Typically, it will include everything from user interface, business logic, and the database.</p><h3>What is Microservices Architecture?</h3><p>Microservices architecture is an approach to software development where an application is built as a collection of small, independent services. Each service runs in its own process, communicates through well-defined APIs, and is responsible for a specific business capability. This architecture allows for greater scalability, flexibility, and easier maintenance of individual components.</p><h3>When do you want to migrate from monolith architecture to microservices architecture:</h3><ul><li><strong>Shorten update cycle:</strong> Many times, updating big monolith application is slower than a small service. So if the application is big and needs to change frequently, microservice is a good choice</li><li><strong>Scalability: </strong>When different parts of your application have different scaling needs, microservices allow you to scale individual components independently.</li><li><strong>Team organization: </strong>For large organizations with multiple teams working on different aspects of the application, microservices can allow for better team productivity.</li></ul><h3>Migration plan</h3><p>Without a plan, the migration process can quickly become a disaster. Here are some tips to help you prepare a plan:</p><ul><li><strong>Migrate gradually:</strong> Instead of replacing the whole monolith with the new one, we will replace it incrementally.</li><li><strong>Parallel Development:</strong> both legacy system and the new system will run and develop in parallel, ensure exisiting logic still work.</li><li><strong>New Module as a Service:</strong> For any new module, separate it to a new service.</li></ul><h4><em>So, how to migrate from monolith to microservice architecture</em></h4><h3>1. Mapping the components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yQ2lL2yD44Lz2aGukEIiA.png" /><figcaption>Mapping the components</figcaption></figure><p>How your monolith application organized, how many main modules that you have that independently from each other, carry a specific business logic? We need to identify those modules first.</p><h3>2. Design communication channels between services.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euvefT14K7ApDpfvshAmrg.png" /><figcaption>Design communication channels</figcaption></figure><p>The next thing is identifying the <strong>inter-system communication</strong> style between those modules. Was it <strong>synchronous or asynchronous</strong> operation? Was it 1–1 or 1 to many, identify them.</p><p>After that, choose which channel you want to use.</p><ul><li>If it’s<strong> 1–1 synchronous,</strong> you can use http call.</li><li>If it’s <strong>1–1 asynchronous, </strong>you can choose either http call or event bus.</li><li>If it’s <strong>1 to many asynchronous,</strong> event bus is the best choice</li></ul><h3>3. Choose the module that you want to extract to a separate module</h3><p>The best way is to start with less critical service to minimize the risk and we can learn from the process.</p><h3>4. Split the code of that module, separate it from the rest of code base.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pD3tBes5grgo7h7tZpickg.png" /><figcaption>Split the codebase</figcaption></figure><h3>5. Split the database, form the communication channel between 2 parts to synchronize the data.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSnyNMdAXWI4sGFRK99l4w.png" /><figcaption>Split the database</figcaption></figure><p>Ideally, your microservice doesn’t have shared data across services. But many times, one service will need data from other. Let’s say the order service needs user data to process its logic. You have multiple methods to deal in this situation.</p><ol><li><strong>Using restAPI:</strong> the easiest way is to expose the user data restAPI endpoint and let other services use it.</li><li><strong>Store duplicate data in both services. </strong>When performance is important, consider store some user data in order service’s database could be a good choice.<br><em>The challenge is how to synchronize duplicate data between user database and order database. This is called data consistency, and it’s such a big topic in microservice, </em><a href="https://daily.dev/blog/10-methods-to-ensure-data-consistency-in-microservices"><em>this post will introduce you many methods to deal with it</em></a></li></ol><h3>6. Moving the new module to a new service, deploying it.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9952kmktyledyVmtSx_Cxw.png" /><figcaption>Moving the new module to a new service</figcaption></figure><h3>7. Delete the old module in monolith application.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_jC9xyq83QB--rXHbIxEA.png" /><figcaption>Delete the old module in monolith application</figcaption></figure><h3>Recap</h3><p>Transforming a monolithic application to a microservices architecture is a complex process that requires careful planning, gradual implementation, and continuous refinement. I hope my post provide you with some valuable insight, helping you complete this proccess successfully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e555deed24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into NestJS Core Components]]></title>
            <link>https://medium.com/@dinh.nt/a-deep-dive-into-nestjs-core-components-dfe0fca33f53?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe0fca33f53</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 14:39:42 GMT</pubDate>
            <atom:updated>2024-10-13T14:39:42.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eqzkOuXG_5MgJLG_x7_VA.png" /></figure><p><strong>NestJS </strong>is a powerful framework for building server-side applications with <strong>Node.js</strong>, designed with a clean architecture inspired by <strong>Angular</strong>. It helps developers create organized and efficient code. In this post, we’ll explore the fundamental components of NestJS, such as controllers, providers, and modules. We’ll also delve into how middleware, exception filters, pipes, and guards function within the framework.</p><p>Whether you’re new to <strong>NestJS </strong>or just want to learn more, this guide will help you understand how to use these tools to build great applications.</p><h3>Controllers</h3><p>This is the layer responsible for handling all incoming requests. It is the core process business logic of the application.</p><pre>import { Controller, Get, Req } from &#39;@nestjs/common&#39;;<br><br>@Controller(&#39;tasks&#39;)<br>export class CatsController {<br>  @Get()<br>  findTask(@Req() request: Request): string {<br>    return &#39;This action returns all tasks&#39;;<br>  }<br>}</pre><p>Besides, it’s handling <strong>routing logic, redirection</strong>, all can be setup using just the decorator system</p><pre>@Get(&#39;sub-task&#39;)<br><br>@Redirect(&#39;https://redirect-url.com&#39;, 301)</pre><h3>Provider</h3><p>What is providers in NestJS? Services, repository, factories, helpers,</p><p>The main idea of provider is that it can be injected as a dependency. <strong>Provider </strong>will use annotation @Injectable() , which means this class will be managed by <strong>NestJS Inversion of Control container</strong>.</p><p>After that, the class can be defined in the constructor of another class and will be injected into it.</p><p><strong>There are 3 types of provider scope in NestJS</strong>, the default one is a single instance, which is tied to the lifetime of the application. Once the application is bootstrapped, all singleton providers have been instantiated.</p><p>The second type is <strong>Request scoped provider</strong>, which will be created by each incoming request, after the request finishes its lifecycle, the provider will be garbage collected.</p><p>The last type is <strong>Transient</strong>, which will always be created as a new instance every time we inject into the constructor.</p><p>For performance concerns, <strong>request-scoped and transient providers</strong> could slow down you request because NestJS always create a new instance for each request or each injection. So use it wisely.</p><h4>Durable Provider:</h4><p>This is an advanced provider concept in NestJS. It optimizes the performance of application by reusing the same provider across requests that share common attributes.</p><p>Usually, this provider will be used in multi-tenant applications, where some providers only exist in one tenant and are separate from all other tenants.</p><h3>Modules</h3><p>Module in NestJs is a way to manage and group controllers and services in the application.</p><p>One module can contain multiple controllers, services and repositories. It can inject other providers into its constructor, but it can’t be injected into provider due to circular dependency.</p><p>Module can import other modules, and have access to exported resources of those modules</p><p>In NextJs, modules are singleton by default. If you want some providers available everywhere, group them on a global module using @Global decorator.</p><h4>Dynamic module</h4><p>This is another term for modules. It is used when the module is used in multiple locations, and we want it to behave differently in each case. For example, ConfigModule in this case, it will load the config from any folder specified in register function. Many modules can use this module in different folders, based on its need.</p><pre>@Module({<br>  imports: [ConfigModule.register({ folder: &#39;./config&#39; })],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><h3>Middleware</h3><p>NestJS middleware are equivalent to express middleware, which is defined as:</p><ul><li>Can make changes to request and reponse object.</li><li>Can end the request response cycle.</li><li>Can call the next() function to move to the next middleware in the stack.</li><li>If the middle doesn’t end the request response cycle, it must call next function. If it doesn’t, the request will be left hanging</li></ul><p>Use case: while <strong>NestJS</strong> provides a specilized construct like <strong>Pipes</strong>, <strong>Guard</strong>,…. for a specific scenario, middleware play a crucial on some scenario:</p><ul><li><strong>Custom Rate Limiting:</strong> in some cases, rate limiting logic might need access to external system, middleware is a great place to do that</li><li>Integrate with third-party middleware: body-parser, morgan ,… many middleware are originally for <strong>Express.js</strong> could be used as <strong>NestJS </strong>middleware.</li><li>Global Request Modifications: in some cases, we need to modify the header, the request data of the whole application.</li></ul><h3>Exception Filters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*a3vpxsJzPvgcCwLB.png" /></figure><p>This is the layer that handles all the unhandle exception across the application. In a <strong>request-response cycle</strong>, if there is an exception that our code doesn’t catch, it will be throw to this layer and <strong>Exception Filter</strong> will send back to user a meaningful response.</p><p>If the exception is an unrecognized exception, the builtin <strong>Exception Filter</strong> will send a general error to client:</p><pre>{<br>  &quot;statusCode&quot;: 500,<br>  &quot;message&quot;: &quot;Internal server error&quot;<br>}</pre><p>So instead, we could define the error and throw it</p><pre>@Get()<br>async findAll() {<br>  throw new HttpException(&#39;Forbidden&#39;, HttpStatus.FORBIDDEN);<br>}</pre><p>and the server will respond with desired message and status code.</p><pre>{<br>  &quot;statusCode&quot;: 401,<br>  &quot;message&quot;: &quot;Forbidden&quot;<br>}</pre><h3>Custom Exception Filter</h3><p>Normally, using built-in HTTP exceptions is enough. But if it doesn’t cover your cases, we could create a new Exception filter.</p><pre>import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from &#39;@nestjs/common&#39;;<br>import { Request, Response } from &#39;express&#39;;<br><br>@Catch(HttpException)<br>export class HttpExceptionFilter implements ExceptionFilter {<br>  catch(exception: HttpException, host: ArgumentsHost) {<br>    const ctx = host.switchToHttp();<br>    const response = ctx.getResponse&lt;Response&gt;();<br>    const request = ctx.getRequest&lt;Request&gt;();<br>    const status = exception.getStatus();<br>    response<br>      .status(status)<br>      .json({<br>        statusCode: status,<br>        timestamp: new Date().toISOString(),<br>        path: request.url,<br>      });<br>  }<br>}</pre><p>The @Catch annotation tell us which type of exception will be handled by our <strong>ExceptionFilter</strong>.</p><p>Then we can access the request and reponse object to do some modification before send the response back to user.</p><p>We can bind this filter to api level, controller level, the whole module level or even global level.</p><h3>Pipes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*pQ6B3HV9dmCVyZQF.png" /></figure><p>Pipes help us transform the request data to a desired form.</p><p>This layer sits before the main handler function. So that mean after request data being transform by Pipes, it will be passed next to the handler.</p><p>So Pipes have 2 typical use cases:</p><ul><li><strong>Tranformation</strong>: tranform the data before passing to controller</li><li><strong>Validation</strong>: evaluate the data, pass unchanged data to the controller if valid, otherwise through exception.</li></ul><h3>Guard</h3><p>Use for authentication, authorization, how it work is similar to Pipes, but it has another meaning.</p><p>Guard being executed after middleware but before any pipes or interceptor.</p><p>Example:</p><pre>import { Injectable, CanActivate, ExecutionContext } from &#39;@nestjs/common&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable()<br>export class RolesGuard implements CanActivate {<br>  canActivate(<br>    context: ExecutionContext,<br>  ): boolean | Promise&lt;boolean&gt; | Observable&lt;boolean&gt; {<br>    return true;<br>  }<br>}</pre><p>If the canActivate return true, this request will be continued,</p><p>If false, it will be denied</p><p>And how to use this <strong>Guard</strong>:</p><pre>// controller scope<br>@Controller(&#39;cats&#39;)<br>@UseGuards(RolesGuard)<br>export class CatsController {}<br><br>// method scope<br>@Controller(&#39;cats&#39;)<br>export class CatsController  {<br>  @Post()<br>  @UseGuards(RolesGuard)<br>  createCats() {<br>    // This endpoint is protected by the AuthGuard<br>    return &#39;This is a protected endpoint&#39;;<br>  }<br>}</pre><p>Guard can be bound to method scope, controller scope, or global scope.</p><p>By understanding these core elements, I hope you can leverage <strong>NestJS </strong>to create scalable and maintainable applications, whether you’re new to the framework or seeking to enhance your knowledge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe0fca33f53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I build a ICS previewer for dev]]></title>
            <link>https://blog.stackademic.com/im-making-a-ics-calendar-preview-website-87cb9867e1f1?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cb9867e1f1</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 14:52:18 GMT</pubDate>
            <atom:updated>2024-10-14T06:35:40.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ng0GnoP2x_P8HpksfAXdyw.jpeg" /></figure><p>Recently I’ve been working with the event feature, especially with the ical file (iCalendar).</p><p>The <strong>problem begins when I have no easy way to preview it.</strong> The easiest way for me is to open in Outlook, which takes quite some time.</p><p>Another way is to use this site: <a href="https://larrybolt.github.io/online-ics-feed-viewer/">https://larrybolt.github.io/online-ics-feed-viewer/</a></p><p>But it has some bugs previewing the <strong>reoccurrence event,</strong> so I decided to build my own ICS calendar preview, and I think many developers might desperately need it.</p><p><strong>My result is here:</strong></p><p><a href="https://ics-preview-cloudflare-nextjs.pages.dev/">ics-preview-cloudflare-nextjs.pages.dev</a></p><h4>I will talk a little bit about how I made it</h4><p>The first thing I did was look at larrybolt work, which is an open-source project:</p><p><a href="https://github.com/larrybolt/online-ics-feed-viewer">larrybolt/online-ics-feed-viewer: Online ICS / iCal feed viewer (github.com)</a></p><p>He uses <strong>FullCalendar library plus an ICS file parser, and written in vanillaJS and jQuery</strong> — I respect him so much — but the project is 6–7 years old, so that makes sense.</p><p>So I use the same library.</p><p>The error causing a reoccurrence event bug in his project is due to missing parser to rrule. But what is rrule, <strong>it’s </strong><a href="https://medium.com/@edouard.courty/the-best-way-to-programmatically-handle-recurrence-11e9b489b27d"><strong>a specification that outlines how recurring events should be represented in a calendar</strong></a><strong> — post by Edouard Courty.</strong></p><p>To handle that problem, first, I need to understand <strong>how FullCalendar handles rrule, then I need to find a new parser to parse the rrule string correctly.</strong> Luckily FullCalendar can handle raw rrule string quite well by its plugin. So, the problem solved.</p><p>You can take a look at my result over here, it isn’t a complete solution yet, but hope by the time you read, it will be.</p><p><a href="https://ics-preview-cloudflare-nextjs.pages.dev/">ics-preview-cloudflare-nextjs.pages.dev</a></p><p><em>Update: my post got a third position on google about this tool, so if you happen to use it and find something I could fix or extend, please add in the comment, i will check.</em></p><p>Happy coding guys.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cb9867e1f1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/im-making-a-ics-calendar-preview-website-87cb9867e1f1">I build a ICS previewer for dev</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to choose the right stack for you next project]]></title>
            <link>https://medium.com/@dinh.nt/how-to-choose-the-right-stack-for-you-next-project-31902b9c12ed?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/31902b9c12ed</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[saas-tools]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[tech-stack]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 14:06:00 GMT</pubDate>
            <atom:updated>2024-09-29T14:06:00.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-udPAgtYHttyT8B90qcGAw.jpeg" /></figure><p>Saas starter package has been rising in popularity recently, it helps developers make their startup quicker, ship product faster than ever before. One of the most successful starter packages I can name is <a href="https://shipfa.st/">ShipFast</a>.</p><p>The downside is when you use someone’s code, it’s <strong>harder to customize</strong> it the way you want. And when you want to customize the prebuilt component, it requires learning curve. If you use the <strong>open source starter</strong> package, sometimes there will be licensing concerns about what you can do and what’s not.</p><p>With the rise of all available libraries, frameworks and especially AI, it’s not hard to build your own starter stack.</p><p><strong>In this post, I will show you my way to develop a stack for my next project, which frontend, backend stack I choose, which auth method I use, and a little bit about DDoS awareness</strong></p><p><em>The complete source code in this post is available</em> <a href="https://github.com/compimprove/fastify-astro"><em>here</em></a></p><h3>Requirement</h3><p>So my stack must ensure some of the requirements:</p><ul><li><em>Must be easy to deploy — startup environment must run fast</em></li><li><em>Can be hosted for free — we have no money at the start</em></li><li><em>Can scale later on</em></li><li><em>DDoS awareness — to prevent a skyrocket cloud bills while you’re sleep</em></li><li><em>SEO friendly.</em></li></ul><p>From all the requirements above, you can say that Next.js is a great fit. It’s an all-in-one tool: static site generation, frontend, API server, serverless hosting on Vercel with big free tier,.. Because it’s an all-in-one tool so it’s complicated to start, customizing is hard when you have little to no experience with this framework.</p><p>And I want to separate the frontend and backend to make it clearer and easier.</p><h3>So for Frontend I choose Astro + React + Shadcn</h3><p>The great thing about Astro is it makes clear distinction about which part is static site rendering for SEO purposes, which part is rendered by React, like this</p><p>pages/app/[…all].astro</p><pre>---<br>import { App } from &quot;../react/App&quot;;<br>export const prerender = false;<br>---<br><br>&lt;App client:only=&quot;react&quot; /&gt;</pre><p>And that means every subdirectory domain.name/app/ will now be rendered all by React</p><p>Astro is supported to deploy on many major cloud platforms, I like Cloudflare pages since it’s completely free.</p><h3>For Backend I choose Fastify</h3><p>It’s one of the most popular nodejs backend frameworks, and the greatest thing is Fastify could be deployed to some serverless cloud platforms: Vercel, Aws lambda, Google Cloud Functions,.. but why serverless? Most platforms have generous free tiers my friend.</p><p>To avoid DDoS skyrocket bill, we shouldn’t deploy our serverless server to a pay-as-go subscription, that’s means the only option for me is to deploy Fastify server to <strong>Vercel</strong>, or <strong>Netlify</strong>.</p><p>The setup with Vercel is straightforward</p><p>api/index.js</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const app = Fastify({<br>  logger: true,<br>});<br><br>app.get(&quot;/&quot;, async (req, reply) =&gt; {<br>  return reply.send(&quot;Hello World&quot;);<br>});<br><br>export default async function handler(req, reply) {<br>  await app.ready();<br>  await mongoose.connect(process.env.MONGO_URI);<br>  app.server.emit(&quot;request&quot;, req, reply);<br>}</pre><p>And vercel.json file</p><pre>{<br>  &quot;rewrites&quot;: [<br>    {<br>      &quot;source&quot;: &quot;/(.*)&quot;,<br>      &quot;destination&quot;: &quot;/api&quot;<br>    }<br>  ],<br>  &quot;framework&quot;: null<br>}</pre><p>Serverless environment has some limitations, but you can always switch Fastify to run on a full VM server when you want an environment without cold start time, scaling with VMs, or you just have a specific need about the runtime.</p><h3>Understanding DDoS Risks</h3><p>A DDoS attack occurs when multiple systems flood the bandwidth or resources of a targeted system, usually one or more web servers. This can overwhelm your application, causing it to slow down and crash.</p><p>For serverless deployments, this can translate to a sudden spike in resource usage and, consequently, costs.</p><h4>Strategies to prevent it</h4><ol><li><strong>Avoid Pay-as-You-Go for Serverless</strong><br>So when we want to deploy Fastify as a serverless server, avoid using pay as you go subscription will be the easiest way to avoid DDoS risks.</li><li><strong>Utilize Cloudflare Protection</strong><br>The next thing you could do is setup your server behind Cloudflare proxy, and enable Cloudflare’s DDoS protection. This setup will prevent most of the DDoS attack.</li><li><strong>Implement Rate Limiting</strong><br>Limit number of request from single source is great way to prevent DDoS. You could easy implement rate limiting using Fastify middleware</li></ol><pre>const fastify = require(&#39;fastify&#39;)()<br>   fastify.register(require(&#39;@fastify/rate-limit&#39;), {<br>     max: 100,<br>     timeWindow: &#39;1 minute&#39;<br>   })</pre><h3>Authentication</h3><p>Another important thing to consider is choosing an authentication method for our stack, we could either use third-party library or an authentication service.</p><p>Using <strong>third-party library</strong> will give us more control with the lowest cost, but maintaining, scaling, and compliance stuff will be a problem. On the other side using an authentication service help us save a lot of time, always updated but it could increase the cost when our app grows. Choosing the right option is just hard</p><p>Currently, I’m using an authentication service, I will try using third party library on another post.</p><p>I used <strong>Clerk </strong>before, they have pretty good generous free tier, easy to implement. They have first-class support for React and an available middleware for <strong>Fastify </strong>too, which is so good.</p><p><em>Note: This post isn’t sponsored by Vercel, Clerk or ShipFast — I have so little audience for that stuff @@</em></p><p>Example implement Clerk in React and Fastify</p><pre>return (<br>    &lt;React.StrictMode&gt;<br>      &lt;ClerkProvider publishableKey={CLERK_PUBLISHABLE_KEY} afterSignOutUrl=&quot;/&quot;&gt;<br>        &lt;SignedOut&gt;<br>          &lt;SignInButton /&gt;<br>        &lt;/SignedOut&gt;<br>        &lt;SignedIn&gt;<br>          &lt;a href=&quot;/dashboard&quot;&gt;Dashboard&lt;/a&gt;<br>          &lt;a href=&quot;/dashboard/settings&quot;&gt;Settings&lt;/a&gt;<br>          &lt;a href=&quot;/dashboard/profile&quot;&gt;Profile&lt;/a&gt;<br>          &lt;UserButton /&gt;<br>        &lt;/SignedIn&gt;<br>        &lt;App /&gt;<br>      &lt;/ClerkProvider&gt;<br>    &lt;/React.StrictMode&gt;<br>  );</pre><pre>import Fastify from &quot;fastify&quot;;<br>import { clerkClient, clerkPlugin, getAuth } from &quot;@clerk/fastify&quot;;<br>import cors from &quot;@fastify/cors&quot;;<br><br>const app = Fastify({<br>  logger: true,<br>});<br>app.register(clerkPlugin);<br><br>app.get(&quot;/user&quot;, async (req, reply) =&gt; {<br>  const { userId } = getAuth(req);<br>  if (!userId) {<br>    return reply.code(401).send();<br>  }<br>  return reply.send({ userId });<br>});</pre><p><em>The complete source code in this post available</em> <a href="https://github.com/compimprove/fastify-astro"><em>here</em></a></p><h3>Recap</h3><p>With many all available libraries and cloud platforms, build your own Saas starter is so easy and fast. My personal way might not fit your case, but I hope how I approach it helps.</p><p>Thank you for reading, have a nice day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31902b9c12ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize your react component with useMemo, useCallback, useTransition]]></title>
            <link>https://blog.stackademic.com/optimize-your-react-component-with-usememo-usecallback-usetransition-bb07f04e5f61?source=rss-25b2d1e0c2ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb07f04e5f61</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react-performance]]></category>
            <dc:creator><![CDATA[DinhNT]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 14:52:29 GMT</pubDate>
            <atom:updated>2024-10-14T06:35:33.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju0X-LLc5cRgHoc5QvJkoA.jpeg" /></figure><p>Hook provides convenient ways to build your react application with functional components.</p><p>When your <strong>React application grows,</strong> unnecessary re-renders can hurt the app’s performance. Luckily there are some <strong>builtin hooks</strong> to solve only that problem for us.</p><p>Today, we’ll explore some powerful hooks that can boost your app performance: <strong>useMemo, useCallback and useTransition</strong></p><h3>useMemo: Memoizing computed value</h3><p>When the app growing, business logic can become more complex and computationally expensive. Those logics could lie anywhere in your component, and every time it re-renders, all those logics will be recalculated — even if it don’t have to.</p><p>Consider the example below:</p><pre>function DataVisualizer({ data, threshold }) {<br><br>  const processedData = data.map(item =&gt; item.value)<br>    .filter(value =&gt; value &gt; threshold);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Data points above threshold: {processedData.length}&lt;/h2&gt;<br>      {/* Render chart using processedData */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Every time DataVisualizer re-render, the filter will be called again, even if data and threshold value doesn’t change.</p><p>How to memoize the result? We can use useMemo</p><pre>function DataVisualizer({ data, threshold }) {<br><br>  const processedData = useMemo(() =&gt; {<br>    return data.map(item =&gt; item.value)<br>      .filter(value =&gt; value &gt; threshold);<br>  }, [data, threshold]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Data points above threshold: {processedData.length}&lt;/h2&gt;<br>      {/* Render chart using processedData */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>From now on, only when data and threshold change, the filter function will be called, otherwise, the old value will be used when the component re-render. That could save your component some milliseconds of rendering time.</p><p><em>Noted: You don’t need to useMemo on simple cases, where memoize logic could be slower than the original.</em></p><h3>useCallback: Memoizing function definition</h3><p>You need memoize your function on a special case.</p><p>Consider this example:</p><pre>export function ProductPage({productId, theme}) {<br><br>  const handleSubmit = (orderDetails) =&gt; {<br>    post(&#39;/product/&#39; + productId + &#39;/buy&#39;, {<br>      orderDetails,<br>    });<br>  };<br><br>  return (<br>    &lt;div className={theme}&gt;<br>      &lt;ShippingForm onSubmit={handleSubmit} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Every time theme change, the whole ProductPage re-renders, make the ShippingForm re-render with it. But what if ShippingForm is requires much calculation to re-render, you can tell React to only re-render it when it’s function props onSubmit change by using memo:</p><pre>const ShippingForm = memo(function ShippingForm({ onSubmit }) {<br>  // ...<br>});</pre><p>But the problem isn’t gone yet.</p><p>Every time theme change, handleSubmit will be redefined again, making it a whole new function (even when the function content is the same)</p><p>And that’s when you need useCallback</p><pre>export function ProductPage({productId, theme}) {<br><br>  const handleSubmit = useCallback((orderDetails) =&gt; {<br>    post(&#39;/product/&#39; + productId + &#39;/buy&#39;, {<br>      orderDetails,<br>    });<br>  }, [productId]);<br><br>  return (<br>    &lt;div className={theme}&gt;<br>      &lt;ShippingForm onSubmit={handleSubmit} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By wrapping it using useCallback, you ensure that only when productId change, handleSubmit will be redefined. Otherwise, it is the same between re-renders.</p><p>And that means only when productId change, ShippingForm will be re-rendered.</p><h3>useTransition: Prioritizing UI Updates</h3><p>Sometimes a component could take a while to render, and you don’t want that process freezing the whole app. You can prevent it by using useTransition</p><p>Let’s take a look at the example based on example of <a href="https://react.dev/reference/react/useTransition">React official doc</a></p><pre>function TabContainer() {<br>  const [tab, setTab] = useState(&#39;about&#39;);<br>  <br>  function selectTab(nextTab) {<br>    setTab(nextTab);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;TabButton<br>        isActive={tab === &#39;about&#39;}<br>        onClick={() =&gt; selectTab(&#39;about&#39;)}<br>        label={&#39;About&#39;} /&gt;<br>      &lt;TabButton<br>        isActive={tab === &#39;posts&#39;}<br>        onClick={() =&gt; selectTab(&#39;posts&#39;)}<br>        label={&#39;Posts&#39;} /&gt;<br>      {tab === &#39;about&#39; &amp;&amp; &lt;AboutTab /&gt;}<br>      {tab === &#39;posts&#39; &amp;&amp; &lt;PostsTab /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><p>Our UI is a tab layout with <strong>Post</strong> and <strong>About</strong> tab. Let’s say the &lt;PostsTab /&gt; takes 500ms to render. So when user chooses the <strong>Post</strong> tab, the whole UI will freeze in 500ms, they can’t do anything, if user wants to switch to another tab immediately, they have to wait.</p><p>To mark this process non-UI blocking, use useTransition like this</p><pre>function TabContainer() {<br>  const [isPending, startTransition] = useTransition();<br>  const [tab, setTab] = useState(&#39;about&#39;);<br>  <br>  function selectTab(nextTab) {<br>    startTransition(() =&gt; {<br>      setTab(nextTab);<br>    });<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;TabButton<br>        isActive={tab === &#39;about&#39;}<br>        onClick={() =&gt; selectTab(&#39;about&#39;)}<br>        label=&#39;About&#39; /&gt;<br>      &lt;TabButton<br>        isActive={tab === &#39;posts&#39;}<br>        onClick={() =&gt; selectTab(&#39;posts&#39;)}<br>        label=&#39;Posts&#39; /&gt;<br>      <br>      {tab === &#39;about&#39; &amp;&amp; &lt;AboutTab /&gt;}<br>      {tab === &#39;posts&#39; &amp;&amp; &lt;PostsTab /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><p>That’s it, startTransition now will take care of the non-blocking UI logic. Let your user switch between tabs without any interruptions.</p><h3>Recap</h3><p>So, in this post, we explore three powerful built-in hooks in React. It will help improve your app performance when used the right way.</p><ul><li><strong>useMemo</strong>: This hook helps memoize computed values, preventing expensive calculations from being re-executed on every render.</li><li><strong>useCallback</strong>: This hook is used to memoize function definitions. It ensures that functions are not redefined on every render unless their dependencies change.</li><li><strong>useTransition</strong>: This hook allows you to prioritize UI updates, making sure that the UI remains responsive even when some components take a while to render.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb07f04e5f61" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/optimize-your-react-component-with-usememo-usecallback-usetransition-bb07f04e5f61">Optimize your react component with useMemo, useCallback, useTransition</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>