<?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 Ali Rafiei on Medium]]></title>
        <description><![CDATA[Stories by Ali Rafiei on Medium]]></description>
        <link>https://medium.com/@a.rafiei1375?source=rss-8e6f9dbd08ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ORMAUquWbElayNaXGZSq2w.jpeg</url>
            <title>Stories by Ali Rafiei on Medium</title>
            <link>https://medium.com/@a.rafiei1375?source=rss-8e6f9dbd08ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:21:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.rafiei1375/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[From Full Scans to Fast Estimates: Solving Django’s Big Table Count Problem]]></title>
            <link>https://towardsdev.com/from-full-scans-to-fast-estimates-solving-djangos-big-table-count-problem-d143936dc887?source=rss-8e6f9dbd08ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/d143936dc887</guid>
            <category><![CDATA[django-orm]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ali Rafiei]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 06:28:17 GMT</pubDate>
            <atom:updated>2026-06-30T13:11:20.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxTx4Mae4ZLzo5viw7lg9g.png" /></figure><p>If you scale a Django application backed by PostgreSQL, you will eventually hit a wall that feels like a rite of passage: <strong>The Slow </strong><strong>COUNT(*) Wall.</strong></p><p>You know the drill. You have a table with 50 million rows. A user loads a page, and the Django Admin or a REST Framework API tries to figure out pagination. Under the hood, Django executes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*vAxgP0tjsFs0L_GUjp8fQg.png" /></figure><p>Because of PostgreSQL’s Multi-Version Concurrency Control (MVCC), the database has to physically scan the table (or a massive index) to count visible rows. The query slows down, CPU spikes, and your app throws a 504 gateway timeout.</p><h3>The Community’s Standard Answers (And Why They Fall Short)</h3><p>When you look for answers in the Django community or search for open-source solutions, you generally run into two paths:</p><p>first is: “Just look at pg_class.reltuples” You&#39;ll find snippets that intercept the count and query the system catalog:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwiuel3C2D9gb0mkgYMyEw.png" /></figure><p><em>The catch:</em> This works beautifully — until your user clicks a single filter. The moment a WHERE clause is added, pg_class becomes completely useless.</p><p><strong>second is: “Submit a PR to Django Core”</strong> Many have tried. However, Django’s core values require database agnosticism. Features that uniquely exploit PostgreSQL’s planner inner workings without clean abstractions for SQLite, MySQL, and Oracle are fundamentally a non-starter for core merge.</p><p>This leaves developers stranded right when they need help the most: when a user runs a complex, filtered search on a multi-million row table, and the pagination count kills the database performance.</p><h3>Going Deeper: Leveraging EXPLAIN on Raw Compilation</h3><p>To truly fix this, we have to look past simple catalog lookups and tap directly into the PostgreSQL query planner itself. PostgreSQL’s EXPLAIN engine calculates remarkably accurate estimates for queries containing intricate WHERE criteria and joins, without actually running the execution path.</p><p>Inspired by the classic <a href="https://wiki.postgresql.org/wiki/Count_estimate">PostgreSQL Wiki patterns on count estimation</a>, I built and open-sourced <strong>django-postgresql-estimated-count</strong>.</p><p>Instead of forcing a full sequential scan or resorting to generic table-level approximations, the library intercepts Django’s compiler lifecycle. When a QuerySet calls .count() and filters have been applied, it dynamically rewrites the query into an EXPLAIN plan statement, safely parses the JSON execution tree, and returns the planner&#39;s estimated row count instantly.</p><h3>When Should You Use This?</h3><ul><li><strong>High-Volume Pagination:</strong> Perfect for Django Admin interfaces or API endpoints serving heavy datasets to users where showing “About 1,450,000 results” is infinitely better than an application crash.</li><li><strong>Simple Filter Queries:</strong> While other approximate-count packages break because they only support table-level totals, this library handles active filtering. Just keep its limitations in mind: it doesn’t perform well with complex JSON field lookups or highly restrictive filters that shrink your dataset down to a few rows. It works perfectly when your filters are straightforward, the remaining dataset is still large, and a solid estimate (like 200,000 vs. 201,000) is all you need.</li></ul><p><em>Check out the repository, try it in your staging environments, and let’s keep Django scaling cleanly on PostgreSQL!</em></p><p>🔗 <strong>Check it out on </strong><a href="https://github.com/alirafiei75/django-postgresql-estimated-count"><strong>GitHub</strong></a><strong> or </strong><a href="https://pypi.org/project/django-postgresql-estimated-count/"><strong>PyPI</strong></a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d143936dc887" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/from-full-scans-to-fast-estimates-solving-djangos-big-table-count-problem-d143936dc887">From Full Scans to Fast Estimates: Solving Django’s Big Table Count Problem</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Frustration to Function: Crafting a Django Soft Delete Tool]]></title>
            <link>https://towardsdev.com/from-frustration-to-function-crafting-a-django-soft-delete-tool-12b239086005?source=rss-8e6f9dbd08ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b239086005</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[soft-delete]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ali Rafiei]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 14:43:09 GMT</pubDate>
            <atom:updated>2025-03-27T15:59:26.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*610F1LBVi6wy1rAH2-nP3A.png" /></figure><p>As Django developers, we often face the challenge of choosing between permanently deleting data or keeping it around for potential recovery or auditing. After evaluating existing soft delete libraries and running into their limitations, I decided to build a better solution. This article shares the journey — what didn’t work, what I built instead, and how you can easily integrate this soft deletion logic into your own Django projects.</p><h3>The Problem with Existing Soft Delete Solutions</h3><p>When working with Django, I needed <strong>soft delete functionality</strong> — a way to <strong>“delete”</strong> objects without actually removing them from the database. Instead of permanently deleting a record, <strong>soft deletion</strong> simply marks it as deleted, usually by setting a deleted_at timestamp.</p><p>Before writing my own solution, I did my homework:</p><ul><li><strong>Checked existing open-source libraries.</strong></li><li><strong>Tried different approaches.</strong></li><li><strong>Investigated Django’s ORM internals.</strong></li></ul><h3>What I Found</h3><p>While there are a few Django soft delete libraries out there, most fall short in key areas:</p><ul><li><strong>They override Django’s </strong><strong>delete() method, </strong>which breaks expected behavior—especially during bulk deletes or cascades.</li><li><strong>They ignore Django’s </strong><strong>on_delete rules, </strong>leading to incorrect handling of related objects.</li></ul><p>It became clear that none of the existing solutions integrated cleanly with Django’s ORM or respected its deletion semantics. So, I set out to build one that does.</p><h3>How I Designed a Better Soft Delete Library</h3><p>I wanted my solution to be:</p><p>✅ <strong>Fully compatible with Django ORM.<br></strong>✅ <strong>Support cascading soft deletes.<br></strong>✅ <strong>Respect Django’s ForeignKey on_delete behaviors.<br></strong>✅ <strong>Work seamlessly with QuerySets.<br></strong>✅ <strong>Include soft delete signals. (pre_soft_delete, post_soft_delete)</strong></p><h3>1. A Custom Collector for Recursive Soft Deletion</h3><p>Django uses a Collector class internally to handle cascaded deletes. I took inspiration from it to build a SoftDeleteCollector that:</p><ul><li><strong>Collects related objects.</strong></li><li><strong>Applies soft deletion recursively.</strong></li><li><strong>Honors </strong><strong>on_delete behavior.</strong></li><li><strong>Bypasses overriding the core </strong><strong>delete() method. (which avoids nasty edge cases)</strong></li></ul><p>This approach keeps everything neatly integrated with Django’s ORM flow.</p><h3>2. Using deleted_at Instead of Deleting Records</h3><p>At the heart of soft deletion is a simple idea: don’t delete the record — just timestamp it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*WIkDU8UPb2A9rbfHDaZxcw.png" /></figure><p>This keeps the data in your database and makes it retrievable anytime, without polluting your regular queries.</p><h3>3. Respecting on_delete Behavior for Foreign Keys</h3><p>One of the major flaws in existing soft delete libraries is their disregard for Django’s on_delete behavior.</p><p>I designed this library to <strong>fully respect</strong> Django’s deletion semantics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*E_1_KeJyN8MxlYF-HMZXlQ.png" /></figure><p>Here’s how each on_delete mode is handled:</p><ul><li>CASCADE → Related objects are soft deleted recursively</li><li>SET_NULL → The foreign key is nullified</li><li>PROTECT → Raises an error and blocks deletion if related objects exist</li></ul><p>This means soft deletion behaves just like native deletion — but safer.</p><h3>4. A Custom QuerySet to Manage Soft-Deleted Records</h3><p>To avoid manual filtering, I implemented a custom QuerySet manager with clear, expressive methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*05YArbk4QHCHugsCtKSeUA.png" /></figure><h3>5. Soft Delete Signals</h3><p>Finally, I introduced pre_soft_delete and post_soft_delete signals—modeled after Django’s native pre_delete and post_delete:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*mAuUq0L7AFRVXadHx-ACPQ.png" /></figure><p>This gives you full control to hook into the soft deletion lifecycle and trigger custom logic when needed.</p><h3>Publishing the Library</h3><p>Once everything was working smoothly, I packaged the project and <strong>published it as an open-source Python package</strong>. If you’re interested in trying it out:</p><blockquote>pip install django-soft-deletion-model</blockquote><h3>Future Plans</h3><p>I plan to <strong>improve this library</strong> by adding:</p><ul><li><strong>Automatic restoration logic</strong> (undo soft deletes)</li><li><strong>Django Admin integration for soft deleted records</strong></li></ul><h3>Final Thoughts</h3><p>If you’re working with Django and need <strong>a reliable soft delete solution</strong>, you no longer have to rely on incomplete implementations. With <strong>proper QuerySets, ForeignKey handling, and signals</strong>, this approach integrates <strong>seamlessly into Django’s ORM</strong>.</p><p>🔗 <strong>Check it out on GitHub or PyPI:</strong> <a href="https://github.com/alirafiei75/django-soft-deletion">GitHub Repo Link</a> , <a href="https://pypi.org/project/django-soft-deletion-model/">PyPI Link</a></p><p>💬 <strong>Have thoughts, suggestions, or want to contribute?</strong> Drop a comment or open an issue on GitHub! 🚀</p><p>Also you can contact me on<a href="https://www.linkedin.com/in/ali-rafiei"> Linkedin</a>!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b239086005" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/from-frustration-to-function-crafting-a-django-soft-delete-tool-12b239086005">From Frustration to Function: Crafting a Django Soft Delete Tool</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Challenges to Contributions: Optimizing Celery Beat for High Loads]]></title>
            <link>https://towardsdev.com/from-challenges-to-contributions-optimizing-celery-beat-for-high-loads-f4e5a119b546?source=rss-8e6f9dbd08ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e5a119b546</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[django-celery-beat]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ali Rafiei]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 13:50:35 GMT</pubDate>
            <atom:updated>2025-01-09T19:47:40.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*V3GXhr3h47ClblaY" /></figure><p>When your tools start breaking under pressure, you have two options: find another one or dive into the code and fix it yourself. This is the story of how I tackled Celery Beat and ended up contributing to its core.</p><h3>What was the problem?</h3><p>In one of the projects I’m working on, which is a customer club software, Celery Beat plays a critical role in scheduling tasks. As the project grew and the number of users and scheduled tasks skyrocketed, Celery Beat started struggling. It didn’t take long before I began noticing strange behaviors:</p><ul><li><strong>Tasks that were supposed to run didn’t.</strong></li><li><strong>The scheduler was getting slower.</strong></li><li><strong>The database load increased significantly as tasks piled up.</strong></li><li><strong>CPU usage of celery-beat skyrocketed at certain times.</strong></li></ul><p>These challenges forced me to dig deep into Celery Beat’s internals and rethink how it manages task scheduling.</p><h3>Challenge 1: Tasks Were Skipped</h3><p>The first issue I noticed was that some tasks simply wouldn’t execute on time. After spending hours debugging, I traced the problem to the <strong>DatabaseScheduler</strong>:</p><ul><li>In every tick, it would fetch <strong>all enabled tasks</strong> from the database and loop through them to find the next task to execute.</li><li>This included tasks scheduled to run hours or even days later, unnecessarily loading the system and delaying important tasks.</li></ul><p>Here’s the original snippet of code that is responsible for querying scheduled tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QrlkbnLNSzpK8HDw" /></figure><p><strong>My Solution:</strong></p><ol><li>For <strong>Clocked Tasks</strong>, I added filters to fetch only tasks scheduled to run in the next 5 minutes.</li><li>For <strong>Crontab Tasks</strong>, I restricted the scheduler to only process tasks scheduled for the current hour, the previous hour, or the next hour.</li><li>For <strong>Solar &amp; Interval Tasks</strong>, I presented no solutions because in my project there are no tasks on these schedule types. 😁</li></ol><p>Here’s the refactored code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p7iRcC0ydNyqKEMY" /></figure><p>* get_excluded_hours_for_crontab_tasks is a static method that returns all hours of the day except current hour, previous hour and next hour.</p><h3>Challenge 2: Dealing with Different Time Zones</h3><p>Another issue I encountered was a clash of time zones:</p><ul><li><strong>Clocked Tasks</strong> were stored and processed in <strong>UTC</strong>.</li><li><strong>Crontab Tasks</strong> were based on the project’s time zone (<strong>Asia/Tehran</strong>).</li></ul><p>This mismatch caused significant confusion and made filtering tasks a headache.</p><p><strong>My Solution:</strong></p><ul><li>I used timezone.now() to get the current UTC time.</li><li>Then, I used Django’s localtime() function to convert the UTC time to the configured time zone (<strong>Asia/Tehran</strong>), ensuring consistency across all task scheduling.</li></ul><h3>Challenge 3: Handling a High Number of Simultaneous Tasks</h3><p>One problem that remains unresolved is <strong>handling a large number of tasks scheduled to run at exactly the same time</strong>. When many tasks are due simultaneously, Celery Beat becomes overwhelmed, and the system slows down as it processes each task individually.</p><p><strong>Possible Solutions (Ideas I’m Exploring):</strong></p><ul><li>Implementing <strong>batch processing</strong> to group tasks and execute them in chunks rather than one by one.</li><li>Developing a <strong>custom scheduler</strong> that can prioritize tasks and reduce the overhead of simultaneous task execution.</li></ul><p>This challenge is still on my to-do list, and I’m looking forward to experimenting with different approaches.</p><h3>Results</h3><p>After implementing these optimizations, the impact on our system was immediate and dramatic.</p><h4>Before Optimization</h4><ul><li>CPU usage: 95–100% during peak times.</li><li>Scheduler lag: Frequently skipped tasks.</li></ul><h4>After Optimization</h4><ul><li>CPU usage: Reduced to 5–10% during peak times.</li><li>Scheduler lag: No skipped tasks.</li></ul><p>Here’s a CPU usage graph showing the before-and-after impact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0uYylNzjwnIInx5D" /></figure><p>* Before the red part there was no optimization.<br>* Red part was after optimizing clocked tasks.<br>* Both clocked and crontab tasks are optimized after the red part.</p><p>Also, RAM usage and Network I/O before-and-after the optimization were like the graphs below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8c4lzOc-kdy1Tn9z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lICsyLNSMukJaj4e" /></figure><h3>Taking It a Step Further: Contributing Back</h3><p>After optimizing Celery Beat for my own project, I realized these changes could benefit others too. I decided to contribute back to the open-source community by submitting a <a href="https://github.com/celery/django-celery-beat/pull/835"><strong>Pull Request</strong></a> to the Celery Beat repository.</p><p>This involved:</p><ul><li>Forking the project and implementing my optimizations.</li><li>Opening a detailed PR explaining the changes and how they improve performance.</li><li>Waiting for a review from the maintainers (and yes, the waiting game is real! 😞).</li></ul><h3>The Lessons:</h3><p>This journey taught me more than just technical skills. It reminded me of the importance of understanding the tools we use, contributing to the open-source ecosystem, and tackling challenges head-on. Whether the PR gets merged or not, I’m proud to have taken the initiative to make a meaningful contribution.</p><h3>What About You?</h3><p>Have you faced similar challenges with scheduling systems or scaling task queues? What solutions worked for you? I’d love to hear your thoughts and experiences in the comments below! 👇</p><p>Also you can contact me on<a href="https://www.linkedin.com/in/ali-rafiei"> Linkedin</a>!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e5a119b546" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/from-challenges-to-contributions-optimizing-celery-beat-for-high-loads-f4e5a119b546">From Challenges to Contributions: Optimizing Celery Beat for High Loads</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>