<?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 Nirmal Yadav on Medium]]></title>
        <description><![CDATA[Stories by Nirmal Yadav on Medium]]></description>
        <link>https://medium.com/@nirmal.yadav00?source=rss-cb7e341bc6f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*68L2kmFQLtakBEw7MqXVkw.png</url>
            <title>Stories by Nirmal Yadav on Medium</title>
            <link>https://medium.com/@nirmal.yadav00?source=rss-cb7e341bc6f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:51:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nirmal.yadav00/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[Redis for Background Jobs in Rails with Sidekiq and Sidekiq-Cron]]></title>
            <link>https://medium.com/@nirmal.yadav00/redis-for-background-jobs-in-rails-with-sidekiq-and-sidekiq-cron-bdc6e9cdeb33?source=rss-cb7e341bc6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc6e9cdeb33</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[asynchronous-processing]]></category>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[background-jobs]]></category>
            <dc:creator><![CDATA[Nirmal Yadav]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 15:02:46 GMT</pubDate>
            <atom:updated>2025-01-14T12:27:36.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*MhLog_ciCUa_vNkRAIlx2A.png" /></figure><h3>Introduction</h3><p>Background job processing is a crucial part of modern web applications, ensuring that time-consuming tasks don’t block user interactions. Redis and Sidekiq form a powerful duo in managing these background tasks efficiently. Redis acts as the message broker, storing job data, while Sidekiq processes jobs concurrently. Sidekiq-Cron further extends this functionality by enabling cron-like job scheduling.</p><p>This article delves into the technical details of how Redis and Sidekiq work together, the structure of data stored in Redis, and how Sidekiq-Cron facilitates scheduled task execution.</p><h3>Redis for Sidekiq</h3><h3>What is Redis?</h3><p>Redis is an in-memory data structure store often used as a database, cache, and message broker. Its speed and support for various data structures (strings, lists, sets, hashes, etc.) make it ideal for queuing systems.</p><h3>How Redis Works with Sidekiq</h3><h4>Job Queues</h4><p>Redis uses a list data structure to store Sidekiq job queues. Each queue represents a different type of job, with jobs enqueued as elements in these lists.</p><ul><li><strong>List Structure</strong>: Jobs are stored in Redis lists (LPUSH to add to the front and BRPOP to retrieve from the end). This structure allows Sidekiq to efficiently manage job queues with FIFO (First-In-First-Out) order.</li></ul><h4>Job Data</h4><p>Jobs are stored as serialized JSON objects, including the following key details:</p><ul><li><strong>Queue Name</strong>: The queue to which the job belongs.</li><li><strong>Class</strong>: The worker class responsible for processing the job.</li><li><strong>Arguments</strong>: Arguments passed to the job.</li><li><strong>Retries</strong>: The number of retries left if the job fails.</li><li><strong>JID</strong>: A unique job identifier.</li></ul><p>Example of a job stored in Redis:</p><pre>{<br>  &quot;queue&quot;: &quot;default&quot;,<br>  &quot;class&quot;: &quot;EmailWorker&quot;,<br>  &quot;args&quot;: [12345],<br>  &quot;retry&quot;: 5,<br>  &quot;jid&quot;: &quot;abcdef123456&quot;,<br>  &quot;created_at&quot;: 1622547802.123456<br>}</pre><h4>Job Enqueueing and Processing</h4><ul><li><strong>Enqueueing</strong>: When a job is enqueued using perform_async, Sidekiq pushes the job to the appropriate Redis list using LPUSH.</li><li><strong>Processing</strong>: Workers fetch jobs using BRPOP, which blocks until a job is available, ensuring efficient use of resources. The job is then deserialized and executed by the worker.</li></ul><h4>Retries and Failure Handling</h4><p>Redis tracks job status and retries:</p><ul><li><strong>Failed Jobs</strong>: If a job fails, it’s moved to a retry queue with a delayed re-enqueue time, stored in a sorted set with the score representing the retry time.</li><li><strong>Exponential Backoff</strong>: The retry delay increases exponentially, managed by Redis timestamps.</li></ul><h4>Enqueuing Jobs with Sidekiq</h4><p>To enqueue a job with Sidekiq:</p><ol><li><strong>Install Sidekiq</strong>:<br>Add the gem to your Gemfile and bundle install</li></ol><pre>gem &#39;sidekiq&#39;</pre><ol><li><strong>Worker Definition</strong>: Workers are defined by including the Sidekiq::Worker module and implementing the perform method.</li></ol><pre>class EmailWorker<br>  include Sidekiq::Worker<br><br>  def perform(user_id)<br>    user = User.find(user_id)<br>    UserMailer.welcome_email(user).deliver_later<br>  end<br>end</pre><p><strong>3. Enqueue a Job</strong>:</p><pre>EmailWorker.perform_async(user.id)</pre><p>Sidekiq pushes the job to Redis, and workers pull it for processing.</p><h3>perform_async, perform_now, and perform_later</h3><h4>perform_async (Async Job)</h4><ul><li><strong>Usage</strong>: This method is used to enqueue a job to be performed asynchronously by Sidekiq workers.</li><li><strong>Behavior</strong>: The job is pushed to Redis and processed by available worker threads in the background.</li><li><strong>Example</strong>:</li></ul><pre>EmailWorker.perform_async(user.id)</pre><ul><li><strong>When to use</strong>: Use perform_async when you want to queue a job to be processed in the background, typically for long-running or non-blocking tasks like sending emails or processing data.</li></ul><h4>perform_now (Immediate Execution in Same Process)</h4><ul><li><strong>Usage</strong>: This method is used to execute a job immediately in the current thread, synchronously.</li><li><strong>Behavior</strong>: The job is not enqueued; instead, it runs immediately in the same process. This is not background processing.</li><li><strong>Example</strong>:</li></ul><pre>EmailWorker.perform_now(user.id)</pre><ul><li><strong>When to use</strong>: Use perform_now if you want to run the job synchronously in the current thread, as if you were calling a regular method. This is useful for tasks that need to run immediately within the same request/response cycle, though it&#39;s typically not recommended for heavy tasks, as it will block the request.</li></ul><h4>perform_later (Active Job)</h4><ul><li><strong>Usage</strong>: This method is part of <strong>Rails’ Active Job</strong> framework and is used to enqueue jobs for background processing.</li><li><strong>Behavior</strong>: Internally, when you call perform_later, it delegates the call to the underlying job processor (in this case, Sidekiq).</li><li><strong>Example</strong>:</li></ul><pre>EmailJob.perform_later(user.id)</pre><ul><li><strong>When to use</strong>: perform_later is the preferred method when working with Active Job in Rails, as it provides a framework-agnostic way to enqueue background jobs. If you&#39;re using Sidekiq as the backend, it will call perform_async under the hood.</li></ul><h3>Redis for Sidekiq-Cron</h3><h4>What is Sidekiq-Cron?</h4><p><strong>Sidekiq-Cron</strong> is an extension to Sidekiq that allows scheduling jobs to run at specific times or intervals, similar to cron jobs in Unix. It provides cron-like syntax to schedule recurring jobs in your Sidekiq workers.</p><h3>How Redis and Sidekiq-Cron Work Together</h3><h4>Job Scheduling</h4><ul><li><strong>Cron Syntax</strong>: Sidekiq-Cron jobs are scheduled using cron expressions, which are parsed and stored in Redis.</li><li><strong>Data Structure</strong>: Scheduled jobs are stored in a Redis hash, mapping job names to their cron expressions and other metadata.</li></ul><p>Example of a scheduled job in Redis:Example: Scheduling a Cron Job</p><pre>{<br>  &quot;name&quot;: &quot;daily_email_reminder&quot;,<br>  &quot;cron&quot;: &quot;0 9 * * *&quot;,<br>  &quot;class&quot;: &quot;EmailReminderWorker&quot;,<br>  &quot;args&quot;: []<br>}</pre><ol><li><strong>Install Sidekiq-Cron</strong>:<br>Add the gem to your Gemfile and bundle install:</li></ol><pre>gem &#39;sidekiq-cron&#39;, &#39;~&gt; 1.0&#39;</pre><p>2. <strong>Define a Cron Job</strong>:</p><p>In config/initializers/sidekiq.rb, you can schedule jobs with cron syntax:</p><pre>Sidekiq::Cron::Job.create(<br>  name: &#39;Email Reminder - every day at 9am&#39;,<br>  cron: &#39;0 9 * * *&#39;,<br>  class: &#39;EmailReminderWorker&#39;<br>)</pre><p>3. <strong>Worker Definition</strong>:</p><pre>class EmailReminderWorker<br>  include Sidekiq::Worker<br><br>  def perform<br>    # Job logic (e.g., send reminders)<br>  end<br>end</pre><p>This schedules the EmailReminderWorker to run every day at 9 AM. Redis stores the schedule, and Sidekiq processes the job when it&#39;s due.</p><h3>Execution Flow for Cron Jobs in Sidekiq-Cron</h3><p>The execution flow for cron jobs in Sidekiq-Cron can be broken down into the following steps:</p><h4>1. Job Definition and Configuration</h4><p>First, the job needs to be defined with the cron expression and the worker class. The job configuration is then stored in Redis.</p><p>Example:</p><pre>Sidekiq::Cron::Job.create(<br>  name: &#39;Daily Email Reminder&#39;,<br>  cron: &#39;0 9 * * *&#39;,<br>  class: &#39;EmailReminderWorker&#39;<br>)</pre><h4>2. Storing Job Data in Redis</h4><p>Sidekiq-Cron stores the cron job configuration in Redis using a hash structure. This includes the cron expression, the worker class, the arguments, and the next execution time.</p><p>Example Redis structure:</p><pre>{<br>  &quot;name&quot;: &quot;daily_email_reminder&quot;,<br>  &quot;cron&quot;: &quot;0 9 * * *&quot;,<br>  &quot;class&quot;: &quot;EmailReminderWorker&quot;,<br>  &quot;args&quot;: [],<br>  &quot;next_at&quot;: &quot;1700000000&quot;  // UNIX timestamp of the next execution time<br>}</pre><h4>3. Periodic Polling for Job Execution</h4><p>Sidekiq-Cron performs periodic polling, typically every 60 seconds, to check if any job’s next execution time has arrived. This is controlled by the SIDEKIQ_CRON_POLL_INTERVAL setting.</p><h4>4. Cron Expression Parsing</h4><p>Sidekiq-Cron uses a cron parser to determine if the current time matches the job’s scheduled time. If the current time is a match, the job is enqueued for execution.</p><h4>5. Enqueuing Jobs</h4><p>When the scheduled time arrives, Sidekiq-Cron enqueues the job into the specified queue. This happens by serializing the job data into a JSON object and pushing it into Redis using the lpush command.</p><h4>6. Job Execution by Workers</h4><p>Once the job is enqueued, a Sidekiq worker fetches the job from the queue, deserializes the payload, and executes the perform method of the worker.</p><h4>7. Logging and Handling Failures</h4><p>After the job executes, Sidekiq logs the execution status. If the job fails, it may be retried with exponential backoff, ensuring that failed jobs don’t block the system.</p><h3>Key Benefits of Redis with Sidekiq and Sidekiq-Cron</h3><ol><li><strong>Scalability</strong>: Redis handles high throughput efficiently, and Sidekiq can process jobs concurrently, making the system highly scalable.</li><li><strong>Reliability</strong>: Redis ensures jobs are safely stored, even if workers fail. Failed jobs are retried automatically.</li><li><strong>Job Scheduling</strong>: Sidekiq-Cron allows for easy scheduling of periodic tasks without external cron job dependencies.</li><li><strong>Concurrency</strong>: Sidekiq workers process multiple jobs in parallel, utilizing Redis to manage job queues.</li></ol><h3>Conclusion</h3><p>Using Redis with <strong>Sidekiq</strong> provides a fast, reliable, and scalable solution for background job processing in Rails applications. Redis acts as the queue manager, storing job data, while Sidekiq processes jobs asynchronously with multi-threading.</p><p>When combined with <strong>Sidekiq-Cron</strong>, you can schedule jobs to run at specific intervals, further automating background task management. Together, these tools allow for highly efficient, fault-tolerant, and scalable job processing systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc6e9cdeb33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Job Scheduling in Rails with Sidekiq Cron]]></title>
            <link>https://medium.com/@nirmal.yadav00/dynamic-job-scheduling-in-rails-with-sidekiq-cron-e2d08bdf8139?source=rss-cb7e341bc6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d08bdf8139</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[cronjob-scheduler]]></category>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[dynamic-job-scheduler]]></category>
            <dc:creator><![CDATA[Nirmal Yadav]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 16:35:54 GMT</pubDate>
            <atom:updated>2025-01-13T15:20:42.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>In many modern applications, background jobs need to run at custom intervals based on user preferences.</p><p>Imagine a scenario where different users want to schedule the same job at different frequencies:</p><ul><li><strong>User A</strong> wants a job to run <strong>every 1 hour</strong>.</li><li><strong>User B</strong> wants the same job to run, but <strong>every 3 hours</strong>.</li></ul><p>Hardcoding schedules or manually adjusting them for each user becomes cumbersome and error-prone as the user base grows.<br>You need a solution that allows your users to specify the frequency at which jobs should run, and dynamically adjust job scheduling without needing code changes for every configuration update. This is where <strong>Sidekiq Cron</strong> comes into play.</p><h3>The Solution: Sidekiq Cron</h3><p>Sidekiq Cron provides an easy way to schedule recurring jobs in a Sidekiq worker using cron expressions. With <strong>Sidekiq Cron</strong>, we can configure jobs dynamically at runtime based on user preferences.</p><p>By integrating <strong>Sidekiq Cron</strong>, you can let users choose their preferred scheduling frequency via a simple UI, and your application will handle the scheduling on the backend without needing manual updates to the cron expressions each time.</p><h3>What Is Sidekiq Cron?</h3><p><a href="https://github.com/ondrejbartas/sidekiq-cron">Sidekiq Cron</a> is a gem that allows you to schedule recurring jobs using cron syntax. It integrates seamlessly with <strong>Sidekiq</strong> and helps you run background tasks on a specified schedule.</p><h3>Why This Approach?</h3><p>Using <strong>Sidekiq Cron</strong> offers several key advantages:</p><ul><li><strong>Customization</strong>: Users can control the frequency of their background jobs.</li><li><strong>Efficiency</strong>: You avoid manual code changes when schedules change.</li><li><strong>Scalability</strong>: It scales effortlessly as new users with different scheduling needs are added.</li><li><strong>Real-time updates</strong>: Schedules can be updated at runtime without requiring application restarts.</li></ul><h3>How to Implement Dynamic Job Scheduling</h3><h4>1. Install the Sidekiq Cron Gem</h4><p>To get started, add the <strong>sidekiq-cron</strong> gem to your Gemfile:</p><pre>gem &#39;sidekiq-cron&#39;, &#39;~&gt; 1.0&#39;</pre><p>Then run:</p><pre>bundle install</pre><h4>2. Job Scheduling with schedule.yml</h4><p>By default, <strong>Sidekiq Cron</strong> loads cron job configurations from a file called schedule.yml stored in the config directory. This file defines the cron jobs and their schedules. Here&#39;s an example:</p><pre># config/schedule.yml<br># Default Job for Report Processing - Runs every hour<br>process_report_user:<br>  cron: &quot;0 * * * *&quot; # Cron expression for every hour<br>  class: &quot;ReportProcessingJob&quot;<br>  args: []<br><br># Default Job for Notification Sending - Runs every 3 hours<br>send_notifications_user:<br>  cron: &quot;0 */3 * * *&quot; # Cron expression for every 3 hours<br>  class: &quot;NotificationSendingJob&quot;<br>  args: []</pre><p><strong>Sidekiq Cron</strong> automatically reads the cron schedules from schedule.yml when the application starts, making it easy to manage predefined schedules.</p><h4>3. Dynamic Updates to Cron Jobs</h4><p>If a user updates their job scheduling preferences (e.g., changing the frequency from hourly to every 3 hours), you need to update the cron job at runtime. <strong>Sidekiq Cron</strong> provides an easy way to do this.</p><p>When a user changes their schedule, the configuration in the database needs to be updated, and then the cron job should be updated dynamically using <strong>Sidekiq Cron’s API</strong>. Here’s how you can handle this:</p><pre>class UserJobScheduler<br>  # klass_name is the Job class name, can get it from config saved in DB<br>  # cron_expression can get it from config saved in DB<br>  def self.update_schedule(user, klass_name, cron_expression)<br>    job_name = &quot;klass_name_#{user.id}&quot;<br><br>    # Creates/Updates job with the updated cron expression<br>    Sidekiq::Cron::Job.create(<br>      name: job_name,<br>      cron: cron_expression,<br>      class: klass_name,<br>      args: [user.id]<br>    )<br>  end<br>end</pre><p>In this case, the cron expression is passed from the UI (e.g., &quot;0 * * * *&quot; for every hour or &quot;0 */3 * * *&quot; for every 3 hours). You simply pass the selected cron expression directly to the method to update the job schedule.</p><h4>4. Where Do Scheduled Jobs Reside?</h4><p>Sidekiq Cron stores job schedules in <strong>Redis</strong>, not the database. Redis handles the cron job configurations in memory, allowing jobs to be triggered at the specified intervals without burdening the database. This approach ensures fast, scalable job scheduling managed entirely by Redis, providing efficiency and minimal overhead.</p><p>For more details on how Redis works and its role in job scheduling, check out this <a href="https://medium.com/@nirmal.yadav00/redis-for-background-jobs-in-rails-with-sidekiq-and-sidekiq-cron-bdc6e9cdeb33">Redis article</a>.</p><h3>Understanding Cron Expressions</h3><p>Cron expressions are strings that represent the timing of scheduled jobs. Here’s a breakdown of the syntax:</p><ul><li>* - Every value</li><li>*/3 - Every 3 units</li><li>0 * * * * - Every hour (at minute 0)</li><li>0 */3 * * * - Every 3 hours (at minute 0)</li></ul><p>To help you understand the exact intervals at which jobs will be triggered in UTC, here are some common cron expressions and their corresponding schedules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6QaTel7Td9QoW_RyxGcgg.png" /></figure><p><strong>For example:</strong></p><ul><li>**”<em>/30 * * * “</em> will trigger the job at the 0th and 30th minute of every hour, like <strong>00:00, 00:30, 01:00, 01:30, 02:00</strong>, and so on.</li></ul><h3>Conclusion</h3><p>With <strong>Sidekiq Cron</strong>, you can build a flexible, dynamic background job scheduling system where users can set their own job frequencies. This approach saves you from hardcoding schedules, ensures scalability, and allows for real-time updates to job schedules without restarting your application. By integrating <strong>Sidekiq Cron</strong>, your application will be able to handle varying scheduling needs efficiently and gracefully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d08bdf8139" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>