<?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 Sourabh garg on Medium]]></title>
        <description><![CDATA[Stories by Sourabh garg on Medium]]></description>
        <link>https://medium.com/@sourabhgarg8?source=rss-4737f35e044e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1yWDwDI74AZWzp-2</url>
            <title>Stories by Sourabh garg on Medium</title>
            <link>https://medium.com/@sourabhgarg8?source=rss-4737f35e044e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:38:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sourabhgarg8/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[Preventing Duplicate Request Madness: Clever Solutions for Android, iOS, PWA, and Backend]]></title>
            <link>https://medium.com/@sourabhgarg8/preventing-duplicate-request-madness-clever-solutions-for-android-ios-pwa-and-backend-3e9504e80a0f?source=rss-4737f35e044e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9504e80a0f</guid>
            <dc:creator><![CDATA[Sourabh garg]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:11:53 GMT</pubDate>
            <atom:updated>2024-09-25T10:17:00.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvlt9yBA5ZA7qZ5yTaaSaw.jpeg" /><figcaption><a href="https://chatgpt.com/">Source</a></figcaption></figure><p><strong>Introduction:</strong><br>Ever clicked a button multiple times, hoping the app would just <em>work faster</em>? Yeah, we’ve all been there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*AQA1WLESiF6fLX_qzco6wQ.gif" /><figcaption><a href="https://tenor.com/en-GB/view/enter-keyboard-anime-clicking-click-gif-17794691">source</a></figcaption></figure><p>Unfortunately, in low-network environments, users might <em>helpfully</em> press that button again…and again…leading to duplicate requests, messed-up data, and backend chaos. It’s like when you try opening a door by pushing and pulling it repeatedly — doesn’t speed things up, right? 😅</p><p>But don’t worry! With the right strategies, you can stop your app from processing the same request over and over like it’s stuck in an infinite loop. Let’s dive into some fun solutions for Android, iOS, PWAs, and the backend so your system stays cool under pressure!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*VuTvwYGFv6sLXaTeAcvTqQ.gif" /><figcaption><a href="https://getyarn.io/yarn-clip/26eb6587-7249-49bd-a615-a9ba86eabe90">Source</a></figcaption></figure><h3>1. Android Solutions 📱</h3><p><strong>a. Debouncing in UI:</strong> Imagine your app is like a very polite friend — when you ask it to do something, it responds right away…and then politely waits before making another request. Debouncing works like that! You temporarily disable a button after it’s clicked to stop users from spamming it like a broken elevator button. 🚪⛔️</p><pre>private boolean isClickAllowed = true;<br>public void onButtonClick(View view) {<br>    if (isClickAllowed) {<br>        isClickAllowed = false;<br>        // Perform your request here<br>        new Handler().postDelayed(() -&gt; isClickAllowed = true, 1000); // 1 second delay<br>    }<br>}</pre><p><strong>b. Network Retry Policies:</strong><br>We all know the drill: bad network = sad user. 😢 But with smart retry policies, you can reattempt failed requests without causing duplicate operations. Your API will feel like it’s having a productive day, not déjà vu.</p><pre>OkHttpClient client = new OkHttpClient.Builder()<br>    .retryOnConnectionFailure(true) // Retry if connection fails<br>    .build();</pre><p><strong>c. Idempotent API Calls:</strong><br>Fancy word alert! “Idempotent” just means that no matter how many times you hit that request, the backend won’t throw a tantrum and do the same thing twice. It’s like pressing the same button on a vending machine 10 times — you’re only getting one snack (if any!). 🍫</p><h3>2. iOS Solutions 🍏</h3><p><strong>a. Throttling Button Clicks:</strong><br>On iOS, we’re doing the same thing as Android — tell your app to <em>chill</em> and process one click at a time. iPhones like to be stylish and efficient, after all. 💁‍♂️</p><pre>class ThrottleButton {<br>    var isThrottled = false<br><br>    func buttonClicked() {<br>        if !isThrottled {<br>            isThrottled = true<br>            // Perform the API request here<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {<br>                self.isThrottled = false<br>            }<br>        }<br>    }<br><br>}</pre><p><strong>b. Request Deduplication with Unique Keys:</strong><br>Generate a fancy idempotency key for each request, and your backend will know it’s the same person trying to buy the same thing for the fifth time. One request, one order — no extra charges! 🛒💳</p><pre>let idempotencyKey = UUID().uuidString<br>var request = URLRequest(url: apiURL)<br>request.addValue(idempotencyKey, forHTTPHeaderField: &quot;Idempotency-Key&quot;)</pre><p><strong>c. Network Error Handling with Retry Logic:</strong><br>Instead of flooding your servers with a billion retries when the network’s acting like it’s 2005 dial-up, use smart retry logic. Retry when it’s worth it — because nobody likes being the annoying kid in class raising their hand over and over.</p><p><strong>d. Handling User Interaction of Action Button:</strong></p><p>You know when you’re ordering food online, click the “Order” button, and it just spins…and spins? 🌀 Well, this is a good thing! When an API is triggered from user action, the button should disable itself and show a loader — so users know something’s happening and can’t accidentally trigger another request. It’s like saying: <em>“Hold on! Your pizza’s already on its way 🍕.”</em></p><pre>class ActionButtonController {<br>    var isRequestInProgress = false<br>    <br>    func onActionButtonClick(button: UIButton) {<br>        if !isRequestInProgress {<br>            isRequestInProgress = true<br>            button.isEnabled = false<br>            <br>            // Show loader<br>            let activityIndicator = UIActivityIndicatorView(style: .medium)<br>            activityIndicator.startAnimating()<br>            button.addSubview(activityIndicator)<br>            <br>            // Perform API request here<br>            DispatchQueue.global().async {<br>                // Simulate network call<br>                sleep(2)<br>                <br>                DispatchQueue.main.async {<br>                    self.isRequestInProgress = false<br>                    button.isEnabled = true<br>                    activityIndicator.removeFromSuperview()<br>                    print(&quot;Request completed successfully!&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>3. PWA (Progressive Web Apps) Solutions 🌐</h3><p><strong>a. Debouncing Button Clicks (Again!):</strong><br>JavaScript’s debounce function is your digital bouncer — only letting one click through the door at a time. 🛑🖱️</p><pre>function debounce(fn, delay) {<br>    let timer;<br><br>    return function(...args) {<br>        clearTimeout(timer);<br>        timer = setTimeout(() =&gt; fn.apply(this, args), delay);<br>    };<br>}<br><br>const sendRequest = debounce(() =&gt; { <br>    // API request here <br>}, 1000);</pre><p><strong>b. Service Worker for Offline Handling:</strong><br>Imagine if your app could <em>remember</em> what you wanted to do when the network was down and automatically retry when it’s back up. It’s like your app saying, “Don’t worry, I got this!” 💪📶</p><pre>self.addEventListener(&#39;fetch&#39;, event =&gt; {<br>    event.respondWith(<br>        caches.match(event.request).then(response =&gt; {<br>            return response || fetch(event.request);<br>        })<br>    );<br>});</pre><p><strong>c.</strong> <strong>Request Deduplication with Fetch API:</strong></p><p>Using idempotency keys in the HTTP headers ensures that duplicate requests don’t reach the backend</p><pre>fetch(&#39;/api/data&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>        &#39;Idempotency-Key&#39;: &#39;some-unique-id&#39;<br>    },<br>    body: JSON.stringify(data)<br>});</pre><h3>4. Backend Solutions (the Unsung Hero) 💻</h3><p><strong>a. Idempotency Keys:</strong><br>The backend can store these magic keys to ensure it processes each request just once. If it’s seen the key before, it’ll just wink at you and say, “Already done!” 😎</p><pre>@RestController<br><br>public class RequestController {<br>    @Autowired<br>    private IdempotencyService idempotencyService;<br><br>    @PostMapping(&quot;/api/process&quot;)<br>    public ResponseEntity&lt;String&gt; processRequest(@RequestHeader(&quot;Idempotency-Key&quot;) String idempotencyKey, @RequestBody RequestData data) {<br>        if (idempotencyService.isDuplicateRequest(idempotencyKey)) {<br>            return ResponseEntity.status(HttpStatus.CONFLICT).body(&quot;Duplicate request - already processed.&quot;);<br>        }<br>        String result = processNewRequest(data);<br>        idempotencyService.saveIdempotencyRecord(idempotencyKey, result);<br>        return ResponseEntity.ok(result);<br>    }<br><br>    private String processNewRequest(RequestData data) {<br>        return &quot;Request processed successfully&quot;;<br>    }<br>}</pre><p><strong>b. Distributed Locking:</strong><br>In case multiple servers are competing to process the same request, give one of them the exclusive rights with a distributed lock. It’s like handing the last slice of pizza to only one person to avoid chaos. 🍕</p><pre>@Service<br><br>public class DistributedLockService {<br>    @Autowired<br>    private RedissonClient redissonClient;<br><br>    public void processWithLock(String key, Runnable task) {<br>        RLock lock = redissonClient.getLock(key);<br>        boolean isLockAcquired = false;<br>        try {<br>            isLockAcquired = lock.tryLock(5, 10, TimeUnit.SECONDS);<br>            if (isLockAcquired) {<br>                task.run();<br>            } <br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        } finally {<br>            if (isLockAcquired) {<br>                lock.unlock();<br>            }<br>        }<br>    }<br>}</pre><h4>c. Rate Limiting with Bucket4J:</h4><p>Rate limiting prevents users from sending too many requests within a short period. This helps avoid system overload caused by repeated requests.</p><pre>@RestController<br><br>public class RateLimitController {<br>    private final Map&lt;String, Bucket&gt; buckets = new ConcurrentHashMap&lt;&gt;();<br><br>    @PostMapping(&quot;/api/rateLimit&quot;)<br>    public ResponseEntity&lt;String&gt; handleRequest(@RequestBody RequestData data) {<br>        String userId = data.getUserId();<br>        Bucket bucket = resolveBucket(userId);<br>        if (bucket.tryConsume(1)) {<br>            return ResponseEntity.ok(&quot;Request processed successfully&quot;);<br>        } else {<br>            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(&quot;Rate limit exceeded. Try again later.&quot;);<br>        }<br>    }<br><br>    private Bucket resolveBucket(String userId) {<br>        return buckets.computeIfAbsent(userId, k -&gt; Bucket4j.builder()<br>                .addLimit(Bandwidth.classic(5, Refill.greedy(5, Duration.ofMinutes(1))))<br>                .build());<br>    }<br>}</pre><h3>Why Bother with All This?</h3><ul><li><strong>Happier Users:</strong> No one likes double-clicking their way to double payments. With these solutions, users only pay once (yay!) and avoid accidental orders.</li><li><strong>Smarter Backend:</strong> Your backend will feel like it’s running a tight ship, not battling constant duplicate requests. Who doesn’t want more CPU cycles for Netflix, right? 💻🍿</li><li><strong>Consistency:</strong> These techniques keep your data squeaky clean and your app humming along smoothly. No more weird, inconsistent orders or mystery bugs.</li></ul><p><strong>Conclusion:</strong><br>With great (button) power comes great responsibility! Whether your users are on Android, iOS, or PWAs, or dealing with low network conditions, these strategies will prevent them from sending your backend into duplicate-request overdrive. Implement them, and you’ll have a scalable, reliable system that laughs in the face of button-mashing chaos.</p><p>Now, go forth and make your app as efficient as a ninja with these anti-duplicate-request tactics! 🥷</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l014hW3qLpkHsKY-HtKgw.jpeg" /><figcaption><a href="https://unsplash.com/photos/smiling-man-reading-book-while-holding-mug-4r72LPFh4Ik?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash">Source</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9504e80a0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>