<?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 Cesar Contreras on Medium]]></title>
        <description><![CDATA[Stories by Cesar Contreras on Medium]]></description>
        <link>https://medium.com/@ccdl15c?source=rss-8df6b38f1cf7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dY8MTyqTL7qUTln2Jj_azw.jpeg</url>
            <title>Stories by Cesar Contreras on Medium</title>
            <link>https://medium.com/@ccdl15c?source=rss-8df6b38f1cf7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:15:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ccdl15c/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 on the Web with Web Locks API]]></title>
            <link>https://tech.olx.com/handling-concurrency-on-the-web-with-web-locks-api-163b7e07eddd?source=rss-8df6b38f1cf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/163b7e07eddd</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[resumable-file-upload]]></category>
            <dc:creator><![CDATA[Cesar Contreras]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 15:36:00 GMT</pubDate>
            <atom:updated>2026-07-14T15:36:00.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkVBdLeQjhg4d7bpbSj2Xg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/the_iop-1181394/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8704819">the_iop</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8704819">Pixabay</a></figcaption></figure><p>Concurrency in programming is the ability to manage and execute multiple tasks or processes at the same time (or appear to), allowing programs to remain responsive and efficient. Think of it like a chef in a busy kitchen: they’re not cooking every dish from start to finish sequentially, but instead chopping vegetables while one pan simmers and another bakes; juggling progress on several tasks concurrently.</p><p>I’m a frontend engineer at <a href="https://www.olxgroup.com/">OLX</a> working mostly with <a href="https://react.dev/">React</a> and <a href="https://nextjs.org/">NextJs</a>, but I also came from a background in which I worked primarily in concurrent programs with Java. Creating multi-threaded applications can be a pain, dealing with <a href="https://en.wikipedia.org/wiki/Lock_(computer_science)">locks</a>, <a href="https://en.wikipedia.org/wiki/Semaphore_(programming)">semaphores</a>… and my favorite… <a href="https://en.wikipedia.org/wiki/Deadlock_(computer_science)">deadlocks</a> (very scary in large codebases). Once I transitioned fully to Web development, I never imagined I would have to deal with scenarios like this, and then here I am writing my first article about it.</p><p>Web development has turned into a very powerful ecosystem, from the previous era where the web was only about flashy animations using HTML marquee (a bit of sarcasm here 😆), dominated by <a href="https://jquery.com/">JQuery</a>, to a really powerful environment where you can use Workers, 2D and 3D animations with <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">WebGL</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">Canvas</a>, offline capabilities with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a>, and the list continues. This is evidence that the Web can now face really complex challenges, and it’s just a matter of time before you have to face similar ones.</p><h3>The problem</h3><p>Recently, at <a href="https://www.olxgroup.com/">OLX</a>, we faced the challenge of working with large file size uploads. Providing the best user experience is tricky when it comes to handling uploads, and most of the real use cases out there require the user to stay in the web app until the upload completes, but we didn’t want that. Since we are working with large file sizes (up to 20GB), we want the user to be free and do other stuff while this is uploading, so if the user closes and opens the browser or tab, the upload should continue with no manual intervention. For this, we had to provide a mechanism to resume uploads.</p><p>But here’s where things get messy. What if your user opens multiple tabs of your app? Suddenly, <strong>every tab tries to restore and resume the same upload simultaneously</strong>. The result? Multiple duplicate uploads hitting your S3 bucket, wasted bandwidth, unnecessary processing costs, and confused users watching their upload progress jump around unpredictably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wez6yCGURFfHSO9cllCqzQ.png" /><figcaption>Two tabs, both restored, independently trigger the same upload; with no coordination, the video gets sent twice.</figcaption></figure><p>If you’re building file upload experiences in modern web applications, you’ve likely encountered this exact scenario. Today, I’ll walk you through a robust solution using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API">Web Locks API</a> that we implemented to solve this coordination nightmare.</p><p>But first, before going in depth into our solution, we need to understand synchronization and locks.</p><h3>First, what is a Lock?</h3><p>A lock is a mechanism that ensures a shared resource (variable, object, function invocation, etc.) can be accessed one at a time and every caller is guaranteed to receive the most recent information. You can think of a very popular scenario — a bank with multiple accounts in shared memory and several ATMs, withdrawing, depositing, and checking balances simultaneously. With no coordination (synchronization), this will be a mess, as you can see in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9sqGTGmbYliZpd1f4bK4A.png" /><figcaption>Image from <a href="https://web.mit.edu/6.005/www/fa15/classes/23-locks/">MIT</a></figcaption></figure><p>To solve this mess, we have to control access by locking read/write to the account. So, with this, the first caller to get the lock, no matter the action being performed (withdrawing, crediting, or checking balance), will acquire the lock. Others have to wait until the lock is finally released after the first acquirer finishes the operation. The following image shows how this looks after synchronizing account accesses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*F5SMBR_lt_R-I7hlwxlvPw.png" /><figcaption>Image from <a href="https://web.mit.edu/6.005/www/fa15/classes/23-locks/">MIT</a></figcaption></figure><p>Now that we understand how synchronization and locks work, let’s dive into how to put it into practice 🚀.</p><h3>The Landscape of Cross-Tab Coordination</h3><p>Before diving into our solution, let’s examine the options available for coordinating actions across browser tabs:</p><h3>Option 1: localStorage + Polling</h3><p>The “classic” approach involves using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> as a shared lock mechanism:</p><pre>// Simplified example - DON&#39;T use this<br>if (!localStorage.getItem(&#39;upload-lock&#39;)) {<br>  localStorage.setItem(&#39;upload-lock&#39;, Date.now());<br>  // Start upload<br>}</pre><p><strong>The problems:</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Race_condition"><strong>Race conditions</strong></a>: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> read/write operations aren’t atomic</li><li><strong>Stale locks</strong>: If a tab crashes, the lock persists forever</li><li><strong>Polling overhead</strong>: You need to continuously check the lock status</li><li><strong>Event limitations</strong>: Storage events only fire in other tabs, not the current one</li></ul><h3>Option 2: Broadcast Channel API</h3><p>This approach uses messaging between tabs to coordinate with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast Channel API</a>:</p><pre>const channel = new BroadcastChannel(&#39;upload-coordination&#39;);<br>channel.postMessage({ type: &#39;REQUEST_UPLOAD_PERMISSION&#39; });</pre><p><strong>The challenges:</strong></p><ul><li><strong>No </strong><a href="https://en.wikipedia.org/wiki/Lock_(computer_science)"><strong>mutex</strong></a><strong> primitive</strong>: You’re building a state machine from scratch</li><li><a href="https://en.wikipedia.org/wiki/Race_condition"><strong>Race conditions</strong></a>: Simultaneous messages can create conflicts</li><li><strong>Complex protocol</strong>: You need to handle heartbeats, crash detection, and conflict resolution manually</li><li><strong>Error-prone</strong>: Message ordering and timing issues are common</li></ul><h3>Enter the Web Locks API: Browser-Native Mutex</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API">Web Locks API</a> provides exactly what we need: a true, atomic <a href="https://en.wikipedia.org/wiki/Lock_(computer_science)">mutex</a> system built directly into the browser. Here’s what makes it special:</p><ul><li><strong>Atomic lock acquisition</strong> — No race conditions</li><li><strong>Automatic cleanup</strong> — Locks are released when tabs close or crash</li><li><strong>Non-blocking options</strong> — Avoid freezing the UI</li><li><strong>Simple API</strong> — No complex protocols to implement</li><li><strong>Browser compatibility — </strong>Supported in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API#browser_compatibility">all browsers</a> 😃</li></ul><h3>Our Implementation: useUploadCoordinator</h3><p>Here’s how we solved the problem with a custom <a href="https://react.dev/">React</a> hook:</p><h3>The Core Strategy</h3><p>Two different approaches for two scenarios:</p><pre>// 1. Fresh uploads (user-initiated): Non-blocking<br>// Try to get the lock, but proceed regardless<br>navigator.locks.request(LOCK_NAME, <br>  { ifAvailable: true }, <br>  async (lock) =&gt; {<br>    if (lock) {<br>      // Hold the lock until upload completes<br>      await holdLockUntilComplete(abortController);<br>    }<br>    // Upload proceeds either way - never block the user<br>  }<br>);<br><br>// 2. Restored uploads: Conditional  <br>// Only proceed if we get the lock<br>navigator.locks.request(LOCK_NAME, <br>  { ifAvailable: true }, <br>  async (lock) =&gt; {<br>    if (lock) {<br>      uploader.emit(&quot;restore-confirmed&quot;); // Proceed with restore<br>      await holdLockUntilComplete(abortController);<br>    }<br>    // If no lock, skip silently - another tab is handling it<br>  }<br>);</pre><h3>Key Implementation Details</h3><p>Lock Lifecycle Management:</p><pre>const holdLockUntilComplete = (abortController: AbortController) =&gt; {<br>  return new Promise&lt;void&gt;((resolve) =&gt; {<br>    const cleanup = () =&gt; {<br>      // Remove all listeners and resolve (releasing the lock)<br>      uploader.off(&quot;complete&quot;, cleanup);<br>      uploader.off(&quot;error&quot;, cleanup); <br>      uploader.off(&quot;cancel-all&quot;, cleanup);<br>      resolve();<br>    };<br><br>    // Release lock on any terminal event<br>    uploader.on(&quot;complete&quot;, cleanup);<br>    uploader.on(&quot;error&quot;, cleanup);<br>    uploader.on(&quot;cancel-all&quot;, cleanup);<br><br>    // Also release if component unmounts<br>    abortController.signal.addEventListener(&quot;abort&quot;, cleanup);<br>  });<br>};</pre><p><strong>Browser Compatibility &amp; Graceful Degradation:</strong></p><pre>const checkWebLocksAvailable = (): boolean =&gt; {<br>  return typeof navigator !== &#39;undefined&#39; &amp;&amp; &#39;locks&#39; in navigator;<br>};<br><br>// Fallback behavior<br>if (!checkWebLocksAvailable()) {<br>  // Allow restores to proceed (accept risk of duplicates)<br>  uploader.emit(&quot;restore-confirmed&quot;);<br>  return;<br>}</pre><h3>The Benefits in Practice</h3><p>Since implementing this solution, we’ve seen:</p><ol><li><strong>Zero duplicate uploads</strong> from cross-tab coordination issues</li><li><strong>Better user experience</strong> — uploads never freeze due to coordination logic</li><li><strong>Reduced infrastructure costs</strong> — no more duplicate processing and storage</li><li><strong>Simpler codebase</strong> — no complex state machines or polling logic</li></ol><p>And now, this is how our solution looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxwpCcjrTlD49iF-UXCWCA.png" /><figcaption>A shared lock ensures only the first tab to acquire it proceeds with the upload; the second tab detects the lock is taken and silently steps aside.</figcaption></figure><h3>Real-World Considerations</h3><h4><strong>When to Use This Pattern:</strong></h4><ul><li>File uploads with persistence/restoration</li><li>Background sync operations</li><li>Any <a href="https://en.wikipedia.org/wiki/Singleton_pattern">singleton</a> operations that should only run in one tab</li></ul><h4><strong>Performance Impact:</strong></h4><ul><li>Minimal — no polling overhead</li><li>Automatic cleanup prevents <a href="https://en.wikipedia.org/wiki/Memory_leak">memory leaks</a></li><li>Non-blocking design ensures UI responsiveness</li></ul><h4><strong>Testing Strategy:</strong></h4><ul><li>Test across all target browsers</li><li>Verify behavior when tabs crash unexpectedly</li><li>Confirm graceful degradation in unsupported environments</li></ul><h3>Conclusion</h3><p>Cross-tab coordination doesn’t have to be a nightmare. The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API">Web Locks API</a> provides a robust, browser-native solution that eliminates the complexity and fragility of custom coordination protocols.</p><p>While building this solution, we learned that the key to successful cross-tab coordination is:</p><ol><li><strong>Never block user actions</strong> — use non-blocking locks for user-initiated operations</li><li><strong>Fail safely</strong> — graceful degradation is better than broken functionality</li><li><strong>Keep it simple</strong> — leverage platform primitives instead of rebuilding them</li></ol><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API">Web Locks API</a> isn’t just for upload coordination; any time you need mutual exclusion across tabs, it’s worth considering. As browser support continues to improve, it’s becoming an increasingly viable tool in the modern web developer’s toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163b7e07eddd" width="1" height="1" alt=""><hr><p><a href="https://tech.olx.com/handling-concurrency-on-the-web-with-web-locks-api-163b7e07eddd">Handling concurrency on the Web with Web Locks API</a> was originally published in <a href="https://tech.olx.com/">OLX Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>