<?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 Kanhaya Yadav on Medium]]></title>
        <description><![CDATA[Stories by Kanhaya Yadav on Medium]]></description>
        <link>https://medium.com/@kanhayaky?source=rss-6fd653d8eb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N-u5CLiAUwnWDj441OqdAA.jpeg</url>
            <title>Stories by Kanhaya Yadav on Medium</title>
            <link>https://medium.com/@kanhayaky?source=rss-6fd653d8eb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:45:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kanhayaky/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[Building a load balancer : part 1]]></title>
            <link>https://kanhayaky.medium.com/building-a-load-balancer-part-1-b21eadddf7e9?source=rss-6fd653d8eb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21eadddf7e9</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sockets]]></category>
            <dc:creator><![CDATA[Kanhaya Yadav]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 19:25:59 GMT</pubDate>
            <atom:updated>2025-10-26T02:56:18.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Load Balancer : Part 1</h3><p>In this article, we’ll build a simple yet functional load balancer using Python. Our load balancer will handle incoming client requests and forward them to a pool of servers using specific algorithms or rules.</p><h3>Introduction to load balancer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*fsVwzXOaMy9fF8tqvFTUyg.png" /><figcaption>An application Load-balancer in action</figcaption></figure><p>A <em>load balancer</em> serves as the single point of contact for clients. The load balancer distributes incoming application traffic across multiple targets efficiently. By ensuring even traffic distribution, it improves reliability, scalability, and performance of applications.</p><blockquote>If you’re new to socket programming and want a basic understanding of how a server is built, I’d recommend reading my post — <strong>Python Socket Programming 101: Build a TCP Server.</strong></blockquote><p><a href="https://kanhayaky.medium.com/python-socket-programming-101-build-a-tcp-server-221ba72ee2f9">Python Socket Programming 101: Build a TCP Server</a></p><h3>The Goal ?</h3><p>Build a load balancer that can distribute traffic to two or more application servers using a chosen strategy (starting with Round Robin).</p><h3>The Approach</h3><p>A load balancer is similar to a simple TCP server, except that it forwards requests to application servers and returns their responses to the client.</p><p>We’ll define a LoadBalancer class structured like this:</p><pre># loadbalancer.py<br><br>class LoadBalancer():<br>  def __init__(self, port):<br>   pass<br>  <br>  def handle(self, connection, address):<br>    pass<br><br>  def forward_request(self, request, address):<br>    pass<br><br>  def start_server(self):<br>    pass</pre><blockquote>In a production-grade load balancer, you would typically use <strong>threads</strong>, <strong>processes</strong>, or <strong>asynchronous I/O (asyncio</strong>) to handle concurrent connections. However, for simplicity and clarity, this example avoids concurrency to focus on the core concept of request forwarding and load balancing.</blockquote><h3>1. Starting the load balancer</h3><p>The start_server method creates a TCP socket, binds it to the load balancer’s port, and listens for incoming connections.</p><pre># loadbalancer.py<br><br>class LoadBalancer():<br>    <br>  ...<br>  <br>  def start_server(self):<br>      server_socket = socket(AF_INET, SOCK_STREAM)<br>      server_socket.bind((&quot;&quot;, self.port))<br>      server_socket.listen(5)<br>      print(f&quot;Starting Load Balancer on port {self.port}...&quot;)<br><br>      while True:<br>          client_connection, client_address = server_socket.accept()<br>          self.handle(client_connection, client_address)<br>          client_connection.close()</pre><h3>2. Handling Client Requests</h3><p>The handle method performs the following steps <br>1. Reads incoming requests<br>2. Forwards them to an application server<br>3. Receives the response<br>4. Sends that response back to the client.</p><pre>class LoadBalancer:<br>    def __init__(self, port, application_servers):<br>        self.port = port<br>        self.application_servers = application_servers<br>        self.current_server = 0<br><br>    def handle(self, client_connection, client_address):<br>        request = client_connection.recv(1024)<br><br>        parsed_request = request.decode(&quot;utf-8&quot;)<br><br>        if not parsed_request:<br>            return<br><br>        print(f&quot;Received request from {client_address}&quot;)<br>        print(parsed_request)<br><br>        server_address = self.application_servers[self.current_server]<br>        server_response = self.forward_request(request, server_address)<br><br>        parsed_response = server_response.decode(&quot;utf-8&quot;)<br>        print(f&quot;Received response from server&quot;)<br>        print(parsed_response)<br><br>        client_connection.send(server_response)</pre><h3>3. Forwarding the Request to the Application Server</h3><p>The forward_request method makes a TCP connection to the server, sends the client’s request received by the load balancer and returns the response received the server’s response</p><pre># loadbalancer.py<br><br>class LoadBalancer():<br>    <br>  ...<br>  def forward_request(self, request, address):<br>      server_socket = socket(AF_INET, SOCK_STREAM)<br>      server_socket.connect(address)<br>      server_socket.send(request)<br>  <br>      server_response = server_socket.recv(1024)<br>      return server_response</pre><h3>4. Creating the Application Server</h3><p>The application server listens on its port, receives requests, and responds with a simple message.</p><pre># application.py<br><br>import sys<br>from socket import socket, AF_INET, SOCK_STREAM<br><br><br>class ApplicationServer:<br>    def __init__(self, port):<br>        self.port = port<br>        self.name = f&quot;app_server_{port}&quot;<br><br>    def handle(self, client_connection, client):<br>        request = client_connection.recv(1024)<br><br>        parsed_request = request.decode(&quot;utf-8&quot;)<br><br>        if not parsed_request:<br>            return<br><br>        print(f&quot;Received request from {client}&quot;)<br>        print(parsed_request)<br><br>        response = f&quot;Hello From Application Server {self.name}\n&quot;<br>        http_response = (<br>            f&quot;HTTP/1.1 200 OK\r\nContent-Length: {len(response)}\r\n\r\n{response}&quot;<br>        )<br><br>        client_connection.send(http_response.encode())<br><br>        print(f&quot;Replied with {response!r} message&quot;)<br><br>    def start_server(self):<br>        server_socket = socket(AF_INET, SOCK_STREAM)<br>        server_socket.bind((&quot;&quot;, self.port))<br>        server_socket.listen(5)<br>        print(f&quot;Starting server {self.name} on port {self.port}...&quot;)<br><br>        while True:<br>            client_connection, client_address = server_socket.accept()<br>            self.handle(client_connection, client_address)<br>            client_connection.close()</pre><p>This server implementation is almost the same as the <strong>Load balancer</strong>, except that it responds to client requests directly instead of forwarding them elsewhere. In this setup, the load balancer connects to the application server, forwards the client’s request, and then relays the server’s response back to the client.</p><h3>5. Running the Servers</h3><p>One last piece before we see this in action will be runner for both the load balancer and application server</p><pre># application.py<br>if __name__ == &quot;__main__&quot;:<br>    PORT = 8000<br>    if len(sys.argv) &gt; 1:<br>        PORT = int(sys.argv[1])<br>    app_server = ApplicationServer(port=PORT)<br>    app_server.start_server()<br><br><br># loadbalancer.py<br>if __name__ == &quot;__main__&quot;:<br>    LB_PORT = 5001<br>    APPLICATION_SERVERS = [(&quot;localhost&quot;, 8000)]<br><br>    load_balancer = LoadBalancer(<br>        port=LB_PORT, application_servers=APPLICATION_SERVERS)<br>    load_balancer.start_server()</pre><p>That’s a lot of code, now let’s start this and see it in action before we move forward. Run both the python files in separate shells</p><pre>&gt;&gt;&gt; python application.py<br>...<br>&gt;&gt;&gt; python loadbalancer.py<br></pre><p>Once both servers are up and running, you can send requests to the load balancer — remember, it’s the load balancer’s endpoint that’s exposed, not the actual application servers. The easiest way to test this is by visiting http://localhost:5001 in your browser or using <strong>cURL</strong> from the terminal.</p><pre>&gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8000</pre><pre>&gt;&gt;&gt; python load_balancer.py<br>Starting Load Balancer on port 5001...<br>Received request from (&#39;127.0.0.1&#39;, 36948)<br>GET / HTTP/1.1<br>Host: localhost:5001<br>User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:139.0) Gecko/20100101 Firefox/139.0<br><br>Received response from server<br>HTTP/1.1 200 OK<br>Content-Length: 46<br><br>Hello From Application Server app_server_8000</pre><pre>&gt;&gt;&gt; python application.py 8000                                                                                ±[●][main]<br>Starting server app_server_8000 on port 8000...<br>Received request from (&#39;127.0.0.1&#39;, 50576)<br>GET / HTTP/1.1<br>Host: localhost:5001<br>User-Agent: curl/8.13.0<br>Accept: */*<br><br><br>Replied with &#39;Hello From Application Server app_server_8000&#39; message</pre><p>Great! Now that we’ve confirmed our load balancer can successfully communicate with the application server, it’s time to take the next step -enabling it to distribute traffic across multiple servers.</p><h3>6. Introducing Load Balancing Strategies</h3><p>A load balancer distributes incoming requests across multiple servers, selecting one from a list of available application servers based on a chosen load balancing strategy (algorithm). There are several such strategies, including:</p><ul><li><strong>Round Robin: </strong>Distribute requests sequentially across servers in a loop.</li><li><strong>Least Connections: </strong>Send the next request to the server with the fewest active connections.</li><li><strong>Least Response Time: </strong>Pick the server responding fastest on average.</li></ul><p>In this article, we’ll focus on the <strong>Round Robin</strong> algorithm.</p><p>Let’s understand how it works. Suppose you have three servers — S1, S2, and S3. The first request goes to S1, the next to S2, then S3, and the cycle repeats from S1 again. This approach ensures an even distribution of traffic when all servers have similar capacity.</p><h3>7. Implementing Round Robin</h3><p>We’ll now enhance our LoadBalancer class to forward requests using this Round Robin strategy. Currently, it always forwards to the first server in the list, but we’ll update it to rotate through all available servers sequentially.</p><pre># loadbalancer.py<br><br>class NoValidServerURLError(Exception):<br>    pass<br><br>class LoadBalancer():<br>    ...<br><br>  def handle(self, client_connection, client_address):<br>      ...<br>      print(parsed_request)<br><br>      server_address = self.get_server_address() # updated<br>      server_response = self.forward_request(request, server_address)<br>      ....<br><br>  def get_server_address(self):<br>      try:<br>          selected_server = self.application_servers[self.current_server]<br>      except IndexError:<br>          raise NoValidServerURLError(&quot;Valid server URL not found&quot;)<br><br>      total_servers = len(self.application_servers)<br>      # Update the current server index in a thread-safe manner<br>      self.current_server = (self.current_server + 1) % total_servers<br><br>      return selected_server</pre><p>We’ve added a new method called get_server_address that implements the <strong>Round Robin</strong> algorithm. It selects the server at the current index (self.current_server), then updates the index to point to the next server in the list and looping back to the first one once it reaches the end.</p><h3>8. Running Multiple Application Servers</h3><p>To see this in action, we’ll need multiple instances of the application server running. Fortunately, our setup already supports that. You can start additional application servers by running the application.py file with different port numbers as arguments. Simply open two or three new terminal windows and start the servers on different ports.</p><pre>&gt;&gt;&gt; python application.py 8000<br>Starting server app_server_8000 on port 8000...<br><br>...<br>&gt;&gt;&gt; python application.py 8001<br>Starting server app_server_8000 on port 8001...<br><br>...<br>&gt;&gt;&gt; python application.py 8002<br>Starting server app_server_8000 on port 8002...<br>                                                                                ±[●][main]</pre><p>Don’t forget to update the runner for loadbalancer.py to include all the servers in the list of APPLICATION_SERVERS</p><pre># loadbalancer.py<br>if __name__ == &quot;__main__&quot;:<br>    LB_PORT = 5001<br>    APPLICATION_SERVERS = [<br>        (&quot;localhost&quot;, 8000),<br>        (&quot;localhost&quot;, 8001),<br>        (&quot;localhost&quot;, 8002),<br>    ]<br>    load_balancer = LoadBalancer(<br>        port=LB_PORT, application_servers=APPLICATION_SERVERS)<br>    load_balancer.start_server()</pre><p>Now we have all the pieces in place let’s restart the loadbalancer server</p><pre>&gt;&gt;&gt; python loadbalancer.py</pre><p>Now send multiple requests, you will see that the load is being distributed among the 3 application servers in a round robin manner.</p><pre>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8000<br>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8001<br>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8002<br>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8000<br>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8001<br>~ &gt;&gt;&gt; curl &quot;localhost:5001&quot;                                                    <br>Hello From Application Server app_server_8002</pre><h3>Source code</h3><p>You can find the complete source code for this tutorial on GitHub:</p><p><a href="https://github.com/kanhayaKy/load-balancer/tree/main/python/v0">load-balancer/python/v0 at main · kanhayaKy/load-balancer</a></p><h3>Conclusion</h3><p>In this guide, we built a simple, <strong>blocking TCP based load balancer</strong> in Python that uses the <strong>Round Robin</strong> strategy to evenly distribute requests across multiple servers.</p><p>This is a foundational <strong>Part 1</strong> — a minimal, hands-on implementation to help you understand how load balancing works under the hood. In <strong>Part 2</strong>, we’ll take this further by adding concurrency, health checks, and smarter routing algorithms to make it more production-ready.</p><p><em>Stay tuned for the next part!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21eadddf7e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Socket Programming 101: Build a TCP Server]]></title>
            <link>https://kanhayaky.medium.com/python-socket-programming-101-build-a-tcp-server-221ba72ee2f9?source=rss-6fd653d8eb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/221ba72ee2f9</guid>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kanhaya Yadav]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 06:54:26 GMT</pubDate>
            <atom:updated>2025-10-21T08:34:02.479Z</atom:updated>
            <content:encoded><![CDATA[<p>This article introduces the basics of network programming in Python by building a simple TCP server. You’ll learn how sockets work, how to set up a server that listens for client connections, and how to send and receive data over the network.</p><h3>Understanding Sockets in Networking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmN56CKQozY79TtI3fVwEQ.png" /><figcaption>Network, OS, Sockets API, Process interaction</figcaption></figure><p>The network is a physical system, but software interacts with it through the operating system (OS). The OS provides access to networking hardware via the sockets API — a standardised interface that allows programs to communicate over networks.</p><h3>What are sockets?</h3><p>Sockets are endpoints for sending and receiving data across a network. In most operating systems, sockets are represented as file descriptors (FDs), which are abstract handles used for various types of I/O, including files, network connections, and inter-process communication.</p><p>In Python, you create a socket by specifying two parameters:</p><ol><li>Address Family: Defines the type of addresses the socket can communicate with.<br>- <strong>AF_INET</strong>: IPv4 addresses<br>- <strong>AF_INET6</strong>: IPv6 addresses<br>- <strong>AF_UNIX</strong> (or <strong>AF_LOCAL</strong>): Local inter-process communication on the same machine</li><li>Socket Type: Determines the communication protocol and characteristics. <br>- <strong>SOCK_STREAM</strong>: Uses TCP for reliable, connection-oriented communication<br>- <strong>SOCK_DGRAM</strong>: Uses UDP for fast, connectionless communication<br>- <strong>SOCK_RAW</strong>: Provides access to lower-level protocols for custom packet handling</li></ol><p>Example :</p><pre>import socket<br>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</pre><h3>Server listening process</h3><p>The steps involved in writing a server program are</p><ol><li>Ask the OS for a socket</li><li>Bind the socket to a port</li><li>Listen for incoming connection</li><li>Accept incoming connection</li><li>Send and receive data</li><li>Accept another connection</li></ol><p>Now that’s a lot of talking, let’s understand these steps using a simple python server program.</p><pre># server.py<br><br>import socket<br><br># Ask OS for the socket<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br><br># Bind the socket to an address and port<br>s.bind((‘localhost’, 12345))<br><br># Listen for incoming connections<br>s.listen(5)<br><br>while True:<br>    # Accept a connection<br>    conn, addr = s.accept()<br>    print(‘Connected by’, addr)<br><br>    # Receive data from the client<br>    data = conn.recv(1024)<br>    if not data:<br>        break<br><br>    print(&#39;Received&#39;, repr(data))<br><br>    # Send a response back to the client<br>    conn.sendall(b&#39;Hello, client&#39;)<br><br>    # Close the current client connection<br>    conn.close()</pre><h4><strong>Additional notes</strong></h4><p>When binding, the server socket is assigned a specific port number. While different computers can use the same port numbers, each port on a single machine can only be assigned to one socket at a time.</p><p>The listen() method takes an argument (5 here) that sets the maximum number of queued incoming connections.</p><p>The server waits (blocks) at the accept() call until a client connects. Once a connection is made, accept() returns a new socket object for communicating with the client, along with the client’s address. This new socket is separate from the original server socket, which continues to listen for additional connections.</p><p>To handle multiple clients concurrently, the server can create a new thread or process for each client connection, allowing it to accept new connections without waiting for previous ones to finish.</p><p>The recv() method takes an argument (1024 here) that specifies the maximum amount of data (in bytes) to be received at once from the socket. If less data is available, it will return whatever is currently received. If more data is waiting, it can be read with another recv() call.</p><h3>Client Connection Process</h3><p>To connect to another computer there are several steps involved</p><ol><li>Ask the OS for the socket</li><li>Perform the DN lookup</li><li>Connect the socket to IP on a port</li><li>Send and receive data</li><li>Close the connection</li></ol><p>Start the server by running the server file and in a new shell</p><pre>import socket<br><br># Ask OS for the socket<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br><br># Perform DNS lookup and connect in one step<br>s.connect((&#39;localhost&#39;, 12345)) # DNS lookup is done by the OS<br><br># Send some data<br>s.sendall(b&#39;Hello, world&#39;) # Data is sent in bytes<br><br># Receive a response<br>data = s.recv(1024)<br>print(&#39;Received&#39;, repr(data))<br><br># Close the socket<br>s.close()</pre><h3>Conclusion</h3><p>We built a simple TCP server and client in Python to understand the basics of socket programming. You learned how to create sockets, connect clients to servers, and exchange data over a network. This forms the foundation for more advanced networking tasks.</p><h3>References</h3><ul><li>Python socket module (<a href="https://docs.python.org/3/library/socket.html">https://docs.python.org/3/library/socket.html</a>)</li><li>Beej’s Guide to Network Programming (<a href="https://beej.us/guide/bgnet/">https://beej.us/guide/bgnet/</a>)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221ba72ee2f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>