<?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 Varanasi Rama Krishna Parjanya on Medium]]></title>
        <description><![CDATA[Stories by Varanasi Rama Krishna Parjanya on Medium]]></description>
        <link>https://medium.com/@vramakrishnaparjanya?source=rss-d911254b31d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RgbmKFi6xBDwvHoVuFWJDw@2x.jpeg</url>
            <title>Stories by Varanasi Rama Krishna Parjanya on Medium</title>
            <link>https://medium.com/@vramakrishnaparjanya?source=rss-d911254b31d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:13:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vramakrishnaparjanya/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[Microservices using Fastapi and Redis Streams]]></title>
            <link>https://vramakrishnaparjanya.medium.com/microservices-using-fastapi-and-redis-streams-f15c09206b0e?source=rss-d911254b31d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f15c09206b0e</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[redis-stream]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Varanasi Rama Krishna Parjanya]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 15:49:29 GMT</pubDate>
            <atom:updated>2023-10-03T15:49:29.240Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://fastapi.tiangolo.com/">Fastapi</a> is a modern high performance python web framework used for building REST APIs.</p><p>Fastapi has multiple features including but not limited as below -</p><ul><li>Built in <a href="https://github.com/OAI/OpenAPI-Specification">OpenApi</a> documentation i.e. <a href="https://github.com/swagger-api/swagger-ui">Swagger</a> UI for endpoints.</li><li>Fastest python frameworks</li><li>Highly suited for microservice applications</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*0r4uvYoUCRPpQSV_.png" /></figure><p>Project Dependencies are listed below</p><pre>fastapi==0.75.0<br>redis-om==0.0.20<br>requests</pre><h3>Design Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kZFPS9X_Z4hyBR8QGZQlg.jpeg" /></figure><h3><strong>Model Classes</strong></h3><ol><li><strong>Product class</strong></li></ol><pre># Model class for Product<br>class Product(HashModel):<br>    name: str<br>    price: float<br>    quantity: int<br><br>    class Meta:<br>        database: redis</pre><p>2.<strong> Order class</strong></p><pre># Model class for Order<br>class Order(HashModel):<br>    product_id: str # mapped to Product<br>    price: float<br>    fee: float # 20% of price<br>    total: float # total = price + fee<br>    quantity: int<br>    status: str  # (&quot;PENDING&quot;, &quot;REFUNDED&quot;, &quot;COMPLETED&quot;, &quot;CANCELLED&quot;)<br><br>    class Meta:<br>        database: redis</pre><h4>1. Inventory Microservice</h4><p>This service serves the below purposes</p><ul><li>exposes REST endpoints to fetch the product info from the inventory</li></ul><pre># Fetches product by id<br>@app.get(&quot;/products/getProductById/{pk}&quot;)<br>def getProductById(pk: str):<br>    try:<br>        getProd = Product.get(pk)<br>        return getProd<br>    except Exception as e:<br>        logging.error(e)<br>        logging.error(&quot;Unable to get the product for this id&quot;)</pre><ul><li>listens to ORDER_COMPLETED_EVENT and places the order.</li><li>publishes ORDER_CANCELLED_EVENT and ORDER_REFUND_EVENT events based on conditional checks</li></ul><pre><br><br># package --&gt; inventory\inventory_consumer.py<br><br>from main import redis, Product<br>import logging, time<br><br># Logging config<br>FORMAT = &quot;%(levelname)s:\t%(message)s&quot;<br>logging.basicConfig(format=FORMAT, level=logging.INFO)<br><br><br>key = &#39;ORDER_COMPLETED_EVENT&#39;<br>group = &#39;inventory-group&#39;<br><br><br>try:<br>    redis.xgroup_create(key, group)<br>except Exception as e:<br>    logging.error(e)<br>    logging.error(&#39;Group already exists&#39;)<br><br><br><br>while True:<br>    try:<br>        results = redis.xreadgroup(group, key, {key: &#39;&gt;&#39;}, None)<br><br>        logging.info(results)<br><br>        if(results!=[]):<br>            for result in results:<br>                order_obj = result[1][0][1]<br>                logging.info(order_obj)<br>                try:<br>                    product = Product.get(order_obj[&#39;product_id&#39;])<br><br>                    if(product.quantity &gt;= int(order_obj[&#39;quantity&#39;])):<br>                        product.quantity = product.quantity - int(order_obj[&#39;quantity&#39;])<br>                        logging.info(&quot;Product == &quot;+product)<br>                        product.save()<br>                    else:<br>                        # There are not enough products in inventory so, cancel the order<br>                        logging.error(&quot;Product Quantity not sufficient !! Can&#39;t proceed !!&quot;)<br>                        <br>                        #Listener for ORDER_CANCELLED_EVENT in payment_order_cancel_consumer.py<br>                        # Publishing ORDER_CANCELLED_EVENT <br>                        redis.xadd(&#39;ORDER_CANCELLED_EVENT&#39;, order_obj, &#39;*&#39;)<br><br>                except:<br>                    #Listener for ORDER_REFUND_EVENT in payment_refund_consumer.py<br>                    # Publishing ORDER_REFUND_EVENT<br>                    redis.xadd(&#39;ORDER_REFUND_EVENT&#39;, order_obj, &#39;*&#39;)<br><br><br>    except Exception as e:<br>        logging.error(e)<br>    <br>    time.sleep(1)<br><br></pre><h4>2. <strong>Payment Microservice</strong></h4><p>This microservice serves below purposes</p><ul><li>exposes REST end point to place the order (calls the inventory endpoint to fetch the product info with the key)</li></ul><pre><br># create an order<br><br>@app.post(&#39;/orders/placeOrder&#39;)<br>async def createOrder(request: Request, background_tasks: BackgroundTasks):<br><br>    requestBody = await request.json()<br>    product_key = requestBody[&quot;id&quot;]<br>    product_quantity = requestBody[&quot;quantity&quot;]<br><br>    logging.info(&quot;Product Key is == &quot;+str(product_key))<br>    url = &#39;http://127.0.0.1:8000/products/getProductById/&#39;+str(product_key)<br>    logging.info(&quot;Inventory endpoint hit ==&quot;+url)<br><br><br>    # Fetch product response from Inventory<br>    try:<br>        inventory_response = requests.get(url)<br>        logging.info(&quot;Response received from inventory ==&quot;+str(inventory_response.json()))<br>    except Exception as e:<br>        logging.error(e)<br><br>    inventory_product = inventory_response.json()<br><br>    order = Order(<br>        product_id= product_key,<br>        price= inventory_product[&#39;price&#39;],<br>        fee= 0.2 * inventory_product[&#39;price&#39;],<br>        total= 1.2 * inventory_product[&#39;price&#39;],<br>        quantity= product_quantity,<br>        status=&#39;PENDING&#39;<br>    )<br><br>    <br>    try:<br>        # Save order<br>        order.save()<br>        <br>        # BackgroundTasks creates a separate thread --&gt; Callable interface<br>        background_tasks.add_task(order_completed, order)<br>        <br>        logging.info(&quot;Order saved successfully for the product == &quot;+requestBody[&#39;id&#39;])<br>        return order<br>    <br>    except Exception as e:<br>        logging.error(e)<br>        logging.error(&quot;Could not save the order&quot;)</pre><ul><li>listens to the ORDER_REFUND_EVENT and updates order status to “<strong>REFUNDED</strong>”</li></ul><pre>from main import redis, Order<br>import logging, time<br><br># Logging config<br>FORMAT = &quot;%(levelname)s:\t%(message)s&quot;<br>logging.basicConfig(format=FORMAT, level=logging.INFO)<br><br><br>key = &#39;ORDER_REFUND_EVENT&#39;<br>group = &#39;payment-refund-group&#39;<br><br><br>try:<br>    redis.xgroup_create(key, group)<br>except Exception as e:<br>    logging.error(e)<br>    logging.error(&#39;Group already exists&#39;)<br><br>while True:<br>    try:<br>        results = redis.xreadgroup(group, key, {key: &#39;&gt;&#39;}, None)<br><br>        print(results)<br>        <br>        if results != []:<br>            logging.info(&quot;Payment Refund Results == &quot;+str(results))<br>            for result in results:<br>                obj = result[1][0][1]<br>                order = Order.get(obj[&#39;pk&#39;])<br>                order.status = &#39;REFUNDED&#39;<br>                order.save()<br><br>    except Exception as e:<br>        logging.error(e)<br>        <br>    time.sleep(1)<br><br></pre><ul><li>listens to the ORDER_CANCELLED_EVENT and deletes the order</li></ul><pre>from main import redis, Order<br>import logging, time, requests<br><br># Logging config<br>FORMAT = &quot;%(levelname)s:\t%(message)s&quot;<br>logging.basicConfig(format=FORMAT, level=logging.INFO)<br><br><br>key = &#39;ORDER_CANCELLED_EVENT&#39;<br>group = &#39;payment-order-cancelled-group&#39;<br><br><br>try:<br>    logging.info(&quot;Trying to create a payment-order-cancel-group&quot;)<br>    redis.xgroup_create(key, group)<br>except Exception as e:<br>    logging.error(e)<br>    logging.error(&#39;Group already exists&#39;)<br><br>while True:<br>    try:<br>        results = redis.xreadgroup(group, key, {key: &#39;&gt;&#39;}, None)<br>        logging.info(&quot;Results are as below&quot;)<br>        logging.info(results)<br>        logging.info(len(results))<br><br>        if(results!=[]):<br>            for result in results:<br>                logging.info(result)<br>                order_obj = result[1][0][1]<br>                logging.info(order_obj)<br><br>                order_pk = order_obj[&#39;pk&#39;]<br>                logging.info(order_pk)<br><br>                delete_order_url = &#39;http://127.0.0.1:8001/orders/deleteOrderByOrderPk/&#39;+str(order_pk)<br><br>                delete_order_response = requests.get(delete_order_url)<br>                logging.info(&quot;Response received from delete order URL ==&quot;+str(delete_order_response.json()))<br>            <br>    except Exception as e:<br>        logging.error(e)<br>        <br>    time.sleep(1)<br></pre><h3><strong>Outputs</strong></h3><ol><li>Created a Product in Inventory</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTpyyDoFP4pLHXzW7rXAPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2IbaKq2qx_tjcZ1Q6yNbg.png" /></figure><p>2. Placing an order for 100 products in Payment</p><p>Initial status stays in “<strong>PENDING”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etjZueTYTHpfVVzL6jdT3Q.png" /></figure><p>Order status changes to “<strong>COMPLETED”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-YcOIR-a2ms8GgXg9YR9w.png" /></figure><p>3. ORDER_COMPLETED_EVENT is published and the order quantity is subtracted from the inventory quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWbaYA7O2okcnZKYsBIwlw.png" /></figure><p>Product quantity is reduced by the order quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPn-fN89QF7GbFZELHHcnw.png" /></figure><p>4. If the order placing fails, ORDER_REFUND_EVENT is published and the order is marked REFUNDED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaygnPxcu_UUB1vtR738rQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWxu2D7s9uz8kJdC72NWnA.png" /></figure><h3><strong>References</strong></h3><ul><li>GitHub — <a href="https://github.com/vramakrishnaparjanya/microservices-with-fastapi">https://github.com/vramakrishnaparjanya/microservices-with-fastapi</a></li><li>Fastapi guide — <a href="https://fastapi.tiangolo.com/tutorial/">https://fastapi.tiangolo.com/tutorial/</a></li><li>Redis Streams — <a href="https://redis.io/docs/data-types/streams/">https://redis.io/docs/data-types/streams/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f15c09206b0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>