<?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 Debaprasan Mallick on Medium]]></title>
        <description><![CDATA[Stories by Debaprasan Mallick on Medium]]></description>
        <link>https://medium.com/@debaprasan.mallick?source=rss-a940f3cfc309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eatAk_f2CX1zZDvhNFoGUg.jpeg</url>
            <title>Stories by Debaprasan Mallick on Medium</title>
            <link>https://medium.com/@debaprasan.mallick?source=rss-a940f3cfc309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:20:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debaprasan.mallick/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[The Future of Instant Retail]]></title>
            <link>https://medium.com/@debaprasan.mallick/the-future-of-instant-retail-e2930acbfa72?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2930acbfa72</guid>
            <category><![CDATA[quick-commerce]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 14:33:09 GMT</pubDate>
            <atom:updated>2026-11-23T14:33:09.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UtlNsRWCHtLZ9r4WjNzQg.png" /></figure><h4>Forecasting, automation, drones, and the hard problem of leaving the metros.</h4><h3>AI-driven demand forecasting</h3><p>Every dark store must answer, for thousands of SKUs, how many will we sell tomorrow, and how many should we order today? Order too little and customers see “out of stock” (lost sales, lost trust). Order too much and perishables expire (waste) and cash is tied up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbhyKov3J8YfMA7CoRdrzg.png" /><figcaption>History becomes features, features feed a model, forecasts drive replenishment, and actuals flow back.</figcaption></figure><h4>A tiny forecasting model you can run</h4><p>The simplest useful forecaster is exponential smoothing: the forecast is a weighted average in which recent days count more than old ones. From the forecast and the error spread you can derive a safety stock, a buffer against uncertainty, and a reorder point.</p><p><strong>Forecast, safety stock and reorder point (runs as is)</strong></p><pre>import statistics<br>from math import sqrt<br><br>history = [42, 38, 45, 50, 47, 52, 60, 58, 55, 61, 64, 59, 66, 70]<br>alpha = 0.4                                   # weight on the newest day<br><br>level, errors = history[0], []<br>for x in history[1:]:<br>    errors.append(x - level)                  # one-step-ahead error<br>    level = alpha * x + (1 - alpha) * level<br><br>sigma = statistics.pstdev(errors)             # typical forecast error<br>lead_days, z = 1, 1.65                        # z=1.65: ~95% service<br>safety = z * sigma * sqrt(lead_days)<br>reorder_point = level * lead_days + safety<br>wape = sum(abs(e) for e in errors) / sum(history[1:])<br><br>print(&#39;forecast for tomorrow:&#39;, round(level, 1), &#39;units&#39;)<br>print(&#39;safety stock         :&#39;, round(safety, 1))<br>print(&#39;reorder point        :&#39;, round(reorder_point, 1))<br>print(&#39;WAPE (error rate)    :&#39;, round(100 * wape, 1), &#39;%&#39;)</pre><p>Notice the trending data makes this simple model lag behind (it under-forecasts a rising series); real systems add trend and weekday effects. The point is the chain: forecast, uncertainty, buffer, order</p><h4>What makes real forecasting hard</h4><ul><li>Censored demand. Sales are not demand. If a shelf was empty at 6 p.m., you did not sell what customers wanted; sales history understates demand. Good systems flag stock-out hours and correct for them.</li><li>Intermittent demand. Many SKUs sell a unit now and then; specialised methods (for example Croston-style models) handle zeros better than plain averages.</li><li>Cold start. A new product has no history; borrow from similar products or categories.</li><li>Hierarchy. Forecast at store, city and category levels, and keep them consistent.</li><li>Events and weather. Festivals, cricket finals, rain and holidays change what and when people buy. These become model features.</li><li>Many models, one measure. Moving averages, gradient-boosted trees and neural networks all compete on a metric such as WAPE (weighted absolute percentage error). Keep the simplest model that wins on held-out data.</li></ul><blockquote><strong><em>Key idea — Forecast errors are asymmetric<br></em></strong>Running out of milk costs a sale and possibly a customer; having one extra packet costs a little waste. The cost of error differs by product (perishable vs shelf-stable, high margin vs low), so the target service level should too. Better forecasts shrink safety stock, which cuts waste and stock-outs together.</blockquote><h3>Automated dark stores</h3><p>Moving goods to the picker, instead of the picker walking to the goods, is the logic behind goods-to-person automation: shuttles, robotic shelving and conveyors that bring bins to a station. They exist today in large e-grocery warehouses elsewhere in the world and deliver high picking speed and accuracy.</p><p>For a small dark store the economics are harder. Automation needs high capital cost, tightly standardised layouts and enough volume to keep machines busy; a store with a few thousand SKUs and uneven demand may not clear that bar. Where labour is relatively affordable, as in India, partial steps (better handhelds, smart slotting, put-walls) tend to be reached first. Treat claims of “fully automated dark stores everywhere” with healthy scepticism, and always ask: what volume, what cost per order, what failure plan?</p><h3>Drones and robots</h3><p>Drone and sidewalk-robot deliveries have been trialled in several countries. Practical limits stay stubborn: airspace and aviation regulation, payload of a few kilograms at most, weather, battery range, safe landing or drop spots in dense apartment blocks, noise and public acceptance. Sidewalk robots need smooth, uncluttered pavements. Both can make sense in specific settings (campuses, controlled zones, remote areas), but they are unlikely to replace two-wheelers for ordinary city orders soon. Engineers should treat them as experiments with clear success metrics, not as a roadmap promise.</p><h3>Scaling beyond the metros</h3><p>The first wave of quick commerce concentrated on dense, high-income neighbourhoods in large cities, where one store can serve many orders per day. Smaller towns change the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VR_8joUCiEdTb6aUrN26MA.png" /><figcaption>The same store cost spread over fewer orders makes each order more expensive. (Illustrative model.)</figcaption></figure><p>The main challenges, and the engineering responses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hULTtRmcUn0TjuCoFxDpMQ.png" /></figure><p>A theme runs through these: in smaller towns, a slower promise delivered reliably can beat a fast promise delivered rarely. Some operators offer scheduled or 30-minute windows rather than ten minutes. The software has to support several promise levels (instant, fast, scheduled) from the same stock and fleet.</p><h3>What to carry forward</h3><p>You started this book with a packet of milk. By now you can explain why it loses money alone and earns when bundled, how its stock is kept honest under a thousand simultaneous buyers, how a map of hexagons finds its store in microseconds, how an assignment algorithm picks its rider, and how an observability stack tells you at 8 p.m. on a Sunday why checkout slowed down.</p><p>The industry will keep changing: new players, new regulation, different economics. The fundamentals will not: make the physical promise explicit, turn it into latency and correctness budgets, protect the critical path, and measure everything.</p><h4>A 90-day plan</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PorX1TFBAIYJXyv5bKjhg.png" /></figure><h3>Chapter recap</h3><ul><li>Forecast, uncertainty, safety stock and reorder point form the replenishment chain.</li><li>Sales are not demand: correct for stock-outs.</li><li>Automation and drones are constrained by economics and regulation; evaluate with numbers.</li><li>Smaller towns need different formats, address handling and promise levels.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://otexts.com/fpp3/ses.html">https://otexts.com/fpp3/ses.html</a></li><li>[2] <a href="https://thedailybrief.zerodha.com/p/a-10-minute-parcel-comes-for-dalal">https://thedailybrief.zerodha.com/p/a-10-minute-parcel-comes-for-dalal</a></li><li>[3] <a href="https://static.hdfcsky.com/wp-content/uploads/2026/04/Eternal-Q4FY26-29th-Apr26.pdf">https://static.hdfcsky.com/wp-content/uploads/2026/04/Eternal-Q4FY26-29th-Apr26.pdf</a></li></ul><p><em>The statements on automation, drones and smaller-town challenges, and the tier-2 cost curve (₹40 variable cost, ₹60,000 store cost per day), are reasoning and an illustrative model, not sourced facts; the payment-mix point is explicitly an assumption to test. The forecasting program was executed and prints its results.</em></p><h4>Further reading</h4><ul><li>Hyndman and Athanasopoulos, Forecasting: Principles and Practice [ ] <a href="https://otexts.com/fpp3/">https://otexts.com/fpp3/</a></li><li>Edward Silver, David Pyke and Douglas Thomas, Inventory and Production Management in Supply Chains</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2930acbfa72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Capstone Proof-of-Work Project]]></title>
            <link>https://medium.com/@debaprasan.mallick/building-your-capstone-proof-of-work-project-0ada8cb8f9bc?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ada8cb8f9bc</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 14:31:50 GMT</pubDate>
            <atom:updated>2026-11-23T14:31:50.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiDwJ74kuwUXtvAUsnTYSQ.png" /></figure><h4>A mini quick-commerce backend with an inventory lock, a Kafka pipeline and a live tracking page, and how to present it.</h4><h3>What you are building</h3><p>A recruiter reading hundreds of applications cannot tell who understands concurrency. A working project with a test that proves no overselling under load tells them instantly. The scope below fits on a laptop and in a few weekends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDQ8TVqG8tJYmqzcpRMQ3A.png" /><figcaption>Five small services, one machine. Each box maps to a chapter.</figcaption></figure><h4>Milestones and “done when” tests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_E6upHB52Qi4bGU2cOX-Rw.png" /></figure><h3>M1: skeleton and environment</h3><p><strong>Project layout:</strong></p><pre>quickmart/<br>  docker-compose.yml<br>  app/<br>    main.py            # FastAPI: /health, /orders, /ws<br>    inventory.py       # interface + Redis and in-memory versions<br>    worker.py          # Kafka consumer (idempotent)<br>    dispatch.py        # matching<br>  tests/<br>    test_inventory.py  # the concurrency proof<br>  README.md</pre><p><strong>docker-compose.yml (versions are examples: pin your own)</strong></p><pre>services:<br>  redis:<br>    image: redis:7<br>    ports: [&quot;6379:6379&quot;]<br>  postgres:<br>    image: postgres:16<br>    environment:<br>      POSTGRES_PASSWORD: dev<br>    ports: [&quot;5432:5432&quot;]<br>  kafka:<br>    image: apache/kafka:3.9.0      # single-node KRaft by default<br>    ports: [&quot;9092:9092&quot;]</pre><p><strong>app/main.py: the API skeleton (FastAPI; documented API)</strong></p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>app = FastAPI()<br><br>class OrderIn(BaseModel):<br>    order_id: str                 # client-made: idempotency key<br>    store_id: int<br>    items: dict[str, int]         # sku -&gt; quantity<br><br>@app.get(&#39;/health&#39;)<br>def health():<br>    return {&#39;ok&#39;: True}<br><br>@app.post(&#39;/orders&#39;, status_code=202)<br>def create_order(order: OrderIn):<br>    # 1) reserve stock  2) write order + outbox  3) return 202<br>    return {&#39;order_id&#39;: order.order_id, &#39;status&#39;: &#39;PROCESSING&#39;}</pre><h3>M2: the inventory lock, and the test that proves it</h3><p>Design the inventory as an interface first, with two implementations: an in-memory one for fast unit tests and a Redis one that uses the scripts from Chapter 6. Tests written against the interface run in milliseconds and then run again against Redis in integration tests.</p><p><strong>tests/test_inventory.py (runs as is; in-memory version)</strong></p><pre>import threading<br><br>class InMemoryInventory:<br>    &quot;&quot;&quot;Same interface the Redis version will have.&quot;&quot;&quot;<br>    def __init__(self, stock):<br>        self.stock, self._lock = dict(stock), threading.Lock()<br><br>    def reserve(self, sku, qty):<br>        with self._lock:                     # check and update are atomic<br>            if self.stock.get(sku, 0) &gt;= qty:<br>                self.stock[sku] -= qty<br>                return True<br>            return False<br><br>def test_no_overselling():<br>    inv = InMemoryInventory({&#39;cereal&#39;: 50})<br>    results = []<br>    def buyer():<br>        results.append(inv.reserve(&#39;cereal&#39;, 1))<br>    threads = [threading.Thread(target=buyer) for _ in range(200)]<br>    for t in threads: t.start()<br>    for t in threads: t.join()<br>    assert sum(results) == 50, sum(results)<br>    assert inv.stock[&#39;cereal&#39;] == 0<br><br>test_no_overselling()<br>print(&#39;ok: exactly 50 of 200 buyers succeeded&#39;)</pre><p>Then swap in <em>RedisInventory</em>, whose reserve calls the Lua script, and run the same test with 200 concurrent clients (use asyncio with a Redis async client, or multiple processes). The passing test is your evidence.</p><blockquote><strong><em>Watch out — Prove the bug first<br></em></strong>Before adding the lock, run the test against a naive “read then write” version and watch it fail. A project that shows both the failing and passing run demonstrates understanding far better than one that only works.</blockquote><h3>M3: the order pipeline</h3><ul><li>POST /orders calls reserve for each item (release any taken if one fails).</li><li>In one Postgres transaction, insert the order and an outbox row.</li><li>A relay publishes outbox rows to the order.events topic, keyed by store_id.</li><li>The worker consumes events with a processed-events table so a redelivered event does nothing the second time (Chapter 5).</li></ul><p>Test it by killing the worker with docker kill mid-run, restarting it, and asserting the database holds exactly one row per order.</p><h3>M4: dispatch simulation</h3><p>Generate random riders and orders on a small grid, compute ETAs with the haversine function from Chapter 7, and run linear_sum_assignment every two simulated seconds (Chapter 8). Compare total waiting time against the greedy baseline over a few hundred orders and plot both. A simple chart that shows optimal beating greedy is a strong portfolio image.</p><h3>M5: tracking page and load test</h3><p>A <strong>WebSocket</strong> endpoint streams rider positions, and a plain HTML page draws them:</p><p><strong>WebSocket endpoint (FastAPI; documented API)</strong></p><pre>from fastapi import WebSocket, WebSocketDisconnect<br><br>@app.websocket(&#39;/ws/orders/{order_id}&#39;)<br>async def track(ws: WebSocket, order_id: str):<br>    await ws.accept()<br>    try:<br>        async for update in updates_for(order_id):   # you implement this<br>        await ws.send_json(update)                   # {lat, lng, eta_s}<br>    except WebSocketDisconnect:<br>        pass</pre><p>For the load test, write an asyncio script (or use a load-testing tool) that sends orders at a steady rate and records latencies; report p50, p95, p99, throughput, and error count. Run it on your laptop and say so.</p><h3><strong>Portfolio and resume: be specific, be honest</strong></h3><p>Recruiters trust measured, specific and reproducible claims. Never invent numbers; every figure on your resume must be one you can regenerate on demand in an interview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJ94HdJBBvgRMphm9GZOHg.png" /></figure><h4>What to put in the repository</h4><ul><li>A README that opens with a one-paragraph problem statement, an architecture diagram, how to run in one command, and results.</li><li>A short design-decisions section with trade-offs (why outbox, why Lua script, what you chose not to build).</li><li>The tests, including the failing-then-passing concurrency demonstration.</li><li>A two-minute demo recording or GIF of the tracking page.</li><li>A “known limitations” section. Honesty here builds more trust than a polished, suspiciously perfect project.</li></ul><blockquote><strong><em>Try it — Stretch goals<br></em></strong>Add H3 cell lookup for store selection (Chapter 7); expose Prometheus metrics and a Grafana dashboard (Chapter 12); deploy to a local Kubernetes cluster with an autoscaler (Chapter 11); add substitution logic (Chapter 9).</blockquote><h3>Chapter recap</h3><ul><li>Pick a scope that fits on a laptop but exercises concurrency, events and real-time.</li><li>Interface first: unit-test with an in-memory version, then run the same test on Redis.</li><li>Show the failing run before the fix.</li><li>Report your own measured numbers, with the hardware, and list the limitations.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a> <a href="https://fastapi.tiangolo.com/advanced/websockets/">https://fastapi.tiangolo.com/advanced/websockets/</a></li><li>[2] <a href="https://docs.docker.com/compose/">https://docs.docker.com/compose/</a></li><li>[3] <a href="https://kafka.apache.org/quickstart">https://kafka.apache.org/quickstart</a></li></ul><p><em>Image versions in docker-compose.yml are examples. The in-memory inventory test was executed and prints its result; the Docker, FastAPI, Redis, Kafka and Postgres parts were not run for this book. The resume-bullet templates deliberately use placeholders such as [N] and [X]: fill them only with numbers you measured.</em></p><h4>Further reading</h4><ul><li>Locust load-testing tool [ ] <a href="https://locust.io/">https://locust.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ada8cb8f9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Quick Commerce Interview Loop]]></title>
            <link>https://medium.com/@debaprasan.mallick/cracking-the-quick-commerce-interview-loop-72d3ba32949f?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d3ba32949f</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 14:29:24 GMT</pubDate>
            <atom:updated>2026-11-23T14:29:24.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9wXGqWVZoULL6bIqZ7F6g.png" /></figure><h4>Data-structure patterns that map to real problems, and a repeatable way to answer “Design Blinkit / Zepto from scratch.”</h4><h3>DSA for scale</h3><p>Interviewers at product companies rarely ask trick puzzles for their own sake. The better questions are small versions of real problems. If you recognise the pattern, you can solve it and explain why it matters at scale. Here is the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeK0pXlBk1jbac4u9XdOtw.png" /></figure><h4>Reading complexity at scale</h4><p>Complexity is about how cost grows with input size, but scale makes it concrete. As a rough rule of thumb for interviews, a solution doing around 10⁷ to 10⁸ simple operations runs in a second or so. At n = 100,000, O(n log n) is about 1.7 million steps (fine) while O(n²) is 10 billion (far too slow). Always state the complexity of your solution aloud and say what n is.</p><p>Space matters as well: a hash map that holds every user’s recent requests for rate limiting costs memory proportional to active users, which is why real systems keep such state in Redis with expiry.</p><h4>Pattern 1: K nearest riders with a heap</h4><p><strong>K nearest riders (runs as is)</strong></p><pre>import heapq<br>from math import cos, radians<br><br>def approx_km(a, b):<br>    &quot;&quot;&quot;Good enough inside one city; avoids heavy trigonometry.&quot;&quot;&quot;<br>    dx = (b[1] - a[1]) * cos(radians((a[0] + b[0]) / 2)) * 111.32<br>    dy = (b[0] - a[0]) * 110.57<br>    return (dx * dx + dy * dy) ** 0.5<br><br>def k_nearest(riders, store, k=2):<br>    return heapq.nsmallest(<br>        k, riders.items(), key=lambda kv: approx_km(kv[1], store))<br><br>riders = {&#39;R1&#39;: (19.0760, 72.8777), &#39;R2&#39;: (19.0800, 72.8800),<br>          &#39;R3&#39;: (19.1200, 72.9000), &#39;R4&#39;: (19.0770, 72.8790)}<br>store = (19.0765, 72.8780)<br>for rid, pos in k_nearest(riders, store, k=2):<br>    print(rid, round(approx_km(pos, store), 2), &#39;km&#39;)</pre><p>Mention in the interview that for thousands of riders you would not scan them all: use the cell index from Chapter 7 to pick candidates first, then run the heap on just those.</p><h4>Pattern 2: sliding-window rate limiter</h4><p><strong>Sliding-window log limiter (runs as is)</strong></p><pre>from collections import deque<br><br>class SlidingWindowLimiter:<br>    def __init__(self, limit, window_s):<br>        self.limit, self.window = limit, window_s<br>        self.events = deque()<br><br>    def allow(self, now):<br>        while self.events and self.events[0] &lt;= now - self.window:<br>            self.events.popleft()      # forget events outside window<br>        if len(self.events) &lt; self.limit:<br>            self.events.append(now)<br>            return True<br>        return False<br><br>lim = SlidingWindowLimiter(limit=3, window_s=10)<br>print([lim.allow(t) for t in (0, 1, 2, 3, 9, 10.5, 11)])<br># [True, True, True, False, False, True, True]</pre><p>Compare it with the token bucket from Chapter 4: the sliding log is exact but stores every event; the token bucket stores two numbers. A good answer names that trade-off.</p><h4>Pattern 3: shortest path</h4><p><strong>Dijkstra on a tiny road graph (runs as is)</strong></p><pre>import heapq<br><br>def dijkstra(graph, source):<br>    dist = {source: 0}<br>    heap = [(0, source)]<br>    while heap:<br>        d, u = heapq.heappop(heap)<br>        if d &gt; dist.get(u, float(&#39;inf&#39;)):<br>            continue                       # stale entry<br>        for v, w in graph[u]:<br>            nd = d + w<br>            if nd &lt; dist.get(v, float(&#39;inf&#39;)):<br>                dist[v] = nd<br>                heapq.heappush(heap, (nd, v))<br>    return dist<br><br>roads = {                                  # minutes between junctions<br>    &#39;store&#39;: [(&#39;A&#39;, 2), (&#39;B&#39;, 5)],<br>    &#39;A&#39;: [(&#39;B&#39;, 1), (&#39;home&#39;, 6)],<br>    &#39;B&#39;: [(&#39;home&#39;, 2)],<br>    &#39;home&#39;: [],<br>}<br>print(dijkstra(roads, &#39;store&#39;))   # home is 5 minutes away via A then B</pre><p>In reality, routing engines use faster techniques (contraction hierarchies and similar) on road networks with millions of nodes, but Dijkstra is the idea underneath, and it is the right answer for an interview.</p><h4>Pattern 4: an LRU cache</h4><p><strong>LRU cache with OrderedDict (runs as is)</strong></p><pre>from collections import OrderedDict<br><br>class LRU:<br>    def __init__(self, capacity):<br>        self.cap, self.data = capacity, OrderedDict()<br><br>    def get(self, key):<br>        if key not in self.data:<br>            return None<br>        self.data.move_to_end(key)            # mark as most recently used<br>        return self.data[key]<br><br>    def put(self, key, value):<br>        self.data[key] = value<br>        self.data.move_to_end(key)<br>        if len(self.data) &gt; self.cap:<br>            self.data.popitem(last=False)     # evict least recently used<br><br>c = LRU(2)<br>c.put(&#39;milk&#39;, 1); c.put(&#39;eggs&#39;, 2); c.get(&#39;milk&#39;); c.put(&#39;rice&#39;, 3)<br>print(list(c.data))      # [&#39;milk&#39;, &#39;rice&#39;]: eggs was least recently used</pre><h3>System design: “Design Blinkit / Zepto from scratch”</h3><p>his is the signature question. Interviewers are not looking for a memorised architecture; they want to watch you structure ambiguity. Use the same six steps every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JbFiCU1tz9SmNANzOv9jw.png" /><figcaption>Say your assumptions out loud; each step builds on the last.</figcaption></figure><h4>Step 1: Clarify scope</h4><p>Ask what is in and out. A sensible scope: browse and search products, add to cart, reserve stock and pay, assign a store and rider, track the order live. Out of scope (say so): supplier procurement, rider payouts, advanced ads. Then state non-functional requirements: very low checkout latency, never oversell, high availability during peaks, eventual consistency is fine for browsing but not for stock at checkout.</p><h4>Step 2: Estimate scale</h4><p>Do a short back-of-envelope calculation and keep every number labelled as an assumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHDF-qDA2LxAB4HUhtdDbQ.png" /><figcaption>Five lines of arithmetic turn “millions of orders” into design targets.</figcaption></figure><h4>Step 3: APIs and data model</h4><pre>GET  /v1/stores/serviceable?lat=..&amp;lng=..     -&gt; store id, ETA, or none<br>GET  /v1/products?store=..&amp;q=..&amp;cursor=..     -&gt; search results<br>POST /v1/cart/items                           -&gt; add / change quantity<br>POST /v1/orders        (Idempotency-Key header) -&gt; 202 + order id<br>GET  /v1/orders/{id}                          -&gt; state, items, rider<br>WS   /v1/orders/{id}/track                    -&gt; live updates<br>Core tables: stores, skus, inventory(store_id, sku_id, quantity), stock_movement (the ledger), orders, order_items, payments, riders,</pre><p>stock_movement (the ledger), orders, order_items, payments, riders, assignments, outbox. Mention an idempotency key on order creation, so a retried tap never creates two orders.</p><h4>Step 4: High-level design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgJE1vqLD2zvhErNx-7_VA.png" /><figcaption>A reference architecture assembled from the patterns in this book. It is not any company’s real system.</figcaption></figure><p>Walk the diagram in the order of a request: apps, edge, services, event bus, data stores. Say one sentence about why each store sits where it does: Redis for carts and stock counters, Postgres with PostGIS for orders and stores, OpenSearch for search, Kafka between services, a lake for analytics.</p><h4>Step 5: Deep dives</h4><p><strong>Expect the interviewer to pick one or two. Prepare these:</strong></p><ul><li><strong>Inventory consistency.</strong> Atomic reserve with expiry (Chapter 6), confirm or release after payment, ledger plus reconcile job, hot-key splitting.</li><li><strong>Store selection.</strong> Cell index to candidate stores, filter, rank by ETA and load, dynamic catchments (Chapter 7).</li><li><strong>Dispatch.</strong> Rolling-window assignment, pre-assignment during pick, batching limits (Chapter 8).</li><li><strong>Search.</strong> Per-store availability must filter results, or customers see items the store lacks. Index store-level stock into the search documents, updated from stock events, with a short staleness allowance.</li><li><strong>Live tracking.</strong> Rider location ingest, latest location in Redis, WebSocket gateway, resume after reconnect.</li><li><strong>Notifications.</strong> Fully asynchronous; retries with backoff; per-channel rate limits.</li></ul><h4>Step 6: Failures and trade-offs</h4><p><strong>Close by naming what breaks and what you would do:</strong></p><ul><li>a Redis failover (reconcile from the ledger),</li><li>Kafka consumer lag (autoscale on lag, degrade non-critical consumers),</li><li>a payment provider outage (second provider, timeouts, circuit breaker),</li><li>a store going offline (remove its cells from the index),</li><li>a regional outage (multi-zone deployment, accept lower capacity).</li></ul><p><em>End with one thing you would improve with more time.</em></p><blockquote><strong><em>Key idea — What interviewers score<br></em></strong>Structure, correct fundamentals, explicit assumptions, awareness of trade-offs, and how you react to pushback. A confident wrong detail costs more than an honest “I would check how that behaves in production.</blockquote><h3>Chapter recap</h3><ul><li>Most coding questions are small versions of real problems: heaps, sliding windows, shortest paths, caches.</li><li>State complexity and what n is, every time.</li><li>Use six steps for system design: clarify, estimate, APIs and data, architecture, deep dives, failures.</li><li>Keep assumptions explicit and trade-offs visible.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://docs.python.org/3/library/heapq.html">https://docs.python.org/3/library/heapq.html</a> <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict">https://docs.python.org/3/library/collections.html#collections.OrderedDict</a></li></ul><p><em>The system-design walk-through, the capacity estimate (3 million orders a day, 5× peak, 12.5 sessions per order, 8 calls per session) and the 45-minute time split are the author’s teaching framework with every number labelled as an assumption. The “10⁷ to 10⁸ simple operations per second” figure is a common interview rule of thumb, not a benchmark.</em></p><h4>Further reading</h4><ul><li>Alex Xu, System Design Interview: An Insider’s Guide (2020)</li><li>Martin Kleppmann, Designing Data-Intensive Applications</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d3ba32949f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability, Logging and Zero-Downtime Deploys]]></title>
            <link>https://medium.com/@debaprasan.mallick/observability-logging-and-zero-downtime-deploys-d6f18d5c9cb2?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f18d5c9cb2</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 08:42:28 GMT</pubDate>
            <atom:updated>2026-11-19T08:42:28.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hK6bkI1EzXZQdnqB83v2tQ.png" /></figure><h4>Finding the bottleneck across twenty services, and shipping changes while ten-minute orders are in flight.</h4><h3>Monitoring vs observability</h3><p>Monitoring watches for problems you predicted (“alert if CPU &gt; 90%”). Observability lets you ask new questions about a system you did not predict (“why are orders from three stores slow only after 7 p.m.?”). With twenty microservices, failures are rarely in the place you first look, so you need data that lets you follow a request across boundaries.</p><h3>The three pillars</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdJyEow2zEGZ5Q2sZa_CAQ.png" /><figcaption>Three kinds of telemetry, and a trace that exposes the slow call.</figcaption></figure><ul><li>Metrics are numbers over time: request rate, error rate, latency percentiles, queue depth, CPU. They are cheap, easy to alert on, and great for spotting that something is wrong. <strong>Prometheus</strong> collects them by pulling from each service, and <strong>Grafana</strong> draws dashboards.</li><li>Logs are events with context. Make them structured (JSON with fields) so they can be searched and filtered, and always include a trace id so one order’s logs from many services can be joined.</li><li>Traces follow one request through every service as a tree of spans, each with a start time and duration. <strong>OpenTelemetry</strong> is the open standard for producing them. Commercial platforms such as <strong>Datadog</strong> bundle metrics, logs and traces; open-source stacks combine Prometheus, <em>Grafana</em>, a log store and a trace viewer.</li></ul><p>Trace context travels between services in a header (<em>the W3C standard is called traceparent</em>), so every service attaches its spans to the same trace.</p><h4>What to measure: the four golden signals</h4><p>For any service, start with:</p><ul><li><strong>Latency:</strong> how long requests take, split by success and failure. Use percentiles.</li><li><strong>Traffic:</strong> requests per second.</li><li><strong>Errors:</strong> the fraction of requests that fail.</li><li><strong>Saturation:</strong> how full the service is (CPU, memory, connection pools, queue depth).</li></ul><h4>Metrics in code</h4><p><strong>Instrumenting a service (prometheus_client; documented API)</strong></p><pre>from prometheus_client import Counter, Histogram, start_http_server<br><br>REQUESTS = Counter(&#39;http_requests_total&#39;, &#39;Requests&#39;,<br>                   [&#39;route&#39;, &#39;status&#39;])<br>LATENCY = Histogram(&#39;http_request_duration_seconds&#39;, &#39;Latency&#39;,<br>                    [&#39;route&#39;],<br>                    buckets=[.01, .025, .05, .1, .25, .5, 1, 2.5])<br><br>def handle(route, fn):<br>    with LATENCY.labels(route).time():<br>        try:<br>            result = fn()<br>            REQUESTS.labels(route, &#39;200&#39;).inc()<br>            return result<br>        except Exception:<br>            REQUESTS.labels(route, &#39;500&#39;).inc()<br>            raise<br><br>start_http_server(9100)       # Prometheus scrapes port 9100, path /metrics</pre><p>A histogram records how many requests fell into each time bucket, which lets the monitoring system estimate percentiles. The PromQL query for p99 latency over the last five minutes is:</p><pre>histogram_quantile(0.99,<br>  sum(rate(http_request_duration_seconds_bucket[5m])) by (le))</pre><blockquote><strong><em>Watch out — Mind your labels<br></em></strong>Every distinct label value creates a new time series. Using order_id or user_id as a metric label can create millions of series and crash your monitoring. Put such high-cardinality fields in logs and traces, never in metric labels.</blockquote><h4>Structured logs with a trace id</h4><p><strong>JSON logging with a trace id (runs as is)</strong></p><pre>import json, logging, sys, uuid<br><br>class JsonFormatter(logging.Formatter):<br>    def format(self, record):<br>        data = {&#39;level&#39;: record.levelname, &#39;msg&#39;: record.getMessage(),<br>                &#39;logger&#39;: record.name}<br>        data.update(getattr(record, &#39;ctx&#39;, {}))<br>        return json.dumps(data)<br><br>handler = logging.StreamHandler(sys.stdout)<br>handler.setFormatter(JsonFormatter())<br>log = logging.getLogger(&#39;order-service&#39;)<br>log.addHandler(handler)<br>log.setLevel(logging.INFO)<br><br>trace_id = uuid.uuid4().hex     # normally from the request header<br>log.info(&#39;stock reserved&#39;, extra={&#39;ctx&#39;: {<br>    &#39;trace_id&#39;: trace_id, &#39;order_id&#39;: 8123, &#39;store_id&#39;: 17, &#39;ms&#39;: 4}})</pre><h3>Finding the bottleneck: a worked example</h3><p>The checkout dashboard shows <strong>p99</strong> latency climbing from under a second to over four. A calm investigation follows the pillars in order:</p><ul><li>Metrics say where in the system: the order service’s p99 rose, and so did its calls to the payment service. Traffic is normal, so this is not load.</li><li>Traces say which call: sample slow traces and the waterfall (previous figure) shows the payment service spending most of its time waiting on an external bank API.</li><li>Logs say why: filtered by trace id, the payment service logs show repeated timeouts and retries against one bank.</li></ul><p>The fix is then clear: add a shorter timeout and a circuit breaker for that bank, route to a backup provider, and alert on that dependency’s latency directly. Without traces, this might take hours of guessing.</p><h3>SLIs, SLOs and error budgets</h3><ul><li><strong>An SLI</strong> (service-level indicator) is a measured quantity, such as “fraction of checkout requests that succeed in under 1 second”.</li><li><strong>An SLO</strong> (service-level objective) is the target for it, such as 99.9% over 30 days.</li><li>The error budget is the allowed failure: 100% minus the SLO. If you spend it, you slow feature releases and fix reliability; if you have plenty left, you can ship fast</li></ul><p><strong>Error budget calculator (runs as is)</strong></p><pre>def budget_minutes(slo_percent, days=30):<br>    return (100 - slo_percent) / 100 * days * 24 * 60<br><br>for slo in (99.0, 99.9, 99.95, 99.99):<br>    print(f&#39;{slo}% -&gt; {budget_minutes(slo):.1f} min per 30 days&#39;)<br># 99.9% allows about 43.2 minutes; 99.99% allows only about 4.3 minutes</pre><p>This is why more nines get extremely expensive: going from 99.9% to 99.99% leaves one-tenth of the allowed failure time, and demands redundancy, automation and discipline everywhere.</p><p>Alert on symptoms, not causes. Page a human when users are hurting (SLO burn rate is high), not whenever one pod restarts. Alert fatigue is a reliability problem: people ignore noisy pagers.</p><h3>Zero-downtime deployments</h3><p>Quick commerce never closes. There is always an order in flight, so deployments must be invisible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JspwGGa_SZlNtOXQt5Zq-w.png" /><figcaption>Blue-green swaps everything at once; a canary shifts a little traffic at a time while watching metrics.</figcaption></figure><h4>Strategies</h4><ul><li><strong>Rolling update:</strong> replace pods one at a time (the Kubernetes default). Simple, uses little extra capacity, and old and new versions run together for a while, so the two must be compatible.</li><li><strong>Blue-green:</strong> run a full copy of the new version (green) beside the current one (blue), test it, then switch traffic in one step. Rollback is switching back. It costs double capacity during the switch.</li><li><strong>Canary:</strong> send a small share of real traffic (for example, 5%) to the new version, compare error rate and latency with the old version, and increase gradually or roll back automatically.</li><li><strong>Feature flags:</strong> deploy code switched off, then enable it for 1%, 10%, 100% of users. This separates deploying code from releasing a feature, and makes rollback instant.</li></ul><h4>Making in-flight orders safe</h4><ul><li>Orders are state machines stored in the database (Chapter 8), not in the memory of a process. A pod can disappear mid-order and another continues from the stored state.</li><li>Consumers are idempotent (Chapter 5), so a message handled by a dying pod and again by its replacement does no harm.</li><li>Graceful shutdown drains in-flight requests and commits offsets (Chapter 11).</li><li>Compatible changes only. Old and new code share the same database and topics during a rollout.</li></ul><h4>Database changes: expand, then contract</h4><blockquote>Never rename or delete a column in the same release that stops using it.</blockquote><p>Use three steps over separate releases:</p><ul><li><strong>expand</strong> (add the new column or table; code writes both),</li><li><strong>migrate</strong> (backfill old data),</li><li><strong>contract</strong> (remove the old one after no code reads it).</li></ul><p>Each release stays compatible with the one before it.</p><blockquote><strong><em>Key idea — Deploy discipline<br></em></strong>Deploy small, deploy often, avoid the evening peak, watch the dashboards for a few minutes after each rollout, and keep rollback one command away. Small changes are easier to understand and to undo.</blockquote><h3>Chapter recap</h3><ul><li>Metrics find that something is wrong, traces find where, logs find why.</li><li>Alert on user-facing symptoms; track SLOs and error budgets.</li><li>Avoid high-cardinality metric labels; put ids in logs and traces.</li><li>Use rolling, blue-green or canary releases, feature flags, idempotent consumers and expand/contract migrations.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://prometheus.io/docs/practices/histograms/">https://prometheus.io/docs/practices/histograms/</a></li><li>[2] <a href="https://prometheus.io/docs/practices/instrumentation/">https://prometheus.io/docs/practices/instrumentation/</a></li><li>[3] <a href="https://www.w3.org/TR/trace-context/">https://www.w3.org/TR/trace-context/</a></li><li>[4] <a href="https://opentelemetry.io/docs/">https://opentelemetry.io/docs/</a></li><li>[5] <a href="https://sre.google/sre-book/monitoring-distributed-systems/">https://sre.google/sre-book/monitoring-distributed-systems/</a> <a href="https://sre.google/sre-book/embracing-risk/">https://sre.google/sre-book/embracing-risk/</a></li><li>[6] <a href="https://martinfowler.com/bliki/BlueGreenDeployment.html">https://martinfowler.com/bliki/BlueGreenDeployment.html</a> <a href="https://martinfowler.com/bliki/CanaryRelease.html">https://martinfowler.com/bliki/CanaryRelease.html</a> <a href="https://martinfowler.com/articles/feature-toggles.html">https://martinfowler.com/articles/feature-toggles.html</a> <a href="https://martinfowler.com/bliki/ParallelChange.html">https://martinfowler.com/bliki/ParallelChange.html</a></li></ul><p><em>The checkout bottleneck walk-through and trace durations are illustrative. The Prometheus client code was not run; the JSON logging and error-budget programs were executed.</em></p><h4>Further reading</h4><ul><li>Google, The Site Reliability Workbook [ ] <a href="https://sre.google/workbook/table-of-contents/">https://sre.google/workbook/table-of-contents/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f18d5c9cb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerization and Kubernetes]]></title>
            <link>https://medium.com/@debaprasan.mallick/containerization-and-kubernetes-d0ba4b87347a?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ba4b87347a</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 08:38:01 GMT</pubDate>
            <atom:updated>2026-11-19T08:38:01.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGwUF8mqm-QntuWK5tisMQ.png" /></figure><h4>ackaging software so it runs anywhere, and letting a cluster add and remove copies as the evening rush comes and goes.</h4><h4>What is Docker?</h4><p>You have probably heard “it works on my machine”. It breaks because machines differ: operating system, library versions, configuration. Docker solves this by packaging an application together with everything it needs into an image, and running that image as an isolated container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzh-DDDCukjIRyNv2BhOGg.png" /><figcaption>A virtual machine carries a whole guest operating system. Containers share the host’s kernel, so they are small and start fast.</figcaption></figure><ul><li>An image is a read-only, layered snapshot: base operating-system files, then libraries, then your code. Layers are cached and shared, so rebuilding after a code change is quick.</li><li>A container is a running instance of an image. You can start dozens of identical containers in seconds.</li><li>A registry stores images so servers can pull them.</li></ul><h4>Dockerfile for a small Python API</h4><pre>FROM python:3.12-slim<br><br>WORKDIR /app<br><br># copy dependency list first so this layer is cached between builds<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY app/ app/<br><br># run as a non-root user<br>RUN useradd --create-home appuser<br>USER appuser<br><br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Order matters: copying requirements.txt and installing before copying your code means a small code change does not reinstall every library. This tiny habit saves minutes on every build, which across a large team saves hours per day.</p><blockquote><strong><em>Note — Containers are not strong security boundaries by default<br></em></strong>Containers share the host kernel. Run as a non-root user, keep images small and patched, scan them for known vulnerabilities, and do not put secrets in images.</blockquote><h3>Orchestration with Kubernetes</h3><p>Running one container is easy. Running hundreds across many machines, restarting the ones that crash, rolling out new versions and scaling with load needs an orchestrator. <strong>Kubernetes (K8s)</strong> is the standard one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0fCtakvQ_PGbJ03RGedBA.png" /><figcaption>The control plane decides; worker nodes run the pods. An autoscaler watches metrics and changes the replica count.</figcaption></figure><p>The objects you need to know:</p><ul><li><strong>Pod:</strong> the smallest unit; one or more tightly coupled containers. Pods are disposable, they die and are replaced, and their IP addresses change.<br>Deployment: declares “keep N copies of this pod running, using this image”, and manages rolling updates and rollbacks.</li><li><strong>Service:</strong> a stable name and address in front of a changing set of pods; it load-balances among them.</li><li><strong>Ingress:</strong> routes external HTTP traffic to services.</li><li><strong>ConfigMap and Secret:</strong> configuration and credentials, kept out of images.</li><li><strong>Horizontal Pod Autoscaler (HPA):</strong> changes the replica count based on metrics.</li></ul><h4>A Deployment, with the settings that matter</h4><p><strong>deployment.yaml (core fields)</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-service<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels: {app: order-service}<br>  strategy:<br>    type: RollingUpdate<br>    rollingUpdate: {maxUnavailable: 0, maxSurge: 1}<br>  template:<br>    metadata:<br>      labels: {app: order-service}<br>    spec:<br>      terminationGracePeriodSeconds: 30<br>      containers:<br>        - name: api<br>          image: registry.example.com/order-service:1.4.2<br>          ports: [{containerPort: 8000}]<br>          resources:<br>            requests: {cpu: &quot;250m&quot;, memory: &quot;256Mi&quot;}<br>            limits: {memory: &quot;512Mi&quot;}<br>          readinessProbe:<br>            httpGet: {path: /ready, port: 8000}<br>            periodSeconds: 5<br>          livenessProbe:<br>            httpGet: {path: /health, port: 8000}<br>            periodSeconds: 10</pre><p>Why these fields matter:</p><ul><li>Requests tell the scheduler how much CPU and memory to reserve; they are also the baseline the CPU autoscaler compares against. Limits cap usage.</li><li>The readiness probe keeps a pod out of the load balancer until it can serve traffic (for example, until caches are warm). The liveness probe restarts a pod that is stuck.</li><li>maxUnavailable: 0 with maxSurge: 1 means a rollout starts a new pod, waits until it is ready, then removes an old one: capacity never drops.</li></ul><h4>Autoscaling on CPU</h4><p><strong>hpa.yaml</strong></p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: order-service<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: order-service<br>  minReplicas: 3<br>  maxReplicas: 30<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target: {type: Utilization, averageUtilization: 60}</pre><p>The HPA periodically compares current CPU use against the 60% target and adds or removes pods. Keep minReplicas high enough to absorb a sudden jump while new pods start.</p><h4>Autoscaling consumers on Kafka lag</h4><p>CPU is a poor signal for a consumer that mostly waits on I/O. A better signal is consumer lag (Chapter 5). KEDA, an event-driven autoscaler, can scale a deployment on exactly that:</p><p><strong>keda-scaledobject.yaml (check the KEDA docs for your version)</strong></p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: inventory-consumer<br>spec:<br>  scaleTargetRef:<br>    name: inventory-consumer<br>  minReplicaCount: 2<br>  maxReplicaCount: 12            # no point exceeding partition count<br>  triggers:<br>    - type: kafka<br>      metadata:<br>        bootstrapServers: kafka:9092<br>        consumerGroup: inventory<br>        topic: order.events<br>        lagThreshold: &quot;500&quot;</pre><p>Remember that more consumers than partitions sit idle, so maxReplicaCount should not exceed the topic’s partition count.</p><h3>Scaling for spikes: a plan</h3><ul><li>Pre-scale on a schedule for known peaks (evening rush, sale launches, match finals) by raising minReplicas ahead of time.</li><li>Autoscale on the right metric: CPU for compute-bound services, request rate or latency for APIs, lag for consumers.</li><li>Protect dependencies: a thousand new pods can overwhelm a database that was fine with a hundred. Use connection pooling and cap pool sizes per pod.</li><li>Scale the nodes too: pods need machines. A cluster autoscaler adds nodes when pods cannot be scheduled, which takes minutes, another reason to pre-scale.</li><li>Shut down gracefully. When Kubernetes stops a pod it sends a termination signal. The service should stop accepting new requests, finish in-flight ones and commit Kafka offsets, within the grace period. Without this, deployments and scale-downs drop live orders.</li></ul><h3>Cloud environments</h3><p>Kubernetes runs on every major cloud as a managed service: <strong>Amazon EKS,</strong> <strong>Google GKE </strong>and <strong>Azure AKS.</strong> They run the control plane for you. Some principles hold on any of them:</p><ul><li>Spread across availability zones. Run pods and data stores in at least two or three zones so one data-centre problem does not stop orders.</li><li>Use managed services for stateful pieces (databases, Kafka, Redis) unless you have a strong reason not to; running them yourself is a full-time job. The trade-off is cost and some loss of control.</li><li>Use spot or preemptible instances for stateless, interruption-tolerant work (workers, batch jobs), and on-demand instances for critical paths. This can reduce cost significantly, with the risk of sudden interruption.</li><li>Avoid multi-cloud unless required. It multiplies complexity; most teams are better served by one cloud, well understood, across several zones.</li><li>Everything as code. Use infrastructure-as-code tools (Terraform and similar) and keep manifests in version control so environments can be rebuilt.</li></ul><h3>Chapter recap</h3><ul><li>Docker packages apps into layered images that run as isolated containers.</li><li>Kubernetes keeps desired state: deployments, services, probes and autoscalers.</li><li>Scale on the right signal, pre-scale known peaks, pool connections and shut down gracefully.</li><li>Use managed services, multiple zones and infrastructure-as-code in the cloud.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://docs.docker.com/build/cache/">https://docs.docker.com/build/cache/</a></li><li>[2] <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">https://kubernetes.io/docs/concepts/workloads/controllers/deployment/</a></li><li>[3] <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/">https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/</a></li><li>[4] <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/</a></li><li>[5] <a href="https://keda.sh/docs/scalers/apache-kafka/">https://keda.sh/docs/scalers/apache-kafka/</a></li><li>[6] <a href="https://aws.amazon.com/eks/">https://aws.amazon.com/eks/</a> <a href="https://cloud.google.com/kubernetes-engine">https://cloud.google.com/kubernetes-engine</a> <a href="https://azure.microsoft.com/products/kubernetes-service">https://azure.microsoft.com/products/kubernetes-service</a></li><li>[7] <a href="https://aws.amazon.com/ec2/spot/">https://aws.amazon.com/ec2/spot/</a></li></ul><p><em>Image tags and API versions in the YAML are examples; pin versions you have tested. The YAML and Dockerfile were not executed for this book. Not sourced facts. Statements framed as design guidance, reasoning or teaching models (for example the ten-minute budget, the break-even model and the capacity estimate) are the author’s analysis, labelled illustrative in the text. Check any number before reusing it.</em></p><h4>Further reading</h4><ul><li>Kubernetes documentation [ ] <a href="https://kubernetes.io/docs/home/">https://kubernetes.io/docs/home/</a></li><li>Docker documentation [ ] <a href="https://docs.docker.com/">https://docs.docker.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ba4b87347a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Stack]]></title>
            <link>https://medium.com/@debaprasan.mallick/choosing-the-right-stack-90a149be7cca?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a149be7cca</guid>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 08:34:24 GMT</pubDate>
            <atom:updated>2026-11-19T08:34:24.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QrLLRPipCAT93e8wOlWuA.png" /></figure><h4>Languages, databases and mobile frameworks: how to decide without starting a religious war.</h4><h3>There is no best language, only best fit</h3><p>Teams argue about languages more than almost anything else, and most arguments skip the real question: <em>what does this particular service need?</em> Quick commerce has services with very different needs. A checkout path wants low, predictable latency. A forecasting job wants rich data libraries. An internal admin tool wants speed of development. One language rarely wins all three.</p><p>This chapter compares options by characteristics, not by benchmark numbers. Benchmarks depend on workload, hardware, framework and tuning, and are easy to misuse; you should measure your own workload before deciding.</p><h3>Backend languages compared</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4Cw5c4CN03r8q3qHNqxnw.png" /></figure><p>A few honest observations:</p><ul><li><strong>Latency tails matter more than averages</strong>. What hurts at <strong>p99</strong> is often garbage-collection pauses, blocking calls, or one slow dependency, not the language’s raw speed. Go and modern Java collectors both manage pauses well when configured; so can the others for most workloads.</li><li>Hiring and team skill dominate. A service in a language your team knows deeply will beat a “faster” language nobody can debug at 2 a.m.</li><li>Standardise on few languages. Every extra language multiplies tooling, libraries, security patches and on-call knowledge. Two or three is usually the sweet spot.</li></ul><blockquote><strong><em>Note — What do real companies use?<br></em></strong>Public job posts and talks suggest that large Indian quick-commerce teams use a mix of these languages. But I have no reliable primary source for any single company’s complete stack, so this book does not make claims about it. Use the comparison above to reason about your system.</blockquote><h4>A decision matrix you can reuse</h4><p>When a choice is truly open, write down criteria and weights before you debate candidates. This forces the team to argue about priorities (explicit) instead of languages (emotional). The scores below are placeholders: replace them with your team’s honest judgement.</p><p><strong>Weighted decision matrix (runs as is)</strong></p><pre>criteria = (&#39;latency&#39;, &#39;team_skill&#39;, &#39;ecosystem&#39;, &#39;ops_simplicity&#39;)<br>weights = (5, 4, 3, 3)<br><br>scores = {              # 1 (poor) to 5 (excellent): YOUR judgement<br>    &#39;Go&#39;:      (5, 3, 3, 5),<br>    &#39;Java&#39;:    (4, 5, 5, 3),<br>    &#39;Node.js&#39;: (3, 4, 4, 4),<br>    &#39;Python&#39;:  (2, 5, 5, 4),<br>}<br><br>def total(name):<br>    return sum(w * s for w, s in zip(weights, scores[name]))<br><br>for name in sorted(scores, key=total, reverse=True):<br>    print(name.ljust(8), total(name))</pre><p>Change the weights and watch the ranking move: that is the point. A latency-critical dispatch service and an internal report generator should produce different winners.</p><h3>Data stores: match the workload</h3><p>The same logic applies to storage. Most quick-commerce systems use several stores, each doing what it is best at (called polyglot persistence).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qNUdrLWbz2TfyjpMhvsPA.png" /></figure><blockquote><strong><em>Watch out — Do not add a database for résumé value<br></em></strong>Each new store is something to deploy, monitor, back up, secure and understand at 3 a.m. Prefer to push PostgreSQL further before adding another system, and add one only when you can name the problem it solves and measure it.</blockquote><h3>Mobile and frontend</h3><p>A quick-commerce company ships at least three apps, and they have different constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbHoAlUMoEehma_lzWmdkA.png" /></figure><p>Practical guidance:</p><ul><li>Use cross-platform for the customer app when team size is limited, and invest in performance profiling on low-end Android phones, which are common in India.</li><li>Put heavy native work behind a thin native module: background location tracking, local storage, and scanner access.</li><li>Use server-driven UI for fast-changing surfaces such as the home page and banners: the backend returns a description of the screen, and the app renders it. You can change the layout without waiting for an app-store release.</li><li>Keep app size and start time small; shoppers on slower phones and networks abandon heavy apps.</li></ul><h3>Chapter recap</h3><ul><li>Choose languages by service needs, team skill and operability; avoid benchmark wars.</li><li>Standardise on two or three languages; measure p99 on your own workload.</li><li>Use each data store for what it does best, and resist adding stores casually.</li><li>Customer app: cross-platform is usually fine. Rider app: care for background and offline. Picker app: hardware first.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://openjdk.org/jeps/444">https://openjdk.org/jeps/444</a></li><li>[2] <a href="https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick">https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick</a></li><li>[3] <a href="https://docs.python.org/3/glossary.html#term-global-interpreter-lock">https://docs.python.org/3/glossary.html#term-global-interpreter-lock</a></li><li>[4] <a href="https://go.dev/doc/effective_go#goroutines">https://go.dev/doc/effective_go#goroutines</a></li><li>[5] <a href="https://martinfowler.com/bliki/PolyglotPersistence.html">https://martinfowler.com/bliki/PolyglotPersistence.html</a></li><li>[6] <a href="https://reactnative.dev/">https://reactnative.dev/</a> <a href="https://flutter.dev/">https://flutter.dev/</a></li></ul><p><em>The comparison table summarises widely documented characteristics, not benchmarks. The decision-matrix scores are placeholders for the reader’s own judgement. No claim is made about which languages any specific company uses. Not sourced facts. Statements framed as design guidance, reasoning or teaching models (for example the ten-minute budget, the break-even model and the capacity estimate) are the author’s analysis, labelled illustrative in the text. Check any number before reusing it.</em></p><h4>Further reading</h4><ul><li>Martin Kleppmann, Designing Data-Intensive Applications (data models and storage)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a149be7cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pick-Path Optimization and Warehouse Software]]></title>
            <link>https://medium.com/@debaprasan.mallick/pick-path-optimization-and-warehouse-software-9cf7fce2ac65?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cf7fce2ac65</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 08:31:55 GMT</pubDate>
            <atom:updated>2026-11-19T08:31:55.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7R1wUNpEqyMP8SOCat9ygw.png" /></figure><h4>How a picker fills an order in a couple of minutes, and what the screen in their hand must do.</h4><h3>The warehouse challenge</h3><p>Once an order reaches the dark store, a picker must collect every item, scan it, and bring it to the pack bench. Warehouse-logistics research widely reports travel (walking between locations) as the largest single component of manual order-picking time, more than the grab itself. So the biggest software lever is not a faster hand; it is a shorter walk.</p><blockquote><strong><em>Note — About “90 seconds”<br></em></strong>You may see claims that pickers finish an order in about 90 seconds. I could not verify a public, company-confirmed figure, so this book treats pick-and-pack time as a budget you tune (our illustrative budget in Chapter 1 allows about three minutes), not as an established fact. Measure your own.</blockquote><p><strong>Two ideas shape the software:</strong></p><ul><li>The pick list must be ordered by the physical layout, not by the order items were added to the cart.</li><li>The layout itself must be encoded: every shelf location has a code such as A3-S4 (aisle 3, shelf 4) that the software can sort and measure.</li></ul><h3>Sorting pick lists by shelf order</h3><p>A customer adds items in the order they think of them: milk, shampoo, bread, chips. A naive pick list follows that order and sends the picker zig-zagging across the store. Sort by location and the same trip becomes one pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0UmDaWzdAqFCTHP6aJ5sQ.png" /><figcaption>Same six items. Sorting by aisle, then shelf, removes the back-and-forth.</figcaption></figure><p>The code below models walking cost with a simple, honest rule: aisles are parallel, the only cross-aisle is at the bottom, moving between aisles costs the distance down to the cross-aisle, across, and back up. It reproduces the numbers in the figure.</p><p><strong>Comparing pick routes (runs as is)</strong></p><pre>ITEMS = [(4, 2), (1, 5), (3, 1), (2, 6), (4, 5), (1, 2)]   # (aisle, shelf)<br>AISLE_GAP = 1.5      # walking units between neighbouring aisles<br>BENCH = (1, 0)       # pack bench at the bottom of aisle 1<br><br>def leg(a, b):<br>    (a1, p1), (a2, p2) = a, b<br>    if a1 == a2:<br>        return abs(p1 - p2)<br>    return p1 + p2 + abs(a1 - a2) * AISLE_GAP<br><br>def route_length(order):<br>    stops = [BENCH] + [ITEMS[i] for i in order] + [BENCH]<br>    return sum(leg(stops[i], stops[i + 1]) for i in range(len(stops) - 1))<br><br>cart_order = list(range(len(ITEMS)))<br>sorted_order = sorted(cart_order, key=lambda i: ITEMS[i])<br>print(&#39;cart order  :&#39;, route_length(cart_order))<br>print(&#39;sorted order:&#39;, route_length(sorted_order))<br># cart order  : 63.0<br># sorted order: 43.0</pre><h4>Beyond a simple sort</h4><p>Finding the shortest possible route is the <strong>travelling salesman problem</strong>, which is hard in general, but warehouse aisles are structured, and two simple heuristics work well:</p><ul><li><strong>Return heuristic:</strong> enter each needed aisle, walk to the farthest item, and come back, visiting aisles in order (what the sort above approximates).</li><li><strong>S-shape heuristic:</strong> when there are cross-aisles at both ends, walk each needed aisle fully, alternating direction like the letter ‘S’.</li></ul><h4>Real constraints on the order</h4><p>Shortest path is not the only goal. Bags must be packed sensibly, so a good pick sequence also respects zones: heavy and sturdy items first, fragile items later, and cold or frozen items last so they stay cold. You can express all of this as a sort key.</p><p><strong>Sort by zone first, then by location (runs as is)</strong></p><pre>ZONE_RANK = {&#39;heavy&#39;: 0, &#39;ambient&#39;: 1, &#39;fragile&#39;: 2, &#39;cold&#39;: 3}<br><br>items = [<br>    {&#39;name&#39;: &#39;Milk 1L&#39;,     &#39;zone&#39;: &#39;cold&#39;,    &#39;loc&#39;: (4, 1)},<br>    {&#39;name&#39;: &#39;Rice 5kg&#39;,    &#39;zone&#39;: &#39;heavy&#39;,   &#39;loc&#39;: (1, 2)},<br>    {&#39;name&#39;: &#39;Eggs&#39;,        &#39;zone&#39;: &#39;fragile&#39;, &#39;loc&#39;: (2, 6)},<br>    {&#39;name&#39;: &#39;Biscuits&#39;,    &#39;zone&#39;: &#39;ambient&#39;, &#39;loc&#39;: (3, 3)},<br>    {&#39;name&#39;: &#39;Atta 5kg&#39;,    &#39;zone&#39;: &#39;heavy&#39;,   &#39;loc&#39;: (1, 5)},<br>]<br><br>pick_list = sorted(items, key=lambda it: (ZONE_RANK[it[&#39;zone&#39;]], it[&#39;loc&#39;]))<br>for it in pick_list:<br>    print(it[&#39;zone&#39;].ljust(8), it[&#39;loc&#39;], it[&#39;name&#39;])</pre><h4>Batching and parallel work</h4><p>In busy hours a picker can collect several orders in one trip (batch picking) and sort them into separate bags at a put-wall or bench. This cuts walking per order but adds sorting steps, so it pays off only when orders share many aisles. Stores also split work by zone, with one person on the cold section and another on ambient, merging at the bench.</p><h4>Slotting: put popular things where walking is short</h4><p>The best route is half the story. Slotting decides where each SKU lives. Fast sellers go close to the bench; items often bought together go near each other (a “co-purchase” analysis on order history finds them). Software can propose a new layout from sales data, but moves must be scheduled carefully, because every move briefly disturbs pickers’ muscle memory and inventory accuracy.</p><h3>Dynamic substitutions</h3><p>Sooner or later a picker reaches the shelf and the item is not there. The system (not the picker’s guess) should decide what happens next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzTuyIwF_FpZfqLJPP3Z-w.png" /><figcaption>Rules propose a candidate; the customer’s standing preference decides whether to swap silently or ask.</figcaption></figure><h4>Choosing a good substitute</h4><p>Score candidates on similarity and keep only those above a threshold. Common signals: same category, same or similar brand tier, similar pack size, matching dietary tag (vegetarian must never be replaced by non-vegetarian), a price not far above the original, and enough stock.</p><h4>A tiny substitution scorer (runs as is)</h4><pre>def score(orig, cand):<br>    if cand[&#39;diet&#39;] != orig[&#39;diet&#39;]:          # hard rule, never break it<br>        return 0<br>    if cand[&#39;stock&#39;] &lt; 1 or cand[&#39;category&#39;] != orig[&#39;category&#39;]:<br>        return 0<br>    s = 50<br>    s += 20 if cand[&#39;brand_tier&#39;] == orig[&#39;brand_tier&#39;] else 0<br>    ratio = cand[&#39;size_g&#39;] / orig[&#39;size_g&#39;]<br>    s += 20 if 0.8 &lt;= ratio &lt;= 1.25 else 0<br>    s += 10 if cand[&#39;price&#39;] &lt;= orig[&#39;price&#39;] * 1.1 else 0<br>    return s<br><br>orig = {&#39;diet&#39;: &#39;veg&#39;, &#39;category&#39;: &#39;biscuits&#39;, &#39;brand_tier&#39;: &#39;mid&#39;,<br>        &#39;size_g&#39;: 100, &#39;price&#39;: 20}<br>cands = [<br>    {&#39;id&#39;: &#39;A&#39;, &#39;diet&#39;: &#39;veg&#39;, &#39;category&#39;: &#39;biscuits&#39;, &#39;brand_tier&#39;: &#39;mid&#39;,<br>     &#39;size_g&#39;: 120, &#39;price&#39;: 21, &#39;stock&#39;: 8},<br>    {&#39;id&#39;: &#39;B&#39;, &#39;diet&#39;: &#39;veg&#39;, &#39;category&#39;: &#39;biscuits&#39;, &#39;brand_tier&#39;: &#39;low&#39;,<br>     &#39;size_g&#39;: 400, &#39;price&#39;: 60, &#39;stock&#39;: 3},<br>    {&#39;id&#39;: &#39;C&#39;, &#39;diet&#39;: &#39;nonveg&#39;, &#39;category&#39;: &#39;biscuits&#39;,<br>     &#39;brand_tier&#39;: &#39;mid&#39;, &#39;size_g&#39;: 100, &#39;price&#39;: 20, &#39;stock&#39;: 9},<br>]<br>ranked = sorted(cands, key=lambda c: score(orig, c), reverse=True)<br>print([(c[&#39;id&#39;], score(orig, c)) for c in ranked])<br># [(&#39;A&#39;, 100), (&#39;B&#39;, 50), (&#39;C&#39;, 0)]</pre><h4>Approvals, timeouts and money</h4><ul><li>If the customer allowed auto-substitution, swap and notify. If not, send a push asking for approval with a short timeout (the picker is waiting and the clock is running), then fall back to removing the item.</li><li>The substitute must be reserved in inventory like any item (Chapter 6), and the bill adjusted: if the substitute costs less, charge less; if more, do not charge more without consent.</li><li>Every stock-out at the shelf is also an inventory-accuracy signal. If the system said 3 in stock and the shelf has 0, schedule a cycle count for that SKU.</li></ul><blockquote><strong><em>Watch out — Measure what matters<br></em></strong>It is tempting to rank pickers purely by speed. Fast pickers who choose wrong items cause refunds and unhappy customers, and rushing causes injuries. Track accuracy (right items, right quantity) and safety alongside speed.</blockquote><h3>Chapter recap</h3><ul><li>Walking dominates picking time, so sort pick lists by shelf location.</li><li>Layered constraints (heavy first, cold last) fit into one sort key.</li><li>Slotting places fast movers and co-purchased items close to the bench.</li><li>Substitution logic should be rules-driven, preference-aware, reserved in inventory and measured.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li><a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">https://en.wikipedia.org/wiki/Travelling_salesman_problem</a></li></ul><p><em>The “about 90 seconds” pick-and-pack claim is deliberately not asserted: no public company-confirmed figure was found. The walking-cost model, the 63.0 versus 43.0 result, the zone ranking and the substitution scorer are teaching models; the two route lengths and scorer outputs were computed by the programs shown.</em></p><h4>Further reading</h4><ul><li>John Bartholdi and Steven Hackman, Warehouse and Distribution Science (free from the authors) [ ] search by title</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf7fce2ac65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dispatch Engine and Real-Time Rider Optimization]]></title>
            <link>https://medium.com/@debaprasan.mallick/the-dispatch-engine-and-real-time-rider-optimization-dea55205b931?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/dea55205b931</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 05:33:49 GMT</pubDate>
            <atom:updated>2026-11-18T05:33:49.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLobKjMH2dhCLUBnwH13BQ.png" /></figure><h4>Matching orders, stores and riders in seconds, and keeping a live dot moving on a bad network.</h4><h3>The assignment problem</h3><p><em>Imagine three new orders and three idle riders.</em> Who should take which order? Each pairing has a cost: the minutes the rider needs to reach the store, perhaps plus how long the order has already waited. We want the assignment of orders to riders that minimises the total cost. This classic problem is called the assignment problem.</p><p>The tempting approach is greedy: take each order in turn and give it the nearest free rider. It is fast and easy, and often poor, because an early order can grab a rider that a later order needed far more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVVMN7HWqOJXdsFT5eVnUw.png" /><figcaption>Greedy totals 13 minutes; the optimal matching totals 7, by letting order 1 accept a slightly worse rider.</figcaption></figure><p><strong>The Hungarian algorithm,</strong> and later refinements of it, solve the problem optimally in time proportional to n³. For the few dozen orders and riders around one store, that is instant. SciPy’s linear_sum_assignment solves exactly this problem with an algorithm from that family:</p><p><strong>Optimal matching (runs as is; needs scipy)</strong></p><pre>import numpy as np<br>from scipy.optimize import linear_sum_assignment<br><br># cost[i][j] = minutes for rider j to reach the store of order i<br>cost = np.array([[1, 2, 9],<br>                 [2, 9, 9],<br>                 [9, 9, 3]])<br><br>rows, cols = linear_sum_assignment(cost)<br>for o, r in zip(rows, cols):<br>    print(&#39;order&#39;, o + 1, &#39;-&gt; rider&#39;, r + 1, &#39;cost&#39;, cost[o][r])<br>print(&#39;total&#39;, cost[rows, cols].sum())<br><br># greedy for comparison: each order takes its nearest free rider<br>free, total = set(range(3)), 0<br>for i in range(3):<br>    j = min(free, key=lambda k: cost[i][k])<br>    free.remove(j); total += cost[i][j]<br>print(&#39;greedy total&#39;, total)<br># optimal total 7, greedy total 13</pre><h4>From a toy to a real dispatcher</h4><p>Real dispatch adds layers on top of this core:</p><ul><li><strong>Rolling batches.</strong> Run the matcher every few seconds on all pending orders and idle riders, rather than once per order. A longer window gives better matches but makes the oldest order wait; the window length is a tuning knob.</li><li><strong>Infeasible pairs.</strong> A rider too far away, off shift, or already carrying a full bag gets a very large cost, so the solver never picks them.</li><li><strong>Pre-assignment.</strong> Pick-and-pack takes minutes. Assign (or at least alert) a rider while the order is still being picked, timed so they arrive just as the bag is ready. This overlap is worth minutes.</li><li><strong>Batching and trips.</strong> One rider can carry two orders from the same store to nearby addresses. This lowers cost per order but raises the second customer’s wait; both effects go into the cost function.</li><li><strong>Fairness and rider welfare.</strong> Earnings, rest, and safe routes are constraints, not afterthoughts. A dispatcher that only minimises minutes burns out its fleet.</li></ul><p><strong>One dispatch tick (illustrative; runs as is with scipy)</strong></p><pre>import numpy as np<br>from scipy.optimize import linear_sum_assignment<br><br>BIG = 10_000          # marks an impossible pairing<br><br>def dispatch_tick(orders, riders, eta_minutes):<br>    &quot;&quot;&quot;eta_minutes(rider, order) -&gt; minutes, or None if infeasible.&quot;&quot;&quot;<br>    cost = np.full((len(orders), len(riders)), BIG, dtype=float)<br>    for i, o in enumerate(orders):<br>        for j, r in enumerate(riders):<br>            eta = eta_minutes(r, o)<br>            if eta is not None:<br>                cost[i, j] = eta - 0.1 * o[&#39;waited_min&#39;]  # favour old<br>    rows, cols = linear_sum_assignment(cost)<br>    return [(orders[i][&#39;id&#39;], riders[j][&#39;id&#39;])<br>            for i, j in zip(rows, cols) if cost[i, j] &lt; BIG]<br><br>orders = [{&#39;id&#39;: &#39;O1&#39;, &#39;waited_min&#39;: 2}, {&#39;id&#39;: &#39;O2&#39;, &#39;waited_min&#39;: 0}]<br>riders = [{&#39;id&#39;: &#39;R1&#39;}, {&#39;id&#39;: &#39;R2&#39;}, {&#39;id&#39;: &#39;R3&#39;}]<br>etas = {(&#39;R1&#39;, &#39;O1&#39;): 3, (&#39;R2&#39;, &#39;O1&#39;): 6, (&#39;R3&#39;, &#39;O1&#39;): None,<br>        (&#39;R1&#39;, &#39;O2&#39;): 4, (&#39;R2&#39;, &#39;O2&#39;): 9, (&#39;R3&#39;, &#39;O2&#39;): 6}<br>print(dispatch_tick(orders, riders, lambda r, o: etas[(r[&#39;id&#39;], o[&#39;id&#39;])]))</pre><h3>Real-time communication</h3><p>Customers watch a moving dot; riders receive offers; the store sees “rider arriving”. All of that is push communication. There are three common approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rbk5UdA_M4pC_IvWEZA-4Q.png" /><figcaption>Polling is simple but wasteful. WebSockets keep one connection open. MQTT adds a broker and delivery levels for flaky networks.</figcaption></figure><h4>WebSockets</h4><p>A WebSocket starts as an ordinary HTTP request and then upgrades to a persistent two-way connection over TCP. After that, either side can send a message at any moment with very little overhead. It is the usual choice between an app and a backend for live tracking.</p><p>Scaling WebSockets has a twist: a connection lives on one specific server, so a location update from the rider must be routed to whichever server holds the customer’s connection. The standard design is:</p><ul><li>The rider app sends location updates to a stateless ingest service.</li><li>Ingest publishes them to Kafka (or a pub/sub channel) keyed by order id.</li><li>A tracking service keeps the latest location per order (for example in Redis) and forwards updates to the gateway node holding that customer’s socket.</li><li>Clients send heartbeats; on disconnect they reconnect with backoff and ask “what did I miss since event id X?” so no update is lost.</li></ul><h4>MQTT</h4><p>MQTT is a lightweight publish/subscribe protocol designed for unreliable networks and small devices. Clients connect to a broker and publish to topics such as rider/42/location. Notable features:</p><ul><li>QoS levels: 0 (at most once), 1 (at least once), 2 (exactly once, at higher cost).</li><li>Keep-alive and Last Will: the broker can announce that a client vanished.</li><li>Retained messages: a new subscriber immediately gets the last known value.</li></ul><p>It suits the rider fleet because messages are tiny and the protocol copes with dropped connections.</p><blockquote><strong><em>Note — Server-sent events<br></em></strong>For one-way updates to a browser (for example an order status page), Server-Sent Events are simpler than WebSockets. Choose the lightest tool that does the job.</blockquote><h4>Send fewer, smarter location updates</h4><p>Streaming a GPS fix every second from every rider is wasteful. Send an update only when the rider has moved enough, or enough time has passed.</p><p><strong>Adaptive location reporting (runs as is)</strong></p><pre>from math import radians, sin, cos, asin, sqrt<br><br>def metres(a, b):<br>    R = 6371008.8<br>    p1, p2 = radians(a[0]), radians(b[0])<br>    h = (sin((p2 - p1) / 2) ** 2 +<br>         cos(p1) * cos(p2) * sin(radians(b[1] - a[1]) / 2) ** 2)<br>    return 2 * R * asin(sqrt(h))<br><br>def should_send(last, now, min_move=25, max_silence=10):<br>    &quot;&quot;&quot;last = (lat, lng, t) of last sent fix; now = same shape.&quot;&quot;&quot;<br>    moved = metres(last[:2], now[:2])<br>    return moved &gt;= min_move or (now[2] - last[2]) &gt;= max_silence<br><br>last = (19.0760, 72.8777, 0)<br>print(should_send(last, (19.07602, 72.87771, 3)))  # False: barely moved<br>print(should_send(last, (19.0765, 72.8777, 4)))    # True: moved 55 m<br>print(should_send(last, (19.07601, 72.87770, 12))) # True: silent too long</pre><h4>Rider app constraints</h4><p>The rider app runs on a mid-range phone, on a bike, outdoors, on patchy mobile data, for ten hours. That shapes every decision.</p><ul><li>Battery. GPS and constant radio use drain it. Sample location adaptively (faster when moving, slower when stopped), batch network calls, avoid wake-ups, and keep screens simple.</li><li>Weak signal. Assume requests will fail. Keep payloads small (compact formats such as Protocol Buffers), retry with backoff, and never block the screen on the network.</li><li>Offline-first. Save every action (accept, picked up, delivered) locally first with a unique event id and timestamp, show the result immediately, and sync when the network returns. The server ignores duplicates by event id. Chapter 5’s idempotency applies directly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6coaXQ8OR6Hmra0q8MBWeQ.png" /><figcaption>Every state change is written locally first; the server accepts each event id at most once.</figcaption></figure><p>A state machine makes the order lifecycle explicit, and rejects impossible jumps such as “delivered” before “picked up”:</p><p><strong>Order state machine for the rider app (runs as is)</strong></p><pre>ALLOWED = {<br>    &#39;IDLE&#39;:           {&#39;OFFERED&#39;},<br>    &#39;OFFERED&#39;:        {&#39;ACCEPTED&#39;, &#39;IDLE&#39;},        # decline or time out<br>    &#39;ACCEPTED&#39;:       {&#39;AT_STORE&#39;, &#39;IDLE&#39;},<br>    &#39;AT_STORE&#39;:       {&#39;PICKED_UP&#39;},<br>    &#39;PICKED_UP&#39;:      {&#39;NEAR_CUSTOMER&#39;},<br>    &#39;NEAR_CUSTOMER&#39;:  {&#39;DELIVERED&#39;},<br>    &#39;DELIVERED&#39;:      set(),<br>}<br><br>def apply(state, new_state):<br>    if new_state not in ALLOWED[state]:<br>        raise ValueError(f&#39;illegal transition {state} -&gt; {new_state}&#39;)<br>    return new_state<br><br>s = &#39;IDLE&#39;<br>for step in [&#39;OFFERED&#39;, &#39;ACCEPTED&#39;, &#39;AT_STORE&#39;, &#39;PICKED_UP&#39;]:<br>    s = apply(s, step)<br>print(&#39;now&#39;, s)<br>try:<br>    apply(s, &#39;DELIVERED&#39;)            # skipped NEAR_CUSTOMER<br>except ValueError as e:<br>    print(e)</pre><blockquote><strong><em>Watch out — Trust, but verify<br></em></strong>Phone clocks drift and GPS can be spoofed. Servers should stamp events with their own time, validate that a “delivered” event happens near the delivery address, and treat the phone as an untrusted source.</blockquote><h3>Chapter recap</h3><ul><li>Matching is an assignment problem: greedy is fast but can be much worse than optimal.</li><li>Real dispatchers batch in short windows, pre-assign riders, and respect fairness.</li><li>Use WebSockets or MQTT for live updates; route messages to the server holding the connection.</li><li>Rider apps must be battery-aware, offline-first and idempotent.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1]<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html</a></li><li>[2] <a href="https://www.rfc-editor.org/rfc/rfc6455">https://www.rfc-editor.org/rfc/rfc6455</a></li><li>[3] <a href="https://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.html">https://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.html</a></li><li>[4] <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html">https://html.spec.whatwg.org/multipage/server-sent-events.html</a></li><li>[5] <a href="https://protobuf.dev/">https://protobuf.dev/</a></li></ul><p><em>The greedy 13-minute versus optimal 7-minute example uses a made-up cost matrix; both totals were computed by the program shown. Rolling windows, pre-assignment and batching are common dispatch ideas presented as design guidance, not a description of any specific company’s dispatcher. The adaptive location-reporting thresholds (25 m, 10 s) are example values.</em></p><h4>Further reading</h4><ul><li>Martin Kleppmann, Designing Data-Intensive Applications (chapter on stream processing)</li><li>MQTT.org introduction [ ] <a href="https://mqtt.org/">https://mqtt.org/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dea55205b931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperlocal Geolocation and Spatial Routing]]></title>
            <link>https://medium.com/@debaprasan.mallick/hyperlocal-geolocation-and-spatial-routing-a937322b8710?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/a937322b8710</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 05:24:13 GMT</pubDate>
            <atom:updated>2026-11-18T05:24:13.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esP3ISWRiMTjBNyBxhZUig.png" /></figure><h4>Turning a blue dot on a phone into “this store, this rider, this many minutes”.</h4><h3>Mapping the physical world</h3><p>Every location on Earth is described by two numbers: <em>latitude</em> (north or south of the equator, -90 to 90) and <em>longitude</em> (east or west of a reference line, -180 to 180). GPS phones report them in the WGS 84 system, which is also what most databases and map libraries expect.</p><p>Two beginner traps appear immediately.</p><blockquote><strong><em>Watch out — Trap 1: the order of the numbers</em></strong><br>People say “lat, long”, but many spatial libraries (PostGIS, GeoJSON) want longitude first: (x, y) = (lng, lat). Mixing them places your Mumbai store somewhere in the Indian Ocean or Antarctica. Write the order into your variable names.</blockquote><blockquote><strong><em>Watch out — Trap 2: degrees are not metres<br></em></strong>One degree of latitude is about 111 km everywhere, but one degree of longitude shrinks as you move away from the equator. Computing distance with Pythagoras on raw degrees gives wrong answers. Use a proper formula.</blockquote><h4>Distance on a sphere: the haversine formula</h4><p>The haversine formula gives the great-circle distance between two points on a sphere. Earth is not a perfect sphere, but for city-scale decisions the error is small.</p><p><strong>Haversine distance (runs as is)</strong></p><pre>from math import radians, sin, cos, asin, sqrt<br><br>def haversine_km(lat1, lng1, lat2, lng2):<br>    R = 6371.0088                       # mean Earth radius in km<br>    p1, p2 = radians(lat1), radians(lat2)<br>    dphi, dlmb = p2 - p1, radians(lng2 - lng1)<br>    a = sin(dphi / 2) ** 2 + cos(p1) * cos(p2) * sin(dlmb / 2) ** 2<br>    return 2 * R * asin(sqrt(a))<br><br># Mumbai to Pune, roughly 120 km in a straight line<br>print(round(haversine_km(19.0760, 72.8777, 18.5204, 73.8567), 1))<br># 0.01 degree of latitude is about 1.1 km<br>print(round(haversine_km(19.00, 72.80, 19.01, 72.80), 2))</pre><p>This is straight-line distance. Real delivery time depends on roads, one-way streets, flyovers and traffic. Production systems use two stages: a cheap straight-line (or cell-based) filter to find a handful of candidates, then a routing engine (open-source ones include <strong>OSRM</strong> and <strong>Valhalla</strong>, or a commercial maps API) to compute road ETA for just those candidates.</p><h3>Three tools for “what is near here?”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9C-aj8W-vxdOyqrKjdyyRw.png" /><figcaption>Hexagonal grids give one kind of neighbour; square grids give two. This matters for any “within N rings” rule.</figcaption></figure><h4>1. A spatial database: PostGIS</h4><p><strong>PostGIS</strong> adds geometry and geography types and spatial indexes to PostgreSQL. A <strong>GiST</strong> index organises shapes by their bounding boxes so a “within 2 km” query touches only nearby rows instead of scanning every store.</p><p><strong>PostGIS: stores near a customer (illustrative)</strong></p><pre>CREATE EXTENSION IF NOT EXISTS postgis;<br><br>CREATE TABLE store (<br>  id           INT PRIMARY KEY,<br>  name         TEXT NOT NULL,<br>  location     geography(Point, 4326) NOT NULL,<br>  service_area geography(Polygon, 4326)<br>);<br>CREATE INDEX store_location_gix ON store USING GIST (location);<br><br>-- stores within 2 km of the customer, nearest first (lng, then lat!)<br>SELECT id, name,<br>       ST_Distance(location, p.pt) AS metres<br>FROM store,<br>     (SELECT ST_SetSRID(ST_MakePoint(:lng, :lat), 4326)::geography<br>      AS pt) AS p<br>WHERE ST_DWithin(location, p.pt, 2000)<br>ORDER BY metres<br>LIMIT 5;</pre><p>With the geography type, distances are in metres. ST_DWithin uses the index; ST_Covers(service_area, point) checks whether a point lies inside a hand-drawn delivery polygon, which is how you honour rivers, railways and gated colonies.</p><h4>2. Geohash</h4><p>A <strong>geohash</strong> converts a coordinate into a short text string such as u4pruydqqvj. Each extra character narrows the cell. Nearby places usually share a prefix, so you can index and group by prefix in any database, even one with no spatial features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-mWTQWujrxFVK6jMfBl6A.png" /><figcaption>Prefix sharing is handy, but two points on opposite sides of a cell edge get different strings.</figcaption></figure><p>The catch is the boundary problem: two points 20 m apart may sit on either side of a cell edge and share no prefix. The standard fix is to search the cell and its eight neighbours. The encoder below is short enough to read in one sitting; it follows the published algorithm, interleaving longitude and latitude bits and writing them in base 32.</p><p><strong>Geohash encoder (runs as is)</strong></p><pre>BASE32 = &#39;0123456789bcdefghjkmnpqrstuvwxyz&#39;<br><br>def geohash(lat, lng, precision=7):<br>    lat_r, lng_r = [-90.0, 90.0], [-180.0, 180.0]<br>    bits, bit, ch, even, out = 0, 0, 0, True, []<br>    while len(out) &lt; precision:<br>        rng, val = (lng_r, lng) if even else (lat_r, lat)<br>        mid = (rng[0] + rng[1]) / 2<br>        if val &gt;= mid:<br>            ch = (ch &lt;&lt; 1) | 1<br>            rng[0] = mid<br>        else:<br>            ch = ch &lt;&lt; 1<br>            rng[1] = mid<br>        even = not even<br>        bit += 1<br>        if bit == 5:<br>            out.append(BASE32[ch])<br>            bit, ch = 0, 0<br>    return &#39;&#39;.join(out)<br><br>print(geohash(42.6, -5.6, 5))          # ezs42 (a well-known example)<br>print(geohash(57.64911, 10.40744, 11)) # u4pruydqqvj</pre><h4>3. H3 hexagons</h4><p><strong>H3</strong>, open-sourced by <strong>Uber</strong>, divides the globe into hexagonal cells at 16 resolutions. Resolution 8 cells average about 0.74 km², resolution 9 about 0.1 km². A few things to know:</p><ul><li>A cell id is a 64-bit number (shown as a 15-character hex string). You can store and join on it like any key.</li><li>grid_disk(cell, k) returns the cell plus every cell within k steps. For k = 2 that is 1 + 6 + 12 = 19 cells; in general 3k(k+1) + 1.</li><li>Twelve cells at every resolution are pentagons, an unavoidable property of tiling a sphere. Library functions handle this for you.</li></ul><p>Because every neighbour is equally far, “ring 2” behaves like a fair circle, which is why ride-hailing and quick-commerce teams like H3 for coverage and demand maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wpK7ZH1P4n29mn5MCHztQ.png" /><figcaption>Converting a store into the set of cells it serves.</figcaption></figure><p><strong>H3 store index (python h3 v4 API; needs the h3 package)</strong></p><pre>import h3<br>from collections import defaultdict<br><br>RES = 8                                   # about 0.74 km2 per cell<br><br>def build_index(stores, rings=2):<br>    index = defaultdict(list)             # cell id -&gt; store ids<br>    for s in stores:<br>        centre = h3.latlng_to_cell(s[&#39;lat&#39;], s[&#39;lng&#39;], RES)<br>        for cell in h3.grid_disk(centre, rings):<br>            index[cell].append(s[&#39;id&#39;])<br>    return index<br><br>def candidates(index, lat, lng):<br>    return index.get(h3.latlng_to_cell(lat, lng, RES), [])</pre><p>The index fits easily in memory (or in a Redis hash), so finding candidate stores is a single dictionary lookup.</p><blockquote><strong><em>Note — Library versions<br></em></strong>H3 renamed its functions between major versions: version 3 used geo_to_h3 and k_ring; version 4 uses latlng_to_cell and grid_disk. Check which one you install.</blockquote><h3>Proximity matching in practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OOQW3grB5nQ1uoUCp2FdA.png" /><figcaption>A cheap lookup finds candidates; filters and ranking pick the winner.</figcaption></figure><p>Here is the full flow behind the home screen:</p><ul><li>Locate the customer. GPS is noisy indoors; let users confirm the pin. Some apps snap the pin to a saved address.</li><li>Index the point into a cell and look up candidate stores in memory.<br>Filter: is the store open, is it inside its service polygon, does it hold the items in the cart (or at least the most important ones)?</li><li>Rank by estimated delivery time, store load and stock coverage. Run the routing engine only for the top few.</li><li>Return the chosen store and a promised time, or “not serviceable”.</li></ul><h3>Dynamic catchments</h3><p>A store has a fixed maximum radius, but its <strong>effective radius </strong>can shrink when it is busy or short of riders: drop the outer ring of cells from the index for a while, so customers there are served by a quieter store or shown a longer time. This turns load balancing into a map operation, and it works because the lookup is just a set of cell ids.</p><blockquote><strong><em>Key idea — Pattern<br></em></strong>Precompute geography into keys (cells), look up at request time, and spend expensive geometry only where the answer is ambiguous.</blockquote><h3>Chapter recap</h3><ul><li>Use longitude-first order carefully; use haversine or geography, never raw degrees.</li><li>PostGIS gives exact answers with indexes; geohash gives prefix strings; H3 gives equal-distance hexagons.</li><li>A two-stage design (cheap candidates, then precise ETA) keeps lookups fast.</li><li>Dynamic catchments adjust service areas by adding or removing cells.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://en.wikipedia.org/wiki/Haversine_formula">https://en.wikipedia.org/wiki/Haversine_formula</a></li><li>[2] <a href="https://en.wikipedia.org/wiki/Earth_radius">https://en.wikipedia.org/wiki/Earth_radius</a></li><li>[3] <a href="https://www.rfc-editor.org/rfc/rfc7946">https://www.rfc-editor.org/rfc/rfc7946</a> <a href="https://postgis.net/docs/ST_MakePoint.html">https://postgis.net/docs/ST_MakePoint.html</a></li><li>[4] <a href="https://postgis.net/docs/ST_DWithin.html">https://postgis.net/docs/ST_DWithin.html</a></li><li>[5] <a href="https://en.wikipedia.org/wiki/Geohash">https://en.wikipedia.org/wiki/Geohash</a></li><li>[6] <a href="https://h3geo.org/docs/core-library/restable/">https://h3geo.org/docs/core-library/restable/</a></li><li>[7] <a href="https://h3geo.org/docs/library/migration-3.x/functions">https://h3geo.org/docs/library/migration-3.x/functions</a></li><li>[8] <a href="https://h3geo.org/docs/core-library/overview/">https://h3geo.org/docs/core-library/overview/</a></li><li>[9] <a href="http://project-osrm.org/">http://project-osrm.org/</a> <a href="https://valhalla.github.io/valhalla/">https://valhalla.github.io/valhalla/</a></li></ul><h4>Further reading</h4><ul><li>Uber Engineering, “H3: Uber’s Hexagonal Hierarchical Spatial Index” (2018)</li><li>PostGIS documentation [ ] <a href="https://postgis.net/documentation/">https://postgis.net/documentation/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a937322b8710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency Control and Inventory Locking: The Redis Masterclass]]></title>
            <link>https://medium.com/@debaprasan.mallick/concurrency-control-and-inventory-locking-the-redis-masterclass-c4f125014d76?source=rss-a940f3cfc309------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f125014d76</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[quick-commerce]]></category>
            <dc:creator><![CDATA[Debaprasan Mallick]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 14:52:16 GMT</pubDate>
            <atom:updated>2026-11-17T14:52:16.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v51CwxLUFTstHhSuUc2Yw.png" /></figure><h4>Two customers, one box of cereal, one millisecond: how to sell it exactly once.</h4><h3>The race condition</h3><p>Two customers add the last box of cereal to their carts and tap pay in the same millisecond. A naive handler does this: read the stock; <em>if it is at least 1, subtract 1 and save.</em> That is two steps, and between them the other request can sneak in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXog2PQjXELsjwK5VYVj5A.png" /><figcaption>Left: both requests read 1 before either writes. Right: a single conditional update lets only the first succeed.</figcaption></figure><p>You can watch it happen. The code below simulates two requests as threads, with a small delay standing in for the network round trip.</p><p><strong>A real race condition (runs as is)</strong></p><pre>import threading, time<br><br>stock = 1<br>sold_to = []<br><br>def buy(name):<br>    global stock<br>    if stock &gt;= 1:            # step 1: read and check<br>        time.sleep(0.01)      # a network or DB round trip<br>        stock -= 1            # step 2: write<br>        sold_to.append(name)<br><br>threads = [threading.Thread(target=buy, args=(n,)) for n in (&#39;A&#39;, &#39;B&#39;)]<br>for t in threads: t.start()<br>for t in threads: t.join()<br>print(&#39;stock =&#39;, stock, &#39; sold to&#39;, sold_to)<br><br># stock = -1  sold to [&#39;A&#39;, &#39;B&#39;]   &lt;- oversold!</pre><p>Adding a threading.Lock around both steps fixes it inside one process. But your service runs as many copies on many machines, and a lock in one process’s memory means nothing to another. We need the check and the update to be atomic somewhere all copies share.</p><p><strong>In-process lock: correct, but only for one process</strong></p><pre>import threading, time<br><br>stock, sold_to = 1, []<br>lock = threading.Lock()<br><br>def buy_safe(name):<br>    global stock<br>    with lock:                # check and update become one step<br>        if stock &gt;= 1:<br>            time.sleep(0.01)<br>            stock -= 1<br>            sold_to.append(name)<br><br>ts = [threading.Thread(target=buy_safe, args=(n,)) for n in &#39;AB&#39;]<br>for t in ts: t.start()<br>for t in ts: t.join()<br>print(&#39;stock =&#39;, stock, &#39; sold to&#39;, sold_to)<br># stock = 0  sold to [&#39;A&#39;]   &lt;- correct, within this one process</pre><h3>Three ways to get atomicity</h3><h4>1. Let the database do it (conditional update)</h4><p>The simplest and often best answer: one SQL statement that checks and changes together. The database locks the row for the instant of the update, so concurrent requests are serialised.</p><p><strong>Atomic check-and-decrement in PostgreSQL</strong></p><pre>UPDATE inventory<br>SET    quantity = quantity - :qty<br>WHERE  store_id = :store AND sku_id = :sku<br>  AND  quantity &gt;= :qty;<br>-- rows affected = 1  -&gt; reserved<br>-- rows affected = 0  -&gt; not enough stock</pre><h4>2. Pessimistic locking</h4><p>SELECT … FOR UPDATE locks the row until your transaction ends; others wait. It is flexible when you must read, think, and then write, but long transactions on hot rows create queues.</p><h4>3. Optimistic locking</h4><p>Read the row with a version number, and write back only if the version is unchanged (UPDATE … WHERE version = :seen). If it changed, someone else won; retry. This is great when conflicts are rare, and poor when everyone wants the same row, which is exactly the “last box of cereal on sale day” case.</p><h3>Relational vs in-memory: why Redis?</h3><p>For ordinary traffic, approach 1 on PostgreSQL is fine. The pain appears with hot items: a few SKUs are checked and reserved by thousands of customers a second. Every update to the same row must wait its turn and must also be made durable (written to the transaction log) before it is acknowledged. Row contention plus durability cost limit how many updates per second that one row can take.</p><p><strong>Redis</strong> keeps data in memory and executes commands one at a time on a single thread. A one-at-a-time executor means each command is automatically atomic, and in-memory work is fast. For multi-step logic Redis can run a <strong>Lua script</strong> as one uninterruptible unit: no other command runs in the middle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsU-gueiQ0ZUaeEDZTzZSA.png" /><figcaption>Redis answers fast; Postgres answers correctly. Events and a reconcile job keep them in agreement.</figcaption></figure><blockquote><strong><em>Watch out — What Redis does not promise</em></strong><br>Redis persistence is not the same as a database’s. A restart or failover can lose the most recent writes (replication is asynchronous by default). So treat Redis stock counters as a fast front line, publish every change as an event, keep the durable truth in the database, and run a reconcile job that re-seeds counters from it. This is a trade-off, and honest teams design for it.</blockquote><h3>Reserve, confirm, release</h3><p>A customer who is paying <em>should not lose the item mid-payment</em>, but a customer who walks away should not hold it forever. The standard pattern is a <strong>time-limited reservation:</strong></p><ul><li><strong>Reserve:</strong> atomically subtract from available stock and record a hold with an expiry time.</li><li><strong>Confirm:</strong> on successful payment, remove the hold (stock stays subtracted).</li><li><strong>Release:</strong> on failure, cancellation or expiry, add the quantity back.</li></ul><p>The Lua script below implements reserve, confirm and release. Because a Lua script must be told every key it touches, we pass three keys: the stock counter, a sorted set of holds scored by expiry time, and a hash of hold quantities.</p><p><strong>reserve.lua (Redis; not executed in the book sandbox)</strong></p><pre>-- KEYS[1] stock counter, KEYS[2] holds (zset), KEYS[3] hold qty (hash)<br>-- ARGV[1] qty, ARGV[2] hold id, ARGV[3] expiry (unix seconds)<br>local qty = tonumber(ARGV[1])<br>local stock = tonumber(redis.call(&#39;GET&#39;, KEYS[1]))<br>if stock == nil then return -1 end          -- unknown: reseed first<br>if redis.call(&#39;ZSCORE&#39;, KEYS[2], ARGV[2]) then return 2 end  -- repeat<br>if stock &lt; qty then return 0 end            -- not enough stock<br>redis.call(&#39;DECRBY&#39;, KEYS[1], qty)<br>redis.call(&#39;ZADD&#39;, KEYS[2], ARGV[3], ARGV[2])<br>redis.call(&#39;HSET&#39;, KEYS[3], ARGV[2], qty)</pre><p><strong>release.lua: cancel, failure or expiry sweep</strong></p><pre>release.lua: cancel, failure or expiry sweep<br>-- KEYS as above; ARGV[1] hold id<br>if redis.call(&#39;ZREM&#39;, KEYS[2], ARGV[1]) == 0 then return 0 end<br>local qty = tonumber(redis.call(&#39;HGET&#39;, KEYS[3], ARGV[1]))<br>redis.call(&#39;HDEL&#39;, KEYS[3], ARGV[1])<br>redis.call(&#39;INCRBY&#39;, KEYS[1], qty)<br>return 1</pre><p>Confirm is the same without the final INCRBY: remove the hold, keep the stock subtracted. A background sweeper runs every second, finds holds whose expiry score is in the past (ZRANGEBYSCORE holds -inf now) and releases each one.</p><p><strong>Calling the script with redis-py (documented API)</strong></p><pre>import time, redis<br><br>r = redis.Redis(decode_responses=True)<br>reserve = r.register_script(open(&#39;reserve.lua&#39;).read())<br><br>def reserve_stock(store, sku, order_id, qty, hold_seconds=120):<br>    tag = &#39;{%s:%s}&#39; % (store, sku)           # same hash slot in a cluster<br>    keys = [&#39;stock:&#39; + tag, &#39;holds:&#39; + tag, &#39;holdqty:&#39; + tag]<br>    expiry = int(time.time()) + hold_seconds<br>    return reserve(keys=keys, args=[qty, order_id, expiry])<br>    # 1 reserved, 0 sold out, 2 already held, -1 reseed needed</pre><p>The {store:sku} part is a hash tag: in Redis Cluster, keys sharing the text in braces land in the same slot, which is required for a script that touches several keys.</p><blockquote><strong><em>Note — Spreading a very hot key</em><br></strong>If one SKU is so hot that a single Redis key becomes the bottleneck, split its stock into several sub-counters (for example 8 buckets) and reserve from a random one, moving to the next if empty. You trade a little exactness (stock is “scattered”) for far more throughput.</blockquote><h3>Distributed locks, and their honest limits</h3><p>Sometimes you do need a lock: one worker should run a nightly job, or only one process should rebuild a cache. The common Redis recipe is a key set with a random token, only if absent, with an expiry:</p><pre>SET lock:rebuild-cache  &lt;random-token&gt;  NX  PX 30000</pre><p>NX means “<em>only if it does not exist</em>”, PX 30000 is a 30-second time-to-live. To release safely, delete the key only if it still holds your token, as one atomic script; otherwise you might delete a lock someone else now owns</p><p><strong>Safe release: compare, then delete</strong></p><pre>if redis.call(&#39;GET&#39;, KEYS[1]) == ARGV[1] then<br>  return redis.call(&#39;DEL&#39;, KEYS[1])<br>end<br>return 0</pre><p>Newer Redis releases (8.4 and later, according to the Redis documentation) add a DELEX key IFEQ value command that does the same compare-and-delete without a script.</p><p>The time-to-live exists so a crashed holder cannot block everyone forever. But it creates a famous hazard. Suppose client A takes the lock, then pauses (a long garbage-collection pause, a stalled network). The TTL expires, client B takes the lock and writes, and then A wakes up, still believing it holds the lock, and writes too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9pm15_Ko5fcyrU6Jv1O9A.png" /><figcaption>A fencing token lets the protected resource reject a stale writer, even when the lock itself failed.</figcaption></figure><p>The fix is a fencing token: the lock service hands out an increasing number with each grant, and the resource being protected remembers the highest token it has seen and refuses older ones. The sketch below proves the idea.</p><p><strong>Fencing token in a few lines (runs as is)</strong></p><pre>class Resource:<br>    def __init__(self):<br>        self.highest = 0<br>        self.value = None<br><br>    def write(self, token, value):<br>        if token &lt; self.highest:<br>            return False                 # stale writer: reject<br>        self.highest = token<br>        self.value = value<br>        return True<br><br>db = Resource()<br>print(db.write(34, &#39;from B&#39;))   # True : B holds the newest lock<br>print(db.write(33, &#39;from A&#39;))   # False: A woke up late, rejected<br>print(db.value)                 # from B</pre><p>Redis also documents a multi-server algorithm called Redlock, and well-known distributed-systems researchers have argued that it is not safe for correctness-critical work without fencing. A good rule: for inventory, prefer atomic operations (conditional updates, Lua scripts) over locks. Use locks for efficiency (avoid duplicate work) and fencing wherever a stale holder could cause real damage.</p><h3>Putting it together: the checkout flow</h3><ul><li>Customer taps pay. The service calls the reserve script for each line item (all or nothing: if any returns 0, release the ones already taken).</li><li>It creates the order, writes to the outbox, and returns “processing”.</li><li>Payment succeeds: confirm the holds, publish payment.captured. Payment fails or times out: release them, publish order.cancelled.</li><li>Consumers write the stock changes to the database ledger; a reconcile job compares counters with the ledger and fixes drift.</li></ul><h3>Chapter recap</h3><ul><li>A race condition happens when check and update are two steps. Make them one atomic step.</li><li>Prefer a conditional UPDATE in the database; use Redis Lua scripts for hot items.</li><li>Reserve, confirm, release with expiry prevents both overselling and stuck stock.</li><li>Locks need TTLs, TTLs create stale holders, and fencing tokens make stale writers harmless.</li></ul><h3>Sources and further reading</h3><h4>Source links</h4><ul><li>[1] <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/</a></li><li>[2] <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/</a></li><li>[3] <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/</a></li><li>[4] <a href="https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html">https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html</a> <a href="https://www.antirez.com/news/101">https://www.antirez.com/news/101</a></li><li>[5] <a href="https://redis.io/docs/latest/develop/programmability/eval-intro/">https://redis.io/docs/latest/develop/programmability/eval-intro/</a></li><li>[6] <a href="https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/">https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/</a></li><li>[7] <a href="https://www.postgresql.org/docs/current/explicit-locking.html">https://www.postgresql.org/docs/current/explicit-locking.html</a></li></ul><p><em>The race-condition, in-process-lock and fencing-token programs in this chapter were executed and their printed output is shown. The Lua scripts and redis-py calls follow the Redis documentation but were not run against a live Redis for this book. Not sourced facts. Statements framed as design guidance, reasoning or teaching models (for example the ten-minute budget, the break-even model and the capacity estimate) are the author’s analysis, labelled illustrative in the text. Check any number before reusing it.</em></p><h4>Further reading</h4><ul><li>Martin Kleppmann, Designing Data-Intensive Applications, chapter “The Trouble with Distributed Systems” and the section on fencing tokens</li><li>Redis documentation on persistence and replication [ ] <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/replication/">https://redis.io/docs/latest/operate/oss_and_stack/management/replication/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f125014d76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>