<?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 Somnath Rangrej on Medium]]></title>
        <description><![CDATA[Stories by Somnath Rangrej on Medium]]></description>
        <link>https://medium.com/@someshrangrej?source=rss-e197f405ab95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*keDR7u4cX8LyurUBqIkc3w.jpeg</url>
            <title>Stories by Somnath Rangrej on Medium</title>
            <link>https://medium.com/@someshrangrej?source=rss-e197f405ab95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:58:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@someshrangrej/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[Understanding Exponential Backoff — a smart retry mechanism]]></title>
            <link>https://medium.com/@someshrangrej/understanding-exponential-backoff-a-smart-retry-mechanism-0de0a7a8ce6f?source=rss-e197f405ab95------2</link>
            <guid isPermaLink="false">https://medium.com/p/0de0a7a8ce6f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Somnath Rangrej]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 13:34:42 GMT</pubDate>
            <atom:updated>2025-09-06T13:53:39.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Exponential Backoff — a smart retry mechanism</h3><blockquote>When you make API calls, send network requests, or run database queries, you’re bound to face <strong>temporary failures</strong> — network timeouts, server overloads, or rate limits.</blockquote><blockquote>Instead of retrying immediately and risking overloading the system, there’s a smarter solution: <strong>exponential backoff</strong>.</blockquote><blockquote>In this article, we’ll explore what exponential backoff is, why it matters, and how to implement it in Python — both manually and using libraries.</blockquote><h3>🧠 What Is Exponential Backoff?</h3><p>Exponential backoff is a <strong>retry strategy</strong> where the wait time between retries <strong>grows exponentially</strong> — typically doubling with each attempt — until a maximum wait time or retry limit is reached.</p><p>Think of it as giving the server <strong>more breathing room</strong> with every failed attempt.</p><h3>✅ Why Use Exponential Backoff?</h3><p>Exponential backoff is widely used by <strong>AWS, Google Cloud, Slack, and many other APIs</strong> because it:</p><ul><li>🛡 <strong>Reduces Load</strong> — prevents overwhelming a busy or failing server</li><li>⏳ <strong>Improves Success Rate</strong> — allows time for temporary issues to resolve</li><li>🔄 <strong>Avoids Cascading Failures</strong> — protects both client and server</li><li>🏆 <strong>Follows Industry Best Practices</strong> — making your system more robust</li></ul><h3>📊 How It Works</h3><p>Here’s what retry intervals look like with a <strong>base delay of 1 second</strong>:</p><pre>| Attempt | Wait Time        |<br>| ------- | ---------------- |<br>| 1       | 1s               |<br>| 2       | 2s               |<br>| 3       | 4s               |<br>| 4       | 8s               |<br>| 5       | 16s (or max cap) |</pre><p>The formula is usually:</p><pre>wait_time = base_delay * (2 ** attempt)</pre><p>This ensures the system backs off progressively rather than retrying aggressively.</p><h3>🐍 Manual Implementation in Python</h3><p>Here’s a simple implementation with exponential backoff:</p><pre>import time<br>import random<br>import logging<br><br># Script: make_request_retry_manual.py<br># Description: Demonstrates retry logic with exponential backoff using logging.<br><br>def make_request():<br>    &quot;&quot;&quot;<br>    Simulates a request that has a 70% chance to fail.<br>    Raises:<br>        Exception: If the simulated request fails.<br>    Returns:<br>        str: &#39;Success!&#39; if the request succeeds.<br>    &quot;&quot;&quot;<br>    if random.random() &lt; 0.7:  # 70% chance to fail<br>        raise Exception(&quot;Temporary failure&quot;)<br>    return &quot;Success!&quot;<br><br>max_retries = 5  # Maximum number of retry attempts<br>base_delay = 1  # Base delay in seconds for exponential backoff<br><br># Configure logging to display timestamp, log level, and message<br>logging.basicConfig(<br>    level=logging.INFO,<br>    format=&#39;%(asctime)s %(levelname)s: %(message)s&#39;,<br>    datefmt=&#39;%Y-%m-%d %H:%M:%S&#39;<br>)<br><br>for attempt in range(max_retries):<br>    try:<br>        # Try to make the request<br>        result = make_request()<br>        logging.info(f&quot;✅ Request succeeded: {result}&quot;)<br>        break  # Exit loop on success<br>    except Exception as e:<br>        # Log the failure<br>        logging.warning(f&quot;❌ Attempt {attempt+1} failed: {e}&quot;)<br>        if attempt &lt; max_retries - 1:<br>            # Calculate wait time using exponential backoff<br>            wait_time = base_delay * (2 ** attempt)<br>            logging.info(f&quot;⏳ Waiting {wait_time} seconds before retry...&quot;)<br>            time.sleep(wait_time)<br>        else:<br>            # Log and exit after max retries<br>            logging.error(&quot;❗ Max retries reached, giving up.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rl2rDSR1mcMeBR8KcRcyJQ.png" /><figcaption>Visualizing with mermaid diagram</figcaption></figure><pre># Below is the script execution output<br>c:\temp&gt;python make_request_retry_manual.py<br>2025-09-06 19:15:10 WARNING: ❌ Attempt 1 failed: Temporary failure<br>2025-09-06 19:15:10 INFO: ⏳ Waiting 1 seconds before retry...<br>2025-09-06 19:15:11 WARNING: ❌ Attempt 2 failed: Temporary failure<br>2025-09-06 19:15:11 INFO: ⏳ Waiting 2 seconds before retry...<br>2025-09-06 19:15:13 WARNING: ❌ Attempt 3 failed: Temporary failure<br>2025-09-06 19:15:13 INFO: ⏳ Waiting 4 seconds before retry...<br>2025-09-06 19:15:17 WARNING: ❌ Attempt 4 failed: Temporary failure<br>2025-09-06 19:15:17 INFO: ⏳ Waiting 8 seconds before retry...<br>2025-09-06 19:15:25 INFO: ✅ Request succeeded: Success!<br>c:\temp&gt;</pre><h3>🧰 Using Libraries (Cleaner &amp; Easier)</h3><p>Instead of reinventing the wheel, you can use libraries like <strong>tenacity</strong> or <strong>backoff</strong>.</p><p>Here’s the same logic with tenacity:</p><pre>from tenacity import retry, stop_after_attempt, wait_exponential<br><br>@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=1, max=16))<br>def make_request():<br>    # Your function logic here<br>    pass</pre><p>This automatically handles:<br> ✅ Exponential wait intervals<br> ✅ Retry limits<br> ✅ Min/max wait caps</p><h3>🎲 Adding Jitter (Optional, Recommended)</h3><p>If many clients retry at the same time, it can cause a <strong>retry storm</strong> — making things worse.<br>The solution is to add <strong>jitter</strong> — a small random delay:</p><pre>import random<br>wait_time = (base_delay * (2 ** attempt)) + random.uniform(0, 1)<br>time.sleep(wait_time)</pre><p>This spreads out retries and avoids synchronized bursts of traffic.</p><h3>🏆 Best Practices</h3><ul><li><strong>Cap the maximum delay</strong> — don’t let retries grow indefinitely</li><li><strong>Add jitter</strong> — prevents traffic spikes</li><li><strong>Retry only on transient errors</strong> — not on permanent failures like invalid credentials</li><li><strong>Log retries</strong> — helps in debugging and monitoring</li></ul><h3>💡 Key Takeaway</h3><p>Exponential backoff is a <strong>simple yet powerful strategy</strong> that makes your Python applications more resilient.</p><p>Whether you implement it manually or use a library like <strong>tenacity</strong>, it helps your code handle failures gracefully, avoid server overload, and improve reliability — which is crucial in production systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0de0a7a8ce6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Different Use Cases of “Decorators” in Python]]></title>
            <link>https://medium.com/@someshrangrej/different-use-cases-of-decorators-in-python-bfa8e79c87f7?source=rss-e197f405ab95------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa8e79c87f7</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Somnath Rangrej]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 14:20:55 GMT</pubDate>
            <atom:updated>2025-07-08T14:22:42.722Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Python decorators</strong> are a powerful and elegant feature that allows you to modify the behavior of functions or methods without changing their code. They act like wrappers, letting you inject additional functionality before or after a function runs — all while keeping your code clean and DRY (Don’t Repeat Yourself).</p><p>In this article, we’ll explore four practical, real-world use cases of decorators:</p><ul><li>Logging function calls</li><li>Access control based on user roles</li><li>Timing function execution</li><li>Caching expensive computations</li></ul><p>Each section includes a decorator definition and an example usage to help you grasp the concept intuitively.</p><h3>🔍 What Are Decorators?</h3><p>At their core, <strong>decorators are functions that take another function as an argument and extend its behavior without explicitly modifying it.</strong></p><p>A simple decorator structure looks like this:</p><pre>def my_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        # Do something before<br>        result = func(*args, **kwargs)<br>        # Do something after<br>        return result<br>    return wrapper</pre><h3>📝 Use Case 1: Logging Function Calls</h3><p>Logging is essential for monitoring application behavior and debugging. A decorator makes it easy to log every time a function is called and when it finishes.</p><pre># Logging Decorator<br>def log_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;[LOG] Calling function: {func.__name__}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;[LOG] {func.__name__} finished execution&quot;)<br>        return result<br>    return wrapper<br><br>@log_decorator<br>def greet(name):<br>    print(f&quot;Hello, {name}!&quot;)<br>greet(&quot;Alex&quot;)</pre><p><strong>Output:</strong></p><pre>[LOG] Calling function: greet<br>Hello, Alex!<br>[LOG] greet finished execution</pre><h3>📝 Use Case 2: Access Control Based on User Roles</h3><p>In web or enterprise applications, access control is crucial. Decorators can check a user’s role before allowing access to sensitive operations.</p><pre># Access Control Decorator<br>def requires_admin(func):<br>    def wrapper(user, *args, **kwargs):<br>        if user != &quot;admin&quot;:<br>            print(&quot;Access Denied.&quot;)<br>            return<br>        return func(user, *args, **kwargs)<br>    return wrapper<br><br>@requires_admin<br>def view_dashboard(user):<br>    print(&quot;Welcome to the admin dashboard!&quot;)<br>view_dashboard(&quot;admin&quot;)<br>view_dashboard(&quot;guest&quot;)</pre><p><strong>Output:</strong></p><pre>Welcome to the admin dashboard!<br>Access Denied.</pre><h3>📝 Use Case 3: Timing Function Execution</h3><p>Performance monitoring is a common need, especially for identifying slow-running parts of a program. This decorator measures the execution time of functions.</p><pre>import time<br><br># Timing Decorator<br>def timer(func):<br>    def wrapper(*args, **kwargs):<br>        start_time = time.time()<br>        result = func(*args, **kwargs)<br>        end_time = time.time()<br>        print(f&quot;[TIMER] {func.__name__} executed in {end_time - start_time:.5f} seconds&quot;)<br>        return result<br>    return wrapper<br><br>@timer<br>def long_task():<br>    time.sleep(2)<br>    print(&quot;Task completed!&quot;)<br><br>long_task()</pre><p><strong>Output:</strong></p><pre>Task completed!<br>[TIMER] long_task executed in 2.00010 seconds</pre><h3>📝 Use Case 4: Caching Expensive Computations</h3><p>When a function performs heavy or time-consuming computations, caching results for repeated calls can improve performance significantly.</p><pre># Caching Decorator<br>def cache_decorator(func):<br>    cache = {}<br>    def wrapper(n):<br>        import time<br>        if n in cache:<br>            start_time = time.time()<br>            result = cache[n]<br>            print(f&quot;Fetching from cache for {n}&quot;)<br>            end_time = time.time()<br>            print(f&quot;[CACHE TIMER] (cache hit) {func.__name__} for {n} took {end_time - start_time:.5f} seconds&quot;)<br>        else:<br>            start_time = time.time()<br>            print(f&quot;Calculating result for {n}&quot;)<br>            result = func(n)<br>            cache[n] = result<br>            end_time = time.time()<br>            print(f&quot;[CACHE TIMER] (cache miss) {func.__name__} for {n} took {end_time - start_time:.5f} seconds&quot;)<br>        return result<br>    return wrapper<br><br>@cache_decorator<br>def square(n):<br>    time.sleep(1)  # Simulate a slow computation<br>    return n * n<br>print(square(4))<br>print(square(4))</pre><p><strong>Output:</strong></p><pre>Calculating result for 4<br>[CACHE TIMER] (cache miss) square for 4 took 1.00025 seconds<br>16<br>Fetching from cache for 4<br>[CACHE TIMER] (cache hit) square for 4 took 0.00001 seconds<br>16</pre><p><strong>Notice how the second call was almost instant — because the result was cached.</strong></p><h3>📌 Conclusion</h3><p>Decorators in Python aren’t just a theoretical concept; they’re immensely useful for writing clean, efficient, and maintainable code. Whether you need to log function calls, enforce access control, measure execution time, or cache expensive computations — decorators provide a neat, scalable way to extend functionality.</p><p>Mastering decorators unlocks a new level of expressive power in Python and helps you build cleaner, more modular applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa8e79c87f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting to the database through python & manipulating the database using SQL queries inside a…]]></title>
            <link>https://medium.com/@someshrangrej/connecting-to-the-database-through-python-manipulating-the-database-using-sql-queries-inside-a-a6fb2bc4058?source=rss-e197f405ab95------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6fb2bc4058</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Somnath Rangrej]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 16:20:17 GMT</pubDate>
            <atom:updated>2022-01-23T16:20:17.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Connecting to the database through python &amp; manipulating the database using SQL queries inside a python script</h3><p>Python provides a very rich set of libraries or modules, which allows us to leverage the power of readily made available methods from the imported modules along with features provided by Python as a programming language.</p><p>Python has dedicated <a href="https://www.python.org/dev/peps/pep-0249/">PEP 249</a> standards for Database API Specification, which encourages similarity between the Python modules that are used to access or manipulate databases.</p><h4>Databases are broadly classified into two different types:</h4><ol><li><strong>Relational database:</strong> For structured data or information storage in the form of rows &amp; columns (which forms a table &amp; multiple tables together forms the database)</li></ol><p>In order to work with relational databases, we need RDBMS (i.e. relational database management systems) like</p><ul><li>SQLite</li><li>MySQL</li><li>PostgreSQL</li></ul><p>2. <strong>Non-Relational database:</strong> For unstructured data or information storage</p><ul><li>Document storage: JSON / XML in the form of key-value pair</li><li>Mongo-DB</li><li>Amazon’s DynamoDB</li><li>Graph with nodes &amp; edges</li></ul><p>Here, we are talking only about RDBMS applications &amp; corresponding python module used to work with these applications,</p><p>A. <strong>SQLite:</strong> pip install sqlite3</p><p>B. <strong>MySQL:</strong> pip install mysql-connector-python</p><p>C: <strong>PostgreSQL:</strong> pip install psycopg2</p><h4>Connecting to database using Python:</h4><p><em>connection object: </em>We create a connection object in order to establish a connection with the existing database</p><p><em>cursor object:</em> We can create a cursor object in order to interact with the database</p><blockquote>&gt;&gt;&gt; import sqlite3</blockquote><blockquote>&gt;&gt;&gt; connection = sqlite3.connect(r’D:\MySQLScripts\quizdata.db’)</blockquote><blockquote>&gt;&gt;&gt; connection</blockquote><blockquote>&lt;sqlite3.Connection object at 0x0000018052330E40&gt;</blockquote><blockquote>&gt;&gt;&gt; cursor = connection.cursor()</blockquote><blockquote>&gt;&gt;&gt; cursor</blockquote><blockquote>&lt;sqlite3.Cursor object at 0x0000018052465420&gt;</blockquote><blockquote>&gt;&gt;&gt; cursor.execute(‘’’ SELECT * FROM people; ‘’’)</blockquote><blockquote>&lt;sqlite3.Cursor object at 0x0000018052465420&gt;</blockquote><blockquote>&gt;&gt;&gt; cursor.fetchone()</blockquote><blockquote>(1, ‘Janice’, ‘Howell’, ‘Los Angeles’, ‘CA’, ‘hat’, 92, ‘Cosmic Cobras’, ‘2021–01–01’, 44, ‘Homenick Group’)</blockquote><blockquote>&gt;&gt;&gt; print(cursor.fetchone())</blockquote><blockquote>(2, ‘Wanda’, ‘Alvarez’, ‘Riverside’, ‘CA’, ‘shirt’, 80, ‘Angry Ants’, ‘2021–01–01’, 33, ‘Nicolas Inc’)</blockquote><p>Just like “sqlite3” we can pretty much do the same operations with MySQL &amp; PostgreSQL as well.</p><h4>For MySQL:</h4><p>connection = mysql.connect(host=’localhost’, user=’root’, password=’12345&#39;, database=’classicmodels’)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6fb2bc4058" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are the signs of brilliant minds?]]></title>
            <link>https://medium.com/@someshrangrej/what-are-the-signs-of-brilliant-minds-a42371d970c0?source=rss-e197f405ab95------2</link>
            <guid isPermaLink="false">https://medium.com/p/a42371d970c0</guid>
            <category><![CDATA[discipline]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[corporate-culture]]></category>
            <dc:creator><![CDATA[Somnath Rangrej]]></dc:creator>
            <pubDate>Sun, 29 Oct 2017 14:14:16 GMT</pubDate>
            <atom:updated>2017-10-29T14:15:22.614Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Very good at prioritizing tasks</li><li>Love to have intellectual discussions</li><li>Keep themselves organised</li><li>Take full responsibility &amp; ownership of each action they do</li><li>Very good listeners</li><li>Create an environment where everyone would like to be a part of it</li><li>Good at analyzing &amp; correlating different things together</li><li>Very good at giving examples &amp; statistics to prove their point</li><li>Keep themselves busy &amp; engaged in some activity all the time</li><li>Never get tired of trying something completely new, even if existing process is good enough to give expected results</li><li>Keep on exploring nontraditional paths towards finding better solutions to existing problems/situations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a42371d970c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>