<?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 Miah Md Shahjahan on Medium]]></title>
        <description><![CDATA[Stories by Miah Md Shahjahan on Medium]]></description>
        <link>https://medium.com/@hasanshahjahan?source=rss-b2241fef3d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QX4ZBpoNxXpQUuucjXZppg.jpeg</url>
            <title>Stories by Miah Md Shahjahan on Medium</title>
            <link>https://medium.com/@hasanshahjahan?source=rss-b2241fef3d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:43:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasanshahjahan/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[Idempotency, Deduplication, and Exactly-Once in Distributed Pipelines]]></title>
            <link>https://medium.com/@hasanshahjahan/-dda85c54d2f0?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dda85c54d2f0</guid>
            <category><![CDATA[exactly-once-processing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[deduplication]]></category>
            <category><![CDATA[idempotency]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 08:30:14 GMT</pubDate>
            <atom:updated>2026-04-06T08:31:22.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jOomNxzV0XectuaqbV3Ig.png" /></figure><p>Idempotency, deduplication, and exactly-once are often mentioned together in distributed systems, but they represent very different guarantees:</p><p>- Idempotency is operation-level safety<br>- Deduplication is data-level safety<br>- Exactly-once is end-to-end safety</p><p>𝗜𝗱𝗲𝗺𝗽𝗼𝘁𝗲𝗻𝗰𝘆<br>It performs the same operation multiple times produces the exact same result as performing it once. For example, charging a credit card with an idempotent API call ensures the customer is billed once, even if the request is retried.</p><p>𝗗𝗲𝗱𝘂𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻<br>It detects and discards duplicate requests so the operation executes exactly once. For example, dropping repeated webhook events from the same source so system doesn’t process the same event multiple times.</p><p>𝗘𝘅𝗮𝗰𝘁𝗹𝘆 𝗢𝗻𝗰𝗲<br>It ensures that each operation affects the system only one time, even if the request is retried or duplicated. This is the ultimate guarantee, but in distributed systems, it is mostly an illusion.</p><p>Most message queues (like Kafka, RabbitMQ, SQS) provide at-least-once delivery. This means a message might be delivered more than once, which is by design.</p><p>𝗧𝗵𝗲 𝘁𝗵𝗿𝗲𝗲 𝗿𝗲𝗮𝗹𝗶𝘁𝗶𝗲𝘀:<br>At-most-once — message may be lost, but never duplicated<br>At-least-once — message always delivered, may be duplicated<br>Exactly-once — a marketing lie with very good PR 😊</p><p>𝗔 𝗿𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗲𝘅𝗮𝗺𝗽𝗹𝗲:<br>- worker pulls a payment request from Kafka.<br>- worker charges the customer’s credit card.<br>- worker crashes before committing the Kafka offset.<br>- kafka redelivers the same payment request.<br>- the next worker charges the card again, resulting in a duplicate charge.</p><p>This happens by design. Trying to implement exactly-once at the system level is always complex, expensive, and often unnecessary. Instead, ensuring idempotent operations and deduplication is simpler, reliable, and practical and the trade-off is consumers must handle duplicates.</p><p>At-least-once + idempotent consumers = effective exactly-once, and this is the production standard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dda85c54d2f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Idempotency in Distributed System]]></title>
            <link>https://medium.com/@hasanshahjahan/how-to-handle-idempotency-in-distributed-system-5af7a6e187b5?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5af7a6e187b5</guid>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 23:39:03 GMT</pubDate>
            <atom:updated>2026-04-03T23:39:44.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9X4ZoEbf3uIl_hs9WNk8SA.png" /></figure><p>Failures, retries, and duplicate requests are common challenges In distributed systems. One of the key techniques to ensure safe and predictable operations in such environments is idempotency.</p><h3>What is Idempotency?</h3><p>Idempotency means that making the same request multiple times has the same effect as making it once.</p><h3>Why Do We Need Idempotency?</h3><p>In distributed systems, retries are common due to network failures, timeouts, client retries, system crashes. Without idempotency, retries could lead to duplicate charges, duplicate records, inconsistent states.</p><h3>Idempotency Patterns</h3><h4><strong>API Layer (Key Idempotency)</strong></h4><p>It prevents duplicate requests and idempotency is achieved using a client-provided idempotency key.</p><ul><li>Each request carries a unique key</li><li>The server stores the result of the first request</li><li>Retries with the same key return the same response</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mw6Dx47MfwymNnq38tIyBQ.png" /></figure><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>type Response struct {<br> OrderID string<br> Status  string<br>}<br><br>type IdempotencyStore struct {<br> mu    sync.Mutex<br> store map[string]Response<br>}<br><br>func NewIdempotencyStore() *IdempotencyStore {<br> return &amp;IdempotencyStore{<br>  store: make(map[string]Response),<br> }<br>}<br><br>func (s *IdempotencyStore) CreateOrder(key string, userID string) Response {<br> s.mu.Lock()<br> defer s.mu.Unlock()<br><br> // Retry with same key, and return same response<br> if resp, exists := s.store[key]; exists {<br>  fmt.Println(&quot;duplicate request, returning stored response&quot;)<br>  return resp<br> }<br><br> resp := Response{OrderID: &quot;ORD-1001&quot;, Status: &quot;CREATED&quot;}<br> s.store[key] = resp<br> fmt.Println(&quot;new order created&quot;)<br><br> return resp<br>}<br><br>func main() {<br> store := NewIdempotencyStore()<br><br> resp1 := store.CreateOrder(&quot;123&quot;, &quot;hasan&quot;)<br> fmt.Println(resp1)<br><br> resp2 := store.CreateOrder(&quot;123&quot;, &quot;hasan&quot;)<br> fmt.Println(resp2)<br>}</pre><pre>new order created<br>{ORD-1001 CREATED}<br>duplicate request, returning stored response<br>{ORD-1001 CREATED}</pre><p>First call with 123 to create order. Second call with same key returns old response. This prevents duplicate side effects like double payments or duplicate orders.</p><h4>Storage Layer (Database-Level Idempotency)</h4><p>It prevents duplicate writes. Idempotency is enforced at the database level using constraints.</p><ul><li>UNIQUE keys</li><li>INSERT (INSERT ... ON CONFLICT)</li><li>Prevent duplicate writes even under concurrency</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUTOiy5mBaU_KX5oRanjTw.png" /></figure><pre>CREATE UNIQUE INDEX ux_orders_order_id ON orders(order_id);<br><br>INSERT INTO orders(order_id, amount) VALUES (&#39;ORD-2001&#39;, 100)<br>ON CONFLICT (order_id) DO NOTHING;</pre><pre>First Execution<br><br>Table is empty so row is inserted<br><br>order_id  | amount<br>----------|--------<br>ORD-2001  | 100<br><br>Second Execution (Retry)<br>order_id = ORD-2001 already exists<br>UNIQUE constraint triggers conflict<br>DO NOTHING → skips insert</pre><h4>Messaging Layer (Event Idempotency)</h4><p>It prevents duplicate event processing. In event-driven systems, message brokers often guarantee at-least-once delivery, meaning duplicates can occur.</p><p>To handle this:</p><ul><li>Each event has a unique ID</li><li>Consumer tracks processed messages</li><li>Duplicate events are ignored</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XG4LhJXXRnack6HDXkWn_Q.png" /></figure><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Event struct {<br> ID      string<br> Payload string<br>}<br><br>type Consumer struct {<br> processed map[string]bool<br>}<br><br>func NewConsumer() *Consumer {<br> return &amp;Consumer{<br>  processed: make(map[string]bool),<br> }<br>}<br><br>func (c *Consumer) Handle(event Event) {<br> if c.processed[event.ID] {<br>  fmt.Println(&quot;duplicate event, skipping:&quot;, event.ID)<br>  return<br> }<br><br> fmt.Println(&quot;processing event:&quot;, event.ID, event.Payload)<br> c.processed[event.ID] = true<br>}<br><br>func main() {<br> consumer := NewConsumer()<br> event := Event{ID: &quot;evt-1&quot;, Payload: &quot;payment_received&quot;}<br><br> consumer.Handle(event)<br> consumer.Handle(event) // duplicate delivery<br>}</pre><pre>processing event: evt-1 payment_received<br>duplicate event, skipping: evt-1</pre><p>First event is processed. Then duplicate event with same ID is skipped.</p><h4>Design Layer (Natural Idempotency)</h4><p>It avoids the problem entirely. Some operations are inherently idempotent by design.</p><ul><li>No need for keys or storage</li><li>Same input, same final state</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7bX1aW4X22WhPOLyn4kZQ.png" /></figure><pre>package main<br><br>import &quot;fmt&quot;<br><br>type User struct {<br> ID    string<br> Email string<br>}<br><br>type UserRepo struct {<br> users map[string]*User<br>}<br><br>func NewUserRepo() *UserRepo {<br> return &amp;UserRepo{<br>  users: map[string]*User{<br>   &quot;user-1&quot;: {ID: &quot;user-1&quot;, Email: &quot;hasan@gmail.com&quot;},<br>  },<br> }<br>}<br><br>func (r *UserRepo) UpdateEmail(userID, email string) {<br> user := r.users[userID]<br> user.Email = email<br>}<br><br>func main() {<br> repo := NewUserRepo()<br><br> repo.UpdateEmail(&quot;user-1&quot;, &quot;shahjahan@smiah.dev&quot;)<br> fmt.Println(&quot;after first update:&quot;, repo.users[&quot;user-1&quot;].Email)<br><br> repo.UpdateEmail(&quot;user-1&quot;, &quot;shahjahan@smiah.dev&quot;)<br> fmt.Println(&quot;after second update:&quot;, repo.users[&quot;user-1&quot;].Email)<br>}</pre><h3>Key Guidelines</h3><ol><li>Use UUIDs for idempotency keys — Clients should generate unique keys</li><li>Validate request parameters match — Same key should have same parameters</li><li>Set appropriate TTL — Balance between memory and retry windows</li><li>Lock during processing — Prevent concurrent duplicate processing</li><li>Store results atomically — Use transactions for consistency</li><li>Return identical responses — Same key should return same response</li><li>Handle errors carefully — Release locks so retries can proceed</li></ol><h3>Common Pitfalls</h3><ol><li><strong>Not storing idempotency keys and results</strong> — Without persistence, retries will re-execute the operation.</li><li><strong>Using non-idempotent operations without safeguards</strong> — Actions like increments or inserts can cause duplicate side effects.</li><li><strong>Ignoring retries in async systems</strong> — Background jobs and message queues can deliver duplicates that must be handled.</li></ol><h3>Conclusion</h3><p>Failures happen. Retries happen.</p><p>Without idempotency, they lead to duplicate actions and inconsistent state. With idempotency, they become safe and predictable. It ensures that no matter how many times the same request is sent, system produces one correct outcome and nothing more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5af7a6e187b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Microbenchmarks Lie & Golang Tells the Truth]]></title>
            <link>https://medium.com/@hasanshahjahan/-e124127a6f97?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e124127a6f97</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[benchmarking]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 08:42:02 GMT</pubDate>
            <atom:updated>2025-11-22T08:43:22.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhWqav59P6cJC2YxQp2ukQ.jpeg" /></figure><p>Recently I ran benchmarks on a Python project. I have learned a key lesson. Microbenchmarks in Python mostly capture interpreter noise, not the algorithm itself.</p><p>In contrary, Go doesn’t have this problem. It is compiled and much less noisy, and that is why it’s benchmark give a much clearer picture.</p><h3>Why Microbenchmarks Lie in Python?</h3><p>Python overhead dominates being interpreter, that tiny snippet often spends most of its time in:</p><p>→ Interpreter dispatch (bytecode loop),</p><p>→ Object creation and refcounting,</p><p>→ Attribute lookup,</p><p>→ Function call overhead.</p><p>So, it mostly measures Python’s machinery, not the actual algorithm. To understand root cause better, I approached it step by step.</p><h4>Let’s start with a clear question</h4><p>Am I measuring a small language idiom( e.g list.append vs deque.append), algorithmic complexity (O(n) scaling), an I/O-bound pipeline?</p><h4>Example:</h4><p>The same problem in Python &amp; Go. The goal is to compare an algorithmic approach, not to micro-measure a function call.</p><h4>Python Version</h4><pre># sum_primes.py<br>def is_prime(n):<br>    if n &lt; 2: return False<br>    if n % 2 == 0 and n != 2: return n == 2<br>    i = 3<br>    while i * i &lt;= n:<br>        if n % i == 0:<br>            return False<br>        i += 2<br>    return True<br><br>def sum_primes(n):<br>    total = 0<br>    for i in range(2, n):<br>        if is_prime(i):<br>            total += i<br>    return total</pre><pre>import timeit<br>setup = &quot;from sum_primes import sum_primes&quot;<br>stmt = &quot;sum_primes(20000)&quot;<br>print(timeit.timeit(stmt, setup=setup, number=3))</pre><p>We have to do warm up runs before collecting measurements. We can use multiple sizes of n to observe scaling.</p><h4>Go Version</h4><pre>// sum_primes.go<br>package main<br><br>func isPrime(n int) bool {<br>    if n &lt; 2 { return false }<br>    if n%2 == 0 &amp;&amp; n != 2 { return n == 2 }<br>    for i := 3; i*i &lt;= n; i += 2 {<br>        if n%i == 0 {<br>            return false<br>        }<br>    }<br>    return true<br>}<br><br>func sumPrimes(n int) int {<br>    total := 0<br>    for i := 2; i &lt; n; i++ {<br>        if isPrime(i) {<br>            total += i<br>        }<br>    }<br>    return total<br>}</pre><h4>What You Will Observe(Analysis, No Magic Numbers)</h4><p>Python most time is spent in function calls, object creation, and the interpreter, so scaling only appears for large N.</p><p>In Go, Low per-iteration overhead. It benchmarks scale clearly, reflecting actual algorithm cost.</p><blockquote>Don’t conclude 𝗚𝗼 𝘃𝘀 𝗣𝘆𝘁𝗵𝗼𝗻 or 𝗚𝗼 𝗶𝘀 𝗙𝗮𝘀𝘁𝗲𝗿 from tiny microbenchmarks.</blockquote><h3>Common Artifacts &amp; How to Avoid Them</h3><p>𝗪𝗮𝗿𝗺-𝘂𝗽 &amp; 𝗰𝗮𝗰𝗵𝗲𝘀 — by running a few throwaways, caches and imports.</p><p>𝗨𝘀𝗲 𝘁𝗵𝗲 𝗿𝗶𝗴𝗵𝘁 𝘁𝗼𝗼𝗹𝗶𝗻𝗴 — timeit, pyperf, pytest-benchmark.</p><p>𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝗚𝗖 𝗰𝗮𝗿𝗲𝗳𝘂𝗹𝗹𝘆 — gc.disable() for tight microbenchmarks.</p><p>𝗔𝘃𝗼𝗶𝗱 𝗺𝗲𝗮𝘀𝘂𝗿𝗶𝗻𝗴 𝘁𝗶𝗻𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗰𝗮𝗹𝗹𝘀 — by measuring meaningful work.</p><p>𝗖𝗵𝗲𝗰𝗸 𝘀𝗰𝗮𝗹𝗶𝗻𝗴 — by running multiple input sizes (1e3,1e4,1e5) and check trends.</p><p>𝗨𝘀𝗲 𝗺𝗲𝗱𝗶𝗮𝗻 &amp; 𝗽𝗲𝗿𝗰𝗲𝗻𝘁𝗶𝗹𝗲𝘀 — Use medians and percentiles, not just mean</p><h3>Interpreting Results(What to Trust)</h3><p>Python 2x slower on real data → Meaningful if profiler confirms.</p><p>Go → Irrelevant if real work is I/O or native code.</p><p>Always correlate microbenchmark numbers with a profiler (cProfile for Python, pprof for Go)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e124127a6f97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Docs Don’t Tell You: Interpreter Deep Truths]]></title>
            <link>https://medium.com/@hasanshahjahan/python-docs-dont-tell-you-interpreter-deep-truths-8e813c72e438?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e813c72e438</guid>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 01:24:23 GMT</pubDate>
            <atom:updated>2025-11-16T08:42:55.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDM-ePdBbMBh2swNZ7Foew.png" /></figure><p>I recently took the chance to explore Python, and found some interesting production-grade interpreter gotchas. The kind of things that even senior Python engineers might misunderstand.</p><p>Not everything in Python is as straightforward as it seems.</p><h3>Identity vs Equality</h3><blockquote>A simple but critical Python rule</blockquote><p>This is simple yet high chances to misuse. None is a singleton in Python, so the proper way to check is with is. It compares identity, not value.</p><pre># equality_vs_identity.py<br>life = None<br>miah = &quot;hello&quot;<br>louge = &quot;hello&quot;<br><br># Identity check with None<br>if life is None:<br>    print(&quot;Yes, life is None → checks identity&quot;)  # correct for None<br><br># Value equality check<br>if miah == louge:<br>    print(&quot;Miah == louge → checks value equality&quot;)  # correct for general equality<br><br># Demonstrate difference with custom object<br>class Miahlouge:<br>    def __eq__(self, other):<br>        print(&quot;Miahlouge __eq__ called&quot;)<br>        return True<br><br>miahlouge1 = Miahlouge()<br>miahlouge2 = Miahlouge()<br><br>if miahlouge1 == miahlouge2:<br>    print(&quot;miahlouge1 == miahlouge2 → uses __eq__ (value equality)&quot;)<br>if miahlouge1 is miahlouge2:<br>    print(&quot;miahlouge1 is miahlouge2 → identity check (same object)&quot;)</pre><pre>Yes, life is None → checks identity<br>Miah == louge → checks value equality<br>Miahlouge __eq__ called<br>miahlouge1 == miahlouge2 → uses __eq__ (value equality)</pre><p>Why &quot;miahlouge1 is miahlouge2 → identity check&quot; did not print?</p><pre>miahlouge1 = Miahlouge() creates one object in memory.<br>miahlouge2 = Miahlouge() creates a separate object in memory.<br><br>So miahlouge1 is miahlouge2 is False and that&#39;s why it did not print. </pre><h3><strong>Import is not Atomic:</strong></h3><blockquote>A failed import can poison entire process.</blockquote><p>If a module import crashes mid-execution, Python keeps the partially-loaded module in sys.modules. Next import of that module? It loads the broken half-initialized state, not the file.</p><pre>#module_miahlouge.py<br>print(&quot;module_miahlouge loaded&quot;)<br>raise Exception(&quot;boom&quot;)</pre><pre>#main.py<br>try:<br>    import module_miahlouge<br>except:<br>    pass<br><br>import module_miahlouge   # ← does NOT retry.</pre><p>This second import doesn’t reload. It returns the corrupted module skeleton.</p><pre>module_miahlouge loaded<br>module_miahlouge loaded<br>Traceback (most recent call last):<br>  File &quot;/Users/miahlouge/python/production-python-myths/main.py&quot;, line 7, in &lt;module&gt;<br>    import module_miahlouge   # ← does NOT retry.<br>    ^^^^^^^^^^^^^^^^^^^^^^^<br>  File &quot;/Users/miahlouge/python/production-python-myths/module_miahlouge.py&quot;, line 2, in &lt;module&gt;<br>    raise Exception(&quot;boom&quot;)<br>Exception: boom</pre><h4><strong>Solution:</strong></h4><p>We need to remove from sys.modules manually or use importlib.reload.</p><pre># main.py<br>import sys<br>import importlib<br><br>module_name = &quot;module_miahlouge&quot;<br><br>try:<br>    import module_miahlouge<br>except Exception as ex:<br>    print(f&quot;Initial import failed: {ex}&quot;)<br><br># Remove the corrupted module so the next import works<br>if module_name in sys.modules:<br>    del sys.modules[module_name]<br><br># Retry a fresh import<br>try:<br>    module_miahlouge = importlib.import_module(module_name)<br>except Exception as ex:<br>    print(f&quot;Second import also failed: {ex}&quot;)</pre><pre>module_miahlouge loaded<br>Initial import failed: boom<br>module_miahlouge loaded<br>Second import also failed: boom</pre><h3>Python Doesn’t Return Memory to The OS</h3><blockquote>The OS never sees this memory as “free”, because Python keeps it internally.</blockquote><p>CPython has its own memory allocator, pymalloc, which manages small objects. Memory is allocated in arenas. Even if Python objects are deleted and garbage collected, the memory stays in the arenas, ready for reuse by Python. The OS never sees this memory as “free”, because Python keeps it internally.</p><pre>#main.py<br>import sys<br>import gc<br><br># Allocate a lot of small objects<br>big_list = [bytearray(1024) for _ in range(100_000)]<br>print(&quot;Memory allocated:&quot;, sys.getsizeof(big_list))<br><br># Delete them<br>del big_list<br><br># Force garbage collection<br>gc.collect()<br><br>input(&quot;Check your system memory usage now (Python process still holds arenas)&quot;)</pre><pre>Memory allocated: 800984<br>Check your system memory usage now (Python process still holds arenas)</pre><p>big_list allocates ~100,000 small objects. Python requests memory from the OS.del big_list + gc.collect() frees the objects at the Python level. But CPython keeps the memory in its arenas for future Python allocations.</p><h4>Common Patterns to Release Memory Back To the OS</h4><p>Periodically recycle processes (e.g., Gunicorn max-requests) and offload large temporary memory to NumPy, mmap, or subprocesses, which can release memory to the OS is necessary.</p><pre>#main.py<br>from multiprocessing import shared_memory<br>import numpy as np<br><br>shm = shared_memory.SharedMemory(create=True, size=1024*1024*100)<br>arr = np.ndarray((100_000_000,), dtype=np.uint8, buffer=shm.buf)<br><br># Done using it<br>shm.close()<br>shm.unlink()  # memory freed from the OS</pre><p>Even <a href="https://docs.python.org/3/c-api/memory.html">Python 3.14</a>, no change. CPython arena behavior is the same, so recycling is still the most reliable way.</p><h3>CPython Executes Function Defaults O<em>nce</em> at Import Time</h3><blockquote>Everyone knows the “mutable default argument” problem.</blockquote><p>It is the runtime impact of expensive defaults.</p><pre># slow_defaults.py<br>def expensive_startup(default=list(range(10_000_000))):<br>    print(&quot;Function called&quot;)</pre><pre>#main.py<br>import slow_defaults  # ← expensive computation runs here</pre><p>The list(range(10_000_000))<strong> </strong>is evaluated immediately when the module is imported, not when the function is called. If defaults include a DB query, file read, or heavy computation, the import will block startup, slowing down the entire interpreter.</p><pre>def safe_startup(default=None):<br>    if default is None:<br>        default = list(range(10_000_000))</pre><p>This ensures the computation happens on function call, not import.</p><h3>File Descriptors Leak into Child Processes</h3><blockquote>Zombie sockets — huge production pain point.</blockquote><p>File descriptors (sockets, pipes) leak into child processes unless:</p><pre>#main.py<br>import subprocess<br><br>subprocess.Popen([&quot;ls&quot;, &quot;-l&quot;])</pre><p>By default, all open file descriptors (FDs) in the parent process are inherited by the child. That includes sockets, open files, pipes, database connections, etc. If the child process keeps them open, it can prevent resources from being released in the parent.</p><h4>Common consequences in production:</h4><p>Sockets appear “in use” cause address conflicts. Pipes never close therefore parent process hangs or deadlocks. Temporary files aren’t freed because FD is held by child.</p><h4>How to fix</h4><p>By using close_fds=True</p><pre>#main.py<br>import subprocess<br><br>subprocess.Popen([&quot;ls&quot;, &quot;-l&quot;], close_fds=True)</pre><h3>Asyncio Still uses The GIL</h3><blockquote>Tasks are concurrent, NOT parallel</blockquote><p>Asyncio still provides concurrency, not parallelism, because of the Global Interpreter Lock(GIL). It is still true in <a href="https://docs.python.org/3/library/threading.html"><strong>Python 3.14</strong></a></p><pre>#main.py<br>import asyncio<br>import time<br><br>async def cpu_task(n):<br>    start = time.time()<br>    total = sum(range(n))  # CPU-bound<br>    print(f&quot;Task finished in {time.time() - start:.2f}s&quot;)<br>    return total<br><br>async def main():<br>    results = await asyncio.gather(<br>        cpu_task(10_000_000),<br>        cpu_task(10_000_000)<br>    )<br>    return results<br><br>if __name__ == &quot;__main__&quot;:<br>    start = time.time()<br>    results = asyncio.run(main())<br>    print(&quot;Results:&quot;, results)<br>    print(f&quot;Total elapsed time: {time.time() - start:.2f}s&quot;)</pre><pre>Task finished in 0.58s<br>Task finished in 0.58s<br>Results: [4999999950000000, 4999999950000000]<br>Total elapsed time: 1.15s</pre><p>Both tasks run <em>sequentially</em>, not in parallel, because of the GIL. Total runtime ≈ sum of both tasks.</p><h4>How to achieve parallelism</h4><p>It provides real parallelism</p><pre>#main.py<br>from concurrent.futures import ProcessPoolExecutor<br>import asyncio<br>import time<br><br>def cpu_task(n):<br>    start = time.time()<br>    total = sum(range(n))<br>    print(f&quot;Task finished in {time.time() - start:.2f}s&quot;)<br>    return total<br><br>async def main():<br>    loop = asyncio.get_running_loop()<br>    with ProcessPoolExecutor() as pool:<br>        # Run two CPU-bound tasks in parallel<br>        results = await asyncio.gather(<br>            loop.run_in_executor(pool, cpu_task, 100_000_000),<br>            loop.run_in_executor(pool, cpu_task, 100_000_000)<br>        )<br>    print(&quot;Results:&quot;, results)<br><br>if __name__ == &quot;__main__&quot;:<br>    start = time.time()<br>    asyncio.run(main())<br>    print(f&quot;Total elapsed time: {time.time() - start:.2f}s&quot;)</pre><pre>Task finished in 0.58s<br>Task finished in 0.58s<br>Results: [4999999950000000, 4999999950000000]<br>Total elapsed time: 1.15s</pre><p>Each task runs in its own process, bypassing the GIL. For large tasks, total runtime ≈ runtime of a single task.</p><h3>Conclusion</h3><p>Small Python behaviors for instance None checks, imports, or defaults can cause big surprises. Knowing them helps write safer, faster &amp; efficient code.</p><p>#python #interpreter</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e813c72e438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Python Threads Wait & Go’s Don’t]]></title>
            <link>https://medium.com/@hasanshahjahan/why-python-threads-wait-gos-don-t-1b2a0645a167?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2a0645a167</guid>
            <category><![CDATA[global-interpreter-lock]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[os-thread]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[go-runtime]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 00:12:09 GMT</pubDate>
            <atom:updated>2025-10-12T06:17:47.593Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python, only one thread runs Python code at a time. <a href="https://wiki.python.org/moin/GlobalInterpreterLock">The Global Interpreter Lock (GIL)</a> ensures this, while the operating system (OS) handles threads waiting for their turn.</p><p>Threads waiting for the GIL, and don’t sit in a Python-level “queue” like queue.Queue. They are managed by the operating system’s thread scheduler.</p><h3>Why Python Threads Wait</h3><p>Here’s what happens in detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qX7P-O_MhOmbDtz2zPOaZA.png" /></figure><p>Each Python thread is an OS-level thread.</p><p>1. Pthread on Unix</p><p>2. Win32 thread on Windows</p><p>When a thread tries to acquire the The Global Interpreter Lock(GIL) and finds it locked, the OS blocks the thread.</p><p>This is done at the kernel level, so the thread doesn’t consume CPU cycles while waiting.</p><h4>Sleeping / Waiting State</h4><p>The blocked thread is put into a waiting/sleeping state by the OS. It will be resumed automatically when the GIL becomes available, but not in Python memory. Python itself doesn’t maintain a queue or list of waiting threads. The OS handles scheduling and waking up threads when the lock is released.</p><pre>Step                               | What happens              | Who manages it <br>-----------------------------------| ------------------------- | -------------- <br>Thread tries to run Python bytecode| Needs the GIL             | CPython        <br>GIL already held                   | Thread blocks             | OS kernel      <br>Thread blocked                     | Put to sleep              | OS             <br>GIL released                       | OS wakes a waiting thread | OS             <br>Next thread runs                   | Acquires GIL and executes | CPython + OS  </pre><h3>Why Go Goroutines Don’t Wait Like Python Threads</h3><p>In Go, goroutines are lightweight user-space threads managed by the Go runtime, not directly by the operating system(OS).</p><p>Go scheduler manages them, deciding which goroutine runs on which thread. OS threads are limited resources, so multiple goroutines can be multiplexed on a single OS thread.</p><p>When a goroutine blocks (e.g., network I/O), the Go runtime moves another runnable goroutine onto that same thread.</p><p>Here’s what happens in detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzrpL-Nzg5loD4RfYy9l3Q.png" /></figure><pre> Step                        | What happens                                                            | Who manages it  <br>-----------------------------| ----------------------------------------------------------------------- | --------------- <br>Goroutine created            | Added to the runnable queue                                             | Go runtime      <br>Scheduler picks a goroutine  | Assigns it to an available OS thread (M)                                | Go scheduler    <br>Goroutine runs               | Executes user code on an OS thread                                      | Go runtime + OS <br>Goroutine blocks (e.g., I/O) | OS thread blocked, scheduler assigns another goroutine to a free thread | Go runtime      <br>Blocked goroutine ready again| Returned to runnable queue                                              | Go runtime      <br>More goroutines than threads | Scheduler multiplexes goroutines over available OS threads              | Go runtime     <br>Execution continues          | Goroutines cooperatively yield and resume                               | Go scheduler    </pre><h3>Conclusion</h3><p>Python’s concurrency is limited by the The Global Interpreter Lock (one thread runs at a time). Go’s concurrency is managed by the Go runtime, which multiplexes many goroutines across a few OS threads efficiently, no global lock.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2a0645a167" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking and Profiling in Python]]></title>
            <link>https://medium.com/@hasanshahjahan/benchmarking-and-profiling-in-python-dd4db60e3149?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd4db60e3149</guid>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[benchmarking]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 15:22:59 GMT</pubDate>
            <atom:updated>2025-10-11T15:22:59.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZAbAC4mhEzM2H1tZ7Jldw.avif" /></figure><p>In Python, measuring performance correctly from small snippets to full-scale tests is key to writing efficient and maintainable code.</p><p>Whether we’re timing a quick function, profiling memory, or running reproducible benchmarks, Python provides multiple tools for each purpose.</p><p>Let’s go through them step by step.</p><ul><li><strong>Benchmarking</strong> → measures how fast or efficient the code runs.</li><li><strong>Profiling</strong> → explains where time/memory is spent.</li></ul><h3>Benchmarking</h3><p>Benchmarking is the process of measuring the performance of code under controlled conditions. It measures execution time, memory, or throughput to compare implementations.</p><h4>Small Snippet Timing</h4><p>A simple and accurate timing to measure execution time. Best suited for tiny code snippets or individual functions, it automatically runs the code multiple times to calculate an average. It is ideal for micro-benchmarks, comparing algorithms, checking small optimizations.</p><pre>import timeit<br><br>def compute():<br>    return sum(i*i for i in range(1000))<br><br>execution_time = timeit.timeit(&quot;compute()&quot;, globals=globals(), number=1000)<br>print(f&quot;Small snippet execution time: {execution_time:.5f} seconds&quot;)</pre><h4>Code Block Timing</h4><p>Measures the execution time of larger code sections or sequences of operations. We need to manually start and stop the timer, making it ideal for benchmarking entire blocks of logic, loops, or workflows rather than single functions.</p><pre>import time<br><br>start = time.perf_counter()<br>total = sum(i*i for i in range(1_000_000))<br>end = time.perf_counter()<br>print(f&quot;Code block execution time: {end - start:.5f} seconds&quot;)</pre><h4>Automated Performance Tests</h4><p>Automated performance tests let us <strong>benchmark code reproducibly</strong> as part of our testing workflow. Tools like pytest-benchmark integrate with pytest to measure execution time, track regressions, and compare different implementations.</p><pre># test_benchmark.py<br>import pytest<br><br>def compute():<br>    return sum(i*i for i in range(1_000_000))<br><br>def test_compute(benchmark):<br>    result = benchmark(compute)<br>    assert result &gt; 0</pre><h4>Example</h4><p>Worth a read if you want to understand <a href="https://medium.com/@hasanshahjahan/why-python-has-multiple-layers-of-concurrency-a1b5cd73c76b">Python’s multiple concurrency layers</a>, otherwise, you can skip it.</p><p>Let’s explore hands-on Concurrency Benchmarking</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8d8LcuAgLKe_fKOzzCJKQ.png" /><figcaption>Figure: Multithreading vs Multiprocessing</figcaption></figure><p>We will likely get something like this on a 8-core CPU machine if we run the below code:</p><pre>Approach    Time(s)    Notes<br>--------    -------    ------<br>Sequential  1.32s       Baseline<br>Threads     1.34s       No real gain (GIL blocks true parallelism)<br>Processes   0.44s       True parallelism, best for CPU-bound<br>Async       1.32s       Uses threads internally, same GIL limit</pre><pre>import time, threading, multiprocessing, asyncio<br><br>def cpu_bound(n):<br>    return sum(i*i for i in range(n))<br><br>def run_sequential():<br>    for _ in range(4):<br>        cpu_bound(10_000_000)<br><br>def run_threads():<br>    threads = [threading.Thread(target=cpu_bound, args=(10_000_000,)) for _ in range(4)]<br>    [t.start() for t in threads]<br>    [t.join() for t in threads]<br><br>def run_processes():<br>    processes = [multiprocessing.Process(target=cpu_bound, args=(10_000_000,)) for _ in range(4)]<br>    [p.start() for p in processes]<br>    [p.join() for p in processes]<br><br>async def run_async():<br>    await asyncio.gather(*[asyncio.to_thread(cpu_bound, 10_000_000) for _ in range(4)])<br><br>if __name__ == &quot;__main__&quot;:<br>    for name, func in [<br>        (&quot;Sequential&quot;, run_sequential),<br>        (&quot;Threads&quot;, run_threads),<br>        (&quot;Processes&quot;, run_processes),<br>    ]:<br>        start = time.perf_counter()<br>        func()<br>        print(f&quot;{name}: {time.perf_counter() - start:.2f}s&quot;)<br>    start = time.perf_counter()<br>    asyncio.run(run_async())<br>    print(f&quot;Async: {time.perf_counter() - start:.2f}s&quot;)</pre><p>Results show clear differences: Sequential is the baseline, Threads gain nothing due to the GIL, Processes achieve true parallelism, and Async performs like Sequential for CPU-heavy tasks.</p><h4>Benchmarking Data Engineering and Analytics Workflows</h4><p>Benchmarking is not only for concurrency or algorithmic performance. It’s equally essential in data engineering and analytics workflows. In real-world pipelines, transformations using Pandas or similar frameworks often process millions of rows, and even small inefficiencies can quickly become major bottlenecks.</p><p>By measuring execution time, memory usage, and scalability of data transformations, we can identify performance gaps early.</p><pre>import pandas as pd<br>import time<br>import tracemalloc<br>import timeit<br><br># Create a large dataset<br>df = pd.DataFrame({<br>    &quot;a&quot;: range(1_000_000),<br>    &quot;b&quot;: range(1_000_000, 2_000_000)<br>})<br><br><br># Method 1: Row-wise apply (slow, memory heavy)<br>def method_apply(df):<br>    return df.apply(lambda x: x[&quot;a&quot;] * x[&quot;b&quot;], axis=1)<br><br><br># Method 2: Vectorized (fast, memory-efficient)<br>def method_vectorized(df):<br>    return df[&quot;a&quot;] * df[&quot;b&quot;]<br><br><br># Benchmark and memory profile<br>def benchmark(func, df, label):<br>    print(f&#39;=== {label} ===&#39;)<br><br>    # Measure execution time with time.perf_counter<br>    start = time.perf_counter()<br>    tracemalloc.start()  # start memory tracking<br><br>    func(df)<br><br>    current, peak = tracemalloc.get_traced_memory()<br>    tracemalloc.stop()<br>    end = time.perf_counter()<br><br>    print(f&#39;Time taken: {end - start:.4f}s&#39;)<br>    print(f&#39;Memory: Current={current / 1024 ** 2:.2f} MB, Peak={peak / 1024 ** 2:.2f} MB\n&#39;)<br><br><br># Micro-benchmark with timeit<br>def micro_benchmark(func, df, label, number=3):<br>    duration = timeit.timeit(lambda: func(df), number=number)<br>    print(f&#39;{label} - timeit for {number} runs: {duration / number:.4f}s per run\n&#39;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    # High-level benchmarking<br>    benchmark(method_apply, df, &quot;Apply&quot;)<br>    benchmark(method_vectorized, df, &quot;Vectorized&quot;)<br><br>    # Micro-benchmark<br>    micro_benchmark(method_apply, df, &quot;Apply&quot;)<br>    micro_benchmark(method_vectorized, df, &quot;Vectorized&quot;)</pre><p>Whether it’s a slow groupby, inefficient joins, or repeated I/O operations. Combining tools like <strong>timeit</strong>, <strong>tracemalloc</strong>, or external frameworks such as <strong>Dask</strong> and <strong>Polars </strong>benchmarking utilities, lets us optimize our entire workflow from prototype to production.</p><p>Benchmarking at this level ensures our pipelines remain efficient, predictable, and cost-effective too<strong>, </strong>not just functionally correct.</p><h3>Profiling</h3><p>Profiling is the process of analyzing program to understand how it behaves during execution, especially to find performance bottlenecks.</p><h4>Line-by-Line Profiling</h4><p>Line-by-line profiling analyzes how much time each individual line of a function takes during execution. By using tools like <strong>line_profiler</strong>, we can pinpoint exactly which operations consume the most time. This is ideal for optimizing hot spots in performance-critical code, especially in loops or heavy computations.</p><pre>from line_profiler import profile<br><br>@profile<br>def heavy_task():<br>    total = 0<br>    for i in range(10_000_000):  # Increased from 1_000_000 to 10 million<br>        total += i * i<br>    return total<br><br>def main():<br>    for _ in range(5):  # Repeat 5 times<br>        heavy_task()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Let’s run the following command to profile the script line by line using line profiler.</p><p>kernprof -l -v main.py</p><pre>Wrote profile results to &#39;main.py.lprof&#39;<br>Timer unit: 1e-06 s<br><br>Total time: 19.947 s<br>File: main.py<br>Function: heavy_task at line 3<br><br>Line #      Hits         Time  Per Hit   % Time  Line Contents<br>==============================================================<br>     3                                           @profile<br>     4                                           def heavy_task():<br>     5         5          6.0      1.2      0.0      total = 0<br>     6  50000005    9592495.0      0.2     48.1      for i in range(10_000_000):  # Increased from 1_000_000 to 10 million<br>     7  50000000   10354487.0      0.2     51.9          total += i * i<br>     8         5         11.0      2.2      0.0      return total</pre><h4>Function Profiling</h4><p>Function profiling analyzes how much time each function takes during execution. By using tools like cProfile, we can identify slow functions and performance bottlenecks in code. It’s ideal for larger programs where understanding which functions consume the most resources is crucial.</p><pre>import cProfile<br><br>def heavy_task():<br>    total = sum(i*i for i in range(1_000_000))<br>    return total<br><br>def main():<br>    for _ in range(5):<br>        heavy_task()<br><br>cProfile.run(&quot;main()&quot;)</pre><h4>Memory Profiling</h4><p>Memory profiling helps track how much memory Python program uses and where allocations happen. By using tools like tracemalloc,let us identify memory leaks, optimize data structures, and understand memory consumption patterns.</p><pre>import tracemalloc<br><br>tracemalloc.start()<br><br>data = [i*i for i in range(100_000)]<br>snapshot = tracemalloc.take_snapshot()<br>top_stats = snapshot.statistics(&quot;lineno&quot;)<br><br>for stat in top_stats[:5]:<br>    print(stat)</pre><h4>Statistical Profiling</h4><p>Statistical profiling periodically samples program’s stack to see where time is being spent. Unlike deterministic profilers (e.g., cProfile), it doesn’t trace every function call, so it adds very little overhead. This makes it ideal for profiling production workloads or long-running programs.</p><pre>from pyinstrument import Profiler<br><br>def heavy_task():<br>    total = sum(i*i for i in range(10_000_000))<br>    return total<br><br>profiler = Profiler()<br>profiler.start()<br><br>for _ in range(5):<br>    heavy_task()<br><br>profiler.stop()<br>print(profiler.output_text(unicode=True, color=True))</pre><h3>Conclusion</h3><p>Benchmarking and profiling help identify performance bottlenecks early. From concurrency to data pipelines, Python offers tools to measure time, memory, and scalability. We can’t improve what we don’t measure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd4db60e3149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Python Has Multiple Layers of Concurrency]]></title>
            <link>https://medium.com/@hasanshahjahan/why-python-has-multiple-layers-of-concurrency-a1b5cd73c76b?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1b5cd73c76b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 04:45:46 GMT</pubDate>
            <atom:updated>2025-10-11T15:36:56.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency is a programming concept that enables applications to execute multiple tasks at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnt0V71hgj1SbusHCRr7Kg.png" /></figure><p>Python faces a similar challenge like programs often need to handle multiple tasks at once (reading files, fetching data, or processing large datasets). But Python doesn’t solve this with a single tool. It has multiple layers of concurrency, each designed for a specific purpose.</p><p>Python’s concurrency model can be confusing at first. Unlike languages such as Go, which has a single, unified <a href="https://medium.com/@hasanshahjahan/concurrency-patterns-in-go-part-1-ca84d6787b90">concurrency</a> mechanism (<a href="https://go.dev/tour/concurrency/1">goroutines</a> and <a href="https://go.dev/tour/concurrency/2">channels</a>), Python takes a <strong>layered approach</strong>. This is a direct consequence of the <a href="https://wiki.python.org/moin/GlobalInterpreterLock"><strong>Global Interpreter Lock (GIL)</strong></a>.</p><h3><strong>Different Types of Tasks Programmers Handle</strong></h3><p>Before exploring each layer, let’s understand the different types of tasks programmers handle. These include CPU-heavy computations, I/O operations, and memory-efficient streaming. Then, we can explore each layer, its purpose, and when to use it.</p><ol><li>CPU-bound tasks: Heavy computations like image processing, scientific calculations, or encryption.</li><li>I/O-bound tasks: Waiting for external resources like reading/writing files, network requests, or database queries.</li><li>Memory-bound tasks / Streaming: Handling large datasets without loading everything into memory (e.g., processing millions of rows in a CSV).</li></ol><p>As programmers, we need to choose the right Python concurrency layer based on the type of task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3I7_u1QB3_hcobwsG3s_kA.png" /><figcaption>Figure: Types of Tasks</figcaption></figure><h3>I/O-Bound</h3><p>I/O-bound tasks spend most of their time waiting for external resources like files, networks, or databases, instead of using the CPU. They can be categorized into two types: non-blocking I/O-bound and blocking I/O-bound.</p><h4>Non-blocking I/O-bound</h4><blockquote>Python Layer/Tool: Coroutines + Event Loop + Cooperative Multitasking</blockquote><p><strong>Coroutines:</strong></p><p>A coroutine is like an actor who can pause mid-performance, letting someone else take the stage, then resume later right where they left off.</p><p><strong>Event Loop:</strong></p><p>The event loop is a conductor in an orchestra, ensuring that each actor (coroutine) performs at the right time without clashing.</p><p><strong>Cooperative Multitasking:</strong></p><p>It is like secret agreement. Every actor agrees: “When I’m waiting, I’ll step aside so others can perform.”</p><h4>Example: <em>Non-blocking with A</em>syncio</h4><pre>import asyncio<br><br>async def download_file(name: str, delay: int) -&gt; str:<br>    &quot;&quot;&quot;Simulate a file download using non-blocking I/O.&quot;&quot;&quot;<br>    print(f&#39;{name}: Started downloading...&#39;)<br><br>    # Non-blocking wait (simulated I/O)<br>    await asyncio.sleep(delay)<br>    print(f&#39;{name}: Finished downloading after {delay}s.&#39;)<br>    return name<br><br>async def main():<br>    # Get the current event loop<br>    loop = asyncio.get_running_loop()<br>    print(f&quot;Event Loop: {loop}\n&quot;)<br><br>    # Create multiple coroutine tasks<br>    tasks = [<br>        loop.create_task(download_file(&quot;File A&quot;, 3)),<br>        loop.create_task(download_file(&quot;File B&quot;, 2)),<br>        loop.create_task(download_file(&quot;File C&quot;, 1)),<br>    ]<br><br>    print(&quot;All downloads started concurrently...\n&quot;)<br><br>    # Wait for all tasks to finish cooperatively<br>    done, pending = await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED)<br><br>    # Collect results from completed tasks<br>    results = [task.result() for task in done]<br>    print(&quot;All downloads completed:&quot;, results)<br><br># Run the event loop<br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><h4>Blocking I/O-bound</h4><blockquote>Python Layer/Tool: Multithreading</blockquote><p>Blocking I/O-bound tasks spend most of their time waiting for external resources using <strong>blocking calls</strong>. These operations prevent the task from doing anything else until the I/O completes.</p><ul><li>Reading or writing files using legacy libraries</li><li>Blocking network requests</li><li>Database queries using synchronous libraries</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6GJZ7rFOJ1HYD83ou9jGw.png" /><figcaption>Figure: Multithreading</figcaption></figure><p><strong>Multithreading</strong> lets multiple threads run concurrently in the same process. Python’s GIL allows only one thread to execute Python code at a time, so true parallelism is limited. Still, threads are useful for I/O-bound tasks, where one thread waits for resources while others run.</p><h4>Example: <strong>Blocking I/O Example with Threads</strong></h4><pre>import threading<br>import time<br><br>def read_file(name, delay) -&gt; None:<br>    &quot;&quot;&quot;Simulate reading a file (blocking I/O)&quot;&quot;&quot;<br>    print(f&#39;{name}: Started reading...&#39;)<br>    time.sleep(delay)  # Blocking I/O simulation<br>    print(f&#39;{name}: Finished reading after {delay}s&#39;)<br><br>def main():<br>    file_tasks = [<br>        (&quot;File A&quot;, 3),<br>        (&quot;File B&quot;, 2),<br>        (&quot;File C&quot;, 1),<br>    ]<br><br>    threads = []<br><br>    # Create and start threads dynamically<br>    for name, delay in file_tasks:<br>        t = threading.Thread(target=read_file, args=(name, delay))<br>        threads.append(t)<br>        t.start()<br><br>    # Wait for all threads to finish<br>    for t in threads:<br>        t.join()<br><br>    print(&quot;All files read.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>CPU-bound</h3><blockquote>Python Layer/Tool: Multiprocessing</blockquote><p>To overcome the limitations of the <a href="https://wiki.python.org/moin/GlobalInterpreterLock"><strong>Global Interpreter Lock (GIL)</strong></a>, Python provides multiprocessing for CPU-bound tasks. Multiprocessing runs multiple processes, each with its own Python interpreter and memory. It enables true parallelism, ideal for CPU-bound tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBCA5Pc97oHFjrxzC2slKw.png" /><figcaption>Figure: Multiprocessing</figcaption></figure><p>Multiprocessing creates a separate Python process for each task, giving each process its own interpreter and memory space and avoiding the GIL. This makes it ideal for CPU-heavy tasks like factorials, data processing, or scientific calculations, and using join() ensures the main program waits until all processes finish.</p><h4>Example: <strong>CPU-bound Tasks using Multiprocessing</strong></h4><pre>import multiprocessing<br>import math<br><br>def compute_factorial(n):<br>    &quot;&quot;&quot;Simulate a CPU-intensive task&quot;&quot;&quot;<br>    print(f&#39;Process {n}: Computing factorial({n})...&#39;)<br>    result = math.factorial(n)  # CPU-heavy computation<br>    print(f&#39;Process {n}: Done&#39;)<br>    return result<br><br>def main():<br>    numbers = [50000, 60000, 70000]  # CPU-heavy tasks<br>    processes = []<br><br>    # Create and start processes dynamically<br>    for num in numbers:<br>        p = multiprocessing.Process(target=compute_factorial, args=(num,))<br>        processes.append(p)<br>        p.start()<br><br>    # Wait for all processes to finish<br>    for p in processes:<br>        p.join()<br><br>    print(&quot;All CPU-bound tasks completed.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Streaming/Memory-Bound</h3><blockquote>Python Layer/Tool : Generators</blockquote><h4>Generators: The Lazy Workers</h4><p>A generator, The Lazy Workers, is like a storyteller who pauses after every sentence, waiting for the audience to ask for the next line. Generators are functions that yield values one at a time instead of computing upfront. They are pull-based, the caller requests the next value, and the generator pauses after each yield.</p><h4>Example: Memory-bound Tasks using Generators</h4><pre>def generate_large_data(n):<br>    &quot;&quot;&quot;Generator that yields numbers from 1 to n, simulating a large dataset.&quot;&quot;&quot;<br>    for i in range(1, n + 1):<br>        yield i<br><br>def main():<br>    # Simulate processing 1 million items<br>    # Use 10 for demo; change to 1_000_000 for large dataset<br>    for item in generate_large_data(10):  <br>        print(item)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>When to Use Each Approach</h3><h4><strong>Multithreading</strong></h4><ul><li>I/O-bound tasks like network operations, file I/O, or database queries.</li><li>Useful when you need shared state between threads.</li><li>Not ideal for CPU-bound tasks due to Python’s GIL.</li></ul><h4><strong>Multiprocessing</strong></h4><ul><li>Ideal for CPU-bound tasks that require true parallelism.</li><li>Bypasses the GIL, allowing each process to run independently.</li><li>Heavy computational workloads like data processing or scientific calculations.</li></ul><h4><strong>Asyncio</strong></h4><ul><li>Excellent for I/O-bound tasks with many concurrent operations.</li><li>Ideal for high-performance network servers or applications with numerous asynchronous tasks.</li><li>Not suitable for CPU-bound tasks unless computation is offloaded to separate processes.</li></ul><h4><strong>Generators</strong></h4><ul><li>Best for memory-bound or streaming tasks where loading all data into memory is impractical.</li><li>Useful for processing large datasets or building streaming pipelines.</li><li>Yield values on demand, making them memory-efficient and lazy.</li></ul><p><a href="https://medium.com/@hasanshahjahan/benchmarking-and-profiling-in-python-dd4db60e3149">Benchmarking and Profiling in Python</a></p><h3>Conclusion</h3><p>Python’s layered approach to concurrency allows developers to choose the right tool for the task at hand. Understanding the strengths and limitations of each layer helps write more efficient, scalable, and maintainable Python applications. By selecting the right concurrency approach workload, we can optimize performance while keeping code clean and readable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1b5cd73c76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Distributed System]]></title>
            <link>https://medium.com/@hasanshahjahan/understanding-distributed-system-36cb53b7cf4b?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/36cb53b7cf4b</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 19:21:58 GMT</pubDate>
            <atom:updated>2024-04-27T22:43:27.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2jcBS_hRP8QjCS62OpW0A.png" /></figure><p>Most engineering books or blogs deep dive right into the heart of some complex topics around distributed systems which can overwhelm you, if you are not experienced enough. A common recommendation is Martin Kleppmann’s <a href="https://www.oreilly.com/library/view/designing-data-intensive-applications/9781491903063/">Designing Data-Intensive Applications</a>, but its concepts may be too advanced for someone new to distributed systms. Even seasoned professionals can find very complex such as consistency models and distributed transactions algorithms.</p><p>However, this article, along with its sub-articles on distributed systems, will give you a complete and solid understanding of distributed system. While I am writing this article, I am quite experienced at scalable systems.</p><h3>What information is necessary to understand?</h3><p>Almost the exact order we follow when creating a new distributed application. This article will be structed with five sections to understand the complete life cycle of distributed sytems ordering with considering one of the most interesting books I have found on this topic is <a href="https://understandingdistributed.systems/?ref=blog.pragmaticengineer.com">Understanding Distributed Systems</a>.</p><ul><li>Communication</li><li>Coordination</li><li>Scalability</li><li><a href="https://www.linkedin.com/pulse/building-resilient-distributed-systems-considerations-md-shahjahan-lfryc/">Resiliency</a></li><li>Maintainability</li></ul><h3>Communication</h3><p>Commucation is important to understanding how distributed systems work or why they are even needed at a basic level. They are essentially separated nodes that are responsible for sharing information over the network. It’s essential to understand the mechanics of network communication, including the concept of a network stack and its operations at each level. With this understanding, we can begin constructing systems that effectively communicate over networks.</p><p>[Undertanding communication in distributed system — Coming Soon]</p><h3>Coordination</h3><p>As we expand our system with additional nodes, coordinating communication becomes essential. In this segment, I’ll detail methods for detecting failures within our system, managing replications, and implementing algorithms for selecting primary nodes, including various consensus algorithms.</p><p>[Undertanding coordination in distributed system — Coming Soon]</p><h3>Scalability</h3><p>When we are able to coordinate well over communication, it comes now to think how we can perform transactions over a distributed system. This is arguably the most important part of building distributed system to handle scale. I will explain how pattern works to achieving scalability like microservices, apis, messaging, partioning, replication, caching, and load balancing.</p><p>[Undertanding scalability in distributed system — Coming Soon]</p><h3>Resiliency</h3><p>A distributed system that can handle scale but is unreliable is not any good. That’s why <a href="https://www.linkedin.com/pulse/building-resilient-distributed-systems-considerations-md-shahjahan-lfryc/">understanding resiliency in distributed system</a> is very important. We need to understand <a href="https://medium.com/@hasanshahjahan/understanding-the-ins-and-outs-of-distributed-systems-2530e0c97684">the ins and outs of distributed systems</a> like single points of failures, circuit breakers, retry patterns, rate limiting. Basically what I refer to as understanding downstream and upstream resiliency of distributed systems. We also need to consider <a href="https://medium.com/stackademic/database-separation-in-microservices-scaling-resilience-8b2deece0b15">database separation</a> in distributed systems and <a href="https://medium.com/stackademic/integrating-multiple-databases-seamlessly-in-golang-with-postgresql-7ff04883de81">integrating multiple databases seamlessly</a> in distributed systems, and much more if necessary to make it resilient.</p><p><a href="https://medium.com/@hasanshahjahan/understanding-the-ins-and-outs-of-distributed-systems-2530e0c97684">Understanding the ins and outs of distributed systems</a></p><h3>Maintainability</h3><p>Maintaining a robust distributed system poses significant challenges. It requires comprehensive testing such as load and stress testing, <a href="https://medium.com/@hasanshahjahan/understanding-chaos-engineering-3e853d757535">chaos engineering</a> and operational procedures, covering various testing methods specific to distributed systems. Additionally, it involves understanding continuous integration and delivery practices, along with implementing crucial monitoring mechanisms essential for distributed applications.</p><p><a href="https://medium.com/@hasanshahjahan/understanding-chaos-engineering-3e853d757535">Understanding Chaos Engineering</a></p><p>[Undertanding maintainability in distributed system — Coming Soon]</p><h3>Conclusion</h3><p>To sum up, I aim to offer sufficient insight into distributed systems, providing a solid understanding and a foundation for further exploration in the field. Additionally, I’ll periodically include complete coding examples with system architecture and a GitHub link, utilizing a modern programming language and its associated datastore.</p><p>Keep an eye out for updates!</p><blockquote>I’m constantly delighted to receive feedback. Whether you spot an error, have a suggestion for improvement, or just want to share your thoughts, please don’t hesitate to comment/reach out. I truly value connecting with readers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36cb53b7cf4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the ins and outs of distributed systems]]></title>
            <link>https://medium.com/@hasanshahjahan/understanding-the-ins-and-outs-of-distributed-systems-2530e0c97684?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2530e0c97684</guid>
            <category><![CDATA[resilient-infrastructure]]></category>
            <category><![CDATA[system-resiliency]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 09:14:15 GMT</pubDate>
            <atom:updated>2024-04-27T22:44:14.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsA-CROJ2sG36vH3Yu3NYQ.png" /></figure><p>Knowing about the ins and outs of distributed systems is key for both backend engineers and anyone working with large-scale systems. These systems might handle heavy loads, store a lot of data, or focus on being fast and reliable. One of the most interesting books I have found on this topic is <a href="https://understandingdistributed.systems/?ref=blog.pragmaticengineer.com">Understanding Distributed Systems</a>.</p><p>In this article, I will continue to discuss understanding the ins and outs of <a href="https://www.linkedin.com/pulse/building-resilient-distributed-systems-considerations-md-shahjahan-lfryc/">building a complex distributed systems resiliency</a> by explaining its downstream and upstream.</p><h3>Downstream Resiliency</h3><p>Downstream resiliency refers to the ability of a component or subsystem in a distributed system to gracefully handle failures or disruptions from components or subsystems it depends on, known as its downstream dependencies. In other words, downstream resiliency ensures that a component can continue to function correctly even if the components it relies on experience issues.In this section, I will discuss patterns that protect a service from failures of downstream dependencies.</p><ul><li>Timeout</li><li>Retry: exponential backoff, retry amplification</li><li>Circuit breaker</li></ul><h4>Timeout</h4><p>When a network call is made, it’s best practice to configure a timeout. If the call is made without a timeout, there is a chance it will never return. Network calls that don’t return lead to resource leaks. The role of timeouts is to detect connectivity faults and stop them from cascading from one component to another. In general, timeouts are a must-have for operations that can potentially never return, like acquiring a mutex.</p><p>Modern HTTP clients such as Java, .NET, Golang etc do a better job and usually, come with default timeouts. For example, .NET Core HttpClient has a default timeout of 100 seconds.</p><p><em>How do we determine a good timeout duration?</em></p><p>One way is to base it on the desired false timeout rate. For example, suppose we have a service customer calling another service order, and we are willing to accept that 0.1% of downstream requests that would have eventually returned a response time out (i.e., 0.1% false timeout rate). To accomplish that, we can configure the timeout based on the 99.9th percentile of the downstream service’s response time.</p><p>To have good monitoring in place to measure the entire lifecycle of a network call. The main point need to make sure here is that we have to measure what happens at the integration points of our systems, or we are going to have a hard time debugging production issues.</p><h4>Retry</h4><p>By now, it’s established that a client should set a timeout when initiating a network request. However, what should we do if the request fails or times out? At this point, the client faces two options: it can either opt for a fail-fast approach or attempt to retry the request. If a short-lived connectivity issue caused the failure or timeout, then retrying after some backoff time has a high probability of succeeding.</p><p>However, if the downstream service is overwhelmed, retrying immediately after will only worsen matters. This is why retrying needs to be slowed down with increasingly longer delays between the individual retries until either a maximum number of retries is reached or enough time has passed since the initial request.</p><p><strong>Exponential Backoff</strong></p><p>To set the delay between retries, we can use a capped exponential function, where the delay is derived by multiplying the initial backoff duration by a constant that increases exponentially after each attempt, up to some maximum value (the cap):</p><blockquote><em>delay = min(cap, initial-backoff.2attempt)</em></blockquote><p>For example, if the cap is set to 8 seconds, and the initial backoff duration is 2 seconds, then the first retry delay is 2 seconds, the second is 4 seconds, the third is 8 seconds, and any further delay will be capped to 8 seconds.</p><p>Although exponential backoff does reduce the pressure on the downstream dependency, it still has a problem. When the downstream service is temporarily degraded, multiple clients will likely see their requests failing around the same time. This will cause clients to retry simultaneously, hitting the downstream service with load spikes.</p><p>To avoid this herding behavior, we can introduce random jitter into the delay calculation. This spreads retries out over time, smoothing out the load to the downstream service:</p><blockquote><em>delay = random(0, min(cap, initial-backoff.2attempt))</em></blockquote><p>Alternatively, a process can park a failed request into a retry queue. The same process, or possibly another, can read from the same queue later and retry the failed requests.</p><p><em>When should we refrain from Retrying?</em></p><p>Just because a network call can be retried doesn’t mean it should be. If the error is not short-lived, for example, because the process is not authorized to access the remote endpoint, it makes no sense to retry the request since it will fail again. In this case, the process should fail fast and cancel the call right away.</p><p><strong>Retry amplification</strong></p><p>Imagine that handling a user request requires going through a chain of three services. The user’s client calls customer service, which call order service, which in turn calls product service.</p><p>If the intermediate request for order service to product service fails, should order service retry the request or not? Well, if order service does retry it, customer service will perceive a longer execution time for its request, making it more likely to hit customer service timeout. If that happens, customer service retries the request, making it more likely for the client to hit its timeout and retry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMb-KTLbjlHh-BylAzSpwQ.png" /><figcaption>Retry amplification in action</figcaption></figure><p>Having retries at multiple levels of the dependency chain can amplify the total number of retries — the deeper a service is in the chain, the higher the load it will be exposed to due to retry amplification.And if the pressure gets bad enough, this behavior can easily overload downstream services. That’s why, when we have long dependency chains, we should consider retrying at a single level of the chain and failing fast in all the others.</p><h4>Circuit Breaker</h4><p>Imagine the customer service encounters persistent failures from a downstream dependency, retrying requests will degrade performance for its clients and potentially impact the entire system. Thus, it needs a mechanism to handle non-transient failures effectively.</p><p>To deal with non-transient failures, we need a mechanism that detects long-term degradations of downstream dependencies and stops new requests from being sent downstream in the first place. After all, the fastest network call is the one we don’t have to make. The mechanism in question is the circuit breaker, inspired by the same functionality implemented in electrical circuits.</p><p>The circuit breaker aims to prevent a subsystem’s failure from affecting the system’s overall speed such as customer service to order service to product service. It achieves this by temporarily stopping requests to the failing subsystem. Once the subsystem recovers, the circuit breaker resumes allowing requests.</p><p>A circuit breaker can be implemented as a state machine with three states: open, closed, and half-open</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLicJ6C96H5xRH3-MEVd4g.png" /><figcaption>Circuit breaker state machine</figcaption></figure><p>When the circuit breaker is closed, it allows network calls to pass through. It monitors failures like errors and timeouts, and if they exceed a certain threshold within a set time, the circuit breaker opens.</p><p>In the open state, network calls are immediately unsuccessful. Since an open circuit breaker can impact business, it’s important to handle non-critical dependencies gracefully. Instead of halting entirely, services should degrade smoothly, ensuring essential functions continue even if non-critical features are unavailable.</p><p>After a period of time, the circuit breaker moves to the half-open state, giving the downstream dependency another opportunity. In this state, the next call is sent to the downstream service. If it succeeds, the circuit breaker returns to the closed state; if it fails, it reverts to the open state.</p><h3>Upstream Resiliency</h3><p>Upstream resiliency refers to a component’s capability to withstand failures or disruptions caused by components that depend on it. In other words, upstream resiliency ensures that a component remains robust and operational even if the components relying on it experience failures or issues.</p><ul><li>Load shedding</li><li>Load leveling</li><li>Rate limiting: single process and distributed implementations</li></ul><h4>Load Shedding</h4><p>A server can become overwhelmed with requests, leading to slow performance or even unavailability. To manage this, it can reject excess requests when it reaches its capacity. This process, known as load shedding, involves the server quickly refusing incoming requests and returning a “Service Unavailable” status code (503). The server might prioritize which requests to reject based on factors like their priority or how long they’ve been waiting. However, even rejecting requests incurs some overhead, like opening a connection or reading the request, which can still strain the server. As a result, while load shedding can provide some relief, if the load continues to increase, the server’s performance will ultimately degrade.</p><h4>Load Leveling</h4><p>Another option besides load shedding is called load leveling. Here, a messaging channel is set up between clients and the service. This channel helps manage the flow of requests, allowing the service to handle them at its own pace. Load leveling works well for smoothing out sudden spikes in demand, but if the service can’t catch up, it will accumulate a backlog of requests, which can cause problems of its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6F_AUYJgnV3YgvmaihWn6g.png" /><figcaption>The channel smooths out the load for the consuming service</figcaption></figure><p>Both load shedding and load leveling don’t directly tackle an increase in demand but rather protect the service from being overwhelmed. To handle more demand, the service must be scaled out. That’s why these protection methods are often used alongside auto-scaling, which detects when the service is under heavy load and automatically increases its capacity to manage the extra demand.</p><h4>Rate-Limiting</h4><p>Rate-limiting, or throttling, is a mechanism that rejects a request when a specific quota is exceeded. A service can have multiple quotas, e.g., for the number of requests or bytes received within a time interval. Quotas are typically applied to specific users, API keys, or IP addresses.</p><p>For example, if a service with a quota of 10 requests per second per API key receives on average 12 requests per second from a specific API key, it will, on average, reject 2 requests per second from that API key.</p><p><strong>Single-process rate limiting implementation</strong></p><p>We will start with a single-process implementation first and then extend it to a distributed one.</p><p>To limit requests to 2 per minute per API key, we can use a method that tracks request times. Initially, we might use a list to store timestamps for each request. Periodically, we clean out timestamps older than a minute. However, this method becomes memory-intensive with many requests. To save memory, we can divide time into fixed intervals, like 1-minute buckets, and count requests in each bucket instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmURbZJLrFSO_cj2c9kGHQ.png" /><figcaption>Buckets divide time into 1-minute intervals, which keep track of the number of requests seen.</figcaption></figure><p>A bucket contains a numerical counter. When a new request comes in, its timestamp is used to determine the bucket it belongs to. For example, if a request arrives at 12.00.18, the counter of the bucket for minute 12.00 is incremented by 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpZQ5aEdKRZHwTvb7blmSQ.png" /><figcaption><em>When a new request comes in, its timestamp is used to determine the bucket it belongs to.</em></figcaption></figure><p>Bucketing compresses request information without growing with the number of requests. Now, with this memory-efficient setup, how can we enforce rate limits? We can implement rate limiting using a sliding window that moves across buckets in real time, tracking the requests within it. The window’s length aligns with the quota time unit, like 1 minute. However, because the sliding window can overlap with multiple buckets, we must calculate a weighted sum of bucket counters to determine the requests within the window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuBNRlNe0i8ZmiWe0B-K0g.png" /><figcaption>A bucket’s weight proportinal to its overlap with the sliding window</figcaption></figure><p>Although this is an approximation, it’s a reasonably good one for our purposes. And it can be made more accurate by increasing the granularity of the buckets. To summarize, this approach requires two counters per API key, which is much more efficient in terms of memory than the naive implementation storing a list of requests per API key.</p><p><strong>Distributed rate limiting implementation</strong></p><p>When multiple processes handle requests, local state isn’t enough to enforce quotas across all instances. A shared data store is needed to track total requests per API key.Initially, storing two integers per key per bucket is considered. However, updating concurrently could cause issues.</p><p>To avoid this, transactions are used, but they’re slow and costly. Instead, atomic operations like get-and-increment or compare-and-swap are better options. Rather than updating the store per request, updates can be batched in memory and flushed asynchronously, reducing load and dependencies on the data store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RZU2YtHNUPfylmR5ZfmTw.png" /><figcaption>Servers batch bucket updates in memory for some time, and flush them asynchoronously to the data store at the end of it.</figcaption></figure><p><em>What happens if the data store is down?</em></p><p>Remember the CAP theorem’s essence: when there is a network fault, we can either sacrifice consistency and keep our system up or maintain consistency and stop serving requests. In our case, temporarily rejecting requests just because the data store used for rate-limiting is not reachable could damage the business. Instead, it’s safer to keep serving requests based on the last state read from the store.</p><h3>Conclusion</h3><p>In summary, failures will happen, but by designing systems resiliently, we can mitigate their impact. By incorporating downstream and upstream resiliency, we can maintain system stability, reliability, and availability despite challenges and failures.</p><blockquote>I’m constantly delighted to receive feedback. Whether you spot an error, have a suggestion for improvement, or just want to share your thoughts, please don’t hesitate to comment/reach out. I truly value connecting with readers!</blockquote><p>Reference</p><p><a href="https://understandingdistributed.systems/?ref=blog.pragmaticengineer.com">Understanding Distributed Systems</a></p><p><a href="https://www.gojek.io/blog/how-to-build-resilience-in-large-scale-distributed-systems">How to build resilience in large-scale distributed systems, Gojek Blog</a></p><p><a href="https://blog.pragmaticengineer.com/">The Pragmatic Engineer Blog</a></p><p><a href="https://medium.com/cwan-engineering/circuit-breaker-bring-resilience-to-modern-distributed-systems-ef6a7207ab55">Bring Resilience to Modern Distributed Systems</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2530e0c97684" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Chaos Engineering]]></title>
            <link>https://medium.com/@hasanshahjahan/understanding-chaos-engineering-3e853d757535?source=rss-b2241fef3d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e853d757535</guid>
            <category><![CDATA[chaos-engineering]]></category>
            <category><![CDATA[stress-management]]></category>
            <category><![CDATA[load-testing]]></category>
            <dc:creator><![CDATA[Miah Md Shahjahan]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 12:36:29 GMT</pubDate>
            <atom:updated>2024-04-27T22:44:45.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61iogk1fRteA2cI6veaVRQ.png" /></figure><p>Enterprise software systems have become more sophisticated, relying heavily on distributed components like cloud services and microservices. Chaos engineering plays a vital role today in <a href="https://www.linkedin.com/pulse/building-resilient-distributed-systems-considerations-md-shahjahan-lfryc/">creating resilient distributed systems</a>.</p><p>This article walks you through the concept of chaos engineering, its importance, and its core principles. Additionally, I’ll explain the tools widely used today for chaos engineering and delve into the benefits and challenges associated with chaos engineering practices.</p><h3>What is Chaos Engineering?</h3><p>Chaos engineering is the practice of intentionally injecting faults into a system to test its resilience. The goal is to identify potential failure points and correct them before they cause an actual outage or other disruption. By proactively testing how a system responds under stress, we can identify and fix failures before they end up in the news. Chaos engineering can significantly increase confidence in the resilience of distributed systems, particularly in unforeseen conditions.We literally “break things on purpose” to learn how to build more resilient systems.</p><h3>Why would we break things on purpose?</h3><p>Think of a vaccine or a flu shot for instance COVID 19, where we inject ourselves with a small amount of a potentially harmful foreign body in order to build resistance and prevent illness. Chaos Engineering is a tool we use to build such an immunity in our technical systems by injecting harm such as latency, CPU failure, or network black holes in order to find and mitigate potential weaknesses.</p><p>According to the chaos engineering report, the most common outcomes of Chaos Engineering are increased availability, lower mean time to resolution, lower mean time to detection fewer bugs shipped to product, and fewer outages. Teams who frequently run Chaos Engineering experiments are more likely to have &gt;99.9% availability.</p><h3>What’s the role of Chaos Engineering in distributed systems?</h3><p>Distributed systems are inherently more complex than monolithic systems, so it’s hard to predict all the ways they might fail. The eight fallacies of distributed systems that programmers new to distributed applications invariably make.</p><h3>Fallacies of Distributed Systems:</h3><ul><li>The network is reliable</li><li>Latency is zero</li><li>Bandwidth is infinite</li><li>The network is secure</li><li>Topology doesn’t change</li><li>There is one administrator</li><li>Transport cost is zero</li><li>The network is homogeneous</li></ul><p>Many of these fallacies drive the design of Chaos Engineering experiments such as “packet-loss attacks” and “latency attacks”. For example, network outages can cause a range of failures for applications that severely impact customers. Applications may stall while they wait endlessly for a packet. Applications may permanently consume memory or other system resources like Linux. And even after a network outage has passed, applications may fail to retry stalled operations, or may retry too aggressively. Applications may even require a manual restart. Each of these examples need to be tested and prepared for.</p><h3>Benefits of Chaos Engineering</h3><ul><li>Customer: The increased availability and durability of service means no outages disrupt their day-to-day lives.</li><li>Business: Chaos Engineering can help prevent extremely large losses in revenue and maintenance costs, create happier and more engaged engineers, improve in on-call training for engineering teams, and improve the incident management for the entire company.</li><li>Technical: The insights from chaos experiments can mean a reduction in incidents, reduction in on-call burden, increased understanding of system failure modes, improved system design, faster mean time to detection for incident management.</li></ul><h3>Organizations that benefit from Chaos Engineering</h3><p>Top tech organizations such as Amazon, Netflix, Microsoft, and National Australia Bank utilize chaos engineering to achieve a better understanding of internal systematic behavior and flaws. Chaos engineering can also help organizations to enhance the velocity of their continuous integration and continuous delivery (CI/CD) pipelines. Incorporating chaos engineering into CI/CD enables organizations to automate continuous experiments while controlling their potential impact.</p><h3>Types of Chaos Engineering Experiments</h3><p>DevOps teams have several options for running chaos engineering experiments to test various system processes.</p><ul><li>Latency injection: DevOps teams intentionally create scenarios that emulate a slow or failing network connection. This includes the introduction of network delays or slower response times.</li><li>Fault injection: This involves purposefully introducing errors into the system to determine how it affects other dependent systems and whether it interrupts services. Examples of fault injections include inducing disk failures, terminating processes, shutting down a host or introducing power or temperature increases. Fault injections can help organizations identify any single points of failure, which can cause the entire system to fail if something happens to them.</li><li>Load generation: This relates to intentionally stressing the system by sending significant traffic levels well beyond normal operations. This helps the site reliability engineers (SREs) to understand any bottlenecks in the system, which in turn allows them to build more scalable systems.</li><li>Canary testing: This involves releasing a new product or feature to a small group of users. That way, any glitches or bugs will only affect a percentage of visitors, leaving the rest of the audience to access the existing website experience.</li></ul><h3>Principles of Chaos Engineering</h3><p>Chaos engineering defines general principles to follow when designing and conducting experiments.</p><h3>Define the system’s steady-state</h3><p>How does the system behave when it is steady? These definitions set the baseline for the experiments. The definition of steady state includes measurable outcomes defined using key performance indicators. Some examples of such KPIs are:</p><ul><li>“The system latency is below 300ms.”</li><li>“The error rate is below 3%.”</li></ul><h3>Create the hypothesis</h3><p>A chaos experiment needs a hypothesis on how the system will behave if a chaotic situation arises in a production environment. It should be based on the established baselines and knowledge of the behavior and weaknesses of the system. When creating a hypothesis, ask ‘what if’ questions or create statements on how the system should behave.</p><p>Examples include:</p><ul><li>“If we increase the load by 1x, the system can handle it without issue.”</li><li>“An increase in request latency will not impact the user experience.”</li><li>“If the primary database is down, the system will automatically failover to the secondary database with minimum downtime.”</li></ul><h3>Experiment by changing real-world conditions</h3><p>Consider real-world scenarios or events that can deviate from the steady state. For example:</p><ul><li>Events resulting in hardware and software failures.</li><li>High network latency and error rates.</li><li>Network traffic spikes.</li></ul><p>It helps identify vulnerabilites and ensures that the system can handle different scenarios.</p><h3>Run automated experiments in production environments</h3><p>Prior systems like development, staging, and pre-production do not simulate the actual production systems. That’s why chaos engineering experiments run in actual production systems under controlled conditions.</p><h3>Minimizing the blast radius</h3><p>Since chaos engineering experiments are conducted within real production environments, it is crucial to minimize any potential performance degradation or disruptions that customers may experience during their execution. The blast radius should be determined using metrics such as:</p><ul><li>The number of affected users</li><li>Impacted locations</li><li>Workload quantities</li></ul><p>Therefore, it is advisable to schedule these experiments during non-peak times and ensure the availability of backup systems for restorations.</p><h3>Chaos Engineering Tools</h3><p>Chaos engineering tools are a relatively new approach to traditional testing methods used to establish confidence in systems. Software platforms will inevitably fail, and therefore it’s critical to pinpoint weaknesses and fix them before they negatively impact business operations.Through the deployment of assumptions and successful chaos experiments, chaos engineering tools can provide a roadmap for uncovering infrastructural failures or unresponsive systems.</p><h3>Chaos Mesh</h3><p>Pros</p><ul><li>Easy-to-use functionality and automation</li><li>The user interface supports many different configurations</li><li>Experiments can be paused and resumed at will</li></ul><p>Cons</p><ul><li>Experiments run indefinitely as there is no ability to schedule attacks</li><li>Node-level attacks cannot be run</li><li>Cannot control user access within the dashboard; as a result, there are increased security risks</li></ul><p><a href="https://github.com/chaos-mesh/chaos-mesh">Chaos Mesh</a> is an open-source cloud-native tool. Using various fault simulations, Chaos Mesh helps organizations determine system abnormalities that may occur during various portions of the development, testing process, and production stages.</p><p>As an open-source chaos tool that’s created with a web user interface known as the Chaos Dashboard, Chaos Mesh can be added to DevOps workflows to spot potential areas of weakness and timeouts. To ensure resiliency, Chaos Mesh utilizes chaos experiments within Kubernetes environments. It’s able to use various types of scenarios related to fault simulations within a distributed system.</p><p>Chaos Mesh is able to deploy attacks that test network latency, system time manipulation, resource utilization, and more. The Chaos Dashboard can be used to modify and manage various forms of experiments within set timeframes.</p><p>Key Features</p><ul><li>Chaos Mesh uses a Kubernetes-based interface that’s supported with full automation and graphical capabilities used in the testing of high visibility distribution systems such as Apache APISIX and RabbitMQ</li><li>Chaos Mesh technology is able to test various scenarios using event-driven fault simulations</li><li>Chaos Mesh provides the ability to design experiments on the platform using different variables and status checks</li></ul><p>Cost</p><p>As an open-source chaos tool, Chaos Mesh is free to use without a commercial license.</p><h3>Should I use Chaos Mesh?</h3><p>Chaos Mesh offers an open-source technology that can be used in Kubernetes to design and manage automated experiments. However, be wary of certain limitations to the technology. Predicting failures can be a cumbersome task due to the complexities in cloud operations. Unreliable functions and outages can result in a downgraded reputation and a loss of consumer trust.</p><h3>Chaos Monkey</h3><p>Pros</p><ul><li>Configurable technology allows for easy monitoring and scheduling of attacks</li><li>Open-source software has no licensing costs</li><li>Extensive development history</li></ul><p>Cons</p><ul><li>Can only perform one type of experiment</li><li>Attacks are randomized and users have limited control of the blast radius</li><li>Requires writing custom code</li></ul><p><a href="https://github.com/Netflix/chaosmonkey">Netflix’s Chaos Monkey</a> is an open-source chaos engineering tool originally created by Netflix developers. It was developed to help test their system reliability and resiliency after moving to the AWS cloud. The software functions by implementing continuous unpredictable attacks. Chaos Monkey uses the basic fundamental approach of terminating one or more virtual machine instances</p><p>The configurability of Chaos Monkey allows for easy scheduling and close monitoring. The technology is easily replicable but can cause headaches if users are unprepared for the aftermath of attacks. Users can check for outages prior to deployment but must be able to write and edit custom Go code.</p><p>Key Features</p><p>Chaos Monkey was one of the first chaos engineering tools and the first open-source technology to help initiate the movement. After its inception, Netflix later developed additional fault injection tools collectively known as the Simian Army.</p><p>Key features of Chaos Monkey include:</p><ul><li>Detects systems bottlenecks to help limit disruption to production environments</li><li>The ability to test resiliency and availability of applications at an infra level</li><li>Tests can be scheduled during certain timeframes</li><li>Allows for easy monitoring</li></ul><p>Cost</p><p>As open-source software, Chaos Monkey is free to use without a commercial license.</p><h3>Should I use Chaos Monkey?</h3><p>Chaos Monkey is a popular chaos engineering tool. While it may have revolutionized the open-source community, its contemporary application is far less practical today. Chaos Monkey is useful to an extent, but users must take into account its limitations and arduous deployment capabilities.</p><h3>Gremlin</h3><p>Pros</p><ul><li>Easy-to-use UI allows for various attacks and tests to onboard teams</li><li>Support with API for creating manual integrations</li><li>Evaluates reliability based on a variety of different factors</li></ul><p>Cons</p><ul><li>Software is not customizable</li><li>Challenging to integrate experiment JSON files into the software delivery pipeline</li><li>Minimal reporting capabilities</li></ul><p><a href="https://github.com/gremlin">Gremlin</a> is the first hosted chaos engineering platform designed to improve web-based reliability. Offered as software-as-a-service (SaaS), Gremlin is able to test system resiliency using multiple attack types. Users provide system inputs as a means of determining which type of attack will provide the most optimal results. Tests can be performed in conjunction with one another as a means of facilitating comprehensive infrastructural assessments.</p><h3>Key Features</h3><p>Features of Gremlin include:</p><ul><li>Controlling failures in a precise and controlled manner</li><li>Custom scenarios that include multi-levels of system attacks</li><li>Testing process for memory leaks, latency injections, disk fill-ups, and more</li><li>GameDay feature</li><li>Reliability score based on predefined tests</li></ul><h3>Cost</h3><p>Gremlin’s pricing has fluctuated over the years ranging from per-agent pricing to attacks per target to support the frequency of testing required by a team.</p><h3>Should I use Gremlin?</h3><p>As the world’s first managed enterprise chaos engineering technology, Gremlin provides users with the ability to launch dozens of attack vectors, stop and roll back attacks, and improve system reliability. Designed with the mission of creating a sustainable and reliable internet, Gremlin pinpoints software weaknesses to minimize revenue loss and negative systematic impacts.</p><h3>Conclusion</h3><p>In conclusion, chaos engineering continues to play a pivotal role in ensuring the resilience and reliability of modern software systems specially distributed systems, offering organizations valuable insights and tools to proactively address potential failures and disruptions.</p><blockquote>I’m constantly delighted to receive feedback. Whether you spot an error, have a suggestion for improvement, or just want to share your thoughts, please don’t hesitate to comment/reach out. I truly value connecting with readers!</blockquote><p>Reference</p><p><a href="https://github.com/mdshahjahanmiah/chaos-engineering">Chaos Engineering</a></p><p><a href="https://groups.google.com/g/chaos-community">Chaos Engineering Community</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e853d757535" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>