<?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 Ricky Mondal on Medium]]></title>
        <description><![CDATA[Stories by Ricky Mondal on Medium]]></description>
        <link>https://medium.com/@rickymondal?source=rss-d3da48512b32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-oedaYzYSBH8jaW6tQqFEQ.png</url>
            <title>Stories by Ricky Mondal on Medium</title>
            <link>https://medium.com/@rickymondal?source=rss-d3da48512b32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:45:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rickymondal/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[Distributed Job Scheduler: Journey Zero to 20K+ Concurrent Jobs]]></title>
            <link>https://engg.glance.com/distributed-job-scheduler-journey-zero-to-20k-concurrent-jobs-1fe8cf8ed288?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe8cf8ed288</guid>
            <category><![CDATA[distributed-scheduler]]></category>
            <category><![CDATA[distributed-system-design]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 08:04:58 GMT</pubDate>
            <atom:updated>2024-07-31T08:13:40.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CX796XtXyohmxhoV3TzGeA.png" /></figure><p>In the realm of modern applications, the ability to efficiently schedule and manage tasks across a distributed system has become a cornerstone of operational success. Whether it’s orchestrating complex workflows, ensuring timely execution of critical jobs, or maintaining high availability and fault tolerance, a robust distributed job scheduler is no longer a luxury but a necessity.</p><p>Recently, I had the opportunity to design a scalable, fault-tolerant distributed job scheduler capable of handling millions of tasks across a vast network of nodes. This system operates on the principle of dynamic load balancing and intelligent task distribution.</p><p>It was a technically challenging problem to tackle, and through this journey, I gained invaluable insights. In this blog, we will explore the High-Level Design of such systems and delve into the nuances of scheduling algorithms, fault tolerance mechanisms, and system orchestration.</p><h3>System Requirements</h3><h4><strong>Functional Requirements</strong></h4><ol><li><strong>Periodic Content Fetching:</strong> As we deliver real-time content to users, we collaborate with multiple news publishing partners who supply us with their content. They provide this content via <a href="https://thebridge.in/custom_feeds.xml">RSS</a> feeds or APIs, which we need to fetch periodically to ensure we have the latest updates.</li><li><strong>Content Parsing:</strong> The system should be capable of parsing and processing the fetched content, transforming it into a format suitable for real-time delivery.</li><li><strong>User-Friendly Onboarding UI:</strong> A user-friendly UI platform is needed to enable product owners or non-technical personnel to onboard new publishing partners. This interface should simplify the process of adding new content sources in a few easy steps.</li><li><strong>Scheduling Flexibility:</strong> The system should allow for flexible scheduling of content fetching intervals to accommodate different update frequencies of various publishing partners.</li></ol><h4><strong>Non Functional Requirements</strong></h4><ol><li><strong>Scalability:</strong> The system must be scalable to handle an increasing number of content sources and higher frequencies of content fetching as the number of publishing partners grows.</li><li><strong>Error Handling:</strong> The system must handle errors gracefully, including issues with fetching or parsing content, and retry fetching content if initial attempts fail.</li><li><strong>Performance Monitoring:</strong> The system should include performance monitoring capabilities to identify and address bottlenecks in content fetching and processing, ensuring efficiency and timeliness.</li></ol><h3>Deep Dive Into the System</h3><h4>High-Level Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyllSRb6EUvic1TdujPb-Q.png" /></figure><h3>Major Components of the System</h3><h4><strong>Andromeda</strong></h4><ul><li>Responsible for handling API requests, including publisher onboarding and job-related requests.</li><li>Manages storage of parsing logic and publisher-related information.</li><li>Maintains records of job history and job results.</li><li>It uses Postgres as a data store.</li><li>Whenever a job is created, updated, or deleted, Andromeda publishes an event to Kafka, which is then consumed by the scheduler.</li></ul><h4><strong>Scheduler:</strong></h4><ul><li>Responsible for scheduling and executing jobs.</li><li>Utilizes core Redis features such as Sorted Set, Locking, Pub/Sub, and Redis Stream (Queue).</li></ul><h4>Scheduler Components:</h4><ol><li><strong>Queues</strong>: A queue is a pipeline for processing jobs. Each queue can have multiple jobs, which are processed by workers.</li><li><strong>Jobs</strong>: Jobs are the individual tasks that need to be processed. Each job is an instance that contains a unique ID, data, and a set of options for its execution.</li><li><strong>Workers</strong>: Workers are responsible for processing the jobs in a queue. They can be configured to process jobs concurrently, ensuring efficient use of resources.</li><li><strong>Delay Queue:</strong> The Delay Queue utilizes Redis sorted sets as a key data structure, allowing elements to be added with a score. These scores enable the elements to be ordered, ensuring that jobs in the Delay Queue are stored in the precise order of execution.</li><li><strong>Delay Queue Worker: </strong>A Polling Worker runs every second to check the sorted set for jobs ready for execution. Using the ZRANGEBYSCORE queue:delayed 0 currentTimestamp command, it retrieves all job IDs with a score (scheduled time) less than or equal to the current timestamp and moves these jobs to the Ready state. This Polling Worker operates independently of the Task Worker.</li></ol><h3>The Beginning: Setting Up Queues and Workers</h3><p>We started with the basics: setting up queues and attaching dedicated workers to execute tasks. Every queue required a worker, and each worker was responsible for processing tasks assigned to its queue. This simple setup laid the groundwork for our distributed job scheduler.</p><h4><strong>Managing Delayed Jobs</strong></h4><p>Next, we tackled the challenge of managing delayed jobs. When a job was created, it was stored in a delayed job queue, using a sorted set ordered by execution time. This allowed us to keep track of when each job was due for execution. A polling worker, running every second, would check this sorted set for jobs that are ready to be moved to the ready state. The command ZRANGEBYSCORE queue:delayed 0 currentTimestamp retrieved all job IDs scheduled to be executed up to the current time, ensuring timely transitions.</p><h4><strong>Real-Time Notifications</strong></h4><p>To ensure our workers were always aware of new jobs, we implemented a real-time notification system. Whenever a new job was added to the queue, Redis published a message to notify all subscribed workers. This enabled immediate awareness and response.</p><h4><strong>Efficient Job Fetching and Execution</strong></h4><p>For job fetching and execution, we utilized Redis’ BLPOP command. This blocking operation allowed workers to wait for new jobs until one became available or a timeout occurred. When a worker received a notification, it woke up and attempted to fetch the job.</p><p>However, we faced a challenge: multiple workers might try to execute the same job simultaneously. To prevent this, we implemented a locking mechanism. When a worker picked up a job, it acquired a lock on that job, ensuring no other worker could process it at the same time. The lock had an expiry time, so if a worker went down, the job would become available again after the lock expired, ready to be picked up by another worker.</p><h4><strong>Managing Job States</strong></h4><p>Our system maintained multiple job states: Delayed, Waiting, Ready, Completed, and Failed. To ensure atomic state transitions and prevent race conditions, we used Lua scripts. These scripts executed all operations as a single, indivisible unit, ensuring consistency and reliability.</p><h4><strong>Capturing Metrics and Notifications</strong></h4><p>Whenever a job transitioned states, a notification was published. Workers could act accordingly, and we could capture valuable metrics. This included the number of running or failed jobs and the time taken by each job to execute. These insights allowed us to optimize performance and identify bottlenecks.</p><h4><strong>Robust Retry Mechanisms</strong></h4><p>Handling job failures and retries was a crucial aspect of our system. We defined clear criteria for job failures, such as errors thrown by the job processor, or timeouts. When a job failed, the system checked if it had remaining retry attempts. If retries were available, the job was re-queued with updated metadata and moved back to the waiting list with an appropriate delay.</p><p>Our system supported automatic retries for failed jobs, which were configurable at the queue or job level. We implemented multiple retry strategies, including fixed delays, exponential backoffs, and custom backoff functions, allowing flexibility and robustness in handling retries.</p><h4><strong>The Power of Lua Scripts</strong></h4><p>Using Lua scripts for state transitions proved invaluable. These scripts ensured atomicity, reducing the risk of race conditions in a multi-worker environment. They also minimized network latency by performing multiple operations in a single script, ensuring consistency and allowing transactional-like behavior.</p><h3>Breaking Down the Workflow: Dedicated Worker Queues</h3><p>Our initial design processed tasks sequentially, but as the demand grew, this approach proved insufficient. We restructured our workflow by breaking down the entire process into discrete steps:</p><ul><li><strong>Fetching and Parsing XML:</strong> A worker queue dedicated to fetching XML data from sources and parsing it according to predefined logic.</li><li><strong>Content Creation:</strong> Another worker queue focused on creating content based on the parsed XML and associated parsing logic.</li><li><strong>Asset Upload:</strong> A separate queue for handling the upload of assets such as images and videos.</li><li><strong>Content Moderation:</strong> A specialized queue for running content through a data science (DS) pipeline for moderation.</li></ul><h4><strong>Sequential and Parallel Processing: Enhancing Scalability</strong></h4><p>By assigning dedicated worker queues to each task, we could process steps both sequentially and in parallel. This design allowed us to:</p><ul><li><strong>Sequential Processing:</strong> Ensure that tasks are processed in a logical order, with each step feeding into the next.</li><li><strong>Parallel Processing:</strong> Utilize multiple worker instances to handle tasks simultaneously within each step, significantly improving throughput and efficiency.</li></ul><p>This approach enabled us to distribute the workload across multiple workers, reducing the time required to complete the entire workflow and preventing any single worker from becoming a bottleneck.</p><h4><strong>Fault Tolerance: Efficient Error Handling and Retrying</strong></h4><p>A key advantage of our design was improved fault tolerance. If a task failed at any step, the system could retry from the point of failure rather than rerunning the entire workflow.</p><p>This targeted retry mechanism significantly enhanced the efficiency and reliability of our system, reducing wasted resources and minimizing downtime.</p><h3>Achieving Peak Performance: Handling 20K+ Concurrent Jobs</h3><p>As our distributed job scheduler evolved, we faced the ultimate challenge of managing a substantial number of concurrent jobs, especially during peak times. Through careful design, optimization, and scaling, we successfully built a system capable of handling up to 20k+ concurrent jobs, ensuring high performance and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5CmeHyBrrHmM-x2Rc6_fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jglzfTK0dMkdCHqsvkw5Cg.png" /></figure><h3><strong>Conclusion: A Robust and Scalable Job Scheduler</strong></h3><p>Through our journey of scaling, we transformed our distributed job scheduler into a robust and scalable system capable of handling thousands of tasks across a vast network of nodes. By leveraging horizontal scaling, dynamic load balancing, fault tolerance, advanced monitoring, and elastic scalability, we created a system that could adapt to the demands of real-time processing, ensuring efficient task management and high availability.</p><p>Our scaling journey was not without its challenges, but it equipped us with the tools and strategies needed to build a resilient and performant distributed job scheduler, ready to meet the demands of a growing and dynamic environment.</p><h3>Credits</h3><p>A huge shout-out to my amazing teammates <a href="https://in.linkedin.com/in/deven-sharma-577131157"><strong>Deven Sharma</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/akshay-sahu-/"><strong>Akshay Sahu</strong></a><strong>, and </strong><a href="https://www.linkedin.com/in/nil1729/"><strong>Nilanjan Deb</strong></a>, without your dedication and hard work, none of this would have been possible. Your support and collaboration have been instrumental in achieving these milestones.</p><p>That’s a wrap for today, everyone! Thanks for tuning in.</p><blockquote>I’m Riki Mondal, a Senior Developer deeply immersed in the world of Distributed Systems. My journey revolves around crafting intricate, high-scale architectures that drive efficiency and innovation. If you’re passionate about technology or have any queries about distributed systems, feel free to connect with me on <a href="https://www.linkedin.com/in/riki-mondal/">LinkedIn</a>.</blockquote><blockquote>Let’s keep pushing the boundaries of what’s possible. Happy learning and exploring!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe8cf8ed288" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/distributed-job-scheduler-journey-zero-to-20k-concurrent-jobs-1fe8cf8ed288">Distributed Job Scheduler: Journey Zero to 20K+ Concurrent Jobs</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: InMemory Key-Value Store With Transaction]]></title>
            <link>https://medium.com/@rickymondal/system-design-inmemory-key-value-with-transaction-0a6df97ccce1?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a6df97ccce1</guid>
            <category><![CDATA[in-memory-cache]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 13:35:34 GMT</pubDate>
            <atom:updated>2024-07-08T13:59:02.875Z</atom:updated>
            <content:encoded><![CDATA[<p>An in-memory key-value store with transaction support is a system that allows clients to perform CRUD (Create, Read, Update, Delete) operations on data stored in memory, with the added capability of executing multiple operations atomically. This ensures data consistency and integrity, especially in concurrent environments.</p><h3><strong>Requirements</strong></h3><ul><li><strong>Basic Key-Value Operations</strong>: Support retrieving, storing, updating, and deleting key-value pairs. (GET<strong><em>, </em></strong>SET<strong><em>, </em></strong>DELETE)</li><li><strong>Transaction Management</strong>: Ability to execute multiple operations atomically using commands like MULTI, EXEC, DISCARD, and WATCH.</li><li><strong>Concurrency Control</strong>: Handle concurrent access to keys, ensuring data integrity using optimistic locking.</li></ul><blockquote><em>I think, I set the context what we want to build, let&#39;s focus on LLD.</em></blockquote><h3>Low-Level Design (LLD)</h3><ul><li><strong>VersionedValue</strong>: Each value in the store is wrapped in a VersionedValue an object that includes a version number.</li><li><strong>AtomicLong globalVersion</strong>: This generates unique version numbers for each update.</li><li><strong>ThreadLocal&lt;Transaction&gt;</strong>: This allows each thread to have its own transaction context.</li><li><strong>Optimistic Reading</strong>: In the get method, we record the version of the value read in the transaction&#39;s readSet.</li><li><strong>Write Buffering</strong>: In set and delete methods, changes are buffered in the transaction&#39;s writeSet and deleteSet.</li><li><strong>Conflict Detection</strong>: In the commit method, we check if any of the values read during the transaction have been modified by comparing their current versions with the versions recorded in the readSet.</li><li><strong>Atomic Commit</strong>: All changes are applied atomically if no conflicts are detected.</li></ul><blockquote><em>Now the Interesting Part, </em><strong><em>The Code !!</em></strong></blockquote><h3>Code</h3><p><strong>Transaction</strong>: The Transaction class is a crucial component in our optimistic concurrency control mechanism. It acts as a container for all the operations performed within a single transaction. Let’s break down each of its components:</p><pre>class Transaction {<br>    Map&lt;String, VersionedValue&gt; readSet = new HashMap&lt;&gt;();<br>    Map&lt;String, String&gt; writeSet = new HashMap&lt;&gt;();<br>    Set&lt;String&gt; deleteSet = new HashSet&lt;&gt;();<br>}</pre><p>Map&lt;String, VersionedValue&gt; readSet:</p><ul><li>Purpose: Tracks all the key-value pairs that have been read during this transaction.</li><li>Key: The key that was read.</li><li>Value: A VersionedValue object containing the value and its version at the time of reading.</li><li>Usage: Used for conflict detection during commit. If any key in the readSet has a different version in the main store at commit time, it indicates a conflict.</li></ul><p>Map&lt;String, String&gt; writeSet:</p><ul><li>Purpose: Buffers all write operations performed during the transaction.</li><li>Key: The key to be written.</li><li>Value: The new value to be set for this key.</li><li>Usage: Stores all modifications without immediately applying them to the main store. These changes are only applied if the transaction is successfully committed.</li></ul><p>Set&lt;String&gt; deleteSet:</p><ul><li>Purpose: Tracks all keys that are marked for deletion in this transaction.</li><li>Usage: Store keys to be deleted without immediately removing them from the main store. These deletions are only applied if the transaction is successfully committed.</li></ul><pre>class VersionedValue {<br>    String value;<br>    long version;<br><br>    VersionedValue(String value, long version) {<br>        this.value = value;<br>        this.version = version;<br>    }<br>}</pre><p>Let’s break down the<strong> KeyValueStore</strong></p><p>This KeyValueStore class implements optimistic concurrency control:</p><ul><li>It allows multiple transactions to proceed without blocking.</li><li>Conflicts are detected at commit time by checking if any read values have changed.</li><li>Write operations are buffered in the transaction and only applied if the commit is successful.</li><li>It provides ACID properties (Atomicity, Consistency, Isolation, Durability) for transactions.</li></ul><pre>class KeyValueStore {<br>    private Map&lt;String, VersionedValue&gt; data = new HashMap&lt;&gt;();<br>    private ThreadLocal&lt;Transaction&gt; currentTransaction = new ThreadLocal&lt;&gt;();<br>    private AtomicLong globalVersion = new AtomicLong(0);<br><br>    // Methods: get, set, delete, begin, commit, rollback<br>}</pre><p>Class Components:</p><p>Map&lt;String, VersionedValue&gt; data:</p><ul><li>The main storage for key-value pairs.</li><li>Each value is wrapped in a VersionedValue object, which includes the value and its version.</li></ul><p>ThreadLocal&lt;Transaction&gt; currentTransaction:</p><ul><li>Allows each thread to have its own transaction context.</li><li>Ensures thread safety for concurrent transactions.</li></ul><p>AtomicLong globalVersion:</p><ul><li>A global counter for generating unique version numbers.</li><li>AtomicLong ensures thread-safe increments.</li></ul><p><strong>Now, let’s go through each method:</strong></p><p>public String get(String key):</p><ul><li>Check if there&#39;s an active transaction.</li><li>If so, check the transaction&#39;s deleteSet and writeSet first.</li><li>If not found in the transaction, reads from the main data store.</li><li>Records the read in the transaction&#39;s readSet for later conflict detection.</li></ul><pre>public String get(String key) {<br>    Transaction transaction = currentTransaction.get();<br>    if (transaction != null) {<br>        if (transaction.deleteSet.contains(key)) return null;<br>        if (transaction.writeSet.containsKey(key)) return transaction.writeSet.get(key);<br>    }<br>    <br>    VersionedValue vv = data.get(key);<br>    if (vv == null) return null;<br>    <br>    if (transaction != null) {<br>        transaction.readSet.putIfAbsent(key, vv);<br>    }<br>    return vv.value;<br>}</pre><p>public void set(String key, String value):</p><ul><li>If in a transaction, adds to the writeSet and removes from deleteSet.</li><li>If not in a transaction, directly updates the main data store with a new version.</li></ul><pre>public void set(String key, String value) {<br>    Transaction transaction = currentTransaction.get();<br>    if (transaction != null) {<br>        transaction.writeSet.put(key, value);<br>        transaction.deleteSet.remove(key);<br>    } else {<br>        data.put(key, new VersionedValue(value, globalVersion.incrementAndGet()));<br>    }<br>}</pre><p>public void delete(String key):</p><ul><li>If in a transaction, adds to deleteSet and removes from writeSet.</li><li>If not in a transaction, directly removed from the main data store.</li></ul><pre>public void delete(String key) {<br>    Transaction transaction = currentTransaction.get();<br>    if (transaction != null) {<br>        transaction.deleteSet.add(key);<br>        transaction.writeSet.remove(key);<br>    } else {<br>        data.remove(key);<br>    }<br>}</pre><p>public void begin():</p><ul><li>Starts a new transaction if one isn’t already in progress.</li></ul><pre>public void begin() {<br>    if (currentTransaction.get() != null) {<br>        throw new IllegalStateException(&quot;Transaction already in progress&quot;);<br>    }<br>    currentTransaction.set(new Transaction());<br>}</pre><p>public boolean commit():</p><ul><li>Checks for conflicts by comparing versions in the readSet with current versions.</li><li>If no conflicts, applies changes from deleteSet and writeSet to the main data store.</li><li>Returns true if the commit was successful, false if there was a conflict.</li></ul><pre>public boolean commit() {<br>    Transaction transaction = currentTransaction.get();<br>    if (transaction == null) {<br>        throw new IllegalStateException(&quot;No active transaction&quot;);<br>    }<br><br>    // Validate read set<br>    for (Map.Entry&lt;String, VersionedValue&gt; entry : transaction.readSet.entrySet()) {<br>        VersionedValue currentVV = data.get(entry.getKey());<br>        if (currentVV == null || currentVV.version != entry.getValue().version) {<br>            // Conflict detected<br>            currentTransaction.remove();<br>            return false;<br>        }<br>    }<br><br>    // Apply changes<br>    for (String key : transaction.deleteSet) {<br>        data.remove(key);<br>    }<br>    for (Map.Entry&lt;String, String&gt; entry : transaction.writeSet.entrySet()) {<br>        data.put(entry.getKey(), new VersionedValue(entry.getValue(), globalVersion.incrementAndGet()));<br>    }<br><br>    currentTransaction.remove();<br>    return true;<br>}</pre><p>public void rollback():</p><ul><li>Discards the current transaction without applying any changes.</li></ul><pre>public void rollback() {<br>    Transaction transaction = currentTransaction.get();<br>    if (transaction == null) {<br>        throw new IllegalStateException(&quot;No active transaction&quot;);<br>    }<br>    currentTransaction.remove();<br>}</pre><h3>Conclusion</h3><p>Designing an in-memory key-value store with transaction support is a powerful way to ensure data consistency and integrity in applications that require high performance and low latency. By implementing core components such as the data store, transaction manager, command processor, and concurrency control mechanisms, you can create a robust system capable of handling complex transactional operations.</p><p>The provided low-level design and example code demonstrate how to structure and implement the essential features of such a system. This foundational knowledge allows for further enhancements, such as adding more sophisticated concurrency control mechanisms, implementing persistence for data recovery, and scaling the system to handle larger datasets and higher traffic loads.</p><p>As you continue to develop and refine your in-memory key-value store, remember to focus on the key principles of simplicity, efficiency, and reliability. These principles will guide you in building a system that meets the demands of modern applications, providing fast and reliable data access with the benefits of transactional integrity.</p><p><em>Github</em>: <a href="https://github.com/riki-nitdgp/inMemoryKeyValueStore">https://github.com/riki-nitdgp/inMemoryKeyValueStore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a6df97ccce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Scheduling Using Redis]]></title>
            <link>https://medium.com/@rickymondal/distributed-scheduling-bullmq-a13ecbb38341?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13ecbb38341</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-scheduler]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[bullmq]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Sun, 19 May 2024 13:45:29 GMT</pubDate>
            <atom:updated>2024-08-11T14:33:43.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIYAck1m1U7McKoYTUDgcA.png" /></figure><p>BullMQ is a popular, high-performance library for managing queues in Node.js. It is built on top of Redis and is used for handling background jobs and message queues (<a href="https://docs.bullmq.io/">Official documentation</a>). I will try to cover the following points in this article:</p><ul><li>How does BullMQ work internally in a distributed environment?</li><li>How does it ensure exactly once queue semantics, i.e., attempts to deliver every message exactly one time?</li><li>What are the different properties of Redis are used?</li><li>How we can scale BullMQ for millions of Requests?</li></ul><h3>Core Components</h3><ol><li><strong>Queues</strong>: A queue is a pipeline for processing jobs. Each queue can have multiple jobs, which are processed by workers.</li><li><strong>Jobs</strong>: Jobs are the individual tasks that need to be processed. Each job is an instance that contains a unique ID, data, and a set of options for its execution.</li><li><strong>Workers</strong>: Workers are responsible for processing the jobs in a queue. They can be configured to process jobs concurrently, ensuring efficient use of resources.</li><li><strong>Redis</strong>: BullMQ uses Redis for storing queue data, job metadata, and providing atomic operations needed for queue management. BullMQ uses some core features of Redis like the <strong>Sorted Set, Distributed locking &amp; Redis Pub/Sub</strong>. We will go into detail how these core features are used.</li></ol><h3>BullMQ in Distributed Environment</h3><p>In a distributed environment, ensuring that each job executes only once is a critical requirement to avoid duplicate processing and maintain data consistency. BullMQ, leveraging <strong>Redis</strong>, is designed to work efficiently in such environments. Here’s how BullMQ handles job execution and guarantees that each job is executed only once:</p><ul><li><strong>Redis-Based Job Management</strong>: BullMQ uses Redis as a central data store to manage job queues and their states. Redis operations are atomic, ensuring that jobs are processed reliably across multiple worker instances.</li><li><strong>Job Locking</strong>: When a worker picks up a job to process, BullMQ uses Redis to lock the job. This lock prevents other workers from picking up the same job simultaneously. If a job is locked, other workers recognize that it is being processed and skip it.</li><li><strong>Lock Mechanism:</strong> Each job has a unique identifier, and BullMQ creates a Redis key for the lock. The worker sets this key with a specified expiration time, ensuring that if a worker crashes or becomes unresponsive, the lock will eventually expire, allowing another worker to pick up the job.</li></ul><pre>// Example pseudo-code for job locking<br>const lockKey = `bull:lock:${job.id}`;<br>const lockTTL = 30000; // 30 seconds<br>const lockAcquired = await redis.set(lockKey, workerId, &#39;NX&#39;, &#39;PX&#39;, lockTTL);<br>if (lockAcquired) {<br>  // Process the job<br>}</pre><ul><li><strong>Atomic State Transitions:</strong> State transitions (from waiting to active, active to completed, etc.) are performed using atomic Redis commands. This ensures that a job’s state is changed in a single, indivisible operation, preventing race conditions.</li><li><strong>Example</strong>: When a worker picks up a job, it atomically changes the job state from “waiting” to “active”.</li></ul><pre>// Example pseudo-code for atomic state transition<br>await redis.multi()<br>  .hset(jobKey, &#39;state&#39;, &#39;active&#39;)<br>  .zrem(waitingQueueKey, job.id)<br>  .zadd(activeQueueKey, Date.now(), job.id)<br>  .exec();</pre><h3>How BullMQ uses Redis Sorted Sets</h3><p>Redis sorted sets are a key data structure in BullMQ for managing job queues. Sorted sets allow elements to be added with a score, and they can be ordered based on these scores. BullMQ leverages this capability to manage the state and priority of jobs in the queue.</p><p><strong>Job Scheduling</strong>:</p><ul><li>Jobs are added to a sorted set where the score represents the job’s scheduled execution time. This allows BullMQ to manage delayed jobs and schedule them for future execution.</li><li><strong>Example</strong>: A job that needs to be processed after a delay of 60 seconds can be added with a score corresponding to the current time plus 60 seconds.</li></ul><pre>const delayUntil = Date.now() + 60000; // 60 seconds delay redis.zadd(&#39;bull:queue:delayed&#39;, delayUntil, jobId)</pre><p><strong>Job Prioritisation</strong>: Jobs can be added to a sorted set with scores representing their priority. Higher-priority jobs get lower scores, ensuring they are processed before lower-priority jobs.</p><pre>const priority = 1; // Higher priority redis.zadd(&#39;bull:queue:waiting&#39;, priority, jobId);</pre><p><strong>Job States</strong></p><p>Jobs in BullMQ go through various states, each managed by different sorted sets in Redis. Here are the primary states:</p><ul><li><strong>Waiting</strong>: Jobs waiting to be processed.</li><li><strong>Delayed</strong>: Jobs that are scheduled to be executed in the future.</li><li><strong>Active</strong>: Jobs currently being processed.</li><li><strong>Completed</strong>: Jobs that have been processed successfully.</li><li><strong>Failed</strong>: Jobs that failed during processing.</li><li><strong>Stalled</strong>: Jobs that are being reprocessed due to worker failure or timeout.</li></ul><pre>// Example states<br>const waitingQueue = &#39;bull:queue:waiting&#39;;<br>const activeQueue = &#39;bull:queue:active&#39;;<br>const completedQueue = &#39;bull:queue:completed&#39;;<br><br>// Moving a job from waiting to active<br>redis.multi()<br>  .zrem(waitingQueue, jobId)<br>  .zadd(activeQueue, Date.now(), jobId)<br>  .exec();</pre><h3>Redis Pub/Sub</h3><p>Redis Pub/Sub is used for real-time notifications and communication between different parts of BullMQ, particularly for job events and worker coordination.</p><p><strong>How Pub/Sub Is Used</strong></p><ul><li><strong>Polling:</strong> Workers use these mechanisms to detect when delayed jobs are ready.</li><li><strong>Job Events</strong>: Workers publish events to Redis channels when jobs are completed, failed, stalled, etc. This allows other components or services to listen to these events and react accordingly.</li></ul><pre>const completedChannel = &#39;bull:queue:completed&#39;;<br>redis.publish(completedChannel, JSON.stringify({ jobId, result }));</pre><ul><li><strong>Worker Coordination:</strong> When jobs are added or state changes occur, workers need to be notified to take action. For instance, when a delayed job becomes ready to process, a worker is notified to move it from the delayed set to the waiting set.</li></ul><pre>const delayedChannel = &#39;bull:queue:delayed&#39;;<br>redis.publish(delayedChannel, JSON.stringify({ jobId, readyTime }));</pre><ul><li><strong>Stalled Job Detection</strong>: Workers can subscribe to a channel for stalled jobs to handle them. When a job is detected as stalled, it is re-enqueued for processing.</li></ul><pre>const stalledChannel = &#39;bull:queue:stalled&#39;;<br>redis.subscribe(stalledChannel);<br>redis.on(&#39;message&#39;, (channel, message) =&gt; {<br>  if (channel === stalledChannel) {<br>    const { jobId } = JSON.parse(message);<br>    // Handle the stalled job<br>  }<br>});</pre><ul><li><strong>Metric Collection</strong>: We can use metric collection, and can write custom logic to collect metrics on different events.</li></ul><h3>Scaling BullMQ</h3><p>There are multiple ways to scale BullMQ:</p><p><strong>Parallelism &amp; Concurrency</strong></p><ul><li><strong>Parallelism</strong> is two or more tasks that can be run in parallel, independently of each other. This is the case when you have a multi-core processor, or if you have several machines running at the same time.</li><li><strong>Concurrency</strong> refers to the ability of different tasks to run at the same time by dividing the available CPU into small slices so that all the tasks can advance in their processing, giving the impression that they are being executed independently in parallel. BullMQ allows you to set a concurrency setting on your workers. This setting is local for the worker and exploits the NodeJS event loop so that jobs that are IO-heavy will benefit from higher throughput, as the worker does not need to wait for a job to complete before it can pick the next one.</li><li>You have 2 ways to increase parallelism and concurrency with BullMQ: you can specify the concurrency factor per worker, and you can have several workers running in parallel. The concurrency factor will just take advantage of NodeJS’s event loop so that the worker can process several jobs concurrently while the jobs are doing IO operations. If your jobs require IO operations, then you can increase this number quite a lot. Something between 100 and 300 is quite a standard setting, the only way to finetune this value is by observing how the worker processes the production workload. If the jobs are very CPU intensive without IO calls, then there is no point in having a large concurrency number as it will just add overhead. Still, since BullMQ itself also performs IO operations (when updating Redis and fetching new jobs), there is a chance that a slight concurrency factor may even improve the throughput of CPU-intensive jobs.</li><li>Secondly, you can run as many workers as you want. Every worker will run in parallel if it has a CPU at its disposal. You can run several workers in a given machine if the machine has more than one core, but you can also run workers in totally different machines. The jobs running on different workers will be running in parallel, so even if the job is CPU-intensive you will be able to increase the throughput which will normally scale linearly with the number of workers.</li></ul><p><strong>Dedicated Redis Cluster:</strong></p><ul><li>Use Redis Cluster to distribute the load across multiple Redis nodes, providing higher throughput and fault tolerance.</li></ul><p><strong>Efficient Job Processing</strong></p><ul><li><strong>Batch Processing</strong>: If possible, batch multiple jobs together to reduce the overhead of job processing.</li></ul><h3>What Next ??</h3><ul><li>We will learn how to capture metrics in BullMQ. (Like the number of jobs running, time spent by each job, etc)</li><li>I will walk you through a real example of how BullMQ helps us to solve our use case. (<a href="https://engg.glance.com/distributed-job-scheduler-journey-zero-to-20k-concurrent-jobs-1fe8cf8ed288">Article</a>)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13ecbb38341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Design A Rate Limiter]]></title>
            <link>https://medium.com/@rickymondal/rate-limiter-c647b40471b8?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/c647b40471b8</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 19:30:16 GMT</pubDate>
            <atom:updated>2024-04-27T19:35:01.767Z</atom:updated>
            <content:encoded><![CDATA[<p>In a network system, a rate limiter is used to control the rate of traffic sent by a client or a service. In the HTTP world, a rate limiter limits the number of client requests allowed to be sent over a specified period. If the API request count exceeds the threshold defined by the rate limiter, all the excess calls are blocked.</p><h3>Rate Limiting Algorithms</h3><ul><li>Token bucket</li><li>Leaking bucket</li><li>Fixed window counter</li><li>Sliding window</li></ul><h3>Token bucket</h3><p>A token bucket is a container that has a pre-defined capacity. Tokens are put into the bucket at preset rates periodically. Once the bucket is full, no more tokens are added. The refiller puts 2 tokens into the bucket every second. Once the bucket is full, extra tokens will overflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmPeB9bOBeSDPvgBBbXiRQ.png" /></figure><p>Each request consumes one token. When a request arrives, we check if there are enough tokens in the bucket.</p><ul><li>If there are enough tokens, we take one token out for each request, and the request goes through.</li><li>If there are not enough tokens, the request is dropped</li></ul><pre>public class Bucket {<br>    private final int size;<br>    private long lastFilled;<br>    private int availableToken;<br>    <br>    public Bucket(int size) {<br>        this.size = size;<br>        this.lastFilled = 0;<br>        this.availableToken = 0;<br>    }<br>    public synchronized boolean getToken() {<br>        if (this.availableToken &gt; 0) {<br>            this.availableToken --;<br>            return true;<br>        } else {<br>            return false;<br>        }<br>    }<br>    public synchronized void fillBucket(int numberOfToken, Long timestamp) {<br>        if (timestamp &lt; this.lastFilled) {<br>            return;<br>        }<br>        this.lastFilled = Instant.now().getEpochSecond();<br>        this.availableToken = Math.min(this.size, this.availableToken + numberOfToken);<br>    }<br>}</pre><h3>Leaking bucket</h3><p>The leaking bucket algorithm is similar to the token bucket except that requests are processed at a fixed rate. It is usually implemented with a first-in-first-out (FIFO) queue. The algorithm works as follows:</p><ul><li>When a request arrives, the system checks if the queue is full. If it is not full, the request is added to the queue.</li><li>Otherwise, the request is dropped.</li><li>Requests are pulled from the queue and processed at regular intervals</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cv6PpSj6JPL0guGHZ8lkKA.png" /></figure><pre>import java.time.Instant;<br>import java.util.LinkedList;<br>import java.util.Queue;<br><br>public class LeakyBucket {<br>    private final int size;<br>    private final Queue&lt;Long&gt; bucketQueue;<br>    public LeakyBucket(int size) {<br>        this.size = size;<br>        this.bucketQueue = new LinkedList&lt;&gt;();<br>    }<br>    public void processRequest(int processingRateSec, Long timestamp) {<br>        while(!this.bucketQueue.isEmpty() &amp;&amp; timestamp - bucketQueue.peek()  &gt;= processingRateSec) {<br>            this.bucketQueue.poll();<br>        }<br>    }<br>    public boolean getToken() {<br>        if (this.bucketQueue.size() &lt; this.size) {<br>            this.bucketQueue.offer(Instant.now().getEpochSecond());<br>            return true;<br>        }<br>        return false;<br>    }<br>}</pre><h3>Fixed Window Counter</h3><p>The fixed window counter algorithm works as follows:</p><ul><li>The algorithm divides the timeline into fixed-sized time windows and assigns a counter for each window.</li><li>Each request increments the counter by one.</li><li>Once the counter reaches the pre-defined threshold, new requests are dropped until a new time window starts.</li></ul><p>A major problem with this algorithm is that a burst of traffic at the edges of time windows could cause more requests than the allowed quota to go through. Consider the following case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5bUEbiPFYX9SDBIkIEzWg.png" /></figure><pre>import java.time.Instant;<br>import java.util.LinkedList;<br>import java.util.Queue;<br><br>public class FixedWindow {<br>    private final int size;<br>    private long startTime;<br>    private final Queue&lt;Long&gt; timeList;<br>    private final int capacity;<br>    public FixedWindow(int size, int capacity) {<br>        this.size = size;<br>        this.startTime = Instant.now().getEpochSecond();<br>        this.timeList = new LinkedList&lt;&gt;();<br>        this.capacity = capacity;<br>    }<br>    public boolean canProcessRequest(Long timeStamp) {<br>        this.startTime = ((timeStamp - this.startTime) / this.capacity) * this.capacity + this.startTime;<br>        while(!this.timeList.isEmpty() &amp;&amp; this.timeList.peek() &lt; this.startTime) {<br>            this.timeList.poll();<br>        }<br>        if (this.timeList.size() &lt; this.size) {<br>            this.timeList.offer(timeStamp);<br>            return true;<br>        }<br>        return false;<br>    }<br>}</pre><h3>Sliding window</h3><p>As discussed previously, the fixed window counter algorithm has a major issue: it allows more requests to go through at the edges of a window. The sliding window log algorithm fixes the issue. It works as follows:</p><ul><li>The algorithm keeps track of request timestamps. Timestamp data is usually kept in a cache, such as sorted sets of Redis.</li><li>When a new request comes in, remove all the outdated timestamps. Outdated timestamps are defined as those older than the start of the current time window.</li><li>Add the timestamp of the new request to the log.</li><li>If the log size is the same or lower than the allowed count, a request is accepted. Otherwise, it is rejected.</li></ul><pre>import java.time.Instant;<br>import java.util.LinkedList;<br>import java.util.Queue;<br>public class SlidingWindow {<br>    private final int size;<br>    private final int capacity;<br>    private Queue&lt;Long&gt; timeList;<br>    public SlidingWindow(int size, int capacity) {<br>        this.size = size;<br>        this.capacity = capacity;<br>        this.timeList = new LinkedList&lt;&gt;();<br>    }<br>    public boolean canProcessRequest(Long timeStamp) {<br>        while (!this.timeList.isEmpty() &amp;&amp; timeStamp - this.timeList.peek() &gt; this.capacity) {<br>            this.timeList.poll();<br>        }<br>        if (this.timeList.size() &lt; this.size) {<br>            timeList.offer(Instant.now().getEpochSecond());<br>            return true;<br>        }<br>        return false;<br>    }<br>}</pre><h3>High-Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVEFEa6fLkYb6hPYjwGddQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c647b40471b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Tracing with OpenTelemetry]]></title>
            <link>https://medium.com/@rickymondal/distributed-tracing-with-opentelemetry-91b76b22abf9?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b76b22abf9</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[otel]]></category>
            <category><![CDATA[honeycomb]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 05:39:04 GMT</pubDate>
            <atom:updated>2023-04-24T05:39:04.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yH2ylJ6gLQ7mOr5mL_tHlA.png" /></figure><p>Running distributed systems in production is very difficult, and it gets more painful when any production issue comes up. As there is limited access, therefore issues are hard to track down and understand. When we are running a distributed system that spans multiple containers and data centers, we need to understand how user requests flow through these services. This enables us to decipher the larger picture of where the request spends most of its time and figure out which service is not working as intended.</p><p><strong>OpenTelemetry</strong> (also known as OTEL) is an open-source <strong>observability</strong> framework made up of a collection of tools, APIs, and SDKs. OTEL enables engineering teams to instrument, generate, collect, and export telemetry data (metrics, logs, and traces) for analysis and to understand software performance and behavior.</p><p><strong>Observability </strong>In software generally refers to the ability to understand an application’s behavior and performance-based only on its telemetry. Put more simply, observability is what allows you to understand what’s happening in production <em>without changing your code</em>.</p><h3><strong>Why OpenTelemetry?</strong></h3><ul><li><strong>Simplicity</strong>: Single way to collect data and have control over the data you collect.</li><li><strong>Vendor Neutral: </strong>Provides a vendor-agnostic implementation that can be configured to send telemetry data to the backend(s) of your choice</li><li><strong>Interoperable</strong>: An end-to-end implementation to generate, emit, collect, process, and export telemetry data.</li><li><strong>Ubiquity</strong>: Promotes better coverage for instrumentation.</li></ul><h3><strong>Components of</strong> <strong>OpenTelemetry</strong></h3><ul><li><strong>API</strong>: Language-specific programs that provide the fundamentals for integrating OpenTelemetry. They make it easy to add new features to the app by providing a framework that can be attached to it.</li><li><strong>SDK: </strong>The SDK is another language-specific component of the architecture. This serves as a sort of mediator, bridging the gap between the exporter and the APIs.</li><li><strong>Collector: </strong>The <a href="https://opentelemetry.io/docs/collector/">OpenTelemetry Collector</a> is an implementation that serves as a central repository, receiving, processing, and exporting telemetry data, regardless of the tools that send the data.</li><li><strong>Exporter: </strong>The telemetry data needs to be translated to the language of its destination and then transported there. Exporters enable telemetry data to be translated to a particular format that a backend observability system requires. And they also enable the transmission of data to the system.</li><li><strong>OTLP</strong> protocol for transmitting telemetry data.</li></ul><h3><strong>Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rmLTz6wqODAyn0zwh0LFkw.png" /><figcaption>OpenTelemetry Architecture</figcaption></figure><p><strong>Distributed tracing</strong> tracks a single request from beginning to end, across all the processes, APIs, and services it interacts with — often across multiple systems and domains. As shown in Figure 1A, each trace is a directed acyclic graph (DAG) of spans that share a unique context ID (known as context propagation). Each span is a named and timed operation comprising a contiguous set of operations, or a workflow, within the trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_zXw_G8gdmfVw7wqrbW7g.png" /><figcaption>Figure: 1A</figcaption></figure><h3><strong>In this article we will learn the following:</strong></h3><ul><li>Instrumenting different applications using OpenTelemetry (Python, Java).</li><li>Configure OpenTelemetry collector and exporter.</li><li>Configure <a href="https://www.jaegertracing.io/">Jaeger</a> for end-to-end distributed tracing.</li><li>Integration with <a href="https://ui.honeycomb.io/">Honeycomb</a>.</li></ul><h3><strong>Before starting let&#39;s consider a scenario</strong></h3><ul><li>We have 4Microservice, (APIGateway, User Service, Product Service, Rating &amp; Review Service)</li><li>For the database, we are using SQLite and H2.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d98a7d06f7b452097ca8ff40fec11d24/href">https://medium.com/media/d98a7d06f7b452097ca8ff40fec11d24/href</a></iframe><h3><strong>Microservice Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*WgOWeDgrwMY0geQ1QjoXVQ.jpeg" /><figcaption>Product Feedback Service</figcaption></figure><h3><strong>Service Configuration</strong></h3><ul><li>Each service is configured with the OpenTelemetry agent (Java) and OpenTelemetry SDK (Python) which helps to send the traces to the OpenTelemetry collector.</li><li><strong>OpenTelemetry Protocol</strong>: OpenTelemetry Protocol (OTLP) specification describes the encoding, transport, and delivery mechanism of telemetry data between telemetry sources, intermediate nodes such as collectors, and telemetry backends.</li><li><strong>OpenTelemetry Collector:</strong> Collector collects all the traces and exports them to different vendors (Honeycomb, Lightstep)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*94N5jCHH3SHFTcLIcMLqdQ.jpeg" /><figcaption>OpenTelemetry Trace Flow</figcaption></figure><h3><strong>OpenTelemetry Collector Components</strong></h3><ul><li><strong>Receiver</strong>: A receiver, which can be push or pull-based, is how data gets into the Collector. Receivers may support one or more <a href="https://opentelemetry.io/docs/concepts/data-sources">data sources</a>.</li></ul><pre><strong>receivers:</strong><br><strong> otlp:<br>  protocols:<br>    grpc:<br>      endpoint</strong>: “0.0.0.0:4317”<br>    <strong>http:<br>      endpoint:</strong> “0.0.0.0:4318”</pre><ul><li><strong>Processor</strong>: Processors are run on data between being received and being exported. Processors are optional though <a href="https://github.com/open-telemetry/opentelemetry-collector/tree/main/processor#recommended-processors">some are recommended</a>.</li></ul><pre><strong>processors:</strong><br>  <em># Data sources: traces</em><br>  <strong>attributes:</strong><br>    <strong>actions:</strong><br>      - <strong>key:</strong> environment<br>        <strong>value:</strong> production<br>        <strong>action:</strong> insert<br>      - <strong>key:</strong> db.statement<br>        <strong>action:</strong> delete<br>      - <strong>key:</strong> email<br>        <strong>action:</strong> hash<br>  <strong>batch:</strong><br>  <strong>filter:</strong><br>    <strong>metrics:</strong><br>      <strong>include:</strong><br>        <strong>match_type:</strong> regexp<br>        <strong>metric_names:</strong><br>        - prefix/.*<br>        - prefix_.*</pre><ul><li><strong>Exporter</strong>: An exporter, which can be push or pull-based, is how you send data to one or more backends/destinations. Exporters may support one or more <a href="https://opentelemetry.io/docs/concepts/data-sources">data sources</a>.</li></ul><pre><strong>exporters:<br> otlp/honeycombtraces:<br>    endpoint: </strong>api.honeycomb.io:443<br>    <strong>headers:<br>      x-honeycomb-team: <br>      x-honeycomb-dataset:<br> <br> otlp/lightstep:<br></strong>     <strong>endpoint</strong>: ingest.lightstep.com:443<br>     <strong>headers: <br>        {&quot;lightstep-access-token&quot;: &quot;Your Token&quot;}</strong></pre><pre> <strong>jaeger:<br>    endpoint:</strong> jaeger:14250<br>    <strong>tls:<br>      insecure:</strong> true<br> <br> <strong>zipkin:<br>    endpoint:</strong> “<a href="http://zipkin:9411/api/v2/spans">http://zipkin:9411/api/v2/spans</a>”<br> <br> <strong>logging:<br>    loglevel:</strong> debug</pre><ul><li><strong>Extensions</strong>: Extensions are available primarily for tasks that do not involve processing telemetry data. Examples of extensions include health monitoring, service discovery, and data forwarding. Extensions are optional.</li><li><strong>Service</strong>: The service section is used to configure what components are enabled in the Collector based on the configuration found in the receivers, processors, exporters, and extensions sections. If a component is configured, but not defined within the service section then it is not enabled.</li></ul><h3><strong>Implementation</strong>:</h3><ul><li>We use docker to implement the OpenTelemetry collector.</li></ul><pre>docker-compose up --build</pre><pre>Default Port for OpenTelemetry Protocol<br>- HTTP: 4318<br>- gRPC: 4317</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/965101657cba19c3a3c854c23f24da53/href">https://medium.com/media/965101657cba19c3a3c854c23f24da53/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b747673c5412ed3868a934720be440/href">https://medium.com/media/65b747673c5412ed3868a934720be440/href</a></iframe><blockquote>Once you deploy collector successfully, Now you need to configure you services using openTelemetry agent or SDK.</blockquote><h3><strong>Configuring Java application with OpenTelemetry agent</strong></h3><ul><li>Download Java agent <a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v1.12.0/opentelemetry-javaagent.jar">Link</a></li><li><strong>Create envieroment variables</strong></li></ul><pre>OTEL_RESOURCE_ATTRIBUTES=service.name=your-service-name<br>OTEL_PROPAGATORS=b3<br>OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 #(Default)</pre><ul><li><strong>Run your application with the OpenTelemetry Java agent</strong></li></ul><pre>java -javaagent:/path/to/agent/javaagent-v1.12.0.jar -jar application.jar</pre><h3><strong>Configure Python(FastAPI) application with OpenTelemetry SDK</strong></h3><ul><li><strong>Package/Libraries to install</strong></li></ul><pre>opentelemetry-distro<br>opentelemetry-instrumentation<br>opentelemetry-exporter-otlp<br>opentelemetry-instrumentation-fastapi<br>opentelemetry-propagator-b3</pre><ul><li><strong>Create envieroment variables</strong></li></ul><pre>OTEL_TRACES_EXPORTER=otlp<br>OTEL_PROPAGATORS=b3<br>OTEL_EXPORTER_OTLP_ENDPOINT=<a href="http://otel-collector:4317/">http://localhost:4317</a><br>OTEL_RESOURCE_ATTRIBUTES=service.name=user-service</pre><ul><li><strong>Instrument your service</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23713ce860bc3b6b720b7a6cc1cc8b52/href">https://medium.com/media/23713ce860bc3b6b720b7a6cc1cc8b52/href</a></iframe><ul><li><strong>Run you application</strong></li></ul><pre>opentelemetry-instrument uvicorn app:app --host 0.0.0.0 --port 8005</pre><p>You can find all the OpenTelemetry environment variables (<a href="https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md">here</a>)</p><p>Services and OpenTelemetry collector are configured, Now need to configure some UI where you can see your traces. For UI you can use any vendor like Honeycomb, or LightStep. I am using Jaeger, it&#39;s an open-source solution for end-to-end distributed tracing.</p><h3><strong>Configure Jaeger</strong></h3><pre>docker-compose up --build</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2c7d4beca582b0172f244b81c78b078/href">https://medium.com/media/a2c7d4beca582b0172f244b81c78b078/href</a></iframe><p>For demo purposes I set up product-feedback-service (<a href="https://github.com/riki-nitdgp/OpenTelemetryDemo">here</a>), Please follow the readme.</p><h3><strong>Integration with other vendors (Honeycomb, Lightstep, Newrelic, etc)</strong></h3><p>One of the best advantages of OpenTelemetry is <strong>vendor agnostic</strong>, you can switch any vendor by doing minimum changes. Only you need to change the OpenTelemetry configuration. For example, if you want to add Honeycomb you just need to add a few lines.</p><pre>exporter:<br>   otel/honeycomb:<br>      headers:<br>          x-honeycomb-team: YourAPI KKey<br>          x-honeycomb-dataset: YourDataset<br>services:<br>  pipeline:<br>     traces:<br>        exporter: [otel/honeycomb]</pre><blockquote>For detailed collector configuration refer <a href="https://gist.github.com/riki-nitdgp/8740d39a090c1c1f9a025dcdfd7865c3.js">here</a>.</blockquote><h3><strong>Let&#39;s look at some examples, How to trace requests</strong></h3><p><strong>Jaeger (http://localhost:16686)</strong></p><p>If we go ahead and run everything together, all the spans should eventually be sent to Jaeger. If we switch over to the Jager UI and select the <strong>api-gateway</strong> service and click on <strong>Find Traces, </strong>we are going to have some results like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMH4jOETf059G-Vxbn_kHw.png" /><figcaption>Jaeger Home Page</figcaption></figure><p><strong>Service Map</strong></p><p>A service map is <strong>a real-time visual representation of the instrumented services in your application’s architecture</strong>. It shows you how these services are connected, along with high-level metrics like average transaction duration, requests per minute, and errors per minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deeOAs0bq5P1kwvWtR7ekg.png" /><figcaption>Service Map</figcaption></figure><p><strong>Trace Overview</strong></p><p>This is what a single request looks like, here the request starts from api-gateway and travels through multiple services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfAM4ow4X8WNgWYgfkkNUQ.png" /></figure><p><strong>Detailed Distributed Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGdyMFl6h8byk-crodwIug.png" /></figure><p>On the top, we can see a timeline containing all spans that are part of this specific request. This helps a lot to identify the bottlenecks and performance issues.</p><p><strong>Honeycomb Traces</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZYR9EcKgJAkha3pfbIzPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n45Xxon5Tq1hDxARkxGdDw.png" /></figure><h3>Conclusion</h3><p>Distributed systems are hard to monitor and troubleshoot. Logs and metrics, although being a very useful thing, but sometimes are not enough for us to understand what happened to a given request or in a given scenario. Correlating between different requests is very difficult, even more, when you have to do it manually or across different technologies and platforms. OpenTelemetry offers a good standard with out-of-the-box functionality to help in these scenarios.</p><h3><strong>References</strong></h3><ul><li><a href="https://opentelemetry.io/docs/">https://opentelemetry.io/docs/</a></li><li><a href="https://docs.honeycomb.io/">https://docs.honeycomb.io/</a></li><li><a href="https://opentelemetry-python.readthedocs.io/en/stable/getting-started.html">https://opentelemetry-python.readthedocs.io/en/stable/getting-started.html</a></li><li><a href="https://signoz.io/blog/opentelemetry-django/">https://signoz.io/blog/opentelemetry-django/</a></li></ul><h3>If you found this helpful, please clap and share the article. Let’s spread the solution to someone who may need it.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b76b22abf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Load Testing Using Locust]]></title>
            <link>https://engg.glance.com/distributed-load-testing-using-locust-99a229ce0ed7?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a229ce0ed7</guid>
            <category><![CDATA[gcp-load-testing]]></category>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[distributed-load-testing]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[load-testing-using-python]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 16:31:18 GMT</pubDate>
            <atom:updated>2024-07-31T08:10:57.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*6ygG7El04v5o8gsYyWIAxg.jpeg" /></figure><p>Load testing is a very important step before releasing any new service/software, that requires serving hundreds of users in real-time. One of the main objectives of load testing is to determine the system bottleneck in terms of a variety of factors like <strong>CPU, Memory, Network Bandwidth, Read/Write Latencies, Response time </strong>&amp; other metrics. This involves simulating similar actions of real users by making requests from computer-created virtual users. Load testing not only helps you to make your system deal with a large number of concurrent users but also helps you to determine how many resources your current infra supports and autoscaling policies in case of intermittent spikes.</p><h3>What we learn in this Article 🧐</h3><p>In this article, you will learn, How to load test different services (microservice) using <a href="https://locust.io/"><strong>Locust</strong></a>, manage and structure code base for load testing for multiple microservices independently, custom docker image, and running load tests in Kubernetes (k8). Before starting let&#39;s consider we have 2 microservice to load test:</p><ul><li><a href="https://github.com/riki-nitdgp/user_service"><strong>User Service</strong></a>: Manages user information.</li><li><a href="https://github.com/riki-nitdgp/inventory"><strong>Inventory Service</strong></a>: Store product information.</li></ul><h3>Locust 🤩</h3><p>Locust is an open-source and easy-to-use, scriptable, and scalable performance testing tool is written in Python. You define the behavior of your users in regular Python code, instead of being stuck in a UI or restrictive domain-specific language.</p><h3>Why Locust 🥰</h3><ul><li>This makes Locust infinitely expandable and very developer-friendly.</li><li>Distributed and scalable supports hundreds of thousands of concurrent users</li><li>Can test any system (HTTP, gRPC), and also we can write a custom client to test other systems.</li><li>Locust has a user-friendly web interface that shows the progress of your test in real-time. You can even change the load while the test is running. It can also be run without the UI, making it easy to use for CI/CD testing.</li></ul><h3><strong>Locust over JMeter </strong>🤔</h3><ul><li>JMeter, released over 20 years ago and built in Java, relies on cumbersome XML for test configuration, making it less intuitive and resource-intensive. In contrast, Locust, a more recent tool released 5 years ago and written in Python, offers a modern, event-based architecture that is highly scalable. Locust is favored by web developers for its straightforward Python test writing, user-friendly web UI, and easily interpretable reports.</li></ul><h3>Let&#39;s Start 🥳 !!!</h3><ul><li>Installing locust using pip/pip3.</li></ul><pre># Install<br>pip3 install locust </pre><pre># Check Version <br>locust -V</pre><ul><li>Writing a simple locust load test. (Assuming we have service running on port 8001 and having an API /hello)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e40217f89151993d4633524c73bb57bf/href">https://medium.com/media/e40217f89151993d4633524c73bb57bf/href</a></iframe><h4><strong>We are done with the locust load test script 😱, now let’s run the load test 😀.</strong></h4><pre># locust -f={file-path}/{file-name}.py<br>locust -f=locustfile.py</pre><p>After running the load test script you will get a web UI on <a href="http://0.0.0.0:8089/">http://0.0.0.0:8089</a>. Set the number of users and spawn rate and click on <strong>Start Swarming</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GVrdbBfJbMZvVaZJ8v7lg.png" /></figure><h3>Understanding locustfile.py 🤕</h3><ul><li><strong><em>class TestAPI(HttpUser)</em></strong><em>:</em> Here we define a class for the users that we will be simulating. It inherits from <a href="https://docs.locust.io/en/stable/api.html#locust.HttpUser"><strong>HttpUser</strong></a> which gives each user an client attribute, which is an instance of <a href="https://docs.locust.io/en/stable/api.html#locust.clients.HttpSession"><strong>HttpSession</strong></a>, that can be used to make HTTP requests to the target system that we want to load test. When a test starts, the locust will create an instance of this class for every user that it simulates, and each of these users will start running within their own green gevent thread.</li><li><strong><em>@task:</em></strong> Methods decorated with @task are the core of your locust file. For every running user, Locust creates a greenlet (micro-thread), that will call those methods.</li><li><strong><em>def</em></strong><em> </em><strong><em>on_start(self): </em></strong>A User will call its <a href="https://docs.locust.io/en/stable/api.html#locust.User.on_start"><strong>on_start</strong></a> method when it starts running, For example, if we want to load test data from CSV or from other sources you can write the logic in the <strong><em>on_start</em></strong> method, so when your test starts it loads data from the source.</li><li><strong><em>def</em></strong><em> </em><strong><em>on_stop(self): </em></strong>It&#39;s similar to <strong><em>on_start</em></strong> method.</li><li><strong><em>self.client.get(&quot;/hello&quot;):</em></strong> The self.client attribute makes it possible to make HTTP calls that will be logged by Locust. Internally it uses the <a href="https://pypi.org/project/requests/"><strong>python requests module</strong></a>.</li><li><strong><em>host=’http://0.0.0.0:8001’:</em></strong> Target host where service is deployed.</li><li><strong><em>TaskSet class:</em></strong> Locust provides the TaskSet class. It is <strong>a collection of tasks that will be executed much like the ones declared directly on a User class</strong>.</li><li><strong><em>SequentialTaskSet class: </em></strong><a href="https://docs.locust.io/en/stable/api.html#locust.SequentialTaskSet"><strong>SequentialTaskSet</strong></a> is a TaskSet whose tasks will be executed in the order that they are declared. It is possible to nest SequentialTaskSets within a TaskSet and vice versa.</li></ul><p><em>For more about Locust, you can follow the official </em><a href="https://docs.locust.io/en/stable/index.html"><strong><em>Documentation</em></strong></a><em>.</em></p><h3><strong>Structuring Code Like Pro </strong>😎</h3><p>Let’s take a scenario, In your organization, you have <strong><em>N</em></strong> number of microservices and you need to write a load test code for these services, How will you manage these codes so that every service load test independently and does not impact other services. It helps you to know your services in a better way. Let’s see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*7A2iB3civSnVa5-35VjKgQ.png" /><figcaption>Code Structure</figcaption></figure><h3><strong>Understanding Code Structure </strong>🥱</h3><p>As we already discussed we have 2 microservices (<em>user_service and inventory</em>), Let’s write test cases for inventory.</p><ul><li><strong><em>Falcon</em></strong>: Load test framework name.</li><li><strong><em>load_tests</em></strong>: This module will consist of all the microservices load tests for example user_service and inventory.</li><li><strong><em>common_utils</em></strong>: This module consists of all the utility functions, for example, the function for reading test data from CSV.</li><li><strong><em>user_service and inventory: </em></strong>These modules will consist of the actual load tests, in locustfile.py.</li></ul><h3><strong>Running Load Test in Kubernetes </strong>😇</h3><h4><strong>Architecture</strong></h4><p>This architecture involves two main components:</p><ul><li><strong>Custom Locust Docker container image: </strong>We need to build a custom Docker image so that it contains all our code in a single image.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/999e7ef35caf3cfd30a4c79101166fe8/href">https://medium.com/media/999e7ef35caf3cfd30a4c79101166fe8/href</a></iframe><pre># Creating Docker Image </pre><pre>$ docker build -t custom-locust:latest .</pre><ul><li><strong>Locust Master and Worker.</strong></li></ul><p><strong>Locust Master: </strong>The Locust master is the entry point for executing the load testing tasks. The Locust master configuration specifies several elements, including the default ports used by the container:</p><ul><li>8089 for the web interface</li><li>5557 and 5558 for communicating with workers</li></ul><p>This information is later used to configure the Locust workers.</p><p><strong>Locust Worker</strong>: The Locust workers execute the load testing tasks. You use a single Deployment to create multiple Pods. The Pods are spread out across the Kubernetes cluster. Each Pod uses environment variables to control configuration information, such as the hostname of the system under test and the hostname of the Locust master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69D-7nJXwkrUoEc-O8tahA.png" /></figure><h3>Locust Deployment Files</h3><ul><li><strong>locust-master-deployment.yaml</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70793d50e0fbd6b1f1c82ace32fb05a8/href">https://medium.com/media/70793d50e0fbd6b1f1c82ace32fb05a8/href</a></iframe><ul><li><strong>locust-worker-deployment.yaml</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30b96e72ca34e3589372a3d581a8cff/href">https://medium.com/media/e30b96e72ca34e3589372a3d581a8cff/href</a></iframe><ul><li><strong>locust-service.yaml</strong></li><li>By using LoadBalancer we can expose our service to the outer world.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f40261b7d4e527f667dc5a145386afb/href">https://medium.com/media/7f40261b7d4e527f667dc5a145386afb/href</a></iframe><ul><li><strong>worker-hpa.yaml</strong></li><li><strong>Autoscaling</strong>: We need to HPA for worker pods, so that it auto-scales when it reaches some threshold, currently I choose CPU matrix for auto-scaling.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a447d580cd7ca91014675a95de185c3/href">https://medium.com/media/5a447d580cd7ca91014675a95de185c3/href</a></iframe><p>Once you are done with k8 deployment files, you need to deploy this one by one. <strong>To make it scalable we can build our own helm chart. (We will discuss this later, How you create your own helm chart)</strong></p><h3>All Done with Deployment 🥳</h3><p>Now we just need to copy <strong>EXTERNAL IP </strong>from k8 service deployment and paste it into the browser you will get some UI like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmP0Nss6ql6L4O1c3z4l9g.png" /></figure><ul><li><strong>Number of users</strong>: It signifies the number of concurrent users in the system.</li><li><strong>Spawn Rate: </strong>Rate to spawn users at (users per second). For example</li></ul><pre><em>number_of_user = 10<br>spawn_rate = 2<br>time_to_ramp_up_all_user = number_of_user/spawn_rate</em></pre><ul><li>It will take 5 seconds to ramp up all the users.</li><li><strong><em>It is recommended to keep a low value for Spawn Rate.</em></strong></li></ul><p>Once you start swarming you can check all details like RPS, Latency can download reports, and many more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KO9dMMZNf8b5rLu0xbbRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7ZYamBbk7mM-nDizfRxNg.png" /></figure><h3>Achieve Maximum RPS/QPS in Locust</h3><ul><li>In the production environment use <a href="https://docs.locust.io/en/stable/increase-performance.html">Locust FastHttpUser</a>.</li><li>Use auto-scaling so that workers automatically scale up.</li><li>Start with a small number of users and a low spawn rate, and gradually increase the users.</li><li>Enable Auto rebalancing, so that users are auto rebalanced when any worker is removed or added.</li></ul><h3>References</h3><ul><li><a href="https://docs.locust.io/en/stable/what-is-locust.html">Locust Document</a></li><li><a href="https://docs.locust.io/en/stable/increase-performance.html">Locust FastHttpUser</a> (For a large number of RPS)</li><li><a href="https://github.com/riki-nitdgp/Falcon">Github Code</a></li><li><a href="https://cloud.google.com/architecture/distributed-load-testing-using-gke">Load Testing using GKE</a></li><li><a href="https://docs.locust.io/en/stable/configuration.html">Locust Configuration</a></li><li><a href="https://github.com/riki-nitdgp/Falcon">Github Code</a></li></ul><h3>If you found this helpful, please clap and share the article. Let’s spread the solution to someone who may need it.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a229ce0ed7" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/distributed-load-testing-using-locust-99a229ce0ed7">Distributed Load Testing Using Locust</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Design my own Web Application Framework]]></title>
            <link>https://medium.com/@rickymondal/how-i-design-my-own-application-web-framework-75ecd3f93c8e?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ecd3f93c8e</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[web-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 17:21:59 GMT</pubDate>
            <atom:updated>2020-09-27T18:59:35.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3M5za9-nfC2ArEmulwKQtQ.png" /></figure><p><strong><em>T</em></strong><em>here are lots of different web application frameworks available in the internet, and we used it for developing our web application. But do we ever think how these WF works ? What are the basic components of a WF ? and many more questions may comes in your mind when you using any WF. So this article is basically give all your answers, discuss about how I build my own WF. So tie your seatbelt, we are going to land with our own custom WF.</em></p><p><em>This WF is based on python 3.6+ asyncio, (Asynchronous Programming). Asynchronous programming is a type of parallel programming in which a unit of work is allowed to run separately from the primary application </em><a href="https://whatis.techtarget.com/definition/thread"><em>thread</em></a><em>. When the work is complete, it notifies the main thread about completion or failure of the worker thread. There are numerous benefits to using it, such as improved application performance and enhanced responsiveness. Libraries like </em><em>aiohttp show incredible growth in usage. They handle a large amount of concurrent connections while still maintain good code readability and simplicity. In this short guide, I tried to go behind the scene and clarify the process, by re-building a little </em><em>aiohttp clone from scratch.</em></p><p><strong>Before starting this I am assuming that you are familiar followings:</strong></p><ul><li>Basic understanding about HTTP requests(GET, PUT, POST, DELETE).</li><li>Have a basic understanding of <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a> to follow this guide, but if you need a refresher here are few articles that may help. (<a href="https://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio">Intro to asyncio</a>, <a href="https://dbader.org/blog/understanding-asynchronous-programming-in-python">Understanding asynchronous programming in Python</a>)</li><li>Already work on any web framework.</li></ul><h3>What is a Web Framework (WF)?</h3><p>A web framework is a code library that makes web development quicker and easier by giving basic patterns for building reliable, scalable and maintainable web applications. Web frameworks exist to make it easier for the developer to make a web application. Think of it as a way to create shortcuts that can prevent otherwise overwhelming and repetitive code. For example, you may have written a code to handle data validation for your web application. In order to prevent having to re-write that code from scratch each time you make a website or web service, the web framework does it for you.</p><p>A web framework differs from a web server in that a web server actually <em>runs</em> the web application, while the web framework is more like a virtual database or library that helps speed up the development and writing process.</p><h3>Building Blocks of a Web Framework</h3><ol><li>Transport and Protocol</li><li>Request and Response objects</li><li>Application and Url Dispatcher</li><li>Exception Handling</li><li>Middleware</li><li>ORM (Not Covered in this article)</li><li>Logging (Not Covered in this article)</li></ol><h3>Transport and Protocol</h3><ul><li>Transports and Protocols are used by the <strong>low-level</strong> event loop APIs such as <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_connection">loop.create_connection()</a>. They use callback-based programming style and enable high-performance implementations of network or IPC protocols (e.g. HTTP).</li><li>Essentially, transports and protocols should only be used in libraries and frameworks and never in high-level asyncio applications.</li><li>At the highest level, the transport is concerned with how bytes are transmitted, while the protocol determines which bytes to transmit (and to some extent when).</li><li>A different way of saying the same thing: a transport is an abstraction for a socket (or similar I/O endpoint) while a protocol is an abstraction for an application, from the transport’s point of view.</li><li>Yet another view is the transport and protocol interfaces together define an abstract interface for using network I/O and interprocess I/O.</li><li>There is always a 1:1 relationship between transport and protocol objects: the protocol calls transport methods to send data, while the transport calls protocol methods to pass it data that has been received.</li><li>Most of connection oriented event loop methods (such as <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_connection">loop.create_connection()</a>) usually accept a protocol_factory argument used to create a Protocol object for an accepted connection, represented by a Transport object. Such methods usually return a tuple of (transport, protocol).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e131d9c7a42e11503bac6e94b2eebc31/href">https://medium.com/media/e131d9c7a42e11503bac6e94b2eebc31/href</a></iframe><p>As you can see from the example above, the code is pretty simple, but as you may realize it is not scalable for writing a high-level application yet.</p><p>As HTTP works over TCP transport we already can send HTTP requests to our server, however, we receive them in raw format and working with it will be annoying as you may guess. So next step we need to add better HTTP handling mechanism.</p><h3>Making server protocol</h3><p>Let’s add request parsing so we can extract some useful info like headers, body, path and work with them instead of raw text. Parsing is a complex topic and it is certainly out of the scope of this guide, thats why we will use <a href="https://github.com/MagicStack/httptools">httptools</a> by MagicStack for this as it rapidly fast, standard compatible and pretty flexible. aiohttp, on the other hand, has own hand-written Python based parser as well as binding to Node&#39;s <a href="https://github.com/nodejs/http-parser/tree/77310eeb839c4251c07184a5db8885a572a08352">http-parser</a>.</p><p>Lets write our parsing class, that will be used as mixin for our main Server class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a9fe192b586f301fecfa9c834f205ce/href">https://medium.com/media/4a9fe192b586f301fecfa9c834f205ce/href</a></iframe><h3>Request/Response objects</h3><p>At this moment we have working server that can parse HTTP calls, but for our apps we need better abstractions to work with.</p><p>Let’s create base Request class that will group together all incoming HTTP request information. We will use yarl library for dealing with urls, make sure you installed it with pip.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/330d0b1ac01a77912de0f6a79c78cc58/href">https://medium.com/media/330d0b1ac01a77912de0f6a79c78cc58/href</a></iframe><p>As a next step, we also need a structure, that will helps us to describe outgoing HTTP response in programmer-friendly manner and convert it to raw HTTP, which can be processed by asyncio.Transport.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f71f3388c40fbc938e98759620a10a/href">https://medium.com/media/45f71f3388c40fbc938e98759620a10a/href</a></iframe><p>As you can see code is pretty straight forward we incapsulate all our data and provide proper getters. Also we have few helpers for reading body text and json, that will be used later. We also need to update our Server to actually construct Request object from message.</p><p>It should be created, when a whole request processed, so we need to add it to on_message_complete event handler in our parser mixin.</p><h3>Application &amp; UrlDispatcher</h3><p>At this stage we already have simple working server that can process HTTP requests and Request/Response objects for dealing with request cycles. However, our web framework still miss few important concepts. First of all right now we have only one main request handler, in large applications we have lots of them for different routes so we certainly need mechanism for registering multiple route handlers.</p><p>So, let’s try to build simplest possible UrlDispatcher, just object with internal dict, that store as a key method and path tuple and actual handler as a value. We also need a handler for situation where user try to reach unrecognized route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d73e43ef84d357e5497c538e33c4a07/href">https://medium.com/media/7d73e43ef84d357e5497c538e33c4a07/href</a></iframe><h3>Exception Handling</h3><p>At this steps we have most of the core features added, however, we still have lack of exceptions handling. Great feature about aiohttp is that it allows you to work with web exceptions as a native python exceptions. It&#39;s done with implementing both Exception and Response classes and it&#39;s really flexible mechanism we would like to have as well.</p><p>So, first thing lets create our base HTTPException class and few helpers based on it that we might need like HTTPNotFound for unrecognized paths HTTPBadRequest for user side issues and HTTPFound for redirecting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/789aa81dccb6c6774661f5fca84f7858/href">https://medium.com/media/789aa81dccb6c6774661f5fca84f7858/href</a></iframe><h3>Middleware</h3><p>For those, who aren’t familiar with a this concept, in simple words middleware is just a coroutine, that can modify incoming request object or change response of a handler. It will be fired before each request to the server. Implementation is pretty trivial for our needs. First of all we need to add list of registered middleware inside our Application object and change a little bit Application._handler to run through them. Each middleware should work with result of previous one in chain.</p><h3>Sample application</h3><p>Now when we have our framework ready, lets test our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85091cbf20f803c2dc836d70bb227f5e/href">https://medium.com/media/85091cbf20f803c2dc836d70bb227f5e/href</a></iframe><h3>Conclusion</h3><p>This is pretty simple and powerful micro framework, but it is not production ready software as it still miss lot’s of useful &amp; important features like more robust server, better HTTP support to fully correlate with specification, web sockets to name a few, logging. However, i believe that through this process we developed better understanding how such web framework built.</p><p>You can find the full code on <a href="https://github.com/riki-nitdgp/PyAsynchronous">https://github.com/riki-nitdgp/PyAsynchronous</a> . Please share any improvement or issue you find. Happy Coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ecd3f93c8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Override Uvicorn Logger in FastAPI using Loguru]]></title>
            <link>https://medium.com/1mgofficial/how-to-override-uvicorn-logger-in-fastapi-using-loguru-124133cdcd4e?source=rss-d3da48512b32------2</link>
            <guid isPermaLink="false">https://medium.com/p/124133cdcd4e</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[uvicorn]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-logging]]></category>
            <dc:creator><![CDATA[Ricky Mondal]]></dc:creator>
            <pubDate>Sun, 17 May 2020 11:52:48 GMT</pubDate>
            <atom:updated>2020-07-10T11:22:02.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiY7rmgrbYD37TjC4s0SBw.png" /></figure><p>Logging is very important for any web application, it helps us to debug faster, a good Logging implementation saves us a lot of time.</p><p>Logging is a mean of tracking the events that happen when some web application runs. Logging is important for software developing, debugging and running. If you don’t have any logging record and your program crashes, there are very little chances that you will able to detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem.</p><p>Python has a built-in module <strong>logging</strong> which allows writing status messages to a file or any other output streams. The file can contain the information on which part of the code is executed and what problems have been arisen.</p><p><strong>In this post, we talk about our challenges in figuring out how to implement a logger in FastAPI.</strong></p><h3><strong>Why we chose FastAPI?</strong></h3><blockquote><strong>FastAPI</strong> is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. (<a href="https://fastapi.tiangolo.com/">official document</a>)</blockquote><ul><li>Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). <a href="https://github.com/tiangolo/medium-posts/tree/master/introducing-fastapi#performance">One of the fastest Python frameworks available</a>.</li><li><strong>Robust:</strong> Get production-ready code. With automatic interactive documentation.</li><li><strong>Standards-based:</strong> Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/">JSON Schema</a>.</li><li><strong>Fewer bugs</strong>: Reduce about 40% of human (developer) induced errors. *</li><li><strong>Intuitive</strong>: Great editor support. Completion everywhere. Less time debugging.</li></ul><p>$ pip install fastapi</p><h3><strong>What is Uvicorn and what’s its role in FastAPI deployment ?</strong></h3><blockquote><strong>Uvicorn</strong> is a lightning-fast ASGI server implementation, using <a href="https://github.com/MagicStack/uvloop">uvloop</a> and <a href="https://github.com/MagicStack/httptools">httptools</a>. Until recently Python has lacked a minimal low-level server/application interface for asyncio frameworks. The <a href="https://asgi.readthedocs.io/en/latest/">ASGI specification</a> fills this gap, and means we’re now able to start building a common set of tooling usable across all asyncio frameworks.</blockquote><p>Uvicorn used as application server in Fastapi.</p><p>$ pip install uvicorn</p><h3><strong>What’s the problem?</strong></h3><p>Generally it is very difficult to override default uvicorn logs. When one deploys an application using Uvicorn, this is how the default logs look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*NleAWyiuHxsGj4qYScwFZQ.png" /><figcaption><strong>Logging with default uvicorn logger</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*6YBtrMvm_JyUC7GYNEAU0w.png" /><figcaption>Exception</figcaption></figure><p>From these system logs we can observe that, logs are not in detail and only few information were given. Another problem is that it is very difficult to write these logs in a log file.</p><p>We try to resolve this problem using custom logs implemented using <strong>Loguru </strong>which is a library that aims to bring enjoyable logging in Python.(<a href="https://loguru.readthedocs.io/en/stable/">official document</a>)</p><p>$ pip install loguru</p><h3>Project Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*2PpV3k7zDwUf3jqwsANpaQ.png" /><figcaption>Project Structure</figcaption></figure><h4>logging_config.json</h4><blockquote><em>It basically contain logging config and other application config. In this example we only store logging configuration.</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01545491720fdeab0b10505d04a029ed/href">https://medium.com/media/01545491720fdeab0b10505d04a029ed/href</a></iframe><p>For more customization follow loguru api <a href="https://loguru.readthedocs.io/en/stable/api/logger.html">documentation</a></p><h4><strong>main.py</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/931ab23fca2bf50f50525aa62514c9af/href">https://medium.com/media/931ab23fca2bf50f50525aa62514c9af/href</a></iframe><h4>costum_logging.py</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1de4d4737d9f04eab033da05ede3f1b/href">https://medium.com/media/e1de4d4737d9f04eab033da05ede3f1b/href</a></iframe><h4>Create a requirement.txt file</h4><pre>loguru==0.4.1<br>fastapi<br>uvicorn</pre><blockquote>So everything is ready!! Excited to see the power of loguru.</blockquote><h4>Installation and Setup</h4><ul><li><strong>Create Virtual Environment</strong></li></ul><pre><strong>#</strong> <strong>Install python virtual environment</strong><br>$ <em>pip install virtualenv</em></pre><pre><strong># Check virtual environment version</strong><br><em>$ virtualenv --version</em></pre><pre><strong># Now Create virtual environment</strong><br><em>$ virtualenv my_name</em></pre><pre><strong># Activate Virtual environment<br></strong>$ source virtualenv_name/bin/activate</pre><ul><li><strong>Install requirements</strong></li></ul><pre>$ pip install -r requirement.txt</pre><ul><li><strong>Run your Application</strong></li></ul><pre>$ uvicorn main:app --port 5008 --access-log</pre><h4><strong>The Final Output</strong></h4><p>Using our custom logger implementation, we are able to achieve logging in the desired format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV6It0YwCF2AaRCYFtg7CQ.png" /><figcaption><strong>Logging with Custom Logger</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7U-Rkg4sE4NdXbAnbp03Q.png" /><figcaption>Exception</figcaption></figure><h4><strong>Conclusion</strong></h4><ul><li>We can use uvicorn default logging, there is no harm in it but your web application logs must be customize as per your needs. So you can try this solution.</li><li>Easy to use and customize with loguru. (You can change you logging config for more customization)</li><li>Produce full details of error.</li><li>Easy to store in a specific log file. (which you mention in logging config)</li><li>Better traceback.</li></ul><h3>If you found this helpful, please clap and share the article. Let’s spread the solution to someone who may need it.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124133cdcd4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1mgofficial/how-to-override-uvicorn-logger-in-fastapi-using-loguru-124133cdcd4e">How To Override Uvicorn Logger in FastAPI using Loguru</a> was originally published in <a href="https://medium.com/1mgofficial">Tata 1mg Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>