<?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 uday on Medium]]></title>
        <description><![CDATA[Stories by uday on Medium]]></description>
        <link>https://medium.com/@uday12kumar?source=rss-60b3cf434807------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BmtSIsEMMpro5o5O.jpeg</url>
            <title>Stories by uday on Medium</title>
            <link>https://medium.com/@uday12kumar?source=rss-60b3cf434807------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:51:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uday12kumar/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[Handling Concurrency (Django way)]]></title>
            <link>https://medium.com/@uday12kumar/handling-concurrency-django-way-c65b89a6565d?source=rss-60b3cf434807------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65b89a6565d</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[uday]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 12:42:51 GMT</pubDate>
            <atom:updated>2020-01-28T12:54:26.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Applications now a days are serving millions of users at the same time. With a lot of requests comes a wide range of problems <strong>concurrency</strong> problems is one of them .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s_FHOwwK1SWEaII8" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Problem<br>To demonstrate common concurrency issues we are going to work on a slot booking model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a021c6b24ef377533ab3654a68d462b/href">https://medium.com/media/3a021c6b24ef377533ab3654a68d462b/href</a></iframe><p>To get started we are going to implement a naive book and cancel methods for an instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62ed621b3caa7f5bbde53c58241e14e3/href">https://medium.com/media/62ed621b3caa7f5bbde53c58241e14e3/href</a></iframe><p>This seems unimpeachable and it might even pass test-cases. But, when two users perform actions on the same slot at the same time will it work the same ?</p><blockquote>Step 1 : John fetches the slot — seats are 10.<br> Step 2 : Sam fetches the slot — seats are 10.<br> Step 3 : Sam books 2 slots — seats is updated to 10–2 = 8.<br> Step 4 : John books 1 slot — seats is updated to 10–1 = 9.<br>What happened here?<br>Sam asked to book 2 slots and John asked to book 1 slot — we expect the seats to be 7, but we ended up with 9.</blockquote><h3><strong>Why did it happen?</strong><br>At step 4, when John updated the seats, the count he had stored in memory was stale (Sam had already booked 2 seats).</h3><p>To prevent this situation from happening we need to make sure the resource we are working/altering is not being alerted by another.</p><p>Locking approach<br>Believe that the worst will happen and avoid it<br>lock the resource exclusively until you are done updating it.</p><blockquote>To acquire a lock on a resource we use a database lock for several reasons:<br> 1. Databases are very good at managing locks and maintaining consistency.<br> 2. The database is the lowest level in which data is accessed — acquiring the lock at the lowest level will protect the data being modified from other processes like cron jobs, cleanup tasks, etc.<br> 3. A Django app can run on multiple processes (workers). Maintaining locks at the app level will require a lot of (unnecessary) work.</blockquote><blockquote>To lock an object in Django we use select-for-update.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d1d4861936cb15661b36fe0616de65a/href">https://medium.com/media/3d1d4861936cb15661b36fe0616de65a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0af3799c80d95ba876b1556aa3dcca6/href">https://medium.com/media/e0af3799c80d95ba876b1556aa3dcca6/href</a></iframe><p>What do we have here:<br> 1. When we use select_for_update on our queryset we tell the database to lock the object until the transaction is done(atomic).<br> 2. Locking a row in the database requires a database transaction — we use Django’s decorator transaction.atomic() to scope the transaction.<br> 3. We use a classmethod instead of an instance method — to acquire the lock we need to tell the database to lock it. To achieve that we need to be the ones fetching the object from the database. <br> 4. All the operations on the slot are executed within the database transaction.</p><blockquote>Let’s see how the scenario from earlier is prevented with our new implementation:<br>Step1 : John asks to book 1 seat :<br>- John acquires a lock on the slot.<br>- seats count is 10.<br>Step2:Sam asks to book 2 seats:<br>- Attempt to acquire lock on account fails (locked by user A).<br>- Sam waits for the lock to release.<br> Step 3: John books 1 seat :<br>- seats count is 9 after booking.<br>- Lock of John on slot is released.<br>Step 4:Sam acquires a lock on the account.<br>- seats count is 9.<br>- new seats count is 9–2 = 7.<br> Step 5: Lock of Sam on account is released, available seats is 7.<br>Bug prevented!</blockquote><p>What you need to know about <strong><em>select_for_update</em></strong>:<br> • In our scenario Sam waited for John to release the lock. Instead of waiting we can tell Django not to wait for the lock to release and raise a DatabaseError instead. To do that we can set the <strong>nowait</strong> argument of <strong><em>select_for_update</em></strong> to True, <strong><em>select_for_update(nowait=True)</em></strong>.<br> • Select related objects are also locked - When using <strong><em>select_for_update</em></strong> with <strong><em>select_related</em></strong>, the related objects are also locked.<br>For example, If we were to <strong><em>select_related</em></strong> the user along with the slot, both the user and the slot will be locked. example, someone is trying to update the user name, that update will fail because the user object is locked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65b89a6565d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>