<?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 Nanda Gopal Pattanayak on Medium]]></title>
        <description><![CDATA[Stories by Nanda Gopal Pattanayak on Medium]]></description>
        <link>https://medium.com/@nandagopal05?source=rss-b7dc56f07e24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z0Li8M_RARpXtYtcfXaGtw.png</url>
            <title>Stories by Nanda Gopal Pattanayak on Medium</title>
            <link>https://medium.com/@nandagopal05?source=rss-b7dc56f07e24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:12:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandagopal05/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[Function Calling with OpenAI APIs: Getting Started]]></title>
            <link>https://ai.plainenglish.io/function-calling-with-openai-apis-getting-started-45905922c2fc?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/45905922c2fc</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 22:59:03 GMT</pubDate>
            <atom:updated>2025-09-30T13:11:04.943Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll break down how function calling works in OpenAI’s models using Python. Function calling lets the LLM choose to ask to run a function or tool, when a user asks for something and it have related additional tool available to get additional context on that topic. We’ll cover everything step by step — from setup, creating functions, connecting tools, to handling the results.</p><blockquote>Function calling (also known as tool calling) provides a powerful and flexible way for OpenAI models to interface with external systems and access data outside their training data.</blockquote><h3>The tool calling flow</h3><p>Tool calling is a multi-step conversation between your application and a model via the OpenAI API. The tool calling flow has five high level steps:</p><ol><li>Make a request to the model with tools it could call</li><li>Receive a tool call from the model</li><li>Execute code on the application side with input from the tool call</li><li>Make a second request to the model with the tool output</li><li>Receive a final response from the model (or more tool calls)</li></ol><p><strong>Step-1:</strong></p><p><strong>Create a OpenAI API</strong></p><pre>import json<br>from dotenv import load_dotenv<br>from openai import OpenAI<br><br>load_dotenv()<br><br>#create the openAI client<br>client = OpenAI()</pre><p><strong>Step-2:</strong></p><p>Define a list of functions which will act essentially as tools and give the llm with additional context or info</p><pre>def get_weather(location: str, unit: str = &quot;celsius&quot;):<br>    &quot;&quot;&quot;Mock weather lookup&quot;&quot;&quot;<br>    data = {<br>        &quot;chennai&quot;: 33,<br>        &quot;delhi&quot;: 29,<br>        &quot;mumbai&quot;: 30,<br>    }<br>    return {<br>        &quot;location&quot;: location,<br>        &quot;temperature&quot;: data.get(location.lower(), 25),<br>        &quot;unit&quot;: unit,<br>    }<br><br>def get_time(city: str):<br>    &quot;&quot;&quot;Mock time lookup&quot;&quot;&quot;<br>    times = {<br>        &quot;chennai&quot;: &quot;2025-09-24 18:30&quot;,<br>        &quot;delhi&quot;: &quot;2025-09-24 18:00&quot;,<br>        &quot;london&quot;: &quot;2025-09-24 14:00&quot;,<br>    }<br>    return {&quot;city&quot;: city, &quot;time&quot;: times.get(city.lower(), &quot;2025-09-24 12:00&quot;)}<br><br>def calculator(expression: str):<br>    &quot;&quot;&quot;Simple math calculator&quot;&quot;&quot;<br>    return {&quot;expression&quot;: expression, &quot;result&quot;: eval(expression)}<br></pre><p>Step-3: Create a detailed structure of the function definition, parameters, type of parameters, constraints etc so the model can understand better about the function requirements &amp; thus provide the output correctly.</p><pre>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;get_weather&quot;,<br>            &quot;description&quot;: &quot;Get the current weather in a location&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;location&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;unit&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;celsius&quot;, &quot;fahrenheit&quot;]},<br>                },<br>                &quot;required&quot;: [&quot;location&quot;],<br>            },<br>        },<br>    },<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;get_time&quot;,<br>            &quot;description&quot;: &quot;Get the current time in a given city&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {&quot;city&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                &quot;required&quot;: [&quot;city&quot;],<br>            },<br>        },<br>    },<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;calculator&quot;,<br>            &quot;description&quot;: &quot;Calculate the result of a mathematical expression&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;expression&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                },<br>                &quot;required&quot;: [&quot;expression&quot;],<br>            },<br>        },<br>    },<br>]<br><br># Tool registry<br>tool_registry = {<br>    &quot;get_weather&quot;: get_weather,<br>    &quot;get_time&quot;: get_time,<br>    &quot;calculator&quot;: calculator,<br>}</pre><p>Step-4: Invoke the chat completion API with the user question. To test the function calling, we will ask a question where the model will need an tool or require additional info from external source to answer.</p><p>As we can see in the Modle output, the model responds with a empty content but it contains a array of tool calls. It gives us the name of the function &amp; the parameters which the function needs.</p><pre>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Whats the current weather in Chennai?&quot;}<br>]<br><br>response = client.chat.completions.create(<br>    model=&quot;gpt-4.1-nano&quot;,<br>    messages=messages,<br>    tools=tools,<br>    tool_choice=&quot;auto&quot;<br>)<br><br>message = response.choices[0].message<br>print(&quot;Model output:&quot;, message)</pre><blockquote><strong><em>Model output: ChatCompletionMessage(content=None, refusal=None, role=’assistant’, annotations=[], audio=None, function_call=None, tool_calls=[ChatCompletionMessageFunctionToolCall(id=’call_XNR1KYaP9ceRmgroki0lLfYb’, function=Function(arguments=’{“location”:”Chennai”}’, name=’get_weather’), type=’function’)])</em></strong></blockquote><p>Step-5:</p><p>Once we receive the tool calls details from LLM response in the first step, from here on, we need to execute the function in our app, get the response or content from the tool &amp; invoke the LLM again with the extra context form tool output. In the entire step, while invoking the LLM with the tool output, its important to make sure that we give the LLM the original user query, the first llm response of tool call request &amp; finally the tool output.</p><pre><br><br># Handle tool calls dynamically<br>if message.tool_calls:<br>    for tool_call in message.tool_calls:<br>        tool_name = tool_call.function.name<br>        params = json.loads(tool_call.function.arguments)<br><br>        func = tool_registry.get(tool_name)<br>        if func:<br>            result = func(**params)<br>        else:<br>            result = {&quot;error&quot;: f&quot;Unknown tool: {tool_name}&quot;}<br><br>        # Send back to model<br>        messages.append(message)<br>        messages.append(<br>            {&quot;role&quot;: &quot;tool&quot;, &quot;tool_call_id&quot;: tool_call.id, &quot;content&quot;: json.dumps(result)}<br>        )<br><br>        final_response = client.chat.completions.create(<br>            model=&quot;gpt-4.1-mini&quot;,<br>            messages=messages,<br>        )<br>        print(&quot;Final Answer:&quot;, final_response.choices[0].message.content)<br>else:<br>    print(&quot;LLM reply:&quot;, message.content)</pre><blockquote><strong>Final Answer: The current temperature in Chennai is 33°C. If you’d like more details about the weather, just let me know!</strong></blockquote><p>Once the model receives the additional context form the tool, it will provide the response accordingly considering all the previous message of user request, tool call response &amp; tool output.</p><p><em>Here for models awareness, I ahve provided the role as ‘tool’ but it’s not a real role. We can provide in other altervative ways like below as well. This is for model’s awareness that the content being passed is an output of the tool call request received in the previous step.</em></p><pre># 4. Provide function call results to the model<br>input_list.append({<br>    &quot;type&quot;: &quot;function_call_output&quot;,<br>    &quot;call_id&quot;: item.call_id,<br>    &quot;content&quot;: tool_output<br>})</pre><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45905922c2fc" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/function-calling-with-openai-apis-getting-started-45905922c2fc">Function Calling with OpenAI APIs: Getting Started</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Annotations in Python is a must thing!]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nandagopal05/type-annotations-in-python-is-a-must-thing-de059cdba971?source=rss-b7dc56f07e24------2"><img src="https://cdn-images-1.medium.com/max/1242/1*YU7ZT3Fjuav7hFtJ5yWMpw.png" width="1242"></a></p><p class="medium-feed-snippet">Yes, you&#x2019;re absolutely right! Python&#x2019;s dynamic nature allows for a lot of flexibility, but it also means that without type hints, it can&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@nandagopal05/type-annotations-in-python-is-a-must-thing-de059cdba971?source=rss-b7dc56f07e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nandagopal05/type-annotations-in-python-is-a-must-thing-de059cdba971?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/de059cdba971</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 06:06:30 GMT</pubDate>
            <atom:updated>2024-09-13T06:06:30.047Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[FastAPI vs Django: Async capabilities]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nandagopal05/fastapi-vs-django-async-capabilities-98833de01bd0?source=rss-b7dc56f07e24------2"><img src="https://cdn-images-1.medium.com/max/1920/0*3Tc9w-Yo2tHYWeSj.png" width="1920"></a></p><p class="medium-feed-snippet">Synchronous programming executes tasks sequentially, whereas async allows it tasks to run concurrently Instead of waiting for a task to&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@nandagopal05/fastapi-vs-django-async-capabilities-98833de01bd0?source=rss-b7dc56f07e24------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nandagopal05/fastapi-vs-django-async-capabilities-98833de01bd0?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/98833de01bd0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[fasting]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 18:58:54 GMT</pubDate>
            <atom:updated>2024-08-16T18:58:54.322Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Deploy Django project with Nginx, Gunicorn & Docker to production]]></title>
            <link>https://medium.com/@nandagopal05/deploy-django-project-with-nginx-gunicorn-docker-to-production-b4368a2fefff?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4368a2fefff</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 04:32:36 GMT</pubDate>
            <atom:updated>2024-06-20T04:32:36.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*Eod2BZmqEjKNNgffaoU_MA.png" /></figure><p>Picture this: I’d just built an amazing Django application, and it was running perfectly on my local machine. But deploying it to production? That was the next big challenge. After some research and trial and error, I found a reliable method using Nginx, Gunicorn, and Docker.</p><p>In this article, I’ll share the process I followed to get my Django project production-ready. Gunicorn handles the application server, Nginx acts as the reverse proxy, and Docker ensures consistent deployment.</p><p>Join me as I walk you through the steps I took. Whether you’re looking to refine your deployment strategy or just curious, I hope my experience will provide you with useful insights. Let’s turn that local masterpiece into a live, production-ready application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*buOhPtQ67evqtiAYiVMUrA.png" /><figcaption>Project folder structure</figcaption></figure><p>So here I will be using multiple Dockerfile’s for each different components like Django, nginx etc. If you have any other service like database, redis etc then those can be added. But since in most of the cases database like service will be separate from the actual project so here I have just used an sqlite database with the project for demonstration.</p><blockquote>Starting with <strong>Dockerfile</strong> for the <strong>Django project</strong> —</blockquote><pre># First stage: build the Python app<br>FROM python:3.11.9-bookworm AS build<br><br># install dependencies<br>COPY ./requirements.txt .<br>RUN pip install --upgrade pip<br>RUN pip install -r requirements.txt<br><br># copy project source code<br>COPY ./ecommerce_project /ecommerce_project<br><br># set working directory<br>WORKDIR /ecommerce_project<br><br># entrypoint shell scripts to be executed<br>COPY ./entrypoint.sh /<br>ENTRYPOINT [&quot;sh&quot;, &quot;/entrypoint.sh&quot;]</pre><p>Each of the above commands are self explanatory. Starting with taking the python layer from an official python base image we proceed on to copying our codes to the docker image, installing dependencies, setting an working directory and then defining an entrypoint script where we will be adding any commands that needs to be executed part of the build process.</p><blockquote><strong>entrypoint.sh</strong> file for the Django project —</blockquote><pre>#!/bin/sh<br><br># collect all static files to the root directory<br>python manage.py collectstatic --no-input<br><br># start the gunicorn worker processws at the defined port<br>gunicorn ecommerce_project.wsgi:application --bind 0.0.0.0:8000 &amp;<br><br>wait</pre><p>In the above code, here I am collecting all the static files using the collectstatic method and then starting the gunicorn worker processes at 8000 port number. If anything custom work needs to be taken care of that can be handled here like applying migrations to the database etc.</p><ul><li>&amp; places the gunicorn command in the background, allowing the terminal to accept new commands while it runs.</li><li>wait pauses the execution of the script until all background jobs are finished.</li></ul><h3>Nginx setup</h3><blockquote>Starting with <strong>configuration </strong>file<strong> </strong>for <strong>Nginx</strong></blockquote><pre>upstream django {<br> server django_ecommerce_project:8000;<br>}<br><br>server {<br> listen 80;<br><br> location / {<br>  proxy_pass http://django;<br> }<br><br> location /static/ {<br>  alias /static/;<br> }<br>}</pre><p>Here this is a standard nginx configuration file where I have defined the listening port to be 80 which will be changed after adding SSL certificate to it. All the requests will be proxied to the upstream server at <strong><em>django_ecommerce_project:8000</em></strong> which we will define as a service in docker-compose later on. And if any request path contains the <strong>/static/</strong> path then it will be served from the static directory which we will be mounting as a volume shortly.</p><blockquote><strong>Dockerfile</strong> for <strong>nginx</strong></blockquote><pre># Second stage: build the Nginx server<br>FROM nginx:1.23-alpine<br><br># Copying our .conf files<br>COPY ./default.conf /etc/nginx/conf.d/default.conf <br><br># remove the log files in order to remove symlink between nginx logs &amp; container log paths to ensure logs are available in default nginx log path<br>RUN rm -f /var/log/nginx/* </pre><p>Similar to the Dockerfile for Django project, here also I are starting from an base template of nginx from their official registry. Then I am copying the configuration file to <strong>/etc/nginx/conf.d/</strong> which then can be used by nginx. One thing to note is that in nginx docker images, the log files have a symlink to standard container logs at <strong>/dev/stdout</strong> or <strong>/dev/stderr</strong>. But in my case as I wanted the logs to be available at their original log path, so i have initially removed the files in order to remove the symlink so I will be ale to access the logs at <strong>/var/log/nginx/</strong></p><blockquote><strong>docker-compose.yml </strong>setup</blockquote><pre>services:<br>  django_ecommerce_project:<br>    volumes:<br>      - static:/static<br>      - sqllite_db:/ecommerce_project/db<br>      - django_logs:/logs<br>    build:<br>      context: .<br>    expose:<br>      - 8000<br>    restart: always<br>    <br>  nginx:<br>    build: ./nginx<br>    volumes:<br>      - static:/static #this is to make sure /static requests are routed to the shared volumne on host machine where django static files are stored<br>      - nginx_logs:/var/log/nginx<br>    ports:<br>      - &quot;8000:80&quot;<br>    depends_on:<br>      - django_ecommerce_project<br>    restart: always<br><br>volumes:<br>  static:<br>  sqllite_db:<br>  django_logs:<br>  nginx_logs:</pre><p>This Docker Compose file defines a multi-service setup for ourDjango eCommerce project and Nginx server.</p><blockquote><strong><em>django_ecommerce_project:</em></strong></blockquote><p><strong>volumes</strong>:</p><ul><li>static:/static: Mounts a volume named static to the /static directory, ensuring that static files are stored persistently even after container is terminated/deleted and files will be available in our host machine.</li><li>sqllite_db:/ecommerce_project/db: Mounts a volume named sqllite_db to the /ecommerce_project/db directory for persistent database storage.</li><li>django_logs:/logs: Mounts a volume named django_logs to the /logs directory to store logs persistently.</li></ul><p><strong>build</strong>:</p><ul><li><strong>context</strong>: .: Builds the Docker image from the Dockerfile available in current directory.</li></ul><p><strong>expose</strong>:</p><ul><li>8000: Exposes port 8000 to other services in the internal Docker network (not to the host) or outside docker network.</li><li><strong>restart</strong>: always: Ensures the container always restarts if it stops or if the Docker daemon restarts.</li></ul><blockquote><strong>nginx</strong>:</blockquote><p><strong>build</strong>:</p><ul><li><strong>context</strong>: ./nginx: Builds the Docker image from the Dockerfile available in ./nginx directory.</li></ul><p><strong>volumes</strong>:</p><ul><li>static:/static: Shares the static volume with the Django service to serve static files.</li><li>nginx_logs:/var/log/nginx: Mounts a named volume nginx_logs to the /var/log/nginx directory for persistent log storage. By default nginx logs are moved to docker logs which we have removed beforehand.</li></ul><p><strong>ports</strong>:</p><ul><li>&quot;8000:80&quot;: Maps port 8000 on the host to port 80 on the container, making the service accessible via <a href="http://localhost:8000.">http://localhost:8000.</a></li></ul><p><strong>depends_on</strong>:</p><p>django_ecommerce_project: Ensures the Nginx service starts after the Django service.</p><p><strong>restart</strong>: always: Ensures the container always restarts if it stops or if the Docker daemon restarts.</p><p><strong>Volumes</strong>:</p><ul><li>static: A named volume to persist and share static files between services.</li><li>sqllite_db: A named volume to persist the SQLite database.</li><li>django_logs: A named volume to persist Django logs.</li><li>nginx_logs: A named volume to persist Nginx logs.</li></ul><p>This setup ensures a robust and persistent environment for the Django eCommerce project, with Nginx serving static files and acting as a reverse proxy.</p><h3>Building and Running Your Docker Containers</h3><p>Once we’ve configured our Docker Compose file for project, we can follow these steps to build and run our containers:</p><pre>docker-compose build #command to build the images for both the Django and Nginx services<br><br>docker-compose up -d # Start the containers in the background using the up command with the -d flag<br><br>docker-compose ps #Check the status of the running containers to ensure everything is working correctly</pre><p>Let’s open a web browser and navigate to http://localhost:8000 to access our Django eCommerce application served by Nginx.</p><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4368a2fefff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Sent Events with Python FastAPI]]></title>
            <link>https://medium.com/@nandagopal05/server-sent-events-with-python-fastapi-f1960e0c8e4b?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1960e0c8e4b</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 04:32:07 GMT</pubDate>
            <atom:updated>2024-03-09T04:32:07.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68Y0uhRbppf9Gcrxn3HEGw.png" /><figcaption>SSE communication model</figcaption></figure><p>Many times when we have a requirement to send continuous stream of data from sever to the client we have majorly three options available of which are pooling the data at the client side, web-sockets or server-sent events(SSE). Each one of them have its own pros &amp; cons. Pooling can put unnecessary load on server when there is no data to be sent whereas websockets can be harder to scale &amp; at the same time SSE is unidirectional from server to client only.</p><blockquote>SSE in a nutshell —</blockquote><ol><li>It is unidirectional in nature meaning only server can send data to frontend unlike traditional request-response architecture, where the client can send the data &amp; receives response from server.</li><li>SSE is a pure text based protocol where everything is transfered in pure text format ending with new line indicator(<strong><em>\n\n</em></strong>) to distinguish between new events. Every message can be segregated into different type of events according to which the client can consume the message appropriately.</li><li>SSE includes automatic reconnection mechanisms, so if the connection is lost, the client will attempt to reconnect to the server without requiring explicit intervention.</li></ol><h4>Use cases —</h4><ol><li>displaying live log information in frontend as new logs created in backend</li><li>updating live locations of tracking objects in frontend by getting the updated coordinates from backend</li><li>Updating informations or graphs on real time basis on dashboards</li></ol><h4>Backend implementation in <strong>FastAPI —</strong></h4><p>Below I have a simple JSON file from which every 1 second I want to stream one coordinate to the client using FastAPI.</p><pre>[<br>    {<br>        &quot;lat&quot;: 22.09769,<br>        &quot;lng&quot;: 87.24068<br>    },<br>    {<br>        &quot;lat&quot;: 22.09776,<br>        &quot;lng&quot;: 87.24075<br>    },<br>    {<br>        &quot;lat&quot;: 22.09784,<br>        &quot;lng&quot;: 87.24082<br>    },<br>    {<br>        &quot;lat&quot;: 22.09811,<br>        &quot;lng&quot;: 87.24098<br>    }<br>]</pre><pre>from fastapi import FastAPI, Response<br>from fastapi.responses import StreamingResponse<br>from fastapi.middleware.cors import CORSMiddleware<br>import json, uvicorn<br>from asyncio import sleep<br><br>app = FastAPI()<br><br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>async def waypoints_generator():<br>    waypoints = open(&#39;waypoints.json&#39;)<br>    waypoints = json.load(waypoints)<br>    for waypoint in waypoints[0: 10]:<br>        data = json.dumps(waypoint)<br>        yield f&quot;event: locationUpdate\ndata: {data}\n\n&quot;<br>        await sleep(1)<br><br>@app.get(&quot;/get-waypoints&quot;)<br>async def root():<br>    return StreamingResponse(waypoints_generator(), media_type=&quot;text/event-stream&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;127.0.0.1&quot;, port=8000)</pre><p>Here I have a generator function waypoints_generator() which yields a response of one coordinate from the JSON file every 1 second which is then streamed to the client side.</p><blockquote>Two things to consider majorly here is that, in order to identify as an SSE response, the content type of the response should be <strong><em>“text/event-stream”</em></strong> and every response should end with <strong><em>\n\n</em></strong> as the response of SSE is always a pure text, so to identify response properly this distinction is a must.</blockquote><p>I have used the StreamingResponse response type from FastAPI here which takes an generator function as an argument to stream the output in batches instead of a single response.</p><p>Since the response is a text response, so every event in the response should be separated by a new line of <strong><em>\n. </em></strong>There should be minimum one event for e.g a default event of <strong><em>data</em></strong> can be made available.</p><h4>FrontEnd —</h4><p>To work with server-sent events JS have the EventSource API for it.</p><p>The EventSource interface is web content&#39;s interface to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events">server-sent events</a>.</p><p>An EventSource instance opens a persistent connection to an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP">HTTP</a> server, which sends <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events">events</a> in text/event-stream format. The connection remains open until closed by calling <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close">EventSource.close()</a>.</p><p>Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event">message</a> event is fired.</p><p>Here I am just updating the received coordinates part of the SSE response into an HTML doc.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;<br>    &lt;title&gt;Live Vehicle Coordinates&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;div id=&quot;coordinates-container&quot;&gt;<br>        &lt;h2&gt;Live Vehicle Coordinates&lt;/h2&gt;<br>        &lt;div id=&quot;coordinates&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/html&gt;</pre><pre>const coordinatesElement = document.getElementById(&#39;coordinates&#39;);<br>let coords;<br><br>// Create EventSource for SSE endpoint<br>const eventSource = new EventSource(&#39;http://127.0.0.1:8000/get-waypoints&#39;);<br><br>eventSource.onopen = () =&gt; {<br>    console.log(&#39;EventSource connected&#39;)<br>    //Everytime the connection gets extablished clearing the previous data from UI<br>    coordinatesElement.innerText = &#39;&#39;<br>}<br><br>//eventSource can have event listeners based on the type of event.<br>//Bydefault for message type of event it have the onmessage method which can be used directly or this same can be achieved through explicit eventlisteners<br>eventSource.addEventListener(&#39;locationUpdate&#39;, function (event) {<br>    coords = JSON.parse(event.data);<br>    console.log(&#39;LocationUpdate&#39;, coords);<br>    updateCoordinates(coords)<br>});<br><br>//In case of any error, if eventSource is not closed explicitely then client will retry the connection a new call to backend will happen and the cycle will go on.<br>eventSource.onerror = (error) =&gt; {<br>    console.error(&#39;EventSource failed&#39;, error)<br>    eventSource.close()<br>}<br><br>// Function to update and display coordinates<br>function updateCoordinates(coordinates) {<br>    // Create a new paragraph element for each coordinate and append it<br>    const paragraph = document.createElement(&#39;p&#39;);<br>    paragraph.textContent = `Latitude: ${coordinates.lat}, Longitude: ${coordinates.lng}`;<br>    coordinatesElement.appendChild(paragraph);<br>}</pre><p>After creating the eventSource object, we can attach various eventListeners on the object based on the event on which we want to subscribe to. If no event is available, a generic onmessage method can be used to get the response.</p><blockquote>Note — In case of any error or the server closing the connection after the response if completed, the client will auto retry and connect to server once again and the loop will continue. So in case of error, it can be handled and if required the eventSource needs to be closed explicitly to avoid retry.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sx31OlqmFjnh3I64GNORqw.png" /><figcaption>Sample response image from PostMan</figcaption></figure><p>In case of SSE, browsers always try to keep the connection alive by retrying the connection in case of any failures, connection clousures form server or intermittent network issues etc. At the same time when browser gets closed the server can also close the connection thus by saving resource. The retry interval can be set from server side by using the retry event keyword.</p><p>The full source code can be found here — <a href="https://github.com/NandaGopal56/server-sent-events-fastapi.git">https://github.com/NandaGopal56/server-sent-events-fastapi.git</a></p><h4>Conclusion —</h4><p>SSE is a very good protocol for use cases where unidirectional communication is required thus by avoiding more resource heavy protocols like web-sockets. But through unit testing is key to achieving the best results.</p><h4><strong>resources —</strong></h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource - Web APIs | MDN</a></p><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1960e0c8e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Live Streaming(HLS) — getting started for Seamless Video Delivery]]></title>
            <link>https://medium.com/@nandagopal05/http-live-streaming-hls-getting-started-for-seamless-video-delivery-12a7224d2ac2?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a7224d2ac2</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[hls]]></category>
            <category><![CDATA[http-live-streaming]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 00:07:55 GMT</pubDate>
            <atom:updated>2023-10-14T00:09:29.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTTP Live Streaming(HLS) — Getting started for Seamless Video Delivery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kCN0uedMEnIlJksyYTiFQ.jpeg" /></figure><p>In the past, streaming videos online posed significant challenges. If a video source was in high definition (HD), the output quality would remain the same, irrespective of the viewer’s internet speed. Due to the large source file size, it was often impossible to stream these videos on low-bandwidth networks, such as 2G. This used to get us frustrated especially with slow internet and was a horrible experience. Usually to get some resource from server there are two ways. The first one is to download the entire resource as a whole while the alternative way will be to segment it into smaller chunks and download as per requirement. This makes sense especially in the case of video files since downloading the whole file is completely unnecessary.</p><p>Apple in 2009 came to our rescue with HTTP Live Streaming(HLS) protocol. Now this is the mainly used protocol for Apple devices while there is another protocol available as DASH. But HLS has a very wide support to start with.</p><p><strong><em>So HLS basically contains two types of file.</em></strong></p><ol><li>.m3u8 manifest file — this file contains a list of URLs or references to the segmented/chunked media files and specifies the order in which these files should be played with some other metadatas.</li><li>.ts file — this will be the actual video segment file. There will be multiple such .ts video chunks which will be created from the main video file</li></ol><p><strong><em>So how does HLS work ?</em></strong></p><ol><li>First a client requests the manifest (.m3u8) file which will be containing the references to the individual chunks in order.</li><li>The client will start requesting for each individual .ts video chunks one after another to load and buffer the content. Now this step is completely upto the client side requirement as how to handle it. For a scenario where a user skipped some part of the video, the client should be smart enough to skip those video chunks and start from the time where its required.</li></ol><p>The main advantage of this is since its based on HTTP and file sizes are also small now, it can be cached easily for better user experience.</p><pre>#EXTM3U<br>#EXT-X-VERSION:3<br>#EXT-X-TARGETDURATION:2<br>#EXT-X-MEDIA-SEQUENCE:0<br>#EXT-X-PLAYLIST-TYPE:VOD<br>#EXTINF:1.920000,<br>segment_0.ts<br>#EXTINF:1.920000,<br>segment_1.ts<br>#EXTINF:1.040000,<br>segment_2.ts<br>#EXT-X-ENDLIST</pre><p>The above is a sample manifest file. It&#39;s pretty straight forward. all the references with .ts are for video chunks while EXTINF contains the duration info with other tags containg some additional meta data about the video.</p><p>We can use some online HLS player like <a href="https://livepush.io/hls-player/index.html">https://livepush.io/hls-player/index.html</a> or create a basic player from scratch using hls.js to test if everything is working out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tE5WC8oP_jSo3_IhJMsE8A.png" /><figcaption>HLS player</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiGmqU-Dhvb3PrgySsJfqw.png" /><figcaption>HLS files</figcaption></figure><p>Here since I am using an online video player, so I uploaded the manifest and .ts files to s3 bucket with CORS enabled so it can be loaded cross domain. Now if everything is good then the video will start playing. But wait, you will see only one video resolution here unlike multiple resolution which we are used to. Now that&#39;s a different topic called Adaptive bitrate streaming(ABR). HLS is always used in conjunction with ABR for better user experience. We will explore this topic some different article.</p><p><strong><em>How to create the HLS files ?</em></strong></p><p>Well, we can use the ffmpeg tool to create the hls files.</p><pre>ffmpeg -i foo.mp4 -codec copy -vbsf h264_mp4toannexb \<br>-map 0 -f segment \<br>-segment_list out_720.m3u8 \<br>-segment_time 2 out_720%03d.ts</pre><p>The above code is a simple example which will accept a video and convert to HLS format. here segment_time is the parameter based on which the duration of each segment will be decided.</p><p>Once everything is ready we can set up a local test server and client to test the files or like me simply upload to an online storage from where we can easily access it and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KENtWtUOWOgcGjUeGtPtNA.png" /></figure><p>Now we can verify this by going to the network tab of the browser. As we can see here once the manifest file is loaded the vidoe chunks will be loaded one by one as per requirement only. Now this becomes very efficient instead of downloading the whole file at once.</p><blockquote><strong>So what&#39;s HLS vs ABR then ?</strong></blockquote><p>In typical video streaming scenarios, the client dynamically assesses the device’s internet bandwidth and selects the most suitable video resolution for streaming. When producing content for HTTP Live Streaming (HLS), a common practice involves creating multiple versions of manifest and video chunks tailored for various resolution levels. These individual manifest files, in turn, are consolidated into a single master manifest file, which serves as the point of reference for all the different resolution options. This approach enables adaptive streaming, ensuring viewers receive the best possible quality based on their network conditions.</p><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a7224d2ac2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling WebSockets with PUB/SUB using Python, Redis & FastAPI]]></title>
            <link>https://medium.com/@nandagopal05/scaling-websockets-with-pub-sub-using-python-redis-fastapi-b16392ffe291?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16392ffe291</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 21:25:01 GMT</pubDate>
            <atom:updated>2023-07-08T21:25:01.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*_z59yp8dPJnWv2vV3KoT5Q.png" /><figcaption>Architecture design of pub/sub with websocket</figcaption></figure><p>WebSocket is a communication protocol that provides full-duplex communication between a client (typically a web browser) and a server over a single, long-lived connection and this means the connection remains open for the entire duration that the client is connected to server. Unlike traditional HTTP requests, which follow a request-response model, WebSockets allow for real-time, bidirectional communication, enabling efficient and interactive web applications and unlike HTTP requests WebSockets are stateful which makes it harder for Horizontal scaling.</p><p>In the context of WebSockets, Vertical scaling can help to handle a larger number of WebSocket connections on a single server and improve overall performance with increasing number of memory &amp; processing power. However, there are practical limits to vertical scaling, and at some point, the cost and performance gains may not justify further vertical expansion. With Horizontal scaling we have to distribute the WebSocket connections across multiple servers to improve performance, handle a larger number of concurrent connections, and ensure high availability. Load balancers are typically used to evenly distribute incoming WebSocket connections across the available server instances. However, horizontal scaling of WebSocket applications can be challenging due to the stateful nature of connections and the need to synchronize and manage state across multiple servers. This is where we can leverage the power of PUB/SUB systems to manage state between multiple server instances.</p><p>Lets consider a app like Google docs where we have two users connected to a server server1. Here whenever there is some new change log available, we can publish the data to all the connected users by creating a channel with a <strong><em>unique identifier for the document</em></strong> to which all of our users will be connected to and can receive the updates. Now because this channel lives in a single instance we can easily distribute the change log to the websockets connected to this server but what will happen in case of other users editing the same document who are connected to server2. They simply wont be able to receive the updates by user1 &amp; user2 as this channels lives in server1 only and there is no link of this with other servers.</p><p>Here the basic concept we can apply is to have a unique channel for the document which will be created in the PUB/SUB system in our case Redis. All the changes made to the document by any user connected to any of the server will be published to the redis channel only . And all the users who are working on this document will be a subscriber of the redis channel. Thus whenever there is some message in the topic/channel all the users will get notified about the change log through the database. The only difference here being PUB/SUB will work as a single point which will help to synchronise and establish link between the different server instances.</p><p>Below I will be using FastAPI for the demo code.</p><ol><li><strong><em>RedisPubSubManger</em></strong> class below will help in creating connection to Redis, Subscribing &amp; unsubscribing to a channel and publish message to the channel.</li></ol><pre>import asyncio<br>import redis.asyncio as aioredis<br>import json<br>from fastapi import WebSocket<br><br><br>class RedisPubSubManager:<br>    &quot;&quot;&quot;<br>        Initializes the RedisPubSubManager.<br><br>    Args:<br>        host (str): Redis server host.<br>        port (int): Redis server port.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, host=&#39;localhost&#39;, port=6379):<br>        self.redis_host = host<br>        self.redis_port = port<br>        self.pubsub = None<br><br>    async def _get_redis_connection(self) -&gt; aioredis.Redis:<br>        &quot;&quot;&quot;<br>        Establishes a connection to Redis.<br><br>        Returns:<br>            aioredis.Redis: Redis connection object.<br>        &quot;&quot;&quot;<br>        return aioredis.Redis(host=self.redis_host,<br>                              port=self.redis_port,<br>                              auto_close_connection_pool=False)<br><br>    async def connect(self) -&gt; None:<br>        &quot;&quot;&quot;<br>        Connects to the Redis server and initializes the pubsub client.<br>        &quot;&quot;&quot;<br>        self.redis_connection = await self._get_redis_connection()<br>        self.pubsub = self.redis_connection.pubsub()<br><br>    async def _publish(self, room_id: str, message: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Publishes a message to a specific Redis channel.<br><br>        Args:<br>            room_id (str): Channel or room ID.<br>            message (str): Message to be published.<br>        &quot;&quot;&quot;<br>        await self.redis_connection.publish(room_id, message)<br><br>    async def subscribe(self, room_id: str) -&gt; aioredis.Redis:<br>        &quot;&quot;&quot;<br>        Subscribes to a Redis channel.<br><br>        Args:<br>            room_id (str): Channel or room ID to subscribe to.<br><br>        Returns:<br>            aioredis.ChannelSubscribe: PubSub object for the subscribed channel.<br>        &quot;&quot;&quot;<br>        await self.pubsub.subscribe(room_id)<br>        return self.pubsub<br><br>    async def unsubscribe(self, room_id: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Unsubscribes from a Redis channel.<br><br>        Args:<br>            room_id (str): Channel or room ID to unsubscribe from.<br>        &quot;&quot;&quot;<br>        await self.pubsub.unsubscribe(room_id)</pre><p>2. <strong><em>WebSocketManger</em></strong> class which will handle the logic of creating room/channel, subscribing/subscribing to rooms etc.</p><pre>class WebSocketManager:<br><br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Initializes the WebSocketManager.<br><br>        Attributes:<br>            rooms (dict): A dictionary to store WebSocket connections in different rooms.<br>            pubsub_client (RedisPubSubManager): An instance of the RedisPubSubManager class for pub-sub functionality.<br>        &quot;&quot;&quot;<br>        self.rooms: dict = {}<br>        self.pubsub_client = RedisPubSubManager()<br><br>    async def add_user_to_room(self, room_id: str, websocket: WebSocket) -&gt; None:<br>        &quot;&quot;&quot;<br>        Adds a user&#39;s WebSocket connection to a room.<br><br>        Args:<br>            room_id (str): Room ID or channel name.<br>            websocket (WebSocket): WebSocket connection object.<br>        &quot;&quot;&quot;<br>        await websocket.accept()<br><br>        if room_id in self.rooms:<br>            self.rooms[room_id].append(websocket)<br>        else:<br>            self.rooms[room_id] = [websocket]<br><br>            await self.pubsub_client.connect()<br>            pubsub_subscriber = await self.pubsub_client.subscribe(room_id)<br>            asyncio.create_task(self._pubsub_data_reader(pubsub_subscriber))<br><br>    async def broadcast_to_room(self, room_id: str, message: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Broadcasts a message to all connected WebSockets in a room.<br><br>        Args:<br>            room_id (str): Room ID or channel name.<br>            message (str): Message to be broadcasted.<br>        &quot;&quot;&quot;<br>        await self.pubsub_client._publish(room_id, message)<br><br>    async def remove_user_from_room(self, room_id: str, websocket: WebSocket) -&gt; None:<br>        &quot;&quot;&quot;<br>        Removes a user&#39;s WebSocket connection from a room.<br><br>        Args:<br>            room_id (str): Room ID or channel name.<br>            websocket (WebSocket): WebSocket connection object.<br>        &quot;&quot;&quot;<br>        self.rooms[room_id].remove(websocket)<br><br>        if len(self.rooms[room_id]) == 0:<br>            del self.rooms[room_id]<br>            await self.pubsub_client.unsubscribe(room_id)<br><br>    async def _pubsub_data_reader(self, pubsub_subscriber):<br>        &quot;&quot;&quot;<br>        Reads and broadcasts messages received from Redis PubSub.<br><br>        Args:<br>            pubsub_subscriber (aioredis.ChannelSubscribe): PubSub object for the subscribed channel.<br>        &quot;&quot;&quot;<br>        while True:<br>            message = await pubsub_subscriber.get_message(ignore_subscribe_messages=True)<br>            if message is not None:<br>                room_id = message[&#39;channel&#39;].decode(&#39;utf-8&#39;)<br>                all_sockets = self.rooms[room_id]<br>                for socket in all_sockets:<br>                    data = message[&#39;data&#39;].decode(&#39;utf-8&#39;)<br>                    await socket.send_text(data)</pre><p>3. API route to connect to WebSocket server and establish connection.</p><pre>import logging<br>import uvicorn<br>from fastapi.middleware.cors import CORSMiddleware<br>from fastapi import FastAPI, WebSocket, WebSocketDisconnect<br>from websocket.socketManager import WebSocketManager<br>import json<br>import argparse<br><br>parser = argparse.ArgumentParser()<br>parser.add_argument(&quot;-p&quot;, &quot;--port&quot;, default=8000, type=int)<br>args = parser.parse_args()<br><br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(&quot;FastAPI app&quot;)<br><br>app = FastAPI()<br><br># Adding the CORS middleware to the app<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>socket_manager = WebSocketManager()<br><br><br>@app.websocket(&quot;/api/v1/ws/{room_id}/{user_id}&quot;)<br>async def websocket_endpoint(websocket: WebSocket, room_id: str, user_id: int):<br>    await socket_manager.add_user_to_room(room_id, websocket)<br>    message = {<br>        &quot;user_id&quot;: user_id,<br>        &quot;room_id&quot;: room_id,<br>        &quot;message&quot;: f&quot;User {user_id} connected to room - {room_id}&quot;<br>    }<br>    await socket_manager.broadcast_to_room(room_id, json.dumps(message))<br>    try:<br>        while True:<br>            data = await websocket.receive_text()<br>            message = {<br>                &quot;user_id&quot;: user_id,<br>                &quot;room_id&quot;: room_id,<br>                &quot;message&quot;: data<br>            }<br>            await socket_manager.broadcast_to_room(room_id, json.dumps(message))<br><br>    except WebSocketDisconnect:<br>        await socket_manager.remove_user_from_room(room_id, websocket)<br><br>        message = {<br>            &quot;user_id&quot;: user_id,<br>            &quot;room_id&quot;: room_id,<br>            &quot;message&quot;: f&quot;User {user_id} disconnected from room - {room_id}&quot;<br>        }<br>        await socket_manager.broadcast_to_room(room_id, json.dumps(message))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(&quot;main:app&quot;, host=&quot;127.0.0.1&quot;, port=args.port, reload=True)</pre><blockquote>When we first receive a request with a <em>room_id</em> , after accepting the websocket connection we check if we already have the <em>room_id</em> available or not. If the <em>room_id</em> is already available then we add the new webSocket connection to the list of WebSocket connections already connected to the room_id and if its not available then we first establish connection to redis and then subscribe to the PUB/SUB topic as <em>room_id</em> . After subscribing we will attach a reader <em>_pubsub_data_reader</em> which will continuously pull data from the topic and within which we will extract the list of websocket connections associated and send the message to the clients. This is the overall working concept of the code.</blockquote><blockquote><em>remove_user_from_room</em> is used when a websocket connection gets disconnected, we remove that connection from the list of connections associated with the <em>room_id</em> . And if there is no connections available for a specific <em>room_id</em> then we unsubscribe to the corresponding topic.</blockquote><p>The complete code can be found on <a href="https://github.com/NandaGopal56/websockets-pubsub.git">my github here</a>:</p><p><strong>Conclusion:</strong></p><p>Although this code is small and simple, implementing a full scale web socket with pub/sub is relatively complex and involves various scenarios to be considered. We need to take into considerations different fail safe mechanisms to avoid any interruptions, connection retry in case of failures etc.</p><p><strong>Resources:</strong></p><ol><li><a href="https://hackernoon.com/scaling-websockets-9a31497af051">https://hackernoon.com/scaling-websockets-9a31497af051</a></li><li><a href="https://betterprogramming.pub/design-considerations-for-scaling-websocket-server-horizontally-with-a-publish-subscribe-pattern-fe6de9988400">https://betterprogramming.pub/design-considerations-for-scaling-websocket-server-horizontally-with-a-publish-subscribe-pattern-fe6de9988400</a></li><li><a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern</a></li><li><a href="https://en.wikipedia.org/wiki/WebSocket">https://en.wikipedia.org/wiki/WebSocket</a></li></ol><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16392ffe291" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Full Text Search with PostgreSQL]]></title>
            <link>https://medium.com/@nandagopal05/django-full-text-search-with-postgresql-f063aaf34e35?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/f063aaf34e35</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 20:44:40 GMT</pubDate>
            <atom:updated>2023-03-29T20:44:40.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJE64G0ZxEhh3p0gqTxjXA.jpeg" /></figure><p>Many of times when developing apps we have a requirement to implement a robust search functionality to provide better user experience. In case of working with Django, as of now there is nothing in-built that Django provides apart from the standard SQL like operators in Django ORM that we can use. Of course we can use different services like Redis Search or AWS Elastic Search etc, but in case of small applications or just to provide a standard search experience we can use the power of PostgreSQL full text search engine in Django.</p><h3><strong>Basic Search:</strong></h3><p>When it comes to basic search, with Django, we can start querying with contains (Case sensitive searches) or icontains (Case insensitive searches) for exact matches. Here I am using Q objects to perform AND, OR conditions. Below is a basic example code and results.</p><pre>@api_view([&#39;GET&#39;])<br>def Basicsearch(request):<br>    query  = request.GET.get(&#39;query&#39;)<br><br>    books = Book.objects.filter(Q(book_name__icontains=query) | Q(description__icontains=query))<br>    serializer = BookSerializer(books, many=True)<br>    <br>    data = {<br>        &quot;Keyword&quot;: query,<br>        &quot;results&quot;: serializer.data<br>    }<br>    return Response(data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTASFIDqyXt9Cd2U9JrZUA.png" /></figure><p>Here we used the basic icontains method to basically compare case insensitive search similar to SQL like operation. This works perfect for small dataset and the main disadvantage of basic search is it will just match exact words. When comes to large data sets we would want to handle complex scenarios so lets move into Full-text search.</p><h3>Full-text Search:</h3><p>Using functions in the <strong>django.contrib.postgres.search </strong>we can use<strong> </strong>PostgreSQL’s <a href="https://www.postgresql.org/docs/current/textsearch.html">full text search engine</a></p><p>First lets start by using Searchvector (To perform search against multiple fields) class from django.contrib.postgres.search . Below is a code snippet for the same.</p><pre>from django.contrib.postgres.search import SearchVector<br><br>@api_view([&#39;GET&#39;])<br>def FullTextSearch(request):<br>    query  = request.GET.get(&#39;query&#39;)<br><br>    books = Book.objects.annotate(<br>        search=SearchVector(&quot;book_name&quot;, &quot;description&quot;)<br>    ).filter(search=query)<br>    <br>    serializer = BookSerializer(books, many=True)<br>    <br>    data = {<br>        &quot;Keyword&quot;: query,<br>        &quot;results&quot;: serializer.data<br>    }<br>    return Response(data)</pre><p>First advantages of Full-text search as we can see form the below result is elimination of stop words like A, Is, The etc which won’t be possible in basic search. Here it have ignored the word The form the search query and searched only for Powerful</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXIKg8akjYAFZoaOKrsjzg.png" /></figure><h3>Stemming :</h3><p><strong>SearchQuery</strong> translates the terms the user provides into a search query object that the database compares to a search vector. If <strong>search_type</strong> is <strong>&#39;plain&#39;</strong>, which is the default, the terms are treated as separate keywords. If <strong>search_type</strong> is <strong>&#39;phrase&#39;</strong>, the terms are treated as a single phrase. If <strong>search_type</strong> is <strong>&#39;raw&#39;</strong>, then you can provide a formatted search query with terms and operators. If <strong>search_type</strong> is <strong>&#39;websearch&#39;</strong>, then you can provide a formatted search query, similar to the one used by web search engines.</p><pre>@api_view([&#39;GET&#39;])<br>def FullTextSearch(request):<br>    query  = request.GET.get(&#39;query&#39;)<br><br>    query = &quot;|&quot;.join(query.split(&#39; &#39;)) #joining the space separated words with | for OR condition<br>    search_query = SearchQuery(query, search_type=&#39;raw&#39;)<br><br>    books = Book.objects.annotate(<br>        search=SearchVector(&quot;book_name&quot;, &quot;description&quot;)<br>    ).filter(search=search_query)<br>    <br>    serializer = BookSerializer(books, many=True)<br>    <br>    data = {<br>        &quot;Keyword&quot;: query,<br>        &quot;results&quot;: serializer.data<br>    }<br>    return Response(data)</pre><p>Here as we can see we first converted the space separated string into words joined by pipe and the result set contains either one of the words being matched in this case The or accessories .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iE2NaThqtEkJWBiDe9Ml4g.png" /></figure><p>below is different types of search types.</p><pre>&gt;&gt;&gt; from django.contrib.postgres.search import SearchQuery<br>&gt;&gt;&gt; SearchQuery(&#39;red tomato&#39;)  # two keywords<br>&gt;&gt;&gt; SearchQuery(&#39;tomato red&#39;)  # same results as above<br>&gt;&gt;&gt; SearchQuery(&#39;red tomato&#39;, search_type=&#39;phrase&#39;)  # a phrase<br>&gt;&gt;&gt; SearchQuery(&#39;tomato red&#39;, search_type=&#39;phrase&#39;)  # a different phrase<br>&gt;&gt;&gt; SearchQuery(&quot;&#39;tomato&#39; &amp; (&#39;red&#39; | &#39;green&#39;)&quot;, search_type=&#39;raw&#39;)  # boolean operators<br>&gt;&gt;&gt; SearchQuery(&quot;&#39;tomato&#39; (&#39;red&#39; OR &#39;green&#39;)&quot;, search_type=&#39;websearch&#39;)  # websearch operators</pre><h3>Ranking :</h3><p>Search is good to produce some results but in order to display to users and make it worthy enough, we should rank the results based on relevancy. This is where SearchRank comes into the picture.</p><p>PostgreSQL provides a ranking function which takes into account how often the query terms appear in the document, how close together the terms are in the document, and how important the part of the document is where they occur. The better the match, the higher the value of the rank. To order by relevancy:</p><pre>search_query = SearchQuery(query, search_type=&#39;raw&#39;)<br>search_vector = SearchVector(&quot;book_name&quot;, &quot;description&quot;)<br><br>books = Book.objects.annotate(<br>    search=search_vector,<br>    rank=SearchRank(search_vector, search_query)<br>).filter(search=search_query).order_by(&quot;-rank&quot;)</pre><h3>Search configuration:</h3><p>We can specify the <strong>config</strong> attribute to a <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/#django.contrib.postgres.search.SearchVector"><strong>SearchVector</strong></a> and <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/#django.contrib.postgres.search.SearchQuery"><strong>SearchQuery</strong></a> to use a different search configuration. This allows using different language parsers and dictionaries as defined by the database:</p><pre>search_query = SearchQuery(query, search_type=&#39;raw&#39;, config=&#39;english&#39;)<br>search_vector = SearchVector(&quot;book_name&quot;, &quot;description&quot;, config=&#39;english&#39;)<br><br>books = Book.objects.annotate(<br>    search=search_vector,<br>    rank=SearchRank(search_vector, search_query)<br>).filter(search=search_query).order_by(&quot;-rank&quot;)</pre><p>As from below screenshot we can see, even if we searched for adaption , it returned results containing the word adapted .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHjAkjpuVKG4dLkArOHiiA.png" /></figure><h3>Weighting queries:</h3><p>Every field may not have the same relevancy in a query. So we can use weights to prioritise specific fields over others and accordingly rank the search results. The weight should be one of the following letters: D, C, B, A. By default, these weights refer to the numbers <strong>0.1</strong>, <strong>0.2</strong>, <strong>0.4</strong>, and <strong>1.0</strong>, respectively.</p><pre>search_query = SearchQuery(query, search_type=&#39;raw&#39;, config=&#39;english&#39;)<br>search_vector = SearchVector(&#39;book_name&#39;, weight=&#39;A&#39;, config=&#39;english&#39;) + SearchVector(&#39;description&#39;, weight=&#39;B&#39;, config=&#39;english&#39;)<br><br>books = Book.objects.annotate(<br>    search=search_vector,<br>    rank=SearchRank(search_vector, search_query)<br>).filter(search=search_query).order_by(&quot;-rank&quot;)</pre><h3>Performance considerations:</h3><p>Performance can be improved by using a <a href="https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/search/#searchvectorfield">SearchVectorField</a>. That field keeps a pre-generated <a href="https://www.postgresql.org/docs/10/datatype-textsearch.html#DATATYPE-TSVECTOR">ts_vector</a> column with all the relevant data alongside the model, rather than generating it on the fly during every search. To enhance it further we can use indexed columns in this case an GIN (<a href="https://www.postgresql.org/docs/current/gin-intro.html">Generalized Inverted Index</a>) index on the search_vector field.</p><pre>from django.db import models<br>from django.contrib.postgres.indexes import GinIndex<br>from django.contrib.postgres.search import SearchVectorField<br><br># Create your models here.<br>class Book(models.Model):<br>    id = models.BigAutoField(primary_key=True, db_index=True, editable=False)<br>    book_name = models.CharField(max_length=50)<br>    description = models.TextField()<br>    search_vector = SearchVectorField(null=True)<br>    <br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    class Meta:<br>        indexes = (GinIndex(fields=[&quot;search_vector&quot;]),)<br><br>    def __str__(self):<br>        return f&quot;{self.book_name} :: {self.description}&quot;</pre><p>After the migration of these changes, we need to create some sort of trigger to populate the field search_vector . In this case i have used a custom migration file (<em>0003_book_search_vector_trigger.py</em>) to set up a PostgreSQL trigger. We can use some different methods like Django signals or override the save method as well to do this.</p><pre>from django.contrib.postgres.search import SearchVector<br>from django.db import migrations<br><br><br>def compute_search_vector(apps, schema_editor):<br>    Quote = apps.get_model(&quot;books&quot;, &quot;Book&quot;)<br>    Quote.objects.update(search_vector=SearchVector(&quot;book_name&quot;, &quot;description&quot;))<br><br><br>class Migration(migrations.Migration):<br><br>    dependencies = [<br>        (&quot;books&quot;, &quot;0002_book_search_vector_and_more&quot;),<br>    ]<br><br>    operations = [<br>        migrations.RunSQL(<br>            sql=&quot;&quot;&quot;<br>            CREATE TRIGGER search_vector_trigger<br>            BEFORE INSERT OR UPDATE OF book_name, description, search_vector<br>            ON books_book<br>            FOR EACH ROW EXECUTE PROCEDURE<br>            tsvector_update_trigger(<br>                search_vector, &#39;pg_catalog.english&#39;, book_name, description<br>            );<br>            UPDATE books_book SET search_vector = NULL;<br>            &quot;&quot;&quot;,<br>            reverse_sql=&quot;&quot;&quot;<br>            DROP TRIGGER IF EXISTS search_vector_trigger<br>            ON books_book;<br>            &quot;&quot;&quot;,<br>        ),<br>        migrations.RunPython(<br>            compute_search_vector, reverse_code=migrations.RunPython.noop<br>        ),<br>    ]</pre><p>Now after migrating this custom trigger, we will see that our search_vector field will be field with some data.</p><p>Now we can directly query the search_vector field to speed up the operation.</p><pre>books = Book.objects.filter(search_vector=query)</pre><p>Other great algorithms that can be used are available <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/#:~:text=Entry%3A%20Pizza%20recipes%3E%5D-,Trigram%20similarity,-%C2%B6"><strong><em>here</em></strong></a>.</p><p>The complete source code can be found <a href="https://github.com/NandaGopal56/Django-full-text-search.git"><strong><em>here</em></strong></a>.</p><p>Resources:</p><p><a href="https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/">Django</a></p><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f063aaf34e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a basic GTID based MySQL Replication setup]]></title>
            <link>https://medium.com/@nandagopal05/setting-up-a-basic-gtid-based-mysql-replication-setup-e615890672?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e615890672</guid>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[replica]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 18:01:24 GMT</pubDate>
            <atom:updated>2022-09-05T18:01:24.385Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Data Replication</strong> is the process of storing data in more than one node or instance. It is simply copying data from a database from one server to another server. It can be used to ensure a fault tolerant system as we are keeping a backup of the data at every point of time. Also, we can setup multiple replicas and divert all our read queries to replica instances and insert/update queries to the primary database thus by decreasing the load and no of TCP connections on a single server. Moreover we can place the replicas in different geographic areas to reduce latency by routing the requests to the closest possible server from the request origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*ZE6gts26I7L3FzH_etVPQg.jpeg" /><figcaption>multiple Replications setup</figcaption></figure><p>In this blog, We will setup GDIT based replication with MySQL. A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (source).</p><p>GTID = <em>source_id</em>:<em>transaction_id</em></p><p>The <strong><em>source_id</em></strong> identifies the originating server. Normally, the source&#39;s server_uuid is used for this purpose. The <strong><em>transaction_id</em></strong> is a sequence number determined by the order in which the transaction was committed on the source.</p><p>The GTID for a transaction is shown in the output from <a href="https://dev.mysql.com/doc/refman/5.7/en/mysqlbinlog.html"><strong>mysqlbinlog</strong></a>, and it is used to identify an individual transaction in the Performance Schema replication status tables. The value stored by the gtid_next system variable (@@GLOBAL.gtid_next) is a single GTID.</p><p>e.g. ubuntu@instance-1:/var/log/mysql$ sudo mysqlbinlog mysql-bin.000002 outputs some GTIDs as in below format</p><p>SET @@SESSION.GTID_NEXT= ‘4e89b248–2c8e-11ed-af3b-020017000790:1’/*!*/;</p><p><strong>Installation of MySQL server on Linux:</strong></p><ol><li>To install it, update the package index on your server if you’ve not done so recently —<strong> </strong>sudo apt update</li><li>install the MySQL-server package —<strong> </strong>sudo apt install mysql-server</li><li>Ensure that the server is running using the systemctl start command — <em>sudo </em>service mysql status</li><li>If it’s not running, start the service using — sudo service mysql start</li><li>First, open up the MySQL prompt —<strong> </strong>sudo mysql</li><li>ALTER USER command to change the root user’s authentication method to one that uses a password —<strong> </strong>ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password@123’;</li><li>Log back in with password —<strong> </strong>mysql -u root -p</li></ol><h4>Setting Up Replication Using GTIDs<strong>:</strong></h4><p>Here I am assuring this setup is done with new servers otherwise we need to setup the DB read only and take backups and synchronize both the servers.</p><p>Here few parameters we need to change in MySQL configuration and as I want to access both these servers from across the internet, so I will be changing the binding address as well accordingly.</p><p><strong><em>Setting up the master server:</em></strong></p><p>Change the mysqld.cnf file as below —</p><p>sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf</p><pre>bind-address            = 0.0.0.0<br>server-id               = 1<br>log_bin                 = /var/log/mysql/mysql-bin.log<br>gtid_mode=ON<br>enforce-gtid-consistency=ON</pre><p>To enable GTID-based replication, each server must be started with GTID mode enabled by setting the gtid_mode variable to ON, and with the enforce_gtid_consistency variable enabled to ensure that only statements which are safe for GTID-based replication are logged. server-id is a unique id for each instance and bind-address is changed in order it to be accessible from internet.</p><p><strong><em>Creating a User for Replication:</em></strong></p><pre>mysql&gt; CREATE USER ‘slaveusr’@’%’ IDENTIFIED BY ‘password@123’;<br>mysql&gt; GRANT REPLICATION SLAVE ON *.* TO &#39;slaveusr&#39;@&#39;%&#39; WITH GRANT OPTION;<br>mysql&gt; FLUSH PRIVILEGES;<br>mysql&gt; ALTER USER ‘slaveusr’@’%’ IDENTIFIED WITH     mysql_native_password BY ‘password@123’;</pre><p>caching_sha2_password is the default authentication plugin rather than mysql_native_password. To connect to the server using the caching_sha2_password plugin, we must use either a secure connection or an unencrypted connection that supports password exchange using an RSA key pair. So, here I have changed the authentication plugin to mysql_native_password for now.</p><p><strong><em>Setting up the replica server:</em></strong></p><p>Change the mysqld.cnf file as below —</p><p>sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf</p><pre>bind-address            = 0.0.0.0<br>server-id               = 2<br>gtid_mode=ON<br>enforce-gtid-consistency=ON</pre><p>It is not mandatory to have binary logging enabled in order to use GTIDs when using the mysql.gtid_executed table Replication source server must always have binary logging enabled in order to be able to replicate. However, replica servers can use GTIDs but without binary logging.</p><p><strong><em>Configure the replica to use GTID-based auto-positioning:</em></strong></p><p>Configure replica to use the source with GTID based transactions as the replication data source, and to use GTID-based auto-positioning rather than file-based positioning. Issue a CHANGE MASTER TO statement on the replica, including the MASTER_AUTO_POSITION option in the statement to tell the replica that the source&#39;s transactions are identified by GTIDs.</p><pre><strong>mysql&gt;</strong> CHANGE MASTER TO<br>MASTER_HOST=&#39;129.184.28.288&#39;,<br>MASTER_PORT = 3306,<br>MASTER_USER=&#39;slaveusr&#39;,<br>MASTER_PASSWORD=&#39;password@123&#39;,<br>MASTER_AUTO_POSITION = 1;</pre><p>Neither the MASTER_LOG_FILE option nor the MASTER_LOG_POS option may be used with MASTER_AUTO_POSITION set equal to 1. Attempting to do so causes the CHANGE MASTER TO statement to fail with an error. This is only required when using binary log file based replication.</p><p>Now, start the replication server with - <strong>mysql&gt; </strong>START SLAVE;</p><p><strong><em>Let’s test now -</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*bqbKxYhSZgmSj-mocmd89A.png" /></figure><p>Here, When I create a database named test in 1st instance, it’s automatically appears in my 2nd instance i.e. the replica instance.</p><p>Verify the slave status and master status as below.</p><p>mysql&gt; show slave status \G;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*BeQmyVC977DRyZkUuXMs3w.png" /></figure><p>mysql&gt; show master status \G;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*I9rlYe5GxqPECvlVy-S5vg.png" /></figure><p><strong><em>Resources:</em></strong></p><ul><li><a href="https://dev.mysql.com/doc/refman/5.7/en/replication-gtids-howto.html">MySQL :: MySQL 5.7 Reference Manual :: 16.1.3.4 Setting Up Replication Using GTIDs</a></li><li><a href="https://dev.mysql.com/doc/refman/5.7/en/replication-howto-repuser.html">MySQL :: MySQL 5.7 Reference Manual :: 16.1.2.2 Creating a User for Replication</a></li><li><a href="https://dev.mysql.com/doc/refman/5.7/en/replication-howto-masterbaseconfig.html">MySQL :: MySQL 5.7 Reference Manual :: 16.1.2.1 Setting the Replication Source Configuration</a></li></ul><p>Thank you everyone for contributing your valuable time on this. Please correct me if any mistakes, comment your thoughts or any suggestions and I am always happy to learn from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e615890672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Axios interceptors to automate refreshing access tokens.]]></title>
            <link>https://medium.com/@nandagopal05/using-axios-interceptors-to-automate-refreshing-access-tokens-c3c344737bcc?source=rss-b7dc56f07e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c344737bcc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[axios-interceptor]]></category>
            <dc:creator><![CDATA[Nanda Gopal Pattanayak]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 19:41:17 GMT</pubDate>
            <atom:updated>2022-07-23T19:41:17.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5nIlt2tAx-cyfLNjkT0iQ.png" /><figcaption>Source:<a href="https://is.docs.wso2.com/">https://is.docs.wso2.com/</a></figcaption></figure><p>Axios interceptors are kind of middlewares which can be used as filters or as a way to manipulate HTTP request and response before they are being sent or received.</p><p>This allows us to modify or add headers, take certain actions based on error responses and specifically will be easier to write common logics for a certain HTTP response scenario, which in here we will use to automate the process of getting access tokens after the access token is expired.</p><p>When using token based authentication system with access token and refresh tokens, the tedious task is to call the refresh token endpoint whenever the access token is expired. There are multiple ways that we can achieve it. We will use the response interceptor to check 401 response code and act on it.</p><p>We will try to replicate the above flow. Whenever we will get an 401 response , we will make a request to get a new access token by using the refresh token and then retry the original request that failed with 401 response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*-t3J6tMVsk4beiEdht6NCw.png" /></figure><p>Below is the complete code of the Axios response interceptor to automate the process of refreshing tokens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0cac5f57fcfedd6320f312282fe8e7/href">https://medium.com/media/7a0cac5f57fcfedd6320f312282fe8e7/href</a></iframe><p>Here inside the response interceptor at line 23 &amp; 24, we are keeping a ref to the originalRequest , refreshTokenError &amp; res in order to use them later.</p><p>On line 25, we will check if the response is 401 and the original request is not retried after, then we will call the <strong>refreshToken </strong>endpoint and get a new pair of accessToken &amp; refreshToken . If we won’t check if the original request is already retied and still getting a 401response we will be stuck in a infinite loop. I am using withCredentials as my tokens are being stored in HttpOnly Cookies .</p><p>On line 28, we will be calling the <strong>refreshToken </strong>endpoint and if the response is successful, we will retry the original request which was intended by the client and if successful return the response at line 59 and finally if the <strong>refreshToken </strong>endpoint also failed to give a success response, we will reject this in line 57.</p><p>In case any of these conditions don’t satisfy in line 25, we will return the error as it is.</p><p>The complete source code can be found <a href="https://github.com/NandaGopal56/axios-interceptors.git"><strong><em>here</em></strong></a><strong> </strong>.</p><p><strong>Axios doc:</strong></p><p><a href="https://axios-http.com/docs/interceptors">Interceptors</a></p><p>Thank you for contributing your valuable time on this. Please feel free to correct if any mistakes, comment your thoughts or any suggestions and I am always happy to learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c344737bcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>