<?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 Thinh Dang on Medium]]></title>
        <description><![CDATA[Stories by Thinh Dang on Medium]]></description>
        <link>https://medium.com/@thinhda?source=rss-bfdec87868e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bZ0WNgWSl85RFrzLA934hg.png</url>
            <title>Stories by Thinh Dang on Medium</title>
            <link>https://medium.com/@thinhda?source=rss-bfdec87868e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:30:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thinhda/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[Introducing LiveKit Dashboard: Simplifying Self-Hosted Real-Time Management]]></title>
            <link>https://medium.com/@thinhda/introducing-livekit-dashboard-simplifying-self-hosted-real-time-management-24a50d742fa9?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/24a50d742fa9</guid>
            <category><![CDATA[livekit]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 04:30:10 GMT</pubDate>
            <atom:updated>2025-10-20T04:31:31.759Z</atom:updated>
            <content:encoded><![CDATA[<p>Running LiveKit at scale is powerful — but it can also feel like you’re managing a live concert with the lights off. You’ve got rooms, participants, servers, and recordings all moving at once, and without a clear dashboard, visibility becomes guesswork.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KaJj_h2ZuElBMqXL.png" /></figure><p>Typical pain points include:</p><ul><li>Using CLI to access Livekit cluster</li><li>Writing ad-hoc scripts to query APIs</li><li>Manually tracking who’s connected where</li><li>Managing egress jobs without clear feedback</li><li>No unified view of SIP or telephony integrations</li></ul><p>If that sounds familiar, you’ll immediately see why <strong>LiveKit Dashboard</strong> exists — it turns that scattered workflow into a single, actionable control panel.</p><h3>What Exactly Is LiveKit Dashboard?</h3><p>LiveKit Dashboard is a <strong>stateless</strong>, <strong>self-hosted</strong> management app built with <strong>FastAPI</strong> and <strong>Jinja2</strong>. It communicates directly with your LiveKit servers using the official Python SDK — fetching live data on demand, with zero persistence or external dependencies.</p><h3>Design Principles That Keep It Simple</h3><ul><li><strong>Stateless by Design</strong> — No database or background workers. Every request reflects real-time data.</li><li><strong>Self-Hosted First</strong> — Deploy anywhere, stay in control of your infrastructure.</li><li><strong>Security-Focused</strong> — Includes HTTP Basic Auth, CSRF protection, and hardened security headers.</li><li><strong>Progressively Enhanced</strong> — Runs without JavaScript, upgraded with HTMX for real-time interactions.</li></ul><h3>Key Features That Make Operations Easier</h3><h3>🏠 Overview Dashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7lRXn1kKzEQMOGLP.png" /></figure><p>Your “cockpit view.”<br>Monitor room counts, participant distribution, SFU health, and API latency — refreshed every few seconds.</p><p><strong>Example</strong>:<br>A DevOps engineer can spot API latency spikes within seconds instead of waiting for alerting tools to trigger. It’s like watching your cluster’s heartbeat live.</p><h3>🚪 Room Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*yIEpICbxJe_p7LT3.png" /></figure><p>Create, view, and control rooms instantly — with visibility into active participants, tracks, and session states.</p><p><strong>Real-World Use Case</strong>:<br>Imagine a live streaming platform where a user reports “no video.” You open the dashboard, drill into the room, and see that their video track is muted — no SSH, no script, no waiting.</p><h3>👥 Participant Controls</h3><p>View participant connection health, media tracks, and latency metrics — and manage permissions or remove users with a single click.</p><p>This transforms support from “reactive triage” to “proactive resolution.”</p><h3>📹 Egress and Recording Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*BXwIYmsrR_nmUgLx.png" /></figure><p>Start composite recordings, monitor live jobs, and download finished files — all from the browser.</p><p><strong>Before:</strong><br>Running curl commands and checking job IDs manually.<br><strong>After:</strong><br>Click “Start Recording,” watch the status live, and access the file when done.</p><h3>📞 Optional SIP Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*5ne1qjORcp_3M7NT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*cOwLRP1IjYIcU67L.png" /></figure><p>Manage SIP trunks, routing, and telephony workflows directly from the interface when enabled.</p><h3>🧪 Token Generator Sandbox</h3><p>Quickly generate test tokens with configurable roles and TTLs. Perfect for debugging or validating new room settings before deploying to production.</p><h3>Under the Hood: A Simple Yet Scalable Architecture</h3><pre>User Browser ─▶ FastAPI + Jinja2 (SSR) ─▶ LiveKitClient SDK ─▶ Your LiveKit Server</pre><p><strong>Why this matters:</strong></p><ul><li><strong>Horizontally scalable:</strong> Run multiple instances with no coordination</li><li><strong>Always current:</strong> Every page fetches live data</li><li><strong>Resilient:</strong> Restart anytime — no state to lose</li><li><strong>Lightweight:</strong> Minimal CPU and memory usage</li></ul><h3>Getting Started in Minutes</h3><h3>🐳 With Docker</h3><pre>git clone &lt;repository-url&gt;<br>cd livekit-dashboard<br>cp .env.example .env  # Add your credentials<br>make docker-run</pre><h3>💻 Manual Setup</h3><pre>make install<br>export LIVEKIT_URL=&quot;https://your-livekit-server.com&quot;<br>export LIVEKIT_API_KEY=&quot;your-api-key&quot;<br>export LIVEKIT_API_SECRET=&quot;your-api-secret&quot;<br>export ADMIN_USERNAME=&quot;admin&quot;<br>export ADMIN_PASSWORD=&quot;secure-password&quot;<br>make dev</pre><p>Then visit http://localhost:8000 and log in — your LiveKit world, finally visible.</p><h3>Before &amp; After: Real Operational Wins</h3><h3>Scenario 1: Debugging Connection Issues</h3><ul><li><strong>Before:</strong> Using CLI to query the API.</li><li><strong>After:</strong> Open Dashboard → see 15 rooms, 127 participants → spot one room with connection drops → inspect the participant → fix instantly.</li></ul><h3>Scenario 2: Recording Oversight</h3><ul><li><strong>Before:</strong> Manually track egress job IDs.</li><li><strong>After:</strong> Dashboard shows all active recordings, with real-time job status and instant access to download URLs.</li></ul><h3>Scenario 3: Capacity Planning</h3><ul><li><strong>Before:</strong> Write API queries to calculate load.</li><li><strong>After:</strong> Dashboard overview shows distribution by room size and participant platform — updated automatically every few seconds.</li></ul><p>These aren’t just convenience improvements — they directly reduce downtime and support overhead.</p><h3>Built for Real-Time Reliability</h3><h3>Real-Time Analytics Example</h3><pre>async def get_enhanced_analytics(self):<br>    # Fetch live participant metrics<br>    ...<br>    return {<br>        &quot;connection_success&quot;: calculate_success_rate(),<br>        &quot;platforms&quot;: {<br>            &quot;Web&quot;: 60,<br>            &quot;iOS&quot;: 20,<br>            &quot;Android&quot;: 15,<br>            &quot;React Native&quot;: 5<br>        }<br>    }</pre><h3>Security First</h3><pre>def verify_credentials(username, password):<br>    return secrets.compare_digest(username, expected_user) and \<br>           secrets.compare_digest(password, expected_pass)</pre><p>Your credentials never leave your environment — no third-party calls, no logs.</p><h3>Current Limitations &amp; Roadmap</h3><p><strong>Today:</strong></p><ul><li>Single admin account</li><li>No historical trend tracking (stateless)</li><li>Basic participant control (kick/mute only)</li></ul><p><strong>Coming Soon:</strong></p><ul><li>WebSocket updates</li><li>Rich participant analytics</li><li>Recording previews</li><li>Mobile-friendly UI</li><li>Optional persistent analytics</li></ul><h3>Quick FAQ</h3><p><strong>Does it work with LiveKit Cloud?</strong><br>No — it’s built for self-hosted LiveKit servers where you control API access.</p><p><strong>Is it secure?</strong><br>Yes — all data flows within your own environment. No external services involved.</p><p><strong>Can I extend it?</strong><br>Absolutely. Add routes, analytics, or custom integrations easily — it’s open and modular.</p><p><strong>Resource usage?</strong><br>Lightweight — runs on a single core and 512 MB of RAM.</p><h3>Example Configuration</h3><pre>LIVEKIT_URL=https://your-livekit-server.com<br>LIVEKIT_API_KEY=your-api-key<br>LIVEKIT_API_SECRET=your-api-secret<br>ADMIN_USERNAME=admin<br>ADMIN_PASSWORD=secure-password<br>ENABLE_SIP=false</pre><h3>Why This Matters: From Monitoring to Mastery</h3><p>For teams running real-time systems, visibility is power.<br>The <strong>LiveKit Dashboard</strong> turns management from reactive firefighting into confident, data-driven operation.</p><p>You don’t just “check if things work” — you <em>see</em> them working.</p><p><strong>Start now</strong>:</p><ul><li><a href="https://github.com/thinhdanggroup/livekit-dashboard">View on GitHub</a></li><li><a href="https://github.com/thinhdanggroup/livekit-dashboard/blob/main/README.md">Read the Docs</a></li><li><a href="https://github.com/thinhdanggroup/livekit-dashboard/blob/main/docs/ARCHITECTURE.md">Explore the Architecture Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24a50d742fa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into the Node.js Event Loop]]></title>
            <link>https://medium.com/@thinhda/diving-into-the-node-js-event-loop-8eff3fa1b874?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eff3fa1b874</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 05:47:28 GMT</pubDate>
            <atom:updated>2024-02-18T05:47:28.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCNS7ecwckvIhMNfB1rnAQ.jpeg" /></figure><p>In this comprehensive guide, we’ll embark on a journey into the Node.js event loop, a fundamental concept that underpins the asynchronous nature of Node.js. We’ll start with an introduction to Node.js and the event loop, emphasizing its significance in asynchronous programming. Next, we’ll delve into the basic concepts of the event loop in Node.js, including asynchronous programming, the event loop’s role, and the differences between synchronous and asynchronous execution. We’ll also explore how Node.js implements the event loop, providing an overview of its architecture, libuv’s role, and the various phases of the event loop. To further our understanding, we’ll examine the event queue in the Node.js event loop, discussing its workings, the types of events (microtasks and macrotasks), and their prioritization. We’ll then explore the relationship between the event loop and JavaScript execution context, examining their interaction and providing code examples for clarity. Additionally, we’ll delve into non-JavaScript tasks in the event loop, such as timers and I/O operations, explaining their management and showcasing their usage through examples. To delve deeper, we’ll explore advanced topics like the microtask queue and macrotask queue in Node.js, comparing their use cases and providing insights into their behavior. Finally, we’ll conclude with a discussion of common pitfalls and misconceptions associated with the Node.js event loop, offering best practices to avoid potential issues. Throughout this guide, we’ll strive to present the information in a clear and engaging manner, making it accessible to both beginners and experienced developers alike. So, let’s embark on this journey together and gain a comprehensive understanding of the Node.js event loop!</p><h3>Introduction to Node.js Event Loop</h3><p>Node.js is a JavaScript runtime environment that allows developers to build server-side applications. It is known for its event-driven architecture, which utilizes an event loop to handle asynchronous operations efficiently. The event loop is a fundamental concept in Node.js that enables it to handle multiple concurrent requests without blocking.</p><p>In this section, we will introduce the Node.js event loop and discuss its importance in asynchronous programming.</p><h3>What is the Event Loop?</h3><p>The event loop is a core component of Node.js that is responsible for handling asynchronous operations. It is an infinite loop that continuously checks for events and callbacks that need to be executed. When an event occurs, the event loop places it in a queue. The event loop then processes the events in the queue in the order they were received.</p><h3>Importance of the Event Loop in Asynchronous Programming</h3><p>The event loop is essential for asynchronous programming in Node.js. Asynchronous programming allows developers to write code that does not block the execution of other tasks. This is achieved by using callbacks, which are functions that are executed when an event occurs.</p><p>For example, consider a web server that needs to handle multiple client requests. If the server were to process each request synchronously, it would have to wait for each request to complete before it could process the next one. This would result in poor performance, especially when there are many concurrent requests.</p><p>Instead, the server can use the event loop to handle requests asynchronously. When a client sends a request, the server places it in a queue. The event loop then processes the requests in the queue in the order they were received. This allows the server to handle multiple requests concurrently without blocking.</p><p>In the next section, we will dive deeper into the basic concepts of the event loop in Node.js. We will explore how asynchronous programming works, the role of the event loop in handling asynchronous operations, and the differences between synchronous and asynchronous execution.</p><h3>Basic Concepts of Event Loop in Node.js</h3><p>In the previous section, we introduced the Node.js event loop and discussed its importance in asynchronous programming. In this section, we will dive deeper into the basic concepts of the event loop and explore how it works.</p><h3>Asynchronous Programming</h3><p>Asynchronous programming is a programming paradigm that allows developers to write code that does not block the execution of other tasks. This is achieved by using callbacks, which are functions that are executed when an event occurs.</p><p>For example, consider a web server that needs to handle multiple client requests. If the server were to process each request synchronously, it would have to wait for each request to complete before it could process the next one. This would result in poor performance, especially when there are many concurrent requests.</p><p>Instead, the server can use asynchronous programming to handle requests concurrently. When a client sends a request, the server places it in a queue. The event loop then processes the requests in the queue in the order they were received. This allows the server to handle multiple requests concurrently without blocking.</p><h3>Role of the Event Loop in Asynchronous Operations</h3><p>The event loop is responsible for handling asynchronous operations in Node.js. When an asynchronous operation is triggered, the event loop places the associated callback function in a queue. The event loop then continues executing synchronous code until the call stack is empty. Once the call stack is empty, the event loop processes the callbacks in the queue in the order they were added.</p><p>This process allows Node.js to handle multiple asynchronous operations concurrently without blocking. The event loop ensures that all asynchronous operations are eventually executed, even if there is a long-running synchronous operation blocking the call stack.</p><h3>Differences Between Synchronous and Asynchronous Execution</h3><p>Synchronous execution is when a program executes code in the order in which it is written. Asynchronous execution is when a program can continue executing while waiting for a response from a long-running operation.</p><p>The following table summarizes the key differences between synchronous and asynchronous execution:</p><p>FeatureSynchronous ExecutionAsynchronous ExecutionExecution OrderCode is executed in the order it is writtenCode can continue executing while waiting for a response from a long-running operationBlockingBlocks the execution of other tasksDoes not block the execution of other tasksUse CasesSimple tasks that do not require waiting for a responseLong-running tasks that do not need to block the execution of other tasks</p><p>In the next section, we will take a closer look at how the event loop is implemented in Node.js. We will explore the different phases of the event loop and discuss how they work together to handle asynchronous operations efficiently.</p><h3>Detailed Explanation of Node.js Event Loop Implementation</h3><h3>Single-Threaded Nature of Node.js</h3><p>Node.js operates on a single-threaded model, meaning it has only one thread that executes JavaScript code. This design choice allows Node.js to handle many concurrent connections with a small number of threads, making it lightweight and efficient for I/O-bound applications. However, since JavaScript is single-threaded, Node.js must manage asynchronous operations carefully to avoid blocking the main thread.</p><p>Blocking the main thread means that the event loop cannot process any other events until the current operation is finished. This can result in poor performance, unresponsiveness, and high latency for the application. Therefore, Node.js uses various techniques to avoid blocking the main thread, such as callbacks, promises, async/await, and event emitters.</p><p>These techniques allow Node.js to delegate the execution of long-running or computationally intensive tasks to the system kernel or the thread pool, while continuing to process other events in the event loop. This way, Node.js can achieve concurrency and parallelism without creating multiple threads.</p><h3>Libuv and Cross-Platform Asynchronous I/O</h3><p>Libuv is a foundational component of Node.js that provides an abstraction layer for asynchronous I/O operations across various platforms. It handles file system operations, networking, child processes, and other system-related tasks. Libuv’s event loop is designed to be non-blocking, allowing Node.js to perform I/O operations without waiting for them to complete.</p><p>Libuv’s event loop works by using a combination of event-driven mechanisms and polling. For example, it can use operating system notifications (like epoll on Linux) to detect when I/O is possible, or it may resort to polling at regular intervals if those mechanisms are not available. This approach ensures that Node.js can efficiently handle a large number of simultaneous connections.</p><p>Libuv also provides a thread pool for executing some types of tasks that cannot be handled by the system kernel, such as DNS lookups, cryptography, compression, and user-defined tasks. The thread pool has a fixed size of four threads by default, but it can be configured by setting the UV_THREADPOOL_SIZE environment variable. The thread pool allows Node.js to offload some CPU-bound tasks to the background, while the main thread remains free to handle other events.</p><h3>Phases of the Event Loop in Detail</h3><p>The event loop in Node.js is divided into several distinct phases, each with its own purpose and set of tasks:</p><ol><li><strong>Timers:</strong> This phase deals with timer callbacks that have reached their scheduled time. Timers in Node.js can be used to schedule code execution after a specified delay or at specific intervals. When a timer’s time comes, its callback function is added to the event queue to be executed.</li><li>Timers are not guaranteed to execute exactly at their scheduled time, as they are subject to the availability of the system and the event loop. For example, if the event loop is busy processing other events, the timer callback may be delayed until the next iteration of the event loop. Therefore, timers should not be used for precise timing, but rather for approximate timing.</li><li>Timers are also subject to the system clock’s drift, which means that the actual time may differ from the expected time by a small margin. This can happen due to various factors, such as changes in the system time, daylight saving time, leap seconds, etc. Therefore, timers should not be used for critical operations that depend on the exact time, but rather for general operations that can tolerate some variance.</li><li><strong>I/O Callbacks:</strong> During this phase, the event loop processes I/O callbacks that are ready to run. These callbacks are triggered by completed I/O operations, such as data being received over the network or a file read operation completing. By processing these callbacks, Node.js can continue executing code without waiting for I/O to finish.</li><li>I/O callbacks are usually generated by the system kernel or the thread pool, which notify Node.js when an I/O operation is done. Node.js then adds the corresponding callback to the event queue, where it will be executed by the event loop. However, some types of I/O callbacks are deferred to the next loop iteration, such as TCP or UDP errors, or some file operations. These callbacks are handled in the pending callbacks phase, which will be discussed later.</li><li><strong>Idle, Prepare:</strong> These two phases are less commonly discussed but are still part of the event loop. The “idle” phase is where idle callbacks are executed, which are typically used for internal purposes like garbage collection. The “prepare” phase is used to prepare for the next cycle of the event loop, resetting certain variables and flags.</li><li>Idle callbacks are registered by calling process.nextTick(), which is a Node.js-specific API that allows you to schedule a callback to be executed at the end of the current operation, before the event loop moves to the next phase. This can be useful for performing some quick or urgent tasks that need to be done before the next event loop cycle.</li><li>Prepare callbacks are registered by calling process.setImmediate(), which is another Node.js-specific API that allows you to schedule a callback to be executed at the beginning of the next event loop cycle, after the poll phase. This can be useful for performing some tasks that need to be done as soon as possible, but not before the current operation finishes.</li><li><strong>Poll:</strong> This phase is the main phase of the event loop, where most of the I/O events are handled. The poll phase retrieves new I/O events from the system kernel or the thread pool, and executes their callbacks. This includes events from network connections, file operations, and other sources. The event loop will block here when there are no other events to process, waiting for new events to arrive.</li><li>The poll phase also checks if there are any timers that have expired, and executes their callbacks if there are. This means that timers can influence the duration of the poll phase, depending on how many timers are scheduled and how long they take to execute. If there are no timers or I/O events, the event loop will move to the next phase.</li><li><strong>Check:</strong> This phase executes callbacks registered by process.setImmediate(). These callbacks are executed after the poll phase and before the close callbacks phase. This phase allows Node.js to handle some tasks that need to be done as soon as possible, but not before the current operation finishes.</li><li><strong>Close Callbacks:</strong> This phase executes callbacks related to closing events, such as socket or stream closures. These callbacks are usually registered by calling socket.on(&#39;close&#39;, callback) or stream.on(&#39;end&#39;, callback). This phase allows Node.js to perform some cleanup operations and release some resources when a connection or a stream is closed.</li></ol><h3>Event Queue and Execution Context</h3><p>The event queue is a crucial part of the Node.js event loop. It holds callbacks that are ready to be executed but have been deferred due to the single-threaded nature of JavaScript. When the event loop reaches the I/O callbacks phase, it takes the first callback from the queue and executes it. If there are multiple callbacks in the queue, they are executed in the order they were added.</p><p>The event queue is divided into two types of events: microtasks and macrotasks. Microtasks are higher-priority events that are executed immediately after the current operation completes and before the event loop moves to the next phase. Microtasks are often associated with JavaScript’s concurrency model, such as promise resolutions (then, catch, finally) and process.nextTick() calls. Macrotasks are lower-priority events that are executed after the current phase of the event loop concludes. Macrotasks include operations like setTimeout(), setInterval(), and I/O callbacks.</p><p>The prioritization of events in the event queue is significant. Microtasks are always processed before macrotasks. This means that even if a macrotask arrives at the front of the queue, it cannot interrupt a series of microtasks that are already being processed. This prioritization helps ensure that short, quick operations (microtasks) do not get delayed by longer, more resource-intensive operations (macrotasks).</p><p>The execution context is another important aspect of the event loop. Each callback function runs within its own execution context, which includes its own scope, local variables, and references to the global object. This isolation ensures that callbacks do not interfere with each other, maintaining the integrity of the application’s state.</p><p>The execution context also affects the value of the this keyword inside the callback function. Depending on how the callback function is defined and invoked, the this keyword may refer to different objects. For example, if the callback function is defined as an arrow function, the this keyword will inherit the value of the outer scope. If the callback function is defined as a regular function, the this keyword will depend on how the function is called. If the function is called as a method of an object, the this keyword will refer to that object. If the function is called as a standalone function, the this keyword will refer to the global object.</p><p>Understanding the event queue and the execution context is essential for writing correct and consistent Node.js code. By knowing how events are prioritized and processed, and how the this keyword behaves, developers can avoid common pitfalls and bugs that may arise from the asynchronous nature of Node.js.</p><h3>Detailed Insight into the Event Queue in Node.js Event Loop</h3><h4>The Event Queue: A Key Component of Asynchronous Behavior</h4><p>The event queue is a critical component of the Node.js event loop. It acts as a buffer, holding events that are awaiting execution. These events originate from various sources, including timers, I/O operations, and user interactions. Once an event is generated, it is enqueued in the event queue, where it waits its turn to be processed by the event loop.</p><p>The event loop retrieves events from the front of the queue and executes them in the order they arrived. This sequential processing ensures that events are handled in a predictable manner, which is essential for maintaining the consistency of the application’s behavior.</p><p>The event queue is also responsible for managing the concurrency of the Node.js application. Since Node.js is single-threaded, it can only execute one task at a time. However, by delegating the heavy-lifting tasks to the system kernel or the thread pool, Node.js can achieve non-blocking I/O operations. This means that Node.js does not wait for the completion of an I/O operation before moving on to the next task. Instead, it registers a callback function that will be executed when the I/O operation is done. This callback function is then added to the event queue, where it will be executed by the event loop when its turn comes.</p><p>This way, Node.js can handle multiple I/O operations concurrently without blocking the main thread. This improves the scalability and performance of the Node.js application, as it can serve more requests with fewer resources.</p><h4>Microtasks and Macrotasks: Distinguishing Between Event Types</h4><p>Events in the event queue are categorized into two types: microtasks and macrotasks.</p><ol><li><strong>Microtasks:</strong> These are higher-priority tasks that are executed immediately after the current operation completes and before the event loop moves on to the next phase. Microtasks are often associated with JavaScript’s concurrency model, such as promise resolutions (then, catch, finally) and process.nextTick() calls. Since they are given immediate attention, microtasks can lead to a rapid sequence of operations that appear synchronous despite being asynchronous under the hood.</li></ol><ul><li>For example, consider the following code snippet:</li></ul><pre>console.log(&#39;A&#39;);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&#39;B&#39;);<br>});<br><br>console.log(&#39;C&#39;);</pre><ul><li>The output of this code will be:</li></ul><pre>  A<br>  C<br>  B</pre><ul><li>This is because the promise resolution callback is a microtask that is executed after the current operation (printing ‘A’ and ‘C’) finishes and before the event loop moves to the next phase. Therefore, it appears as if the callback is executed synchronously, even though it is actually an asynchronous operation.</li></ul><p>2. <strong>Macrotasks:</strong> These are lower-priority tasks that are executed after the current phase of the event loop concludes. Macrotasks include operations like setTimeout(), setInterval(), and I/O callbacks. They are considered &quot;macro&quot; because they represent larger units of work compared to microtasks and are typically used for longer-running operations.</p><ul><li>For example, consider the following code snippet:</li></ul><pre>  console.log(&#39;A&#39;);<br><br>  setTimeout(() =&gt; {<br>    console.log(&#39;B&#39;);<br>  }, 0);<br><br>  console.log(&#39;C&#39;);</pre><ul><li>The output of this code will be:</li></ul><pre>  A<br>  C<br>  B</pre><ul><li>This is because the setTimeout() callback is a macrotask that is executed after the current phase of the event loop ends. Therefore, it appears as if the callback is executed asynchronously, even though it has a zero delay.</li></ul><h3>Prioritization and Order of Execution</h3><p>The prioritization of events in the event queue is significant. Microtasks are always processed before macrotasks. This means that even if a macrotask arrives at the front of the queue, it cannot interrupt a series of microtasks that are already being processed. This prioritization helps ensure that short, quick operations (microtasks) do not get delayed by longer, more resource-intensive operations (macrotasks).</p><p>The visual representation of the event queue’s structure highlights this priority:</p><pre>+-------------------------------------------------+<br>| Event Queue                                     |<br>+-------------------------------------------------+<br>|                                                 |<br>| Microtasks                                     |<br>|                                                 |<br>+-------------------------------------------------+<br>|                                                 |<br>| Macrotasks                                     |<br>|                                                 |<br>+-------------------------------------------------+</pre><p>This diagram shows that microtasks are processed first, followed by macrotasks. This order is maintained throughout the lifecycle of the event loop, ensuring that the event queue’s contents reflect the correct execution order.</p><p>The order of execution of events in the event queue is also influenced by the phases of the event loop. The event loop has six major phases, each with its own queue of events:</p><ul><li><strong>Timers phase:</strong> This phase executes callbacks scheduled by setTimeout() and setInterval(). The event loop checks if any timers have expired and executes their callbacks accordingly.</li><li><strong>Pending callbacks phase:</strong> This phase executes I/O callbacks that were deferred to the next loop iteration. These callbacks are usually related to TCP or UDP errors, or some types of file operations.</li><li><strong>Idle, prepare phase:</strong> This phase is only used internally by the event loop for housekeeping purposes. It does not execute any user callbacks.</li><li><strong>Poll phase:</strong> This phase retrieves new I/O events and executes their callbacks. This includes events from network connections, file operations, and other sources. The event loop will block here when there are no other events to process, waiting for new events to arrive.</li><li><strong>Check phase:</strong> This phase executes callbacks registered by setImmediate(). These callbacks are executed after the poll phase and before the close callbacks phase.</li><li><strong>Close callbacks phase:</strong> This phase executes callbacks related to closing events, such as socket or stream closures.</li></ul><p>The following diagram shows a simplified overview of the event loop’s order of operations:</p><pre>┌───────────────────────────┐<br>┌─&gt;│ timers                 │<br>└─────────────┬─────────────┘<br>┌─────────────┴─────────────┐<br>│ pending callbacks         │<br>└─────────────┬─────────────┘<br>┌─────────────┴─────────────┐<br>│ idle, prepare             │<br>└─────────────┬─────────────┘<br>┌───────────────┐<br>│ ┌─────────────┴─────────────┐<br>│ incoming:                   │<br>│ │ poll │&lt;─────┤ connections,│<br>│ └─────────────┬─────────────┘<br>│ data, etc.    │<br>└───────────────┘<br>┌─────────────┴─────────────┐<br>│ check                     │<br>└─────────────┬─────────────┘<br>┌─────────────┴─────────────┐<br>└──┤ close callbacks        │<br>└───────────────────────────┘</pre><p>Each phase has its own queue of events to execute. When the event loop enters a given phase, it will perform any operations specific to that phase, then execute the events in that phase’s queue until the queue is exhausted or the maximum number of events has been executed. When the queue is empty or the limit is reached, the event loop will move to the next phase, and so on.</p><p>The order of execution of events in the event queue is also affected by the nesting of events. For example, a timer callback can enqueue a promise resolution callback, which can enqueue another timer callback, and so on. This creates a nested hierarchy of events that are executed according to their priority and phase.</p><p>The following diagram shows an example of the nesting of events in the event queue:</p><pre>+-------------------------------------------------+<br>| Event Queue                                     |<br>+-------------------------------------------------+<br>|                                                 |<br>| Microtasks                                     |<br>|                                                 |<br>| +---------------------------------------------+ |<br>| | Promise resolution callback                 | |<br>| +---------------------------------------------+ |<br>| +---------------------------------------------+ |<br>| | process.nextTick() callback                 | |<br>| +---------------------------------------------+ |<br>|                                                 |<br>+-------------------------------------------------+<br>|                                                 |<br>| Macrotasks                                     |<br>|                                                 |<br>| +---------------------------------------------+ |<br>| | Timer callback                              | |<br>| |                                             | |<br>| | +-----------------------------------------+ | |<br>| | | Promise resolution callback             | | |<br>| | +-----------------------------------------+ | |<br>| | +-----------------------------------------+ | |<br>| | | Timer callback                          | | |<br>| | |                                         | | |<br>| | | +-------------------------------------+ | | |<br>| | | | Promise resolution callback         | | | |<br>| | | +-------------------------------------+ | | |<br>| | +-----------------------------------------+ | |<br>| +---------------------------------------------+ |<br>| +---------------------------------------------+ |<br>| | I/O callback                               | |<br>| +---------------------------------------------+ |<br>|                                                 |<br>+-------------------------------------------------+</pre><p>This diagram shows that the event queue can have multiple levels of nesting, depending on the source and type of the events. The event loop will execute the events from the innermost level to the outermost level, following the microtask-macrotask priority and the phase order.</p><h3>Implications for Performance and Application Logic</h3><p>Understanding the event queue and its order of execution has implications for both the performance and the logic of Node.js applications. Since the event queue can have different types and sources of events, it is important to be aware of how they affect the event loop and the application behavior.</p><p>Some of the implications are:</p><ul><li>Since microtasks are executed before macrotasks, they can delay the execution of macrotasks if they are too many or too long. This can affect the responsiveness of the application, as it may delay the processing of user interactions, timers, or I/O events. Therefore, it is advisable to avoid creating too many microtasks or making them too long or complex. Therefore, it is advisable to use microtasks sparingly and for short, quick operations.</li><li>Since macrotasks are executed after the current phase of the event loop, they can be affected by the length and number of events in the same phase. For example, if the poll phase has a large number of I/O events to process, it may delay the execution of timers or setImmediate callbacks that are waiting in the queue. Therefore, it is advisable to avoid creating too many macrotasks or making them too long or resource-intensive.</li><li>Since the order of execution of events in the event queue depends on the priority, phase, and nesting of events, it is important to be aware of how these factors affect the application logic. For example, if a timer callback enqueues a promise resolution callback, which enqueues another timer callback, the order of execution will be different from what might be expected. Therefore, it is advisable to avoid creating too many nested events or relying on the exact timing of events.</li><li>Since the event queue is a key component of the Node.js event loop, it is also important to monitor its performance and health. For example, using tools like process.memoryUsage() or process.nextTick() can help measure the memory usage and the event loop lag of the application. These metrics can help identify potential bottlenecks or memory leaks in the event queue and the event loop.</li></ul><p>By understanding the event queue and its order of execution, developers can write more efficient and reliable Node.js applications that leverage the power of asynchronous behavior.</p><h3>Event Loop and JavaScript Execution Context in Node.js Event Loop</h3><p>In the previous section, we explored the event queue in Node.js. In this section, we will explore the relationship between the event loop and the JavaScript execution context. We will discuss how events are executed in the context of the JavaScript execution context and how the event loop affects the performance of Node.js applications.</p><h3>Relationship Between the Event Loop and JavaScript Execution Context</h3><p>The JavaScript execution context is the environment in which JavaScript code is executed. It consists of the global object, the call stack, and the variable environment.</p><p>The global object is the top-level object that provides access to built-in values and functions, such as Math, Date, console, etc. The global object also contains properties that are specific to the Node.js environment, such as process, Buffer, module, etc.</p><p>The call stack is a data structure that stores the currently executing functions. When a function is called, it is placed on the call stack. When the function returns, it is removed from the call stack. The call stack follows the last-in, first-out (LIFO) principle, meaning that the last function that was pushed onto the stack is the first one to be popped off.</p><p>The variable environment is a collection of variables and their values that are accessible within a function. Each function has its own variable environment, which is created when the function is invoked. The variable environment contains the arguments object, the local variables, and the value of the this keyword. The variable environment also has a reference to the outer variable environment, which is the variable environment of the enclosing function. This creates a chain of variable environments, also known as the scope chain.</p><p>The event loop is responsible for executing JavaScript code in the execution context. When an event occurs, the event loop places the associated callback function in the call stack. The event loop then continues executing synchronous code until the call stack is empty. Once the call stack is empty, the event loop executes the callback functions in the call stack in the order they were added.</p><h3>Call Stack Interaction</h3><p>The call stack is a data structure that stores the currently executing functions. When a function is called, it is placed on the call stack. When the function returns, it is removed from the call stack.</p><p>The event loop interacts with the call stack in the following ways:</p><ul><li>When an event occurs, the event loop places the associated callback function in the call stack.</li><li>The event loop continues executing synchronous code until the call stack is empty.</li><li>Once the call stack is empty, the event loop executes the callback functions in the call stack in the order they were added.</li></ul><p>The call stack can be visualized as a stack of plates, where each plate represents a function. When a function is called, a new plate is added to the top of the stack. When the function returns, the plate is removed from the top of the stack. The event loop can only access the plate that is on the top of the stack, which is the currently executing function.</p><p>The following diagram illustrates the call stack interaction:</p><pre>+-----------------+<br>| Event Loop      |<br>+-----------------+<br>|                 |<br>| +-------------+ |<br>| | Callback 3  | |<br>| +-------------+ |<br>| +-------------+ |<br>| | Callback 2  | |<br>| +-------------+ |<br>| +-------------+ |<br>| | Callback 1  | |<br>| +-------------+ |<br>|                 |<br>+-----------------+</pre><p>This diagram shows that the event loop has three callback functions in the call stack. The event loop will execute the callback functions from the top of the stack to the bottom of the stack, in the order they were added.</p><h3>Code Example</h3><p>The following code demonstrates the interaction between the event loop and the JavaScript execution context:</p><pre>// Define a callback function<br>const callback = () =&gt; {<br>  console.log(&#39;Callback function executed&#39;);<br>};<br>// Add the callback function to the event queue<br>setTimeout(callback, 0);<br>// Execute synchronous code<br>for (let i = 0; i &lt; 1000000; i++) {<br>  // Do something computationally expensive<br>}<br>// The callback function will be executed after the synchronous code has finished executing</pre><p>In this example, the setTimeout() function is used to add the callback function to the event queue. The for loop is used to execute synchronous code. The event loop will continue executing the synchronous code until the call stack is empty. Once the call stack is empty, the event loop will execute the callback function.</p><p>The following diagram illustrates the code execution:</p><pre>+-----------------+     +-----------------+<br>| Event Loop      |     | Event Loop      |<br>+-----------------+     +-----------------+<br>|                 |     |                 |<br>| +-------------+ |     | +-------------+ |<br>| | Callback    | |     | | Callback    | |<br>| +-------------+ |     | +-------------+ |<br>|                 |     |                 |<br>| +-------------+ |     |                 |<br>| | for loop    | |     |                 |<br>| +-------------+ |     |                 |<br>|                 |     |                 |<br>+-----------------+     +-----------------+</pre><p>This diagram shows that the event loop first executes the for loop, which is a synchronous operation. The for loop is placed on the call stack and blocks the event loop until it is finished. After the for loop is done, the event loop executes the callback function, which is an asynchronous operation. The callback function is placed on the call stack and executed by the event loop.</p><h3>Performance Implications</h3><p>The event loop can have a significant impact on the performance of Node.js applications. If the event loop is blocked, it can prevent other events from being processed. This can lead to poor performance and unresponsive applications.</p><p>There are a number of things that can block the event loop, including:</p><ul><li>Long-running synchronous operations</li><li>Uncaught exceptions</li><li>Deadlocks</li></ul><p>Long-running synchronous operations are operations that take a long time to complete and do not yield control to the event loop. For example, a for loop that iterates over a large array, a complex computation, or a blocking I/O operation. These operations can block the event loop and prevent it from executing other events.</p><p>Uncaught exceptions are errors that are not handled by a try...catch block or a Promise rejection handler. For example, a TypeError or a ReferenceError. These errors can cause the event loop to crash and terminate the Node.js process.</p><p>Deadlocks are situations where two or more operations are waiting for each other to finish, but none of them can proceed. For example, two threads that are trying to acquire the same lock, or two promises that are waiting for each other to resolve. These situations can cause the event loop to hang and stop processing events.</p><p>It is important to avoid blocking the event loop in order to ensure the performance of Node.js applications. Some of the best practices to avoid blocking the event loop are:</p><ul><li>Use asynchronous APIs whenever possible, such as fs.readFile() instead of fs.readFileSync(), or crypto.randomBytes() instead of crypto.randomBytesSync().</li><li>Break down long-running synchronous operations into smaller chunks, and use setImmediate() or process.nextTick() to defer them to the next event loop cycle.</li><li>Use error handling mechanisms, such as try...catch blocks, Promise rejection handlers, or process.on(&#39;uncaughtException&#39;) event listeners, to handle errors gracefully and prevent the event loop from crashing.</li><li>Avoid creating deadlocks by using proper synchronization mechanisms, such as locks, semaphores, or mutexes, or by avoiding circular dependencies between promises.</li></ul><p>In this section, we explored the relationship between the event loop and the JavaScript execution context. We discussed how events are executed in the context of the JavaScript execution context and how the event loop affects the performance of Node.js applications.</p><p>In the next section, we will explore non-JavaScript tasks in the event loop, such as timers and I/O operations. We will discuss how these tasks are managed within the event loop and how they can be used to build asynchronous applications.</p><h3>Non-JavaScript Tasks in the Event Loop (Timers, I/O Operations)</h3><h3>Introduction</h3><p>In addition to JavaScript code, the Node.js event loop also manages non-JavaScript tasks, such as timers and I/O operations. These tasks are handled by the libuv library, which provides an event-driven I/O framework for Node.js.</p><h3>Timers</h3><p>Timers are used to schedule functions to be executed at a specific time or after a specified delay. Node.js provides two main types of timers:</p><ul><li>setTimeout()<strong>:</strong> Schedules a function to be executed after a specified delay.</li><li>setInterval()<strong>:</strong> Schedules a function to be executed repeatedly at a specified interval.</li></ul><p>Both setTimeout() and setInterval() return a timer object that can be used to cancel the timer.</p><h3>I/O Operations</h3><p>I/O operations are used to read from and write to files, communicate with network sockets, and perform other I/O-related tasks. Node.js provides a number of built-in modules for performing I/O operations, such as the fs module for file I/O and the net module for network I/O.</p><h3>Management of Non-JavaScript Tasks in the Event Loop</h3><p>Non-JavaScript tasks are managed by the libuv library, which uses a polling mechanism to monitor for I/O events. When an I/O event occurs, libuv notifies the event loop, which then executes the appropriate callback function.</p><p>Timers are also managed by libuv. When a timer expires, libuv notifies the event loop, which then executes the associated callback function.</p><h3>Examples of Using Timers and I/O Operations</h3><p>Here are some examples of how timers and I/O operations can be used in Node.js applications:</p><ul><li><strong>Using </strong>setTimeout()<strong> to delay the execution of a function:</strong></li></ul><pre>setTimeout(() =&gt; {<br>  console.log(&#39;Hello, world!&#39;);<br>}, 1000);</pre><ul><li><strong>Using </strong>setInterval()<strong> to execute a function repeatedly:</strong></li></ul><pre>setInterval(() =&gt; {<br>  console.log(&#39;Hello, world!&#39;);<br>}, 1000);</pre><ul><li><strong>Using the </strong>fs<strong> module to read a file:</strong></li></ul><pre>const fs = require(&#39;fs&#39;);<br>fs.readFile(&#39;file.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  if (err) {<br>    console.error(err);<br>    return;<br>  }<br>  console.log(data);<br>});</pre><ul><li><strong>Using the </strong>net<strong> module to create a TCP server:</strong></li></ul><pre>const net = require(&#39;net&#39;);<br>const server = net.createServer((socket) =&gt; {<br>  socket.on(&#39;data&#39;, (data) =&gt; {<br>    console.log(data.toString());<br>  });<br>});<br>server.listen(3000);</pre><p>Non-JavaScript tasks, such as timers and I/O operations, are an important part of the Node.js event loop. These tasks are managed by the libuv library, which uses a polling mechanism to monitor for I/O events. Timers are used to schedule functions to be executed at a specific time or after a specified delay, while I/O operations are used to read from and write to files, communicate with network sockets, and perform other I/O-related tasks.</p><h3>Advanced Topics: Microtask Queue and Macrotask Queue in Node.js</h3><p>In the previous section, we explored non-JavaScript tasks in the event loop, such as timers and I/O operations. In this section, we will take a deeper dive into the microtask queue and the macrotask queue in Node.js. We will discuss the differences between these two queues, their use cases, and how they can be used to improve the performance of Node.js applications.</p><h3>Deep Dive into Microtask Queue (process.nextTick, Promises)</h3><p>The microtask queue is a queue of tasks that are executed before the event loop continues to the next phase. Microtasks are typically generated by JavaScript code, such as promises and process.nextTick().</p><p><strong>process.nextTick()</strong></p><p>The process.nextTick() function is used to schedule a function to be executed in the next tick of the event loop. This means that the function will be executed before any other tasks in the event loop, including I/O callbacks and timers.</p><p>The following code demonstrates how to use process.nextTick():</p><pre>process.nextTick(() =&gt; {<br>  console.log(&#39;Microtask executed&#39;);<br>});<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Macrotask executed&#39;);<br>}, 0);</pre><p>In this example, the process.nextTick() function is used to schedule a function to be executed in the next tick of the event loop. The setTimeout() function is used to schedule a function to be executed after a delay of 0 milliseconds.</p><p>The output of this code will be:</p><pre>Microtask executed<br>Macrotask executed</pre><p>This demonstrates that microtasks are executed before macrotasks, even if the macrotask is scheduled to be executed first.</p><p><strong>Promises</strong></p><p>Promises are another way to generate microtasks. When a promise is resolved or rejected, the associated callback function is placed in the microtask queue.</p><p>The following code demonstrates how to use promises to generate microtasks:</p><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Promise resolved&#39;);<br>  }, 0);<br>});<br><br>promise.then((result) =&gt; {<br>  console.log(result);<br>});</pre><p>In this example, a promise is created and a callback function is attached to it using the then() method. The setTimeout() function is used to schedule the resolution of the promise after a delay of 0 milliseconds.</p><p>The output of this code will be:</p><pre>Promise resolved</pre><p>This demonstrates that the callback function attached to the promise is executed in the next tick of the event loop, even though the promise is resolved asynchronously.</p><h3>Deep Dive into Macrotask Queue (setImmediate, setTimeout, setInterval)</h3><p>The macrotask queue is a queue of tasks that are executed after the event loop continues to the next phase. Macrotasks are typically generated by I/O operations, such as setTimeout() and setInterval().</p><p><strong>setImmediate()</strong></p><p>The setImmediate() function is used to schedule a function to be executed in the next tick of the event loop, after all microtasks have been executed. This means that the function will be executed before any I/O callbacks or timers.</p><p>The following code demonstrates how to use setImmediate():</p><pre>setImmediate(() =&gt; {<br>  console.log(&#39;Macrotask executed&#39;);<br>});<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Macrotask executed&#39;);<br>}, 0);</pre><p>In this example, the setImmediate() function is used to schedule a function to be executed in the next tick of the event loop, after all microtasks have been executed. The setTimeout() function is used to schedule a function to be executed after a delay of 0 milliseconds.</p><p>The output of this code will be:</p><pre>Macrotask executed<br>Macrotask executed</pre><p>This demonstrates that macrotasks are executed after microtasks, even if the macrotask is scheduled to be executed first.</p><p><strong>setTimeout() and setInterval()</strong></p><p>The setTimeout() and setInterval() functions are used to schedule functions to be executed after a specified delay or at a specified interval. These functions are typically used to perform I/O operations or to schedule periodic tasks.</p><p>The following code demonstrates how to use setTimeout() and setInterval():</p><pre>setTimeout(() =&gt; {<br>  console.log(&#39;Macrotask executed&#39;);<br>}, 0);<br><br>setInterval(() =&gt; {<br>  console.log(&#39;Macrotask executed&#39;);<br>}, 1000);</pre><p>In this example, the setTimeout() function is used to schedule a function to be executed after a delay of 0 milliseconds. The setInterval() function is used to schedule a function to be executed every 1000 milliseconds.</p><p>The output of this code will be:</p><pre>Macrotask executed<br>Macrotask executed<br>Macrotask executed<br>...</pre><p>This demonstrates that setTimeout() and setInterval() schedule macrotasks that are executed after all microtasks have been executed.</p><h3>Comparisons and Use Cases for Microtasks and Macrotasks</h3><p>Microtasks and macrotasks are two types of events that are processed by the event loop in Node.js. They have different use cases and performance characteristics, depending on their priority and execution order.</p><p><strong>Microtasks</strong></p><p>Some of the use cases for microtasks are:</p><ul><li>Updating the UI: Microtasks can be used to update the UI in response to user input or data changes. For example, when a user clicks a button, a microtask can be used to change the button’s color or text. This way, the UI can reflect the user’s action without waiting for the next event loop cycle.</li><li>Handling user input: Microtasks can be used to handle user input events, such as keyboard or mouse events. For example, when a user types a character, a microtask can be used to validate the input or provide autocomplete suggestions. This way, the user can get immediate feedback without any noticeable delay.</li><li>Resolving promises: Microtasks can be used to resolve promises, which are objects that represent the outcome of an asynchronous operation. For example, when a promise is fulfilled or rejected, a microtask can be used to execute the corresponding then, catch, or finally handler. This way, the promise resolution can be handled as soon as possible, without blocking the event loop.</li></ul><p>Some of the performance characteristics of microtasks are:</p><ul><li>Executed before macrotasks: Microtasks are always processed before macrotasks. This means that even if a macrotask arrives at the front of the queue, it cannot interrupt a series of microtasks that are already being processed. This prioritization helps ensure that short, quick operations (microtasks) do not get delayed by longer, more resource-intensive operations (macrotasks).</li><li>Can be used to improve the responsiveness of an application: Microtasks can be used to improve the responsiveness of an application, as they can provide immediate feedback to the user or update the UI without waiting for the next event loop cycle. However, microtasks should be used sparingly and for short, quick operations, as too many microtasks can block the event loop and prevent other events from being processed.</li></ul><p><strong>Macrotasks</strong></p><p>Some of the use cases for macrotasks are:</p><ul><li>Performing I/O operations: Macrotasks can be used to perform I/O operations, such as reading or writing files, sending or receiving data over the network, or accessing databases. For example, when an I/O operation is completed, a macrotask can be used to execute the corresponding callback function. This way, the I/O operation can be performed without blocking the main thread, while the callback function can be executed when the event loop is ready.</li><li>Scheduling periodic tasks: Macrotasks can be used to schedule periodic tasks, such as timers or intervals. For example, when a timer or an interval is due, a macrotask can be used to execute the corresponding callback function. This way, the periodic task can be performed at regular intervals, without blocking the event loop.</li><li>Running long-running tasks: Macrotasks can be used to run long-running tasks, such as complex computations, heavy processing, or user-defined tasks. For example, when a long-running task is completed, a macrotask can be used to execute the corresponding callback function. This way, the long-running task can be performed in the background, while the callback function can be executed when the event loop is ready.</li></ul><p>Some of the performance characteristics of macrotasks are:</p><ul><li>Executed after microtasks: Macrotasks are executed after microtasks. This means that even if a microtask enqueues a macrotask, the macrotask will not be executed until the next event loop cycle. This prioritization helps ensure that higher-priority operations (microtasks) are executed before lower-priority operations (macrotasks).</li><li>Can block the event loop: Macrotasks can block the event loop, as they can take a long time to complete and prevent other events from being processed. This can affect the responsiveness of the application, as it may delay the processing of user input, timers, or I/O events. Therefore, macrotasks should be used carefully and for longer-running operations, as too many macrotasks can cause the event loop to lag or hang.</li></ul><p>In this section, we took a deeper dive into the microtask queue and the macrotask queue in Node.js. We discussed the differences between these two queues, their use cases, and how they can be used to improve the performance of Node.js applications.</p><p>In the next section, we will discuss common pitfalls and misconceptions about using microtasks and macrotasks in Node.js. We will also provide some best practices for using these features effectively.</p><h3>Common Pitfalls and Misconceptions Node.js Event Loop</h3><p>In the previous section, we took a deeper dive into the microtask queue and the macrotask queue in Node.js. We discussed the differences between these two queues, their use cases, and how they can be used to improve the performance of Node.js applications.</p><p>In this section, we will discuss common pitfalls and misconceptions about using microtasks and macrotasks in Node.js. We will also provide some best practices for using these features effectively.</p><h3>Common Misconceptions</h3><p>Here are some common misconceptions about the event loop in Node.js:</p><ul><li><strong>Misconception 1:</strong> The event loop runs in a separate thread.</li></ul><p><strong>Reality:</strong> The event loop runs in the same thread as the JavaScript code. This means that any blocking operation in the JavaScript code can block the event loop and prevent it from processing events.</p><ul><li><strong>Misconception 2:</strong> All asynchronous operations are handled by the event loop.</li></ul><p><strong>Reality:</strong> Not all asynchronous operations are handled by the event loop. For example, long-running I/O operations are typically handled by worker threads.</p><ul><li><strong>Misconception 3:</strong> The event loop is a stack or queue.</li></ul><p><strong>Reality:</strong> The event loop is not a stack or queue. It is a set of phases that are executed in a round-robin manner. This means that the event loop can process multiple events concurrently.</p><h3>Common Pitfalls</h3><p>Here are some common pitfalls that developers encounter when working with the event loop in Node.js:</p><ul><li><strong>Callback hell:</strong> This occurs when a developer uses nested callbacks to handle asynchronous operations, resulting in code that is difficult to read and debug.</li><li><strong>Race conditions:</strong> This occurs when multiple asynchronous operations are executed concurrently and the order in which they complete is not deterministic, leading to unexpected results.</li><li><strong>Deadlocks:</strong> This occurs when two or more asynchronous operations wait for each other to complete, resulting in a situation where neither operation can progress.</li></ul><h3>Best Practices</h3><p>Here are some best practices for working with the event loop in Node.js:</p><ul><li><strong>Use promises or async/await:</strong> These constructs allow developers to write asynchronous code in a more synchronous style, making it easier to read and debug.</li><li><strong>Use concurrency control mechanisms:</strong> This includes using locks, mutexes, or semaphores to ensure that asynchronous operations are executed in a controlled manner.</li><li><strong>Design your code to be resilient to failures:</strong> This includes handling errors gracefully and implementing retry mechanisms to ensure that asynchronous operations are eventually successful.</li></ul><p>In this section, we discussed common pitfalls and misconceptions about using microtasks and macrotasks in Node.js. We also provided some best practices for using these features effectively.</p><p>By following these best practices, developers can avoid common pitfalls and write asynchronous code that is reliable, scalable, and easy to maintain.</p><h3>Conclusion</h3><p>In this comprehensive guide, we have delved into the intricacies of the Node.js event loop, exploring its fundamental concepts, implementation details, and practical applications. We have gained a deeper understanding of how the event loop manages asynchronous operations, enabling Node.js to handle multiple concurrent requests efficiently.</p><p>As we conclude this journey, it is important to emphasize the significance of the event loop in building scalable and responsive applications. By mastering the concepts and best practices discussed in this blog, developers can harness the full potential of Node.js and create applications that excel in performance and reliability.</p><p>Remember, the event loop is a fundamental building block of Node.js, and mastering it is essential for writing high-performance and scalable applications. Embrace the asynchronous nature of Node.js, leverage the power of the event loop, and unlock the full potential of this versatile platform.</p><p>Happy coding!</p><p><a href="https://thinhdanggroup.github.io/nodejs-event-loop/">Diving into the Node.js Event Loop</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eff3fa1b874" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining LLM Applications with LiteLLM Proxy: A Comprehensive Guide]]></title>
            <link>https://medium.com/@thinhda/streamlining-llm-applications-with-litellm-proxy-a-comprehensive-guide-875122c00974?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/875122c00974</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[litellm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agi]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 02:48:03 GMT</pubDate>
            <atom:updated>2023-12-08T02:48:03.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwytEttQZYhEWLirQz-46g.jpeg" /><figcaption>LiteLLM</figcaption></figure><p>This comprehensive guide will delve into the world of LiteLLM Proxy, a crucial component in LLM applications. We’ll start with an introduction to LiteLLM Proxy, exploring its purpose and the role it plays in LLM applications. We’ll then take a deep dive into understanding the functions of LiteLLM Proxy, including its ability to handle requests for multiple LLM models, provide a consistent input/output format, error handling, logging, token usage &amp; spend tracking, and streaming &amp; async support. Real-world examples will be provided to illustrate how LiteLLM Proxy can be used in various scenarios. Next, we’ll guide you through the process of setting up LiteLLM Proxy, including how to deploy it and run it with Docker. We’ll also provide tips for troubleshooting common setup issues. The blog post will then explore the advanced usage of LiteLLM Proxy, discussing how to optimize it for performance, secure it, scale it for large applications, and what future developments and improvements are in store for LiteLLM Proxy. By the end of this guide, you’ll have a thorough understanding of LiteLLM Proxy and its significant role in streamlining LLM applications.</p><h3>Introduction to LiteLLM Proxy</h3><p>LiteLLM Proxy is a significant component of the LiteLLM model I/O library, aimed at standardizing API calls to various services such as Azure, Anthropic, OpenAI, and others. It’s a middleware that acts as an intermediary between the client application and the language model API services. The primary purpose of LiteLLM Proxy is to streamline and simplify the process of making API calls to these services. It abstracts away the complexity of interacting with different APIs by providing a unified interface and additional features like caching.</p><p>In LLM (Language Model Microservice) applications, LiteLLM Proxy plays a crucial role. It handles the standardization of API calls, manages the API keys and credentials, and provides additional functionality like caching and rate limiting. It serves as a central place to manage integrations with multiple LLM models. It provides a consistent input/output format for calling all models using the OpenAI format. It also handles error handling using model fallbacks, logging of requests and responses, token usage and spend tracking, caching, and streaming and async support for text responses.</p><p>Throughout this blog, we will explore how LiteLLM Proxy can handle cross-cutting concerns in LLM applications. We will delve into understanding the functions of LiteLLM Proxy, such as handling requests for multiple LLM models, providing a consistent input/output format, error handling, logging, token usage &amp; spend tracking, and streaming &amp; async support. We will also provide examples of how to use LiteLLM Proxy in different scenarios, such as making /chat/completions requests for different models.</p><p>Furthermore, we will guide you on how to set up LiteLLM Proxy locally and deploy it. We will explain how to run LiteLLM Proxy with Docker. Lastly, we will discuss how LiteLLM Proxy can handle cross-cutting concerns like logging, error handling, and consistent input/output format. We will provide examples of how these cross-cutting concerns are handled in LiteLLM Proxy.</p><p>Stay with us as we embark on this journey to explore the capabilities of LiteLLM Proxy and how it can be a game-changer in your LLM applications.</p><h3>Understanding LiteLLM Proxy</h3><p>LiteLLM Proxy is a versatile tool that offers a multitude of functionalities aimed at enhancing the user experience while interacting with various LLM models. Let’s delve into these functionalities and understand how they can be used in real-world scenarios.</p><h3>Handling Requests for Multiple LLM Models</h3><p>One of the key features of LiteLLM Proxy is its ability to handle requests for multiple LLM models. It can make /chat/completions requests for more than 50 LLM models, including Azure, OpenAI, Replicate, Anthropic, and Hugging Face. This feature allows users to interact with multiple models through a single interface, greatly simplifying the process.</p><p>For instance, consider a scenario where you are developing an application that utilizes multiple LLM models. Instead of writing separate code to handle requests for each model, you can use LiteLLM Proxy to manage all requests. This not only reduces the complexity of your code but also makes it easier to maintain and update.</p><h3>Consistent Input/Output Format</h3><p>LiteLLM Proxy uses the OpenAI format for all models. This means that regardless of the LLM model you are interacting with, the format for sending requests and receiving responses remains consistent. Specifically, text responses are available at [&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;].</p><p>This feature is particularly useful when you are dealing with different models. For example, if you are developing an application that uses both Azure and OpenAI models, you do not need to write separate code for handling the input/output format for each model. Instead, you can use the same format for all models, making your code cleaner and more efficient.</p><h3>Error Handling</h3><p>Error handling is a crucial aspect of any application, and LiteLLM Proxy excels in this regard. It uses model fallbacks for error handling. If a model fails, it tries another model as a fallback.</p><p>Consider a scenario where your application makes a request to a specific LLM model, but the model fails to respond due to some issue. In such a case, LiteLLM Proxy will automatically try another model as a fallback, ensuring that your application continues to function smoothly without any interruptions.</p><h3>Logging</h3><p>LiteLLM Proxy is equipped with robust logging capabilities. It can log requests, responses, and errors to various providers such as Supabase, Posthog, Mixpanel, Sentry, LLMonitor, Traceloop, and Helicone.</p><p>Logging is crucial for monitoring the performance of your application and troubleshooting any issues. With LiteLLM Proxy, you can easily keep track of all the requests and responses, and quickly identify and resolve any errors.</p><h3>Token Usage &amp; Spend Tracking</h3><p>LiteLLM Proxy provides the feature of tracking the input and completion tokens used, as well as the spend per model. This feature is particularly useful when you are dealing with multiple models and want to keep track of the usage and expenditure for each model.</p><h3>Streaming &amp; Async Support</h3><p>Last but not least, LiteLLM Proxy supports streaming and async by returning generators to stream text responses. This feature can be extremely useful when dealing with large amounts of text data, as it allows for real-time processing.</p><p>In conclusion, LiteLLM Proxy is a powerful tool that offers a wide range of functionalities to streamline and enhance the user experience while interacting with various LLM models. Its ability to handle requests for multiple models, provide a consistent input/output format, handle errors, log data, track token usage and spend, and support streaming and async makes it an indispensable tool for any LLM application.</p><p>In the next section, we will guide you on how to set up LiteLLM Proxy and get it up and running on your local machine.</p><h3>Setting Up LiteLLM Proxy</h3><p>Setting up LiteLLM Proxy involves a few steps that require a basic understanding of command-line interfaces and Python. In this section, we will guide you through the process of setting up LiteLLM Proxy on your local machine, deploying it, and running it with Docker. We will also provide some tips for troubleshooting common setup issues.</p><h3>Setting Up LiteLLM Proxy Locally</h3><p>To set up LiteLLM Proxy locally, follow these steps:</p><ol><li>Install liteLLM-proxy using pip:</li></ol><pre>pip install litellm[proxy]</pre><p>or</p><pre>pip install &#39;litellm[proxy]&#39;</pre><p>2. Start the LiteLLM Proxy:</p><pre>litellm --model huggingface/bigcode/starcoder</pre><p>3. Make a request to the LiteLLM Proxy:</p><pre>curl --location &#39;http://0.0.0.0:8000/chat/completions&#39; \<br>    --header &#39;Content-Type: application/json&#39; \<br>    --data &#39; {<br>    &quot;model&quot;: &quot;gpt-3.5-turbo&quot;,<br>    &quot;messages&quot;: [<br>        {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;what llm are you&quot;<br>        }<br>    ]<br>}&#39;</pre><h3>Deploying LiteLLM Proxy</h3><p>Once you have set up LiteLLM Proxy locally, you might want to deploy it to a live server. Here are a few options for deploying LiteLLM Proxy:</p><ol><li><strong>Railway</strong>: You can deploy LiteLLM Proxy to Railway by following the deployment guide provided in the repository’s documentation.</li><li><strong>Cloud Providers (GCP, AWS, Azure)</strong>: LiteLLM Proxy can be deployed to any of these cloud providers by containerizing the application and deploying it to a cloud service like Google Kubernetes Engine (GKE), Amazon Elastic Container Service (ECS), or Azure Kubernetes Service (AKS).</li><li><strong>Self-hosting</strong>: You can also deploy LiteLLM Proxy on your own infrastructure by building and running the Docker container locally or on a server.</li></ol><p>Choose the deployment option that best suits your needs and infrastructure.</p><h3>Running LiteLLM Proxy with Docker</h3><p>If you prefer to use Docker, you can run LiteLLM Proxy using Docker. Here’s how:</p><ol><li>Pull the litellm ghcr docker image</li><li>See the latest available ghcr docker image here: <a href="https://github.com/berriai/litellm/pkgs/container/litellm">https://github.com/berriai/litellm/pkgs/container/litellm</a></li></ol><pre>docker pull ghcr.io/berriai/litellm:main-v1.10.1</pre><p>2. Run the Docker Image</p><pre>docker run ghcr.io/berriai/litellm:main-v1.10.0</pre><p>3. Run the Docker Image with LiteLLM CLI args</p><p>4. See all supported CLI args <a href="https://docs.litellm.ai/docs/proxy/cli">here</a></p><p>5. Here’s how you can run the docker image and pass your config to litellm</p><pre>docker run ghcr.io/berriai/litellm:main-v1.10.0 --config your_config.yaml</pre><p>6. Here’s how you can run the docker image and start litellm on port 8002 with num_workers=8</p><pre>docker run ghcr.io/berriai/litellm:main-v1.10.0 --port 8002 --num_workers 8</pre><h3>Troubleshooting Common Setup Issues</h3><p>If you encounter any issues during the setup of LiteLLM Proxy, here are some common troubleshooting steps:</p><ol><li>Make sure you have the correct versions of Python and the required dependencies installed.</li><li>Check if there are any conflicting processes running on port 8000, which is the default port for LiteLLM Proxy.</li><li>Review the LiteLLM Proxy documentation and GitHub repository for any reported issues or solutions.</li><li>If the issue persists, consider opening a GitHub issue or reaching out to the LiteLLM Proxy team for support.</li></ol><p>By following these steps, you should be able to set up and run LiteLLM Proxy without any issues. In the next section, we will explore how LiteLLM Proxy handles cross-cutting concerns in LLM applications.</p><h3>Advanced Usage of LiteLLM Proxy</h3><p>In this section, we will explore the advanced features of LiteLLM Proxy, including performance optimization, security measures, scalability for large applications, and future developments and improvements.</p><h3>Optimizing LiteLLM Proxy for Performance</h3><p>Performance optimization is crucial in ensuring a smooth and efficient user experience. LiteLLM Proxy offers several features to enhance its performance:</p><ol><li><strong>Caching</strong>: Enabling caching in LiteLLM Proxy can significantly reduce response time for subsequent requests.</li><li><strong>Custom Rate Limits</strong>: Setting custom rate limits based on your application’s requirements can prevent overloading the system and ensure optimal performance.</li><li><strong>Retries</strong>: Configuring LiteLLM Proxy to automatically retry failed requests can help handle temporary network issues and improve the overall success rate.</li><li><strong>Streaming</strong>: Streaming the responses from LiteLLM Proxy instead of waiting for the complete response can improve the perceived performance of your application.</li><li><strong>Network Communication Optimization</strong>: Minimizing unnecessary network requests and reducing the payload size can improve response times.</li></ol><p>By implementing these optimization techniques, you can ensure that LiteLLM Proxy performs at its best and delivers a seamless user experience.</p><h3>Securing LiteLLM Proxy</h3><p>Security is a paramount concern when dealing with applications that handle sensitive data. Here are some best practices to secure LiteLLM Proxy:</p><ol><li><strong>Use HTTPS</strong>: Always use HTTPS to encrypt the communication between your application and LiteLLM Proxy.</li><li><strong>Implement Access Controls</strong>: Use authentication mechanisms such as API keys or tokens to control access to LiteLLM Proxy.</li><li><strong>Enable Rate Limiting</strong>: Implement rate limiting to prevent abuse and protect LiteLLM Proxy from excessive requests.</li><li><strong>Validate User Input</strong>: Sanitize and validate user input to prevent malicious requests or injection attacks.</li><li><strong>Regularly Update LiteLLM Proxy</strong>: Keep LiteLLM Proxy up to date with the latest security patches and updates.</li></ol><p>By following these security practices, you can ensure that LiteLLM Proxy is secure and protected against potential threats.</p><h3>Scaling LiteLLM Proxy for Large Applications</h3><p>As your application grows, so does the demand on your resources. Here are some strategies to scale LiteLLM Proxy for large applications:</p><ol><li><strong>Load Balancing</strong>: Distribute incoming requests across multiple LiteLLM Proxy instances using load balancing techniques.</li><li><strong>Horizontal Scaling</strong>: Add more LiteLLM Proxy instances to your infrastructure to handle increased traffic and workload.</li><li><strong>Auto-Scaling</strong>: Implement auto-scaling based on the demand and usage patterns of your application.</li><li><strong>Caching</strong>: Utilize caching mechanisms to reduce the load on LiteLLM Proxy.</li><li><strong>Optimize Database and Storage</strong>: Ensure that the underlying database and storage systems can handle the increased load.</li></ol><p>By adopting these scaling strategies, you can ensure that LiteLLM Proxy can handle the demands of large applications and provide a reliable and responsive experience to users.</p><h3>Future Developments and Improvements in LiteLLM Proxy</h3><p>LiteLLM Proxy is continuously evolving, and there are several future developments and improvements planned for the tool. Some of the key areas of focus include:</p><ol><li><strong>Enhanced Performance</strong>: The LiteLLM team is working on further optimizing the performance of the proxy, reducing latency, and improving response times.</li><li><strong>Expanded Integration Support</strong>: LiteLLM Proxy plans to add support for more API providers, allowing developers to easily integrate with a wide range of services.</li><li><strong>Advanced Caching Options</strong>: The team is exploring additional caching strategies and options to improve the overall caching capabilities of LiteLLM Proxy.</li><li><strong>Security Enhancements</strong>: LiteLLM Proxy will continue to prioritize security and introduce new features to enhance the security posture of the tool.</li><li><strong>Developer Experience Improvements</strong>: The LiteLLM team aims to enhance the developer experience by providing better documentation, tutorials, and examples to facilitate easier integration and usage of LiteLLM Proxy.</li></ol><p>By investing in these future developments and improvements, LiteLLM Proxy aims to provide an even more robust and feature-rich solution for developers.</p><p>In conclusion, LiteLLM Proxy is a powerful tool with a wide range of advanced features. By understanding how to optimize its performance, secure it, scale it for large applications, and keep abreast of future developments and improvements, you can maximize the benefits of using LiteLLM Proxy in your LLM applications.</p><h3>Conclusion</h3><p>Throughout this blog, we have explored the various aspects of LiteLLM Proxy and its impact on LLM applications. We started with an introduction to LiteLLM Proxy, understanding its purpose, role, and the myriad of functionalities it offers. We then delved into the process of setting up LiteLLM Proxy locally, deploying it, and running it with Docker. Lastly, we explored the advanced usage of LiteLLM Proxy, focusing on performance optimization, security measures, scalability for large applications, and future developments and improvements.</p><p>LiteLLM Proxy is a powerful tool that serves as a middleware between the client application and the language model API services. It simplifies the process of making API calls to various services by abstracting away the complexity and providing a unified interface. Its ability to handle requests for multiple LLM models, provide a consistent input/output format, handle errors, log data, track token usage and spend, and support streaming and async makes it an indispensable tool for any LLM application.</p><p>By understanding how to optimize its performance, secure it, scale it for large applications, and keep abreast of future developments and improvements, developers can maximize the benefits of using LiteLLM Proxy. It not only enhances the user experience but also improves the efficiency and reliability of LLM applications.</p><p>In conclusion, LiteLLM Proxy is a game-changer in the world of LLM applications. It streamlines the process of interacting with various LLM models, thereby allowing developers to focus more on building quality applications. Whether you are a seasoned developer or a beginner venturing into the world of LLM applications, LiteLLM Proxy is a tool you should definitely consider adding to your toolbox.</p><p><a href="https://thinhdanggroup.github.io/litellm-proxy/">Streamlining LLM Applications with LiteLLM Proxy: A Comprehensive Guide</a></p><h3>References</h3><ul><li><a href="https://www.linkedin.com/posts/reffajnaahsi_llm-index-model-overview-and-comparison-activity-7120077401815990272-GFmA">LinkedIn</a></li><li><a href="https://docs.helicone.ai/getting-started/integration-method/litellm">Helicone</a></li><li><a href="https://www.linkedin.com/posts/reffajnaahsi_litellm-proxy-now-handles-500-requests-activity-7135502298193006592-6IPg?trk=public_profile_like_view">LinkedIn</a></li><li><a href="https://github.com/microsoft/autogen/issues/46">GitHub</a></li><li><a href="https://github.com/BerriAI/liteLLM-proxy">GitHub</a></li><li><a href="https://news.ycombinator.com/item?id=37095542">Hacker News</a></li><li><a href="https://github.com/BerriAI/liteLLM-proxy">GitHub</a></li><li><a href="https://news.ycombinator.com/item?id=37095542">Hacker News</a></li><li><a href="https://docs.helicone.ai/getting-started/integration-method/litellm">Helicone</a></li><li><a href="https://docs.litellm.ai/docs/routing">LiteLLM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875122c00974" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal vs Airflow: A Comparative Analysis]]></title>
            <link>https://medium.com/@thinhda/temporal-vs-airflow-a-comparative-analysis-915d2954f592?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/915d2954f592</guid>
            <category><![CDATA[temporal]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 04:31:08 GMT</pubDate>
            <atom:updated>2023-11-04T04:31:08.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XQ1M6hw9dA3wWJe0uah_Q.jpeg" /></figure><p>In this blog post, we will delve into a comparative analysis of two popular workflow orchestration platforms, Temporal and Airflow. By understanding their basic concepts, key features, and differences, we will gain a comprehensive overview of these tools. We will then explore the pros and cons of using Temporal and Airflow, providing a balanced view of their advantages and disadvantages. Real-world applications and use cases of Temporal and Airflow will be highlighted to demonstrate their practicality and effectiveness. Finally, we will provide guidance on when to use Temporal and when to use Airflow, and discuss the factors to consider when choosing between the two. This blog post will serve as a valuable resource for anyone looking to make an informed decision on which workflow orchestration platform to use.</p><h3>Introduction</h3><p>In the world of data engineering and workflow management, there are two popular platforms that are often compared — Temporal and Airflow. Both of these platforms are designed to help engineers author, schedule, and monitor workflows, but they have different features and use cases that make them suitable for different scenarios. Understanding the differences between these two platforms can help you make an informed decision about which one to use for your specific needs.</p><p>Temporal is a workflow orchestration framework that allows you to automate business workflows and track them, supporting triggering workflows via APIs and multiple concurrent workflow runs. On the other hand, Airflow is a platform used to programmatically author, schedule, and monitor workflows. While Temporal focuses on creating triggers based on time delays, Airflow provides a more comprehensive platform for workflow management.</p><p>In this blog post, we will delve deeper into the basic concepts of Temporal and Airflow, their pros and cons, and their use cases. By the end of this post, you should have a clear understanding of these two platforms and be able to decide which one is the best fit for your workflow management needs.</p><p>Stay with me as we unravel the intricacies of these two powerful workflow management platforms.</p><h3>Understanding the Basics of Temporal and Airflow</h3><p>Before we delve into the differences between Temporal and Airflow, it’s essential to understand the basic concepts of these two platforms, their key features, and how they work.</p><h3>Temporal</h3><p>Temporal is a robust workflow orchestration platform that allows you to automate business workflows and track them. It supports triggering workflows via APIs and multiple concurrent workflow runs. Some of Temporal’s key features include:</p><ol><li>Support for long-running workflows that can span multiple days or even months.</li><li>Fault-tolerance and automatic retries for failed tasks.</li><li>Scalability to handle high-throughput workloads.</li><li>Visibility into workflow execution and history.</li><li>Support for temporal queries and event-driven workflows.</li></ol><p>Temporal workflows are dynamic and can handle multi-step core business logic. They can send or wait for signals from external processes and can notify a human or launch a process for intervention. Temporal also supports always running workflows to model the lifecycle of various entities.</p><h3>Airflow</h3><p>On the other hand, Airflow is a platform used to programmatically author, schedule, and monitor workflows. It is primarily focused on Python and allows you to define complex workflows as code, manage dependencies between tasks, and monitor the execution of workflows. Some of the key features of Airflow include:</p><ol><li>Directed Acyclic Graph (DAG) based workflow definition.</li><li>Dynamic and flexible task scheduling.</li><li>Support for dependencies and triggers between tasks.</li><li>Extensibility through custom operators and hooks.</li><li>Integration with external systems and services.</li><li>Monitoring and logging of workflow execution.</li></ol><p>Airflow workflows can handle fixed workflows such as fetching data from a website and loading it into a database. However, it may be less flexible for more complex workflows where each entry needs to be processed in a certain way and trigger new workflows based on conditions.</p><h3>Differences Between Temporal and Airflow</h3><p>Although Temporal and Airflow are both workflow orchestration platforms, they have some key differences:</p><ol><li>Language and runtime support: Temporal supports multiple languages and runtimes, while Airflow is primarily focused on Python.</li><li>Workflow execution model: Temporal uses a stateful execution model where the workflow state is managed by the Temporal service, while Airflow uses a stateless execution model where the state is stored in a separate metadata database.</li><li>Fault-tolerance and retries: Temporal provides built-in fault-tolerance and automatic retries for failed tasks, while Airflow relies on external systems for fault-tolerance.</li><li>Visibility and monitoring: Temporal provides rich visibility into workflow execution and history, while Airflow has a web-based UI for monitoring workflows.</li><li>Event-driven workflows: Temporal has built-in support for event-driven workflows, while Airflow requires external systems for event triggering.</li></ol><p>In the next section, we will discuss the pros and cons of each platform to give you a better understanding of their strengths and weaknesses.</p><h3>Pros and Cons of Temporal and Airflow</h3><p>Understanding the advantages and disadvantages of both Temporal and Airflow can provide valuable insights into which platform may be better suited for your specific use cases. Let’s explore these in detail.</p><h3>Advantages of Temporal</h3><p>Temporal offers several benefits that make it a compelling choice for workflow orchestration:</p><ol><li><strong>Better Lifecycle Management</strong>: Temporal provides robust support for long-running workflows, including automatic retries for failed tasks and visibility into workflow execution and history.</li><li><strong>Polyglot Support</strong>: Unlike Airflow, which is primarily Python-based, Temporal supports multiple languages, allowing you to write a workflow in one language and its activities in others.</li><li><strong>Signals and Queries</strong>: Temporal supports signals and queries, enabling more dynamic and interactive workflows.</li><li><strong>Low Latency</strong>: Temporal is designed for relatively low latency, making it suitable for high-throughput workloads.</li><li><strong>Ease of Deployment Management</strong>: Compared to Airflow, managing deployments for Temporal workflows is much easier, especially when multiple projects with conflicting dependencies are involved.</li></ol><h3>Disadvantages of Temporal</h3><p>While Temporal has many advantages, it does not come without its challenges.</p><ul><li>Learning curve: Temporal has a steep learning curve, especially for developers who are new to workflow orchestration.</li></ul><h3>Advantages of Airflow</h3><p>Airflow also offers several benefits that make it a popular choice for workflow management:</p><ol><li><strong>Existing Integrations</strong>: Airflow has many pre-built integrations for tasks such as importing data from GCS to BigQuery, copying data from Postgres to GCS, and working with KubernetesPodOperator.</li><li><strong>Better for ETL Jobs</strong>: Due to its existing integrations, Airflow is often better suited for ETL or data plumbing jobs.</li><li><strong>Python-based</strong>: Airflow is primarily Python-based, which may be advantageous if your team prefers working with Python.</li></ol><h3>Disadvantages of Airflow</h3><p>Despite its advantages, Airflow also has its share of challenges:</p><ol><li><strong>Less Flexibility for Business Workflows</strong>: Airflow can be more challenging to work with for implementing business workflows compared to Temporal.</li><li><strong>All-or-Nothing Success or Failure</strong>: Airflow is more all-or-nothing in terms of success or failure, and re-entering the workflow after an issue can be challenging.</li></ol><p>In the next section, we will discuss some real-world use cases of Temporal and Airflow to better understand how they can be applied in practice.</p><h3>Use Cases of Temporal and Airflow</h3><p>After understanding the basics of Temporal and Airflow, and their respective pros and cons, it’s essential to see how these platforms are used in real-world applications. In this section, we will explore some use cases of Temporal and Airflow.</p><h3>Use Cases of Temporal</h3><p>Temporal has a wide range of applications, particularly in scenarios that require long-running, complex business workflows. Here are some of the ways Temporal is used in real-world applications:</p><ol><li><strong>Business Process Automation</strong>: Temporal can be used to automate complex business processes, such as order processing, customer onboarding, and inventory management. It provides the ability to model and orchestrate multi-step workflows, with support for error handling, retries, and task scheduling.</li><li><strong>ETL for ML Models</strong>: Temporal is also used in ETL (Extract, Transform, Load) processes for pulling and training Machine Learning models. It offers robust support for long-running workflows, making it suitable for tasks that require extensive computational resources and time.</li><li><strong>Infrastructure Management</strong>: Temporal can be used to orchestrate asynchronous tasks in infrastructure management. For instance, it can be used to automate the deployment of applications, manage system updates, and monitor system health.</li></ol><p>In a case study, Airbyte adopted Temporal to solve their data extraction and loading challenges. Temporal’s ability to handle long-running workflows and its support for fault tolerance and automatic retries made it an ideal choice for Airbyte’s needs.</p><h3>Use Cases of Airflow</h3><p>Airflow, on the other hand, is commonly used in scenarios that require data pipeline orchestration. Here are some of the ways Airflow is used in real-world applications:</p><ol><li><strong>Data Pipeline Orchestration</strong>: Airflow is widely used to orchestrate complex data pipelines. For example, it can be used to automate the process of extracting data from various sources, transforming the data to a suitable format, and loading it into a data warehouse.</li><li><strong>Task Scheduling and Monitoring</strong>: Airflow’s Directed Acyclic Graph (DAG) based workflow definition makes it a powerful tool for scheduling and monitoring tasks. It can be used to define complex workflows, manage task dependencies, and monitor task execution.</li><li><strong>Integration with External Systems</strong>: Airflow’s support for custom operators and hooks allows it to integrate with a wide range of external systems and services. This makes it a versatile tool for workflows that involve interactions with external APIs, databases, or cloud services.</li></ol><p>Despite the differences between Temporal and Airflow, both platforms provide powerful tools for workflow management. The choice between them depends on your specific needs, the nature of your workflows, and your team’s preferences.</p><p>In the next section, we will conclude our comparison between Temporal and Airflow and provide some final thoughts on choosing between these two platforms.</p><h3>Choosing Between Temporal and Airflow</h3><p>Now that we have explored the basics, pros and cons, and use cases of both Temporal and Airflow, it’s time to discuss when and why you might choose one over the other. The decision will largely depend on your specific needs, the nature of your workflows, and your team’s preferences.</p><h3>When to Use Temporal</h3><p>Temporal is a robust choice for situations where you need to handle long-running asynchronous workflows, have the ability to programmatically configure workflows, and require easy embedding of the tool in your Open Source Software (OSS) releases.</p><p>Temporal is scalable and can handle many thousands of workflows simultaneously across multiple nodes. If you prefer to use a high-quality Java SDK for interacting with the orchestrator, Temporal is a great choice.</p><p>Temporal’s support for multiple languages, signals and queries, low latency, and ease of deployment management make it a compelling choice for complex business workflows. If your workflows involve complex business logic, require interaction with external processes, or need to be always running, Temporal might be the right fit for you.</p><h3>When to Use Airflow</h3><p>On the other hand, Airflow is a popular choice for situations where you need to schedule and orchestrate complex workflows with dependencies, handle data pipelines, and perform retries and error handling.</p><p>Airflow has a rich set of features and a large community of users and contributors, which can be beneficial if you need a wide range of plugins and integrations. If you prefer a Python-based workflow management system and want to take advantage of its extensive ecosystem, Airflow is a good choice.</p><p>Airflow’s Directed Acyclic Graph (DAG) based workflow definition, flexible task scheduling, and support for dependencies and triggers between tasks make it a powerful tool for data pipeline orchestration.</p><h3>Factors to Consider When Choosing Between Temporal and Airflow</h3><p>When choosing between Temporal and Airflow, there are several factors to consider:</p><ol><li><strong>Workflow Requirements</strong>: Consider the specific requirements of your workflows, such as their complexity, the need for programmability, and the type of operations they perform.</li><li><strong>Language Preference</strong>: Temporal has a strong Java SDK, while Airflow is primarily Python-based. Consider your team’s language preferences and expertise.</li><li><strong>Scalability</strong>: Temporal is designed to handle large-scale workflows and can scale horizontally across multiple nodes. Consider the scalability needs of your workflows.</li><li><strong>Ecosystem and Community</strong>: Airflow has a large and active community, with a wide range of plugins and integrations available. Consider the availability of resources and community support.</li><li><strong>Integration with Existing Systems</strong>: Consider how well each tool integrates with your existing systems and technologies.</li></ol><h3>Final Thoughts on Temporal vs Airflow</h3><p>Temporal and Airflow are both powerful workflow management systems with their own strengths and use cases. The choice between them depends on your specific requirements, preferences, and the nature of your workflows. It’s important to evaluate each tool based on factors such as scalability, programmability, language preference, ecosystem, and community support. Consider conducting a proof-of-concept or pilot project to assess how well each tool meets your needs before making a decision.</p><h3>Future Trends in Workflow Management Systems</h3><p>Workflow management systems are continuously evolving to meet the changing needs of organizations. Some future trends in this space include:</p><ol><li><strong>Low-code and No-code Workflow Builders</strong>: These tools aim to make it easier for non-technical users to create and manage workflows without the need for extensive coding.</li><li><strong>Cloud-native Workflow Engines</strong>: Workflow engines that are designed to run in cloud environments, taking advantage of cloud-native features and scalability.</li><li><strong>Integration with Machine Learning and AI</strong>: Workflow management systems are increasingly incorporating machine learning and AI capabilities to automate decision-making and optimize workflow execution.</li><li><strong>Event-driven Workflows</strong>: Workflow systems that are designed to react to events in real-time, allowing for more dynamic and responsive workflows.</li><li><strong>Hybrid and Multi-cloud Support</strong>: As organizations adopt hybrid and multi-cloud architectures, workflow management systems are being adapted to work seamlessly across different cloud environments.</li></ol><p>In conclusion, both Temporal and Airflow have their unique strengths and can be powerful tools for managing complex workflows. The choice between them should be guided by your specific needs and the nature of your workflows. Happy orchestrating!</p><h3>Conclusion</h3><p>In this blog post, we have delved into a detailed comparison between two popular workflow management platforms, Temporal and Airflow. We have explored their basic concepts, key features, pros and cons, and real-world use cases.</p><p>Temporal, with its robust support for long-running workflows, multi-language support, and low latency, is a compelling choice for complex business workflows. Its ability to handle multi-step core business logic, interact with external processes, and support always running workflows makes it a versatile tool for a variety of scenarios.</p><p>On the other hand, Airflow, with its Directed Acyclic Graph (DAG) based workflow definition, flexible task scheduling, and extensive ecosystem, is a powerful tool for data pipeline orchestration. It is particularly useful in scenarios that require complex workflows with dependencies and data pipelines.</p><p>However, the choice between Temporal and Airflow is not a one-size-fits-all. It largely depends on your specific needs, the nature of your workflows, and your team’s preferences. Factors such as workflow requirements, language preference, scalability needs, ecosystem and community support, and integration with existing systems should be considered when choosing between these two platforms.</p><p>As we look towards the future, we can expect to see continuous evolution in the field of workflow management systems. Trends such as low-code and no-code workflow builders, cloud-native workflow engines, integration with machine learning and AI, event-driven workflows, and hybrid and multi-cloud support are likely to shape the future of workflow orchestration.</p><p>In conclusion, both Temporal and Airflow are powerful tools for managing complex workflows. The choice between them should be guided by your specific needs and the nature of your workflows. As always, it’s important to evaluate each tool based on your specific requirements and conduct a proof-of-concept or pilot project before making a final decision.</p><h3>References</h3><ul><li><a href="https://community.temporal.io/t/temporal-compared-to-airflow/4729">Temporal Community</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/triggers/temporal/index.html">Airflow Documentation</a></li><li><a href="https://news.ycombinator.com/item?id=34164779">Hacker News</a></li><li><a href="https://temporal.io/case-studies/airbyte-case-study">Temporal Case Studies</a></li><li><a href="https://airbyte.com/blog/scale-workflow-orchestration-with-temporal">Airbyte Blog</a></li></ul><p><a href="https://thinhdanggroup.github.io/temporal-airflow/">Temporal vs Airflow: A Comparative Analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915d2954f592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A valuable resource for anyone looking to harness the power of GraphQL and FastAPI]]></title>
            <link>https://medium.com/@thinhda/a-valuable-resource-for-anyone-looking-to-harness-the-power-of-graphql-and-fastapi-25b4096fa376?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b4096fa376</guid>
            <category><![CDATA[graphqh]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 14:49:13 GMT</pubDate>
            <atom:updated>2023-10-31T14:51:06.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*heEO0FqeHGuwxrpPcRXKLA.png" /><figcaption>GraphQL and FastAPI</figcaption></figure><p>In this blog post, we delve into the world of GraphQL and FastAPI with Python, two powerful technologies that are revolutionizing how we build and interact with APIs. We kick off by introducing GraphQL and FastAPI, explaining what they are, their benefits, and why there’s a growing need to integrate them. We then provide a comprehensive guide on how to build a GraphQL and FastAPI application with Python, covering everything from setting up the development environment to creating a new project and integrating GraphQL with FastAPI. We also touch on deployment strategies for your application, including containerization with Docker and scaling the application. In addition, we share some best practices for working with GraphQL and FastAPI, such as optimizing GraphQL queries, effective error handling, database modeling, automated testing, and documentation. We also discuss how to improve the performance of your application, focusing on asynchronous programming with FastAPI. Lastly, we explore the importance of unit tests and how to write them for your application. So, whether you’re a seasoned developer or just starting out, this blog post is a valuable resource for anyone looking to harness the power of GraphQL and FastAPI with Python.</p><h3>Introduction</h3><p>Today, we are going to delve into the world of GraphQL and FastAPI, two powerful technologies that are making waves in the field of API development. We will discuss what they are, why they are needed, and how they can be integrated to create efficient and robust APIs.</p><h3>What is GraphQL?</h3><p>GraphQL, according to Hasura , is a query language for APIs and a runtime for executing those queries with your existing data. It offers an efficient and powerful alternative to REST. With GraphQL, you can define the shape of your data and operations that can be performed on it. This gives you more control over the data you receive, helping to avoid over-fetching or under-fetching of data. This is especially useful in scenarios where the client needs to interact with an API and would benefit from more control over the data it receives .</p><h3>What is FastAPI?</h3><p>FastAPI, on the other hand, is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints . It is used for creating REST endpoints. FastAPI is easy to use and comes with automatic interactive API documentation. It is also very fast, allowing for the creation of high-performance REST APIs quickly and efficiently. FastAPI can be used when you need to build REST APIs quickly and efficiently, with automatic interactive API documentation .</p><h3>Why Use GraphQL and FastAPI?</h3><p>The combination of GraphQL and FastAPI offers several advantages. GraphQL allows for more efficient data retrieval as only the required data is transferred, reducing the amount of data that needs to be transferred over the network . This can significantly improve the performance of your app.</p><p>FastAPI, being a high-performance framework, allows for quick development of robust web APIs with very little boilerplate code . It also supports asynchronous code, which can lead to significant performance improvements .</p><p>These technologies are ideal for building high-performance web APIs that need to aggregate data from multiple sources, and when the client needs to have flexibility in the structure of the data returned from the server. They are also perfect for real-time applications due to GraphQL’s support for subscriptions .</p><h3>The Need for Integration</h3><p>The integration of GraphQL and FastAPI allows developers to build efficient and reliable APIs that take advantage of GraphQL’s flexibility in querying data. This combination allows for faster development times, improved performance, and less boilerplate code. More so, FastAPI’s support for asynchronous code can lead to significant performance improvements .</p><p>In the following sections, we will delve deeper into how to build, deploy, and optimize GraphQL and FastAPI with Python. We will also cover best practices and how to write unit tests for your GraphQL and FastAPI applications. So, let’s dive in!</p><h3>Understanding GraphQL and FastAPI</h3><p>In this section, we will delve deeper into understanding what GraphQL and FastAPI are. We will also look at their benefits and the scenarios where they are best used.</p><h3>Elaborating on GraphQL</h3><p>As mentioned earlier, GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. Developed by Facebook, it provides a more efficient, powerful, and flexible alternative to REST. It allows clients to define the structure of the data required, and the same structure of the data is returned from the server. This makes it easier to aggregate data from multiple sources.</p><p>One of the key advantages of using GraphQL is efficient data loading. It allows clients to specify exactly what data they need, which can reduce the amount of data that needs to be transferred over the network. This is particularly beneficial for applications with large data sets or complex data structures.</p><p>Furthermore, GraphQL schemas are strongly typed, providing compile-time checks of the data you are querying. This ensures type safety and helps to prevent errors that might occur due to incorrect data types.</p><p>Finally, GraphQL includes support for subscriptions, which allows real-time data updates. This makes it ideal for applications that require real-time functionality, such as chat applications, live updates, and more.</p><h3>Elaborating on FastAPI</h3><p>FastAPI, on the other hand, is a high-performance framework for building web APIs with Python. It’s built on top of Starlette for web routing and Pydantic for data validation.</p><p>FastAPI is designed to be easy to use, while also enabling high performance. It allows developers to quickly develop robust web APIs using very little boilerplate code. This leads to faster development times and more efficient code.</p><p>Moreover, FastAPI supports asynchronous code, which can lead to significant performance improvements. This is particularly beneficial for applications that require handling of multiple requests concurrently or applications with I/O-bound tasks.</p><p>FastAPI also provides automatic interactive API documentation. This makes it easier for developers to understand and use the API, leading to increased productivity and efficiency.</p><h3>Best Use Cases for GraphQL and FastAPI</h3><p>Given their features and benefits, GraphQL and FastAPI can be used in a variety of applications. They are particularly useful in scenarios where the client needs to interact with an API and would benefit from more control over the data it receives.</p><p>For instance, social media platforms, e-commerce sites, and any other application that involves complex querying of data can greatly benefit from using GraphQL and FastAPI. They are also ideal for real-time applications due to GraphQL’s support for subscriptions.</p><p>In conclusion, understanding GraphQL and FastAPI, their benefits, and their best use cases can help developers make informed decisions when building APIs. In the next section, we will look at how to build GraphQL and FastAPI with Python.</p><h3>Building GraphQL and FastAPI with Python</h3><p>In this section, we’ll walk you through the process of building a GraphQL and FastAPI application with Python. We’ll cover everything from setting up the development environment to creating a new project, integrating GraphQL with FastAPI, and building GraphQL queries and mutations.</p><h3>Setting up the Development Environment</h3><p>First, we need to set up our development environment. FastAPI requires Python 3.6+ installed. To install FastAPI, you can use pip, the Python package manager:</p><pre>pip install fastapi</pre><p>You also need Uvicorn, an ASGI server to serve your app:</p><pre>pip install uvicorn</pre><p>Additionally, for building GraphQL schemas and types, you need to install strawberry-graphql:</p><pre>pip install &#39;strawberry-graphql[fastapi]&#39;</pre><p>To work with JSON data, the built-in json package is used.</p><h3>Creating a New FastAPI Project</h3><p>Once you have your development environment set up, you can start a new FastAPI project by creating a new directory for your app. Inside this directory, create a new file named main.py. This will be the index file for your server.</p><h3>Integrating GraphQL with FastAPI</h3><p>With your project set up, the next step is to integrate GraphQL with FastAPI. FastAPI is based on the ASGI standard, making it very easy to integrate any GraphQL library also compatible with ASGI. You can combine normal FastAPI path operations with GraphQL on the same application.</p><p>Here is an example of how you can integrate Strawberry, a GraphQL library with ASGI support, with FastAPI:</p><pre>from typing import List<br><br>import strawberry<br>from fastapi import FastAPI<br>from strawberry.asgi import GraphQL<br>import uvicorn<br><br>@strawberry.type<br>class User:<br>    id: int<br>    name: str<br>    age: int<br><br>Users: List[User] = [User(id=1, name=&quot;Patrick&quot;, age=100)]<br><br>@strawberry.type<br>class Query:<br>    @strawberry.field<br>    def user(self, id: int) -&gt; User:<br>        for user in Users:<br>            if user.id == id:<br>                return user<br>        raise ValueError(f&quot;User with id {id} not found&quot;)<br>schema = strawberry.Schema(query=Query, mutation=Mutation)<br>graphql_app = GraphQL(schema)<br>app = FastAPI()<br>app.add_route(&quot;/graphql&quot;, graphql_app)<br>app.add_websocket_route(&quot;/graphql&quot;, graphql_app)<br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>In this code, we first define a User type with name and age fields. We then define a Query type with a user field that returns a User. We then create a Strawberry schema with our Query type and use it to create a GraphQL application. Finally, we add a route for our GraphQL application in our FastAPI application.</p><h3>Building GraphQL Queries and Mutations</h3><p>In GraphQL, queries are used to fetch data, and mutations are used to modify data.</p><p>Here is an example of how you can define a query to fetch a user and a mutation to add a user:</p><pre>@strawberry.type<br>class Query:<br>    @strawberry.field<br>    def user(self, id: int) -&gt; User:<br>        for user in Users:<br>            if user.id == id:<br>                return user<br>        raise ValueError(f&quot;User with id {id} not found&quot;)<br><br>@strawberry.type<br>class AddUserResult:<br>    user: User<br>@strawberry.type<br>class Mutation:<br>    @strawberry.mutation<br>    def add_user(self, name: str, age: int) -&gt; AddUserResult:<br>        # add user to database<br>        user = User(id=len(Users) + 1, name=name, age=age)<br>        Users.append(user)<br>        print(f&quot;Added user: {user}&quot;)<br>        return AddUserResult(user=user)<br><br>schema = strawberry.Schema(query=Query, mutation=Mutation)</pre><p>This code is a simple GraphQL API built with Strawberry, a Python library for building GraphQL APIs. It defines two types, Query and Mutation, and a schema that includes these types.</p><ol><li>Query class: This class represents the queries that clients can make to the API. It has one field, user, which is a method that takes an id parameter and returns a User object. The @strawberry.field decorator indicates that this method is a field in the GraphQL schema. The method iterates over the Users list (which is assumed to be a list of User objects defined elsewhere in your code), and returns the user with the matching id. If no user is found, it raises a ValueError.</li><li>AddUserResult class: This class is a custom output type for the add_user mutation. It has one field, user, which is a User object. This class is used to wrap the result of the add_user mutation.</li><li>Mutation class: This class represents the mutations that clients can make to the API. It has one field, add_user, which is a method that takes name and age parameters and returns an AddUserResult object. The @strawberry.mutation decorator indicates that this method is a mutation in the GraphQL schema. The method creates a new User object, adds it to the Users list, prints a message to the console, and returns an AddUserResult object that wraps the new user.</li><li>schema object: This object represents the GraphQL schema for the API. It is created with the strawberry.Schema function, which takes the Query and Mutation classes as arguments. This schema can be used to create a GraphQL server that serves the defined queries and mutations</li></ol><p>To use this code, you would need to define the User class and the Users list, and create a server with the schema object. You could then send GraphQL queries to get users and mutations to add users. The server would execute the corresponding methods in the Query and Mutation classes and return the results in a GraphQL response.</p><p>And there you have it! A step-by-step guide on how to build a GraphQL and FastAPI application with Python. In the next section, we will look at how to deploy this application.</p><h3>Deploying GraphQL and FastAPI with Python</h3><p>After building our GraphQL and FastAPI application, the next step is to deploy it. Deployment involves making our application available on a server so that it can be accessed by users over the internet. In this section, we will look at how to containerize our application with Docker and how to scale it to handle more traffic.</p><h3>Containerizing GraphQL and FastAPI Application with Docker</h3><p>Docker is a popular platform that allows us to package our application and its dependencies into a container. Containers are lightweight, standalone, and executable software packages that include everything needed to run an application, including the code, a runtime, libraries, environment variables, and config files.</p><p>Containerizing our application with Docker provides several benefits. It ensures that our application runs the same way regardless of the environment. This means that we can avoid the common problem of “it works on my machine” where an application works on one machine but not on another due to differences in the environment.</p><p>To containerize our GraphQL and FastAPI application, we need to create a Dockerfile. A Dockerfile is a text file that contains the instructions to build a Docker image. Here is an example of a Dockerfile for our application:</p><pre>## Use an official Python runtime as a parent image<br>FROM python:3.9-slim-buster<br><br>## Set the working directory in the container to /app<br>WORKDIR /app<br>## Add the current directory contents into the container at /app<br>ADD . /app<br>## Install any needed packages specified in requirements.txt<br>RUN pip install --no-cache-dir -r requirements.txt<br>## Make port 8000 available to the world outside this container<br>EXPOSE 8000<br>## Run app.py when the container launches<br>CMD [&quot;python&quot;, &quot;graphql_fastapi/main.py&quot;]</pre><p>Run the following command to build the Docker image:</p><pre>docker build -t graphql-fastapi .</pre><p>And then run the following command to run the Docker container:</p><pre>docker run -p 8000:8000 graphql-fastapi</pre><p>This Dockerfile starts with a Python 3.9 image, sets the working directory to /app, and adds the contents of the current directory to the container. It then installs the required packages using pip and exposes port 8000. Finally, it starts our application using the uvicorn command.</p><h3>Scaling GraphQL and FastAPI Application</h3><p>Once our application is containerized, we can easily scale it to handle more traffic. Scaling involves increasing the resources available to our application, such as CPU, memory, and network bandwidth. There are two main types of scaling: vertical scaling and horizontal scaling.</p><p>Vertical scaling, also known as scaling up, involves increasing the resources of an existing server. For example, we can upgrade our server to have a faster CPU, more memory, or more network bandwidth.</p><p>Horizontal scaling, also known as scaling out, involves adding more servers to our application. For example, we can deploy our Docker container to multiple servers and use a load balancer to distribute the traffic among these servers.</p><p>FastAPI is built on Starlette for the web parts and Pydantic for the data parts, which allows it to be one of the fastest Python frameworks. This makes it an excellent choice for building high-performance applications that can handle a large number of requests per second.</p><p>In conclusion, deploying a GraphQL and FastAPI application involves containerizing the application with Docker and scaling it to handle more traffic. By following these steps, we can ensure that our application is available to users over the internet and can handle a large number of requests.</p><h3>Playground for GraphQL and FastAPI with Python</h3><p>GraphQL Playground is a powerful web-based IDE (Integrated Development Environment) that allows you to interact with a GraphQL API. It provides a user-friendly interface where you can send GraphQL queries and mutations, view the responses, and explore the available schema.</p><p>When you access GraphQL Playground over “<a href="http://localhost:8000/graphql">http://localhost:8000/graphql</a>&quot;, it means that you can access the GraphQL API running on your local machine at port 8000. This is typically the default URL and port for a FastAPI-based GraphQL server.</p><p>Once you open GraphQL Playground in your web browser, you will see a text editor where you can write your GraphQL queries and mutations. You can use the auto-complete feature to easily explore the available fields and types in the schema.</p><p>To send a query or mutation, simply type it in the editor and press the play button (usually located at the top right corner of the interface). The response will be displayed in the right panel, showing the data returned by the API.</p><p>GraphQL Playground also provides additional features to enhance your development experience. For example, you can view the documentation for the available types and fields by hovering over them or clicking on them. You can also save your queries and mutations for future use, and even share them with others.</p><p>Overall, GraphQL Playground is a valuable tool for developers working with GraphQL APIs. It simplifies the process of testing and exploring the API, making it easier to understand and work with the data provided by the server.</p><h3>Best Practices for GraphQL and FastAPI with Python</h3><p>When working with GraphQL and FastAPI, it’s essential to follow best practices to ensure that your application is robust, efficient, and maintainable. In this section, we will share some of these best practices, including optimizing GraphQL queries, effective error handling, database modeling, automated testing, and documentation.</p><h3>Optimizing GraphQL Queries</h3><p>One of the key advantages of GraphQL is the ability to fetch exactly the data you need. This is known as query optimization and is a crucial practice when working with GraphQL. When designing your GraphQL schema and queries, consider the following:</p><ol><li><strong>Specify only the fields you need</strong>: GraphQL allows clients to specify exactly what data they need, which can reduce the amount of data that needs to be transferred over the network. This can lead to significant performance improvements, especially for large applications and networks.</li><li><strong>Use aliases for renamed fields</strong>: If you need to request the same field with different arguments, you can use aliases to rename the result field in the response.</li><li><strong>Use fragments to reuse parts of queries</strong>: Fragments are a way to reuse parts of GraphQL queries. This can make your queries more readable and maintainable.</li></ol><h3>Effective Error Handling</h3><p>Proper error handling is crucial for any application. In GraphQL and FastAPI, you can handle errors by raising exceptions. When an exception is raised, GraphQL will return an error. For example, you can raise an exception if a user tries to create a course with an ID that already exists in your data store.</p><p>In FastAPI, unhandled exceptions will result in a 500 Internal Server Error response. However, you can also handle exceptions manually by using FastAPI’s @app.exception_handler decorator to define a custom exception handler.</p><h3>Database Modeling and Relationships</h3><p>When working with databases, it’s crucial to model your data correctly and define the right relationships between your tables. In FastAPI, you can use Pydantic models for data validation. Each Pydantic model defines a set of fields and their types, and FastAPI will automatically validate request data against these models.</p><h3>Automated Testing</h3><p>Automated testing is a best practice for any software development process. It helps to ensure that your code works as expected and makes it easier to catch and fix bugs early. In FastAPI, you can use the TestClient class to make requests to your application and check the responses.</p><h3>Documentation</h3><p>Good documentation is crucial for any API. It helps developers understand how to use your API and what to expect from it. FastAPI provides automatic interactive API documentation. By navigating to ‘<a href="http://localhost:8000/docs">http://localhost:8000/docs</a>&#39; in a browser, one can view the beautiful documentation that FastAPI has.</p><p>In conclusion, following these best practices when working with GraphQL and FastAPI can help you build robust, efficient, and maintainable APIs. In the next section, we will look at how to improve the performance of your GraphQL and FastAPI application.</p><h3>Improving Performance for GraphQL and FastAPI with Python</h3><p>As we’ve seen, GraphQL and FastAPI are powerful technologies for building efficient and robust APIs. However, as with any technology, there are ways to optimize your use of GraphQL and FastAPI to further improve the performance of your application. One key strategy for improving performance is to leverage the power of asynchronous programming in FastAPI.</p><h3>Asynchronous Programming with FastAPI</h3><p>Asynchronous programming is a design pattern that is used in computing to enhance the performance of your application. It allows a unit of work to run separately from the main application thread and notifies the main thread when it is done. In the context of a FastAPI application, it can be beneficial in handling and making requests.</p><p>FastAPI, as a modern web framework, is built to enable high performance and it supports HTTP/2 and WebSockets. It is built on top of Starlette for the web parts and Pydantic for the data parts, which allows it to be one of the fastest Python frameworks. This makes it an excellent choice for building high-performance applications that can handle a large number of requests per second.</p><p>FastAPI is designed to be easy to use and comes with built-in support for data validation, serialization, and documentation, along with several other features. However, one of its most powerful features is its support for asynchronous request handling.</p><p>In Python, the keywords async and await are used to define coroutines. Coroutines are special functions that can be paused and resumed, allowing them to be non-blocking. This means that in a FastAPI application, you can define route handling functions with async def instead of just def, and FastAPI will run them in a non-blocking way using Python&#39;s asyncio. Here&#39;s an example:</p><pre>@app.get(&#39;/&#39;)<br>async def read_root():<br>    return {&quot;Hello&quot;: &quot;World&quot;}</pre><p>In this example, the function read_root is defined with async def instead of just def. This means that FastAPI can pause and resume the execution of the function, allowing it to handle other requests while waiting for the function to complete. This can lead to significant performance improvements, especially in I/O-bound scenarios where the function is waiting for a response from a database or an external API.</p><p>In conclusion, asynchronous programming in FastAPI can be a powerful tool for improving the performance of your GraphQL and FastAPI application. By using async and await in your route handling functions, you can make your application more responsive and capable of handling a larger number of requests.</p><h3>Writing Unit Tests for GraphQL and FastAPI with Python</h3><p>Testing is a key aspect of software development that helps to ensure the functionality and reliability of your code. In particular, unit tests, which test individual units of code in isolation, can be invaluable in catching bugs early in the development process.</p><p>In this section, we will discuss the importance of unit tests and provide a step-by-step guide on how to write them for a GraphQL and FastAPI application.</p><h3>The Importance of Unit Tests</h3><p>Unit tests are a type of automated test that focus on a small “unit” of code, such as a single function or method. By testing these small pieces of code in isolation, we can ensure that they function correctly in any situation. This can help us catch bugs and errors early in the development process, before they become bigger problems.</p><p>In addition, unit tests serve as a form of documentation. They demonstrate how a piece of code is supposed to work, and what its expected behavior is in different situations. This can be especially useful for other developers who might be working with your code.</p><p>Finally, having a suite of unit tests can make it easier to refactor or add new features to your code. By running the tests after making changes, you can ensure that your changes haven’t broken anything.</p><h3>Writing Unit Tests for GraphQL and FastAPI</h3><p>When writing unit tests for a GraphQL and FastAPI application, there are a few key steps to follow:</p><ol><li><strong>Set Up Your Testing Environment</strong>: Before you can write your tests, you need to set up a testing environment. This might involve creating a separate database configuration to avoid overwriting data in your main development database.</li><li><strong>Create Test Data</strong>: You’ll also need to create some test data. This can be done using pytest fixtures, which are functions that provide a fixed baseline of data for your tests.</li><li><strong>Write Your Tests</strong>: Now you’re ready to write your tests. In each test, you’ll want to make a request to your application and then check the response. To make requests to your application, you can use FastAPI’s TestClient class.</li></ol><p>Here’s an example of what a unit test might look like for a GraphQL and FastAPI application:</p><pre>from fastapi.testclient import TestClient<br>from graphql_fastapi.graphql_fastapi.main import app<br><br>client = TestClient(app)<br><br>def test_get_user():<br>    response = client.post(&quot;/graphql&quot;, json={<br>        &quot;query&quot;: &quot;&quot;&quot;<br>            query($id: Int!) {<br>                user(id: $id) {<br>                    id<br>                    name<br>                    age<br>                }<br>            }<br>        &quot;&quot;&quot;,<br>        &quot;variables&quot;: {<br>            &quot;id&quot;: 1<br>        }<br>    })<br>    assert response.status_code == 200<br>    assert response.json() == {<br>        &quot;data&quot;: {<br>            &quot;user&quot;: {<br>                &quot;id&quot;: 1,<br>                &quot;name&quot;: &quot;Patrick&quot;,<br>                &quot;age&quot;: 100<br>            }<br>        }<br>    }<br><br>def test_get_user_not_found():<br>    response = client.post(&quot;/graphql&quot;, json={<br>        &quot;query&quot;: &quot;&quot;&quot;<br>            query($id: Int!) {<br>                user(id: $id) {<br>                    id<br>                    name<br>                    age<br>                }<br>            }<br>        &quot;&quot;&quot;,<br>        &quot;variables&quot;: {<br>            &quot;id&quot;: 100<br>        }<br>    })<br>    assert response.status_code == 200<br>    assert &quot;errors&quot; in response.json()<br>    assert response.json()[&quot;errors&quot;][0][&quot;message&quot;] == &quot;User with id 100 not found&quot;<br><br>def test_add_user():<br>    response = client.post(&quot;/graphql&quot;, json={<br>        &quot;query&quot;: &quot;&quot;&quot;<br>            mutation($name: String!, $age: Int!) {<br>                addUser(name: $name, age: $age) {<br>                    user {<br>                        name<br>                        age<br>                    }<br>                }<br>            }<br>        &quot;&quot;&quot;,<br>        &quot;variables&quot;: {<br>            &quot;name&quot;: &quot;John&quot;,<br>            &quot;age&quot;: 25<br>        }<br>    })<br>    assert response.status_code == 200<br>    assert response.json() == {<br>        &quot;data&quot;: {<br>            &quot;addUser&quot;: {<br>                &quot;user&quot;: {<br>                    &quot;name&quot;: &quot;John&quot;,<br>                    &quot;age&quot;: 25<br>                }<br>            }<br>        }<br>    }</pre><p>This code is a set of unit tests for a GraphQL API built with FastAPI. It uses the TestClient class from the fastapi.testclient module to send requests to the API and pytest to define and run the tests.</p><ol><li>test_get_user: This test function sends a GraphQL query to get the user with the ID of 1. It checks that the response status code is 200 (which means the request was successful) and that the response data matches the expected user data.</li><li>test_get_user_not_found: This test function sends a GraphQL query to get a user with a non-existing ID (100 in this case). It checks that the response status code is 200 and that the response contains an error with the expected message. The status code is 200 because in GraphQL, an error in a query or mutation does not result in an HTTP error status code. Instead, the error is included in the &quot;errors&quot; field of the GraphQL response.</li><li>test_add_user: This test function sends a GraphQL mutation to add a new user. It checks that the response status code is 200 and that the response data matches the expected data for the added user.</li></ol><p>In each test function, the client.post method is used to send a POST request to the &quot;/graphql&quot; endpoint of the API. The GraphQL query or mutation is passed as a string to the json parameter of this method. The json parameter also includes a &quot;variables&quot; field that contains the variables for the query or mutation.</p><p>The assert statements are used to check that the actual response matches the expected response. If an assert statement fails, pytest will report the test as failed.</p><ol><li><strong>Run Your Tests</strong>: Once you’ve written your tests, you can run them using a test runner like pytest. If any of your tests fail, the test runner will provide detailed output that can help you diagnose and fix the problem.</li></ol><p>In conclusion, unit tests are a crucial part of developing a robust and reliable GraphQL and FastAPI application. They help you catch bugs early, serve as documentation, and make it easier to refactor your code or add new features. By following the steps outlined above, you can write effective unit tests for your own applications.</p><h3>Conclusion</h3><p>In this blog post, we have taken a deep dive into the world of GraphQL and FastAPI with Python, two powerful technologies that are transforming the way we build APIs. We discussed what GraphQL and FastAPI are, their benefits, and the best use cases for each.</p><p>We’ve learned that GraphQL is a query language for APIs that provides an efficient and powerful alternative to REST. It allows clients to define the structure of the data required, leading to more efficient data retrieval. FastAPI, on the other hand, is a high-performance framework for building web APIs with Python. It’s built on top of Starlette for web routing and Pydantic for data validation.</p><p>We also explored how to build a GraphQL and FastAPI application with Python, from setting up the development environment to creating a new project, integrating GraphQL with FastAPI, and building GraphQL queries and mutations.</p><p>We also covered essential aspects of deploying our application, including containerizing our application with Docker and scaling it to handle more traffic.</p><p>Following best practices when working with GraphQL and FastAPI was emphasized, including optimizing GraphQL queries, effective error handling, database modeling, automated testing, and documentation.</p><p>We also discussed how to improve the performance of our GraphQL and FastAPI application by leveraging the power of asynchronous programming in FastAPI.</p><p>Finally, we highlighted the importance of unit tests and provided a step-by-step guide on how to write them for a GraphQL and FastAPI application.</p><p>With the knowledge gained from this blog post, I encourage you to start building your own GraphQL and FastAPI applications with Python. Remember, the key to mastering any technology is through consistent practice and continuous learning. Happy coding!</p><p>Source code for this blog post can be found <a href="https://github.com/thinhdanggroup/thinhda_dev_blog/tree/main/graphql_fastapi">here</a>.</p><p><a href="https://thinhdanggroup.github.io/python-graphql/">Building and Optimizing GraphQL and FastAPI with Python</a></p><p>References</p><ul><li><a href="https://www.obytes.com/blog/getting-started-with-graphql-in-python-with-fastapi-&amp;-ariadne">Obytes</a></li><li><a href="https://testdriven.io/blog/fastapi-graphql/">Testdriven.io</a></li><li><a href="https://blog.logrocket.com/building-a-graphql-server-with-fastapi/">LogRocket</a></li><li><a href="https://fastapi.tiangolo.com/how-to/graphql/">FastAPI</a></li><li><a href="https://github.com/tiangolo/fastapi/issues/1664">FastAPI GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b4096fa376" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executor: Worker Pool in Go]]></title>
            <link>https://medium.com/@thinhda/executor-worker-pool-in-go-86ef94ffb141?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/86ef94ffb141</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 10:20:58 GMT</pubDate>
            <atom:updated>2020-04-02T10:20:58.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CEwJQL4bdhLIgXk6ZfJvZg.jpeg" /></figure><p>The purpose of creating this library is because Go’s existing libraries don’t have features such as flexibility with the definition of job running, limiting the number of jobs executed over a period of time. In the past, I created the code based on the idea of the Worker Pool and know the trouble when working with but never generalized to create a complete library. Finally, I stopped and created <strong>Executor</strong>.</p><h3>Overview</h3><p><a href="https://github.com/thinhdanggroup/executor"><strong>Executor</strong></a> is a simple Worker Pool library with features:</p><ul><li>Job has an implementation function with a variety of params passed by reflection</li><li>Worker created by Goroutine</li><li>A “rate limiter” to support jobs like crawl data, load test, load balance upstream and downstream, …</li></ul><h3>How It Works</h3><p>The principle is quite simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*SEwhjRvDa5JAVOZkRqe2WQ.png" /></figure><p>The <strong>Executor</strong> will push <strong>Jobs</strong> into a <strong>Channel</strong>. The <strong>Channel</strong> will mediate to transfer <strong>Jobs</strong> to the <strong>Workers</strong> and also make sure the <strong>Workers</strong> are not overloaded.</p><p>The most interesting part is still how to generalize Jobs. Now that I have started to learn about Go Reflection, I have seen that we can implement a function with just the <em>interface</em> provided, function “Call” will do it. But what about the input parameters. At this time, <em>Variadic Functions</em> promote its advantages. And finally, I just need to validate the information of the input:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0b2e734c30d3381faf3dcea5be9270a/href">https://medium.com/media/a0b2e734c30d3381faf3dcea5be9270a/href</a></iframe><h3>Example</h3><p>Executor Config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f57d2b3b5c3ab6b54fb0d8d49c8ac99/href">https://medium.com/media/3f57d2b3b5c3ab6b54fb0d8d49c8ac99/href</a></iframe><p><strong>Executor</strong> will use 3 basic parameters:</p><ul><li><em>ReqPerSeconds</em>: limit the number of jobs per second. if it is 0, the executor will be no limit.</li><li><em>QueueSize</em>: buffer size of the channel.</li><li><em>NumWorkers</em>: the number of workers executing.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5d1b5618d3e2ffc7d1cf04d937b776/href">https://medium.com/media/bb5d1b5618d3e2ffc7d1cf04d937b776/href</a></iframe><p>After initializing the <strong>Executor</strong>, remember the <strong>Close</strong> resource. Inside the <strong>Close</strong>, the library will wait for the <strong>Job</strong> to complete and then close the Channel.</p><p>As you can see, we just have to execute the function and the parameter, the worker will do the rest for us. <em>Too simple is not it!</em></p><p><a href="https://github.com/thinhdanggroup/executor">thinhdanggroup/executor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ef94ffb141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compare gRPC-Web with grpc-gateway]]></title>
            <link>https://medium.com/@thinhda/compare-grpc-web-with-grpc-gateway-fa1e2acdf29f?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1e2acdf29f</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[grpc-web]]></category>
            <category><![CDATA[grpc-gateway]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 17:24:04 GMT</pubDate>
            <atom:updated>2020-01-21T06:56:18.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fE5kkrWa7EzDWQBA.png" /></figure><p>Your company has a service that uses gRPC to reduce communicate latency. But then one day, you want to build a web admin for this service but the browser doesn’t support the HTTP/2 protocol, or client’s service wants to call your service over HTTP. So, you find grpc-gateway and gRPC-Web solutions but don’t know which one to use. This article will give you an overview of these two solutions.</p><h3><strong>1. Overview</strong></h3><h4><strong>1.1. What is grpc-gateway</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*vXSA-ktC80rd3526.png" /></figure><p><a href="https://github.com/grpc-ecosystem/grpc-gateway"><strong>grpc-gateway</strong></a> is a <em>reverse-proxy</em> server that helps us convert from <em>RESTful HTTP API</em> to <em>gRPC</em>. It will read the definition of the protobuf service and generate the code itself to run the gateway. <strong>grpc-gateway </strong>provided <em>protoc-gen-grpc-gateway</em> tool to create gateway. But this tool requires installing the golang environment and quite a lot of libraries included, we can use a docker solution (<a href="https://medium.com/zalopay-engineering/buildingdocker-grpc-gateway-e2efbdcfe5c">tạo grpc-gateway bằng docker</a>) to make creating a gateway easier. Besides, it is easy to define the HTTP API with the specifications right in the proto file.</p><h4><strong>1.2. What is gRPC-Web</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SlrO0jUtS8zhxMQ5.png" /></figure><p><strong>gRPC-Web</strong> provides a JavaScript library that lets browser clients access a gRPC service. Currently, <strong>gRPC-Web </strong>is now Generally Available, and considered stable enough for production use. <strong>gRPC-Web</strong> communicates with gRPC service via a proxy gateway (default is Envoy).</p><p>gRPC-Web have two wire format:</p><ol><li><strong>mode=grpcwebtext : </strong>The default generated code sends the payload in the <em>grpc-web-text</em> format.</li></ol><ul><li><em>Content-type: application/grpc-web-text</em></li><li>Payload isbase64-encoded.</li><li>Both unary and server streaming calls are supported.</li></ul><p>2. <strong>mode=grpcweb : </strong>A binary protobuf format is also supported.</p><ul><li><em>Content-type: application/grpc-web+proto</em></li><li>Payload are in the binary protobuf format.</li><li>Only unary calls are supported for now.</li></ul><h3>2. Comparison</h3><p>Before going into the detailed comparison of gRPC-Web and grpc-gateway, I will compare these two methods with the non-gateway method such as <a href="https://medium.com/@thinhda/build-service-that-provides-http-and-grpc-api-with-spring-9e7cff7aa17a">grpc_http_spring</a>:</p><ul><li>A lot of performance impact when going through <em>an additional hop</em>, can cost you even more parsing.</li><li>It’s costly to maintain the system, require monitor an additional gateway and fix the gateway errors if they have a problem.</li><li>Using a gateway minimizes the chance of duplicate code.</li></ul><p>Those are all the biggest differences between using and not using a gateway. Next, we go into the most important part is comparing the differences between gRPC-Web with grpc-gateway.</p><h4>2.1. Usage</h4><p>We can clearly see the difference in usage. With <strong>grpc-gateway</strong>, we will create a reverse-proxy using the built-in protobuf definition. On the front-end, we call directly through REST APIs. As for <strong>gRPC-Web</strong>, we must code directly in the front-end.</p><p>With the gRPC-Web model using Envoy, we can provide gRPC service over Envoy proxy. <strong>Mobile applications</strong>,<strong> gRPC-Web</strong> or <strong>other services</strong> can easily communicate with the server with just <em>a link address</em>. <strong>grpc-gateway</strong> expose REST API to client, and gateway must call the backend service directly.</p><h4>2.2. Performance</h4><p><strong>grpc-gateway </strong>uses a reverse proxy to parsing json to binary, then it uses the parsing message to send our<strong> gRPC service</strong>, and when the service response, it takes more time to parsing step. As you can see, there are too many parsing costs here, which will have a negative impact on performance.</p><p>As for <strong>gRPC-Web</strong>, the message is sent in binary format so the transmission cost will be low. When it comes to the proxy, there is no cost for parsing because the message is in its correct format.</p><p>Obviously, in terms of performance, <strong>grpc-gateway</strong> loses quite a lot to <strong>gRPC-Web</strong>. To have an objective assessment, a performance test was performed with the results as shown below (<a href="https://github.com/thinhdanggroup/benchmark-grpc-web-gateway">repository details</a>). I created a backend service and used a client to call the backend in four ways:</p><ul><li>“<strong><em>Ping to server</em></strong>”: direct call to the backend via the backend HTTP.</li><li>“<strong><em>Ping to gateway</em></strong>”: call the backend via grpc-gateway.</li><li><em>“</em><strong><em>Ping with grpc-web text</em></strong><em>”: call the backend with gRPC-Web with mode=grpcwebtext</em>.</li><li>“<strong><em>Ping with grpc-web binary</em></strong>”: call the backend with gRPC-Web with <em>mode=grpcweb</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*mXLw7NDcfWqlJeqT.png" /></figure><p>As you can see:</p><ul><li>The throughput of making direct calls to the backend via <strong>HTTP </strong>and the use of <strong>gRPC-Web</strong> are nearly equal.</li><li>The call through <strong>grpc-gateway</strong> has reduced the throughput.</li><li>Finally, it was the call through the <strong>gRPC-Web</strong> protocol with binary mode that brought an <strong><em>impressive performance</em></strong>. Beyond the traditional <strong>HTTP </strong>protocol.</li></ul><h4>2.3. Security</h4><p>Both of them support <strong>TLS configuration</strong>. This ensures the safety when you provide API to outside.</p><p>Next, we will consider <strong>Authorization</strong>. If you’ve ever worked with gRPC, you probably know that user credentials are usually located in the header <em>authorization </em>field, most of which is in <strong>JWT</strong>. And both of these gateways support this header transmission.</p><p>As for <strong>CORS</strong>, this is not a big deal because both ways we can configure them.</p><h4>2.4. Maintenance</h4><p>With <strong>grpc-gateway</strong>, if your API specification change in the proto file, we have to run the tool to recreate the gateway code. And if you have previously made modifications to the gateway’s code, this requires you to find a way to sum up the old and new code. At this point, we must change the code to at least 2 locations, front-end and grpc-gateway.</p><p>As for <strong>gRPC-Web</strong>, the front-end codebase need to change.</p><h3>3. Summary</h3><p>Both of them have advantages and disadvantages. Depending on your business, what you have and what you need, you will choose the most appropriate method. If you are writing a service from scratch or already have an envoy proxy, use <strong>gRPC-Web</strong>. But if you already have a front-end and gRPC backend, using grpc-gateway will save a lot of cost of rewriting front-end. And <strong><em>don’t forget to consider the amazing performance</em></strong> of gRPC-Web when sending in binary, it’s time for us to consider completely changing the traditional HTTP protocol to gRPC for Web applications.</p><p><a href="https://github.com/thinhdanggroup/benchmark-grpc-web-gateway">thinhdanggroup/benchmark-grpc-web-gateway</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1e2acdf29f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load testing với Locust và Boomer]]></title>
            <link>https://medium.com/@thinhda/load-testing-v%E1%BB%9Bi-locust-v%C3%A0-boomer-1f0041b94934?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0041b94934</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[distributed]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 14:15:50 GMT</pubDate>
            <atom:updated>2020-01-07T03:28:45.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*0P1YMyK3Eu3s3UwqIMjuAw.png" /></figure><p>Một bước mà chúng ta thường xuyên bỏ qua và coi thường khi xây dựng một service mới đó là load test. Load test là một quá trình quan trọng trước khi đưa sản phẩm vào thực tế. Load test mang lại rất nhiều lợi ích: cho ta biết khả năng phục vụ bao nhiêu người dùng cùng lúc của service, chất lượng dịch vụ trong các tình trạng tải khác nhau, phát hiện được những <strong>bug</strong> chỉ xảy ra trong môi trường multi-threading, …</p><h3><strong>Giới thiệu</strong></h3><p>Load test là một dạng của <a href="https://www.guru99.com/performance-testing.html"><em>performance testing</em></a>. Chúng ta sẽ xác định được hiệu năng của hệ thống trong các điều kiện tải khác nhau trong thực tế. Bài kiểm tra này giúp ta hiểu hơn về hành vi của hệ thống khi có nhiều người dùng truy cập đồng thời.</p><p>Các bài load testing thường dùng để:</p><ul><li>Đo lượng request tối đa mà ứng dụng có thể phục vụ.</li><li>Số lượng người dùng có thể phục vụ đồng thời và khả năng mở rộng khi có nhiều người dùng hơn truy cập.</li><li>Nhận dạng những vị trí <strong>bottleneck</strong> trước khi lên production.</li><li>Giảm rủi ro khi hệ thống downtime.</li><li>Hiểu về hệ thống trong các điều kiện tải khác nhau: đánh giá hiệu năng database, thời gian các transaction, vấn đề thiết kế, giới hạn phần cứng,… để tạo ra những quyết định tinh chỉnh phù hợp.</li></ul><p>Load testing còn nhiều lợi ích tích cực khác, nếu bạn vẫn chưa quen với khái niệm load testing có thể tìm hiểu thêm ở <a href="https://www.guru99.com/load-testing-tutorial.html">Load Testing Tutorial</a>.</p><p>Để thực hiện một bài load testing, ta có thể chọn nhiều công cụ khác nhau như Gatling, JMeter, The Grinder,… Nhưng trong bài viết này, mình sẽ sử dụng một công cụ khá nổi tiếng khác đó là Locust. Tại sao Locust được xem là tốt hơn, mình sẽ cho bạn thấy lợi thế của Locust so với Jmeter ( Đây là tool khá nổi tiếng về load testing). Đầu tiên, GUI của Jmeter khá tốt nhưng không phải nghiệp vụ nào cũng có thể <strong><em>point-and-click</em></strong> là được. Thứ hai, Jmeter là <em>thread-bound</em>, nghĩa là mỗi user bạn tạo ra trong quá trình test là một thread, hay nói cách khác, khi ta giả lập hàng ngàn người dùng cùng lúc trên một máy thì nó không thực hiện tốt được.</p><p>Locust là một công cụ load testing mà có thể tính toán được có bao nhiêu user đồng thời mà hệ thống có thể xử lý được. Locust cung cấp một Web-based UI, khả năng <strong>load test distributed</strong> trên nhiều máy và có thể tạo ngữ cảnh test với Python, Golang hoặc Java. Mình đã thử qua các thư viện kết nối với Locust và thấy <a href="https://github.com/myzhan/boomer">Boomer</a> là tốt nhất vì các ưu điểm sau:</p><ul><li>Tạo load test nhưng ít tốn tài nguyên và tối ưu hóa resource nhờ được biết bằng Golang.</li><li>Viết các testcase khá nhanh và dễ.</li><li>Hỗ trợ rate limit.</li><li>Có thể custom output.</li></ul><h3><strong>Chế độ phân tán của Locust</strong></h3><p>Khi mà một máy đơn không thể tạo đủ số lượng người dùng mà bạn cần, thì lúc này cơ chế phân tán sẽ giúp ta chạy load test trên nhiều máy khác nhau. Locust sẽ hoạt động gồm 2 thành phần: master và slave.</p><ul><li><strong>Master</strong>: Khi ta khởi chạy một instance Locust dưới chế độ master thì nó sẽ cung cấp một giao diện web để xem các giá trị thống kê, nó cũng sẽ không giả lập bất kì người dùng nào để load test mà chỉ đảm bảo nhiệm vụ cung cấp UI.</li><li><strong>Slave</strong>: Có thể được viết bằng nhiều ngôn ngữ Python, Java hoặc Golang. Slave sẽ hoạt động độc lập nhau, nhận lệnh điều khiển từ Locust master. Slave sẽ giả lập người dùng và gửi yêu cầu cho service, sau đó nó ghi nhận thông tin như latency rồi trả cho master.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9n2njTvtTBw-jQDkG10CNg.png" /></figure><h3><strong>Boomer</strong></h3><p>Trong phần này chúng ta sẽ đi sâu vào cơ chế hoạt động master slave của Locust thông qua thư viện boomer. Thư viện boomer cung cấp khả năng giả lập số người dùng gửi yêu cầu vào hệ thống. Nhờ vào việc sử dụng goroutine nên boomer mang lại hiệu năng vượt trội so với các ngôn ngữ khác. Có một lưu ý là hãy sử dụng boomer như thư viện chứ không phải một công cụ benchmark.</p><p>Để dễ hiểu hơn về cách sử dụng boomer. Mình sẽ tạo ra một ví dụ đơn giản như sau: mình sẽ load test một <strong>ping pong service</strong> bằng locust và boomer (Source code có thể tham khảo ở <a href="https://github.com/thinhdanggroup/example_locust_boomer">example_locust_boomer</a>). Mô hình triển khai và hoạt động như hình bên dưới:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*WwmTjSbhls-pq-46E8YXAw.png" /></figure><p>Khi ta thực hiện việc tạo một bài test mới trên Locust UI thì chuyện gì sẻ xảy ra?</p><ul><li>Người dùng sẽ tạo ra một bài kiểm tra gồm lượng người dùng cần mô phỏng (Number of users to simulate) và số lượng request mỗi giây (Hatch rate).</li><li>Hai thông số cấu hình bài test trên sẽ được gửi đến từng slave của locust. Với boomer, mỗi người cần mô phỏng là một goroutine. Số lượng người dùng cần tạo ra để mô phỏng sẽ được chia đều cho số slave, ví dụ bạn có 4 slave và cần tạo 10000 người dùng thì mỗi slave sẽ tọa 2500 người dùng để bắn request.</li><li>Sao khi mỗi goroutine được khởi tạo, nó sẽ thực hiện một <strong>Task</strong> được định nghĩa sẵn từ trước. <strong>Task </strong>sẽ thực hiện một business logic của bạn. Như ví dụ ở đây, Task sẽ là thực hiện một request gọi vào API ping. Ngoài ra, Boomer hỗ trợ việc đặt trọng số cho từng task, tính năng này khá hữu hiệu khi bạn cần test nhiều API cùng lúc.</li><li>Ở mỗi <strong>Task</strong>, ta cần ghi nhận trạng thái của request là thành công hay thất bại và các meta data cho nó. Như ví dụ dưới đây là mình đã tính latency cho việc request vào API /ping sau đó ghi nhận kết quả về Locust thông qua hàm <strong>RecordSuccess</strong>. Trong trường hợp lỗi xảy ra, chúng ta cũng cần ghi nhận các kết quả để hỗ trợ thống kê qua <strong>RecordFailure</strong>.</li><li>Ở trên giao diện của Locust, ta sẽ thấy được các thông số cần thiết như về latency như giá trị trung bình, min, max, p95. Ngoài ra, các bạn có thể thêm nhiều metric khác như p99 ở phần thống kê.</li></ul><p>Đi sâu một tí về cách hiện thực, ở đây mình dùng ví dụ có sẵn ở trang chủ <a href="https://github.com/myzhan/boomer/blob/master/examples/http/client.go">client.go</a>. Ta sẽ gửi thông tin về cho master thông qua 2 hàm:</p><p>- <strong>RecordFailure</strong>: ghi nhận các giá trị lỗi.</p><p>- <strong>RecordSuccess</strong>: ghi nhận các giá trị thành công. Lưu ý: locust chỉ tính throughput và latency cho các record success.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96ff5554b7c2eec6182f22c020a92b7/href">https://medium.com/media/d96ff5554b7c2eec6182f22c020a92b7/href</a></iframe><h3><strong>Load testing với rate limit</strong></h3><p>Tại sao load test lại cân <strong>rate limit</strong>?</p><ul><li>Hãy nhớ lại khái niệm load test, ta cần phải hiểu rõ hệ thống trong những điều kiện tải khác nhau. Thông thường, ta sử dụng rate limit để đo được trạng thái giá trị latency và throughput của hệ thống trong điều kiện tải bình thường, với mục đích là tạo ra một cam kết SLA chính xác.</li><li>Cùng với việc sử dụng rate limit, ta có thể tìm ra được giá trị tối đa của throughput mà việc load test bình thường không thể hiện được. Khi có rate limit, tỉ lệ xung đột tải nguyên sẽ giảm, ở một mức độ nào đó, ta sẽ tìm được lượng tải tối đa mà hệ thống hoạt động ở mức hiệu quả nhất. Từ đó, ta có thể giới hạn lượng request để hệ thống không hoạt động quá tải và phí tài nguyên cho <strong>context switch</strong>.</li><li>Giả sử, bạn nói rằng service của bạn có thể xử lý đồng thời 100000 req/s. Nhưng nó vẫn chưa đủ, bạn vẫn chưa nói về latency khi có 100000 req/s. Nếu p99 lúc đó là 60 giây thì thật không thể chấp nhận được. Vì vậy, khi một cam kết nào đó ta luôn phải ưu tiên latency hay cụ thể là p99 ở ngưỡng nào đó với throughtput là bao nhiêu. Ví dụ: service của tôi có khả năng xử lý 10000 req/s với p99 &lt; 10ms.</li><li>Từ lý do đó, ta phải sử dụng <strong>rate limit</strong> để tìm ra throughput phù hợp với p99 mà ta mong đợi.</li></ul><p>Lưu ý về cách đặt giá trị rate limit:</p><ul><li>Chúng ta thường chọn tham số rate limit với đơn vị là <strong><em>req/s</em></strong>. Đây có thể là một sai lầm lớn khi load test một service mà sử dụng rate limit. Nó sẽ không có vấn đề gì nếu số lượng request được phân bố trong một giây. Nhưng với boomer, nếu bạn chọn sai cấu hình rate limit thì bài test sẽ không đánh giá đúng chất lượng của service. Tại sao mình lại đưa ra nhận định này? Cùng tìm hiểu cách boomer hiện thực rate limiter.</li><li>Khi hết một chu kì, boomer sẽ làm đầy số request còn được phép bắn vào service. Ví dụ: ta cấu hình số rate limit là 100 req/s thì cứ mỗi 1s sẽ có tối đa 100 request được phép bắn tới service. Và boomer sẽ cố gắng bắn số request này nhanh nhất có thể, dẫn đến hiện tượng toàn bộ request tập trung ở phần đầu chu kì, còn phần sau thì không có request nào được bắn nữa. Lúc này, hiện tượng nút thắc cỗ chai diễn ra, và ta sẽ đánh giá sai năng lực của service. Vì vậy, hãy lun cân nhất chọn cấu hình với chu kì nhỏ để phù hợp hơn, 100req/s thành 1req/10ms.</li></ul><p>Vậy làm sao sử dụng được rate limit trong boomer? Bommer hỗ trợ hai cơ chế rate limit như sau:</p><ul><li>Standard ratelimiter: số lượng request bắn đi sẽ được cấu hình đúng với mức tối đa. Điều này có thể tạo ra hiện tượng tăng vọt về latency lúc mới bắt đầu test và nó sẽ ổn định về sau khi. Nhưng những kết quả lúc ban đầu này làm ảnh hưởng tới các kết quả trung bình hay p99 nếu bài test của bạn quá ngắn.</li><li>Rampup rate limiter: số lượng request sẽ tăng đều cho đến khi đạt giá trị giới hạn. Nó giúp service có thời gian <strong><em>warn-up</em></strong>, giúp ta có những số liệu thống kê chính xác hơn.</li></ul><p>Cách thiết lập rate limit cực kì đơn giản khi trang chủ đã có ngay <a href="https://github.com/myzhan/boomer/tree/master/examples/ratelimit">hai ví dụ</a> về hai rate limiter này.</p><h3><strong>Tổng kết</strong></h3><p>Nhờ các công cụ như locust và boomer thì việc load testing nay đã dễ dàng hơn rất nhiều. Từ việc tạo ra các ngữ cảnh test, vận hành các công cụ test đến các số liệu thống kê và hiển thị, chúng ta có thể có tất cả chúng một cách dễ dàng. Vậy còn chờ gì nữa mà không tạo ra một bài test cho chính service của bạn ngay bây giờ.</p><p><a href="https://github.com/thinhdanggroup/example_locust_boomer">thinhdanggroup/example_locust_boomer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0041b94934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So sánh grpc-gateway với gRPC-Web]]></title>
            <link>https://medium.com/zalopay-engineering/grpc-gateway-vs-grpc-web-vn-4d85868a80e2?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d85868a80e2</guid>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[grpc-gateway]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[grpc-web]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 15:42:51 GMT</pubDate>
            <atom:updated>2020-09-08T02:25:57.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU21HDaoJbMOruy2cevCDA.png" /></figure><p>Bạn đang có một service sử dụng gRPC để đảm bảo vấn đề hiệu năng khi giao tiếp. Nhưng rồi một ngày, bạn muốn xây một admin web cho nó nhưng trình duyệt lại không hỗ trợ giao thức HTTP/2, hay đơn giản là service khác muốn gọi qua HTTP. Và bạn tìm đến hai giải pháp grpc-gateway và gRPC-Web nhưng lại không biết nên dùng cái nào. Bài viết này sẽ cho bạn cái nhìn tổng quát về hai giải pháp này.</p><h3>1. Khái niệm cơ bản</h3><h3><strong>1.1. grpc-gateway là gì</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*HMgUtXEIT1jsq36-OYMThQ.png" /></figure><p><a href="https://github.com/grpc-ecosystem/grpc-gateway">grpc-gateway</a> là một reverse-proxy server mà giúp ta chuyển từ RESTful HTTP API sang gRPC. Nó sẽ đọc định nghĩa của protobuf service và tự tạo ra đoạn mã để chạy gateway.</p><p>grpc-gateway đã cung cấp công cụ protoc-gen-grpc-gateway để tạo ra gateway. Nhưng công cụ này yêu cầu phải cài đặt môi trường golang và khá nhiều thư viện đi kèm, ta có thể sử dụng giải pháp dùng docker (<a href="https://medium.com/zalopay-engineering/buildingdocker-grpc-gateway-e2efbdcfe5c">tạo grpc-gateway bằng docker</a>) để việc tạo gateway dễ dàng hơn. Bên cạnh, ta cũng dễ dàng định nghĩa HTTP API với các đặc tả ngay trong file proto.</p><h3><strong>1.2. gRPC-Web là gì</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrva-numgJnaANcVrEMEkg.png" /></figure><p><a href="https://github.com/grpc/grpc-web">gRPC-Web</a> là một thư viện Javascript để người dùng trình duyệt giao tiếp được với gRPC service. Hiện taị, gRPC-Web đang được sử dụng rộng rãi và có thể sử dụng cho production. gRPC-Web giao tiếp với gRPC service qua một gateway proxy (mặc định là <a href="https://www.envoyproxy.io/">Envoy</a>).</p><p>gRPC-Web hỗ trợ hai dạng gửi tin nhắn:</p><ol><li><strong>mode=grpcwebtext : </strong>Đây là dạng mặc định.</li></ol><ul><li>Content-type: application/grpc-web-text.</li><li>Payload là base64-encoded.</li><li>Hỗ trợ gọi một chiều và server streaming.</li></ul><p>2. <strong>mode=grpcweb : </strong>hỗ trợ định dạng binary protobuf.</p><ul><li>Content-type: application/grpc-web+proto</li><li>Payload là định dạng binary.</li><li>Chỉ hỗ trợ gửi một chiều.</li><li>Sẽ có hiệu năng đường truyền tốt hơn vì nội dung tin nhắn ở dạng binary.</li></ul><h3>2. So sánh</h3><p>Trước khi đi vào so sánh chi tiết về grpc-gateway và gRPC-Web, mình sẽ so sánh hai phương pháp này với phương pháp không sử dụng gateway như <a href="https://medium.com/@thinhda/build-service-that-provides-http-and-grpc-api-with-spring-9e7cff7aa17a">grpc_http_spring</a>:</p><ul><li>Ảnh hưởng nhiều hiệu năng khi phải đi qua thêm 1 hop, có thể tốn thêm cả chi phí parsing.</li><li>Tốn chi phí vận hành hệ thống khi phải theo dõi thêm một gateway và sửa lỗi gateway nếu chúng xảy ra vấn đề.</li><li>Sử dụng gateway sẽ giảm thiểu được khả năng bị duplicate code.</li></ul><p>Đó là tất cả những khác biệt lớn nhất giữa việc sử dụngvà không sử dụng gateway. Tiếp theo, chúng ta đi vào phần quan trọng nhất là so sánh sự khác biệt giữa hai phương pháp.</p><h3><strong>2.1. Cách sử dụng</strong></h3><p>Ta có thể rõ ràng thấy được khác biệt ở việc sử dụng là với grpc-gateway, ta sẽ tạo riêng một reverse-proxy bằng định nghĩa protobuf có sẵn. Ở phía front-end, ta gọi được trực tiếp qua REST APIs. Còn với gRPC-Web, ta phải hiện thực trực tiếp đoạn code ở phía front-end.</p><p>Với mô hình của gRPC-Web dùng Envoy, ta có thể cung cấp gRPC service với một port của Envoy. Các <strong>ứng dụng mobile</strong>, <strong>gRPC-Web</strong> hay <strong>service khác</strong> có thể dễ dàng giao tiếp với máy chủ chỉ với một đường dẫn. Còn grpc-gateway chỉ cung cấp duy nhất REST API, còn gRPC thì phải gọi trực tiếp service bên trong.</p><h3>2.2. Hiệu năng</h3><p><strong>grpc-gateway</strong> sử dụng một <strong>reverse proxy</strong> để parsing tin nhắn json sang binary của protobuf, sau đó mới dùng tin nhắn được <strong>parsing</strong> gọi vào gRPC service của chúng ta, rồi khi có phản hồi, lại tốn thêm một bước parsing nữa. Như các bạn thấy, quá nhiều chi phí parsing ở đây, điều này sẽ ảnh hưởng không tốt tới hiệu năng.</p><p>Còn với <strong>gRPC-Web</strong> thì tin nhắn gửi đi đã là định dạng binary nên chi phí truyền tải sẽ thấp. Khi đến proxy, sẽ không có chi phí nào cho việc parsing vì tin nhắn đã đúng định dạng của nó.</p><p>Rõ ràng, về mặt hiệu năng thì grpc-gateway thua khá nhiều so với gRPC-Web. Để có một đánh giá khách quan, một bài kiểm tra hiệu năng đã được thực hiện với kết quả như hình bên dưới (chi tiết <a href="https://github.com/thinhdanggroup/benchmark-grpc-web-gateway">repository</a>). Mình đã tạo một service backend và dùng một client để gọi tới backend thông qua 4 cách sau:</p><ul><li>“Ping to server”: gọi trực tiếp tới backend thông qua đầu HTTP của backend.</li><li>“Ping to gateway”: gọi tới backend thông qua grpc-gateway.</li><li>“Ping with grpc-web text”: gọi tới backend bằng gRPC-Web với <em>mode=grpcwebtext.</em></li><li>“Ping with grpc-web binary”: gọi tới backend bằng gRPC-Web với <em>mode=grpcweb.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggVRs46rj_khrbr1CtQOLw.png" /></figure><p>Nhận xét:</p><ul><li>Request per second của việc gọi trực tiếp tới backend qua HTTP và việc sử dụng gRPC-Web gần bằng nhau.</li><li>Còn việc gọi thông qua grpc-gateway đã làm ảnh hưởng giảm đi throughput.</li><li>Cuối cùng, đó là việc gọi thông qua giao thức gRPC-Web với mode binary đã đem lại một hiệu năng khá ấn tượng. Vượt hơn cả giao thức HTTP truyền thống.</li></ul><h3>2.3. Bảo mật</h3><p>Đầu tiên là bảo mật kênh truyền, cả hai đều hỗ trợ việc cấu hình TLS. Điều này đảm bảo sự an toàn khi bạn cung cấp API cho bên ngoài.</p><p>Tiếp theo, mình nói về cách <strong>Authorization</strong>. Nếu bạn đã từng làm việc với gRPC hẳn bạn cũng biết các thông tin về xác thực của người dùng thường nằm ở trường header authorization, đa số là jwt sẽ nằm trong đó. Và cả hai cách dùng gateway đều hỗ trợ truyền header này.</p><p>Về CORS, đây không phải là vấn đề lớn vì cả hai cách ta đều có thể cấu hình chúng.</p><h3><strong>2.4. Khả năng mở rộng</strong></h3><p>Với <strong>grpc-gateway</strong>, với mỗi thay đổi đặc tả API ở file proto, ta phải chạy tool để tạo lại code gateway. Và nếu trước đây bạn có một số chỉnh sửa ở đoạn code của gateway, điều này lại cần bạn phải tìm cách tổng hợp giữa code cũ và mới. Lúc này, ta phải thay đổi code ít nhất 2 vị trí là front-end và grpc-gateway.</p><p>Còn <strong>gRPC-Web</strong>, mỗi khi thay đổi về API ta chỉ cần thay đổi code ở phía front-end.</p><h3>3. Tổng kết</h3><p>Như các bạn đã thấy, cả hai cách trên đều có ưu và nhược điểm riêng. Tuỳ điều kiện bạn đang có và nhu cầu bạn cần, bạn sẽ chọn một cách thức phù hợp nhất. Nếu bạn đang viết một service từ đầu hay đã có sẵn một envoy proxy, hãy sử dụng gRPC-Web. Nhưng nếu bạn đã có một front-end và đang cần thay đổi backend sang gRPC, hãy dùng grpc-gateway sẽ tiết kiệm được nhiều chi phí viết lại front-end. Và đừng quên cân nhắc đến hiệu năng tuyệt vời của gRPC-Web khi gửi bằng binary, đã đến lúc chúng ta cân nhắc việc thay đổi hoàn toàn giao thức HTTP truyền thống thành gRPC cho các ứng dụng Web.</p><p><em>Originally published at </em><a href="https://gist.github.com/8ede71cb5957b3dc45973771f6c47f01"><em>http://github.com</em></a><em>.</em></p><p><a href="https://github.com/thinhdanggroup/benchmark-grpc-web-gateway">thinhdanggroup/benchmark-grpc-web-gateway</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d85868a80e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zalopay-engineering/grpc-gateway-vs-grpc-web-vn-4d85868a80e2">So sánh grpc-gateway với gRPC-Web</a> was originally published in <a href="https://medium.com/zalopay-engineering">ZaloPay Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Service that provides HTTP and GRpc API with Spring]]></title>
            <link>https://medium.com/@thinhda/build-service-that-provides-http-and-grpc-api-with-spring-9e7cff7aa17a?source=rss-bfdec87868e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7cff7aa17a</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thinh Dang]]></dc:creator>
            <pubDate>Sun, 25 Aug 2019 14:49:30 GMT</pubDate>
            <atom:updated>2020-07-31T07:28:37.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Service that provides HTTP and gRPC API with Spring (without Proxy)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*fQQaxMLLVs0bg1IRsXtR7A.png" /></figure><p>If you’ve ever built a gRPC application, you probably know the advantages of gRPC being fast (up to 8 times faster than Http) and optimizing the content of messages sent. But you probably know its biggest drawback is that not all applications can use the gRPC protocol. For example, the browser can not call a gRPC service directly. So why don’t we build a service that can support API for gRPC and Http?</p><h3><strong>1. Introduction</strong></h3><p><a href="https://github.com/grpc-ecosystem/grpc-gateway"><strong>GRPC Gateway</strong></a> is a solution to this problem but it requires us to deploy a <strong><em>sidecar</em></strong> service, a solution using <a href="https://github.com/grpc/grpc-web"><strong>gRPC Web</strong></a> is similar to the gateway but has many benefits. I’ve tried it for a real product, but there have been many problems with this <strong><em>gRPC Gateway</em></strong> such as authenticate, streaming data, line security, networking partition between the gateway and service, … In this situation, the only way to solve this problem is to change the <strong><em>gRPC Gateway</em></strong> source code, but not everyone knows about golang. Along with that, a common shortcoming of the gateway is that the packet will take time to go through an additional <strong><em>hop</em></strong>, which also partly affects the latency of the message.</p><p>That’s when we need a service that supports both API gRPC and Http. With <strong><em>Spring Boot</em></strong>, everything becomes easy when we just need to add some configuration. At this point, our service will have both ends of the <strong><em>data transfer object</em></strong> API which is an object created from the <strong><em>proto</em></strong> file.</p><p>Before coming to part 2, I hope you have basic knowledge about Spring Boot, gRPC, Protobuf, …</p><h3>2. How to</h3><p>In the next session, I will create a Ping Pong service that supports API Http and gRPC. The entire repository sample example <a href="https://github.com/thinhdanggroup/spring_grpc_http">spring_grpc_http</a>.</p><h3>2.1 API Specification</h3><p>Creating a proto API is Ping according to the following <a href="https://github.com/thinhdanggroup/spring_grpc_http/blob/master/core/src/main/proto/ping.proto">definition</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db59ea83dea689eaaf6394f26c78be9d/href">https://medium.com/media/db59ea83dea689eaaf6394f26c78be9d/href</a></iframe><p>Use command <strong>mvn clean install</strong> to create objects from proto file.</p><h3>2.2. Building gRPC Controller</h3><p>First, we have to initialize gRPC controller with the <a href="https://github.com/yidongnan/grpc-spring-boot-starter">grpc-spring-boot-starter</a> library, this is a pretty powerful library if you want to create a gRPC service. Just configure the port to run gRPC and focus on implementing the desired logic without worrying about how to initialize gRPC Server. Besides, this library also provides <a href="https://github.com/LogNet/grpc-spring-boot-starter#interceptors-support">interceptor</a>, we can add multiple interceptor classes to support logging, <a href="https://gist.github.com/thinhdanggroup/11babf895e1958f86dae0701c2c702b8">authenticate</a>, <a href="https://gist.github.com/thinhdanggroup/fe8327bbe949d928a1f123994369fdce">translate the exception</a> to the corresponding error code to return the user, …</p><p>Add port configuration to the <strong><em>application.yaml</em></strong> file to launch gRPC service at port 6790:</p><pre>grpc:<br>    port: 6789</pre><p>Next, we also need to add the annotation <a href="http://twitter.com/GRpcService"><strong>@GRpcService</strong></a><strong> </strong>to the <a href="https://github.com/thinhdanggroup/spring_grpc_http/blob/master/core/src/main/java/com/thinhda/spring/grpc/core/controller/GrpcController.java">GrpcController</a> class to be able to initialize a service gRPC.</p><h3>2.3. Use protobuf class for Http Controller</h3><p>This is the most important part for us to use the object generated from the proto file. Add the following configuration <a href="https://github.com/thinhdanggroup/spring_grpc_http/blob/master/core/src/main/java/com/thinhda/spring/grpc/core/config/ApiConfig.java"><strong>class config</strong></a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b674714018c1289146768537c547661b/href">https://medium.com/media/b674714018c1289146768537c547661b/href</a></iframe><p>Spring’s default decoder does not support format and decode <strong>generated objects</strong> from proto files. But we can change this decoder by providing Spring a bean called <strong>ProtobufJsonFormatHttpMessageConverter</strong>.</p><p><strong>2.4. Experiment</strong></p><p>Use <a href="https://github.com/uw-labs/bloomrpc"><strong><em>BloomRPC</em></strong></a><strong><em> </em></strong>( GUI Client for gRPC services) to test gRPC API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUy3WbskfC_u4g6Ts4UMqw.jpeg" /></figure><p>Check Http API with <strong>Postman</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9Fp8syMcFkIHuL9tFrw2w.jpeg" /></figure><p>Benchmark:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRHKmeRle7gevK8h94AlLA.png" /></figure><ul><li>Use</li></ul><h3>3. Conclusion</h3><p>A service that provides both API Http and gRPC ends has a lot of benefits when users want to call into your service, they can choose fast and light transmission speeds when communicating by gRPC or can choose the simple way, easy to implement by Http. Also on your side, there is<em> no duplicate code</em>. <strong>That’s great</strong>, <strong>isn’t it</strong>?</p><p><a href="https://github.com/thinhdanggroup/spring_grpc_http">thinhdanggroup/spring_grpc_http</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7cff7aa17a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>