<?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 Pratham Mehta on Medium]]></title>
        <description><![CDATA[Stories by Pratham Mehta on Medium]]></description>
        <link>https://medium.com/@pratham_dev?source=rss-36307a40de7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mTMSWX1kExkWNaiUAe7-JQ.jpeg</url>
            <title>Stories by Pratham Mehta on Medium</title>
            <link>https://medium.com/@pratham_dev?source=rss-36307a40de7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:21:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pratham_dev/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[Let’s Create a Load Balancer]]></title>
            <link>https://medium.com/@pratham_dev/lets-create-a-load-balancer-75ebe133c956?source=rss-36307a40de7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ebe133c956</guid>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <dc:creator><![CDATA[Pratham Mehta]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 05:42:43 GMT</pubDate>
            <atom:updated>2026-04-09T05:42:43.186Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will understand what a load balancer is, how it works, and then build a working prototype of one. I heavily recommend reading the full article and then creating your own version of a load balancer — implementing at least 10 different features in your favourite language.</p><h3>What is a Load Balancer?</h3><p>Before going forward, let’s understand what a load balancer is and what problem it solves.</p><p>Imagine you have an application running on a simple single VM or EC2 instance. You have 100 users using your application and everything is working fine. Life is good.</p><p>Now you add a few new features, and users are loving them. Traffic starts scaling — from 100 users to 200, then to 500. Your server starts choking. Things are not working fine anymore because one server cannot handle all these requests.</p><p>So you decide to increase the capacity of the server — you upgrade the RAM, CPU, and storage of the machine. This is called <strong>Vertical Scaling</strong>: increasing the capacity of a single machine. Things start working fine again.</p><p>You add more features, users keep increasing, and you increase the size of the machine again. This cycle continues — but here is the real problem: <strong>how much can you actually increase the size of a machine?</strong> There is a hard limit to vertical scaling. You cannot scale it to infinity. At some point, the cloud provider simply does not offer a machine large enough for your needs.</p><p>And even if they did — what happens when that <strong>one giant machine goes down</strong> for maintenance or crashes? Your entire application dies. Every single user is affected. This is called a <strong>Single Point of Failure</strong>, and it is a serious risk at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*0xYJdONS2NvwLKTXVP017A.png" /></figure><h3>Enter: Horizontal Scaling</h3><p>Instead of making one machine bigger, what if you added <strong>more machines</strong> of a reasonable size and split the traffic across them? This is called <strong>Horizontal Scaling</strong> — scaling <em>out</em> instead of scaling <em>up</em>.</p><p>You spin up 3 servers, all running the same application. Now traffic is spread across all three. If one crashes, the other two keep serving users. If traffic doubles, you add a fourth server. No downtime. No replacing giant machines. Just plug it in.</p><p>But wait — if you have 3 servers, how does a user know which one to talk to? They cannot have 3 different IP addresses exposed. They need a <strong>single entry point</strong>.</p><p>That entry point is the <strong>Load Balancer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*cLjbYVs08v_HgLTI7CD_8A.png" /></figure><h3>How Does a Load Balancer Work?</h3><p>A Load Balancer sits in front of your servers. When a user makes a request, they do not talk to a server directly — they talk to the Load Balancer. The Load Balancer then decides which server should handle that request and forwards it there. The server processes the request and sends the response back, usually through the Load Balancer.</p><p>From the user’s perspective, they are talking to one address. Behind the scenes, there are multiple servers doing the actual work.</p><h3>Load Balancing Algorithms</h3><p>The Load Balancer uses different strategies — called algorithms — to decide which server gets the next request:</p><p><strong>1. Round Robin</strong> Requests are distributed one by one to each server in rotation. Server 1 gets request 1, Server 2 gets request 2, Server 3 gets request 3, then back to Server 1. Simple and fair, but does not account for server load.</p><p><strong>2. Weighted Round Robin</strong> Same as Round Robin, but servers with more capacity get a larger share of traffic. If Server 1 is twice as powerful as Server 2, it gets twice as many requests.</p><p><strong>3. Least Connections</strong> The request goes to whichever server currently has the fewest active connections. Great when requests vary in how long they take to process.</p><p><strong>4. IP Hashing</strong> The user’s IP address is hashed and mapped to a specific server. The same user always hits the same server. Useful when you need session stickiness.</p><p><strong>5. Random</strong> Requests are sent to a randomly chosen server. Surprisingly effective at scale due to the law of large numbers.</p><h3>Health Checks</h3><p>A Load Balancer does not blindly send traffic to all servers. It continuously runs <strong>health checks</strong> — pinging each server every few seconds to confirm it is alive and responding. If a server fails to respond, the Load Balancer marks it as unhealthy and stops sending it traffic. When the server recovers, it is added back automatically.</p><p>This is what eliminates the Single Point of Failure. If one of your 3 servers crashes, the Load Balancer detects it within seconds and routes all traffic to the remaining two. Your users barely notice.</p><p>A Load Balancer does not blindly send traffic to all servers. It continuously runs <strong>health checks</strong> — pinging each server every few seconds to confirm it is alive and responding. If a server fails to respond, the Load Balancer marks it as unhealthy and stops sending it traffic. When the server recovers, it is added back automatically.</p><p>This is what eliminates the Single Point of Failure. If one of your 3 servers crashes, the Load Balancer detects it within seconds and routes all traffic to the remaining two. Your users barely notice.</p><h3>How to Create a Load Balancer</h3><p>So now we understand what a load balancer is, how it works, and what the different algorithms are. But the natural question arises — <strong>how do you actually build one?</strong></p><p>The answer is simpler than you might think.</p><p>If you observe carefully, a load balancer is nothing but a <strong>reverse proxy</strong>. It takes a connection from the client, forwards it to one of the backend servers based on the chosen algorithm, then takes the response from that server and sends it back to the client.</p><p>That is it. No rocket science.</p><h3>Forward Proxy vs Reverse Proxy</h3><p>Before going further, let’s make sure these two terms are clear, because they confuse a lot of people.</p><p>A <strong>Forward Proxy</strong> sits in front of the <em>client</em>. The client talks to the proxy, and the proxy talks to the internet on behalf of the client. The server never knows who the real client is. This is what a VPN essentially does.</p><p>Client → Forward Proxy → Internet / Server</p><p>A <strong>Reverse Proxy</strong> sits in front of the <em>server</em>. The client talks to the proxy, and the proxy decides which backend server to forward the request to. The client never knows which server actually handled its request.</p><p>Client → Reverse Proxy → Server 1<br> xxxxxxxxxxxxxxxxxxx→ Server 2<br>xxxxxxxxxxxxxxxxxxx → Server 3</p><h3>What Is Actually Happening Under the Hood</h3><p>At its core, a load balancer is just a <strong>raw TCP server</strong>. Here is the entire flow in plain terms:</p><ol><li>Client opens a TCP connection to the load balancer</li><li>Load balancer receives the raw bytes of the request</li><li>Based on the algorithm, it picks a backend server</li><li>It opens a new TCP connection to that backend server</li><li>It pipes the client’s bytes straight through to the backend</li><li>The backend processes the request and sends bytes back</li><li>The load balancer pipes those bytes back to the client</li><li>Both connections close</li></ol><p>I have created my version of it in Nodejs, Typescript you can create it in any language</p><p>checkout here : <a href="https://bit.ly/3Q0bXbF">https://bit.ly/3Q0bXbF</a></p><p>In the Next Article we will understand how to scale a Load Balancer slighly hard problem .</p><p>Let’s Connect</p><p>x.com/Hi_Prathamm</p><p>linkedin.com/in/itsprathammehta/</p><p>medium.com/@pratham_dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ebe133c956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Understand Web Sockets]]></title>
            <link>https://medium.com/@pratham_dev/lets-understand-web-sockets-9f4ca4dcb09a?source=rss-36307a40de7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4ca4dcb09a</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[websocket-server]]></category>
            <dc:creator><![CDATA[Pratham Mehta]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 12:30:55 GMT</pubDate>
            <atom:updated>2026-04-04T12:30:55.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding WebSockets From the Ground Up</p><h4>The Problem: HTTP Was Never Built for Real-Time</h4><p>Before we talk about WebSockets, we need to talk about the world without them — because WebSockets did not appear out of thin air. They were invented to solve a very specific, very painful problem.</p><p>HTTP is the foundation of the web. Every time you load a page, fetch some JSON, or submit a form, you are using HTTP. It follows a simple pattern: the client asks, the server answers, and then the connection closes. This is called the <strong>request-response cycle</strong>, and for most of the web’s history, it worked perfectly.</p><p>But here is the problem. What if the server needs to tell <em>you</em> something — without you asking first?</p><p>Imagine you are building a chat application. User A sends a message to User B. The server receives it. Now how does User B’s browser know the message arrived? With plain HTTP, it simply cannot know — unless it keeps asking.</p><p>This is the core limitation that gave birth to three increasingly better solutions: short polling, long polling, and eventually WebSockets. Let’s walk through each one and understand exactly why each step was necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*MCNWBewWfg9ipI8euGWxPw.png" /></figure><h3>The Naive Approach: Short Polling</h3><p>Short polling is the most obvious solution. If the server cannot push data to you, just ask it over and over again on a timer.</p><pre>// Server-side (Node.js)<br>app.get(&#39;/poll&#39;, async (req, res) =&gt; {<br>  // Hold this request open — up to 30 seconds<br>  const data = await waitForNewData(30_000);<br>  res.json(data); // Only respond when there&#39;s something to say<br>});<br><br>// Client-side: re-poll immediately after every response<br>function longPoll() {<br>  fetch(&#39;/poll&#39;)<br>    .then(r =&gt; r.json())<br>    .then(data =&gt; {<br>      render(data);<br>      longPoll(); // Fire the next request immediately<br>    });<br>}</pre><p>Simple. Works. But deeply broken at scale.</p><p>Picture a WhatsApp-style chat app. It is 3am. Nobody is messaging anyone. But you have 10,000 users whose browsers are still open. Every 2 seconds, every single browser fires a GET request to your server. That is <strong>5,000 requests per second</strong> hitting your infrastructure — while absolutely nothing is happening.</p><p>And when something <em>does</em> happen — say User A sends a message at the 0.5-second mark of a 2-second poll cycle — User B will not see it for another 1.5 seconds. In a chat app, that feels like an eternity.</p><p><strong>The fundamental issue:</strong> the poll interval is a compromise you can never win. Make it faster (500ms) and you flood your server. Make it slower (5s) and your app feels sluggish. There is no right answer because the approach itself is wrong.</p><p>Short polling is fine for things like refreshing a weather widget every 60 seconds. It is completely unsuitable for chat, live notifications, collaborative editing, or anything where timing matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6Yk_n66fuJGjwrEzeCQSg.png" /></figure><h3>The Smarter Trick: Long Polling</h3><p>Engineers realized the problem with short polling: most requests return nothing. So they inverted the model. Instead of the server responding immediately, what if the server <em>held the request open</em> until it actually had something to say?</p><p>This is long polling.</p><pre>// Server-side (Node.js)<br>app.get(&#39;/poll&#39;, async (req, res) =&gt; {<br>  // Hold this request open — up to 30 seconds<br>  const data = await waitForNewData(30_000);<br>  res.json(data); // Only respond when there&#39;s something to say<br>});<br><br>// Client-side: re-poll immediately after every response<br>function longPoll() {<br>  fetch(&#39;/poll&#39;)<br>    .then(r =&gt; r.json())<br>    .then(data =&gt; {<br>      render(data);<br>      longPoll(); // Fire the next request immediately<br>    });<br>}</pre><p>This is genuinely better. When nothing happens, no wasted responses fire. When a message arrives, it gets delivered almost instantly — the response is already waiting in the queue, so delivery is near real-time.</p><p>Facebook’s early chat system used long polling. Twitter’s streaming API used long polling. It powered most of the “real-time” web from roughly 2006 to 2012.</p><p>But long polling has a deep structural flaw: the server is holding thousands of open HTTP connections in memory simultaneously. With 10,000 active users, you have 10,000 suspended request handlers sitting there, each consuming memory and a file descriptor. This is expensive. And at 30,000 or 100,000 users, it becomes a serious engineering problem.</p><p>There is also a subtler problem. Long polling is still <strong>half-duplex</strong> — the server can only send data in response to a client request. The client always has to “open the door” first. You can work around this, but it means every piece of server-initiated communication requires this roundabout mechanism.</p><p>And then there are proxies. Many corporate firewalls and load balancers aggressively kill connections that have been idle for more than 30 to 90 seconds. Your long-polling connection looks idle (no data flowing), so the proxy kills it. Your client has to detect this, reconnect, and re-establish the poll. The edge cases are endless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6Dbr7ahAG1O-jYbEsSoeA.png" /></figure><h3>Why Not UDP? The Reliability Argument</h3><p>At this point you might ask: why not skip TCP entirely and use UDP? UDP is fast, lightweight, and connectionless. Could it solve the real-time problem?</p><p>For some applications — video calls, multiplayer games, live audio streams — yes, UDP is the right choice. A dropped video frame is annoying but acceptable. You move on to the next frame.</p><p>But for chat, UDP is disqualifying. Here is why.</p><p>UDP is a fire-and-forget protocol. It has no acknowledgement system, no retransmission, and no ordering guarantees. When you send three UDP packets:</p><p>Packet 1: “Hey”</p><p>Packet 2: “How are” &lt;- router drops this under load</p><p>Packet 3: “you?”</p><p>The receiver sees: &quot;Hey&quot; and &quot;you?&quot;. Packet 2 is gone forever. UDP will not retransmit it. UDP does not even know it was lost.</p><p>For a chat message, this is catastrophic. Your conversation is now corrupted. You cannot tell the user “a packet was lost, please re-read from…” — that is not how messaging works.</p><p>TCP — the protocol underneath WebSockets — solves this at the transport layer. When a TCP segment goes missing, the OS automatically retransmits it. The receiver buffers out-of-order segments and delivers them in the correct order. The application layer (your code) never has to think about this. Messages always arrive complete and in order.</p><p>WebSockets are built on TCP precisely for this reason. You get UDP’s “always-open channel” feeling while keeping TCP’s ironclad delivery guarantees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAstS4PAEMMY6ZB_Zu5ctw.png" /></figure><h3>The Real Solution: WebSockets</h3><p>WebSocket is a communication protocol that provides a <strong>persistent, full-duplex, bidirectional channel</strong> between a client and a server over a single TCP connection.</p><p>Let’s unpack that:</p><ul><li><strong>Persistent</strong> — the connection stays open for the lifetime of your session. One connection, not thousands of reconnects.</li><li><strong>Full-duplex</strong> — both sides can send data at any time, independently. The server does not need to wait for you to ask.</li><li><strong>Bidirectional</strong> — messages flow freely in both directions simultaneously.</li><li><strong>Single TCP connection</strong> — no repeated handshakes, no repeated header negotiation, no overhead.</li></ul><p>Once a WebSocket connection is established, sending a message from server to client costs 2 bytes of framing overhead. Compare that to an HTTP request, which carries 400 to 800 bytes of headers every single time — even for a 10-byte payload. The efficiency difference is dramatic at scale.</p><h3>How the Protocol Switch Actually Works</h3><p>This is where it gets interesting. WebSocket does not replace HTTP — it <strong>starts as HTTP and then upgrades itself</strong>. This is clever design: it means WebSocket works through existing HTTP infrastructure (proxies, load balancers, firewalls) without needing a separate port or protocol negotiation.</p><p>Here is the exact sequence of what happens when you write new WebSocket(&#39;wss://example.com/chat&#39;) in your browser.</p><h3>Step 1 — TCP 3-Way Handshake</h3><p>Before anything WebSocket-related happens, the OS establishes a plain TCP connection to the server. This is invisible to your code — the OS handles it.</p><p>Client → Server:</p><p>SYN Server → Client:</p><p>SYN-ACK Client → Server: ACK</p><p>TCP connection established. This takes one round-trip — roughly 20ms on a fast connection, 150ms across continents.</p><h3>Step 2 — HTTP Upgrade Request</h3><p>The browser sends what looks like a totally normal HTTP GET request. But it contains special headers signalling the intention to upgrade:</p><pre>GET /chat HTTP/1.1<br>Host: example.com<br>Upgrade: websocket<br>Connection: Upgrade<br>Sec-WebSocket-Key: dGhlIHNhbXBsZQ==<br>Sec-WebSocket-Version: 13</pre><p>The Sec-WebSocket-Key is a randomly generated base64 string. The server uses it to prove it genuinely understands the WebSocket protocol (rather than being a confused HTTP server or a man-in-the-middle).</p><h3>Step 3 — Server Accepts (101 Switching Protocols)</h3><p>The server responds with HTTP status 101 — a status code you will almost never see anywhere else:</p><pre>HTTP/1.1 101 Switching Protocols<br>Upgrade: websocket<br>Connection: Upgrade<br>Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=</pre><p>The Sec-WebSocket-Accept value is computed by the server: it takes your key, appends a fixed GUID defined in the WebSocket RFC, SHA-1 hashes the result, and base64 encodes it. Your browser verifies this. This handshake proves both sides genuinely implement the WebSocket protocol.</p><h3>Step 4 — The Protocol Switch Is Complete</h3><p>After the 101 response, something fundamental changes. The TCP socket that carried your HTTP conversation is now <strong>repurposed</strong>. HTTP is gone. The protocol running over that socket is now WebSocket’s binary framing protocol. No new connection is made. The same TCP pipe is reused.</p><p>From this point forward, both sides can send WebSocket frames at any time:</p><p>Client → Server: WS Frame { data: “Hello!” }</p><p>Server → Client: WS Frame { data: “Hi back!” }</p><p>Server → Client: WS Frame { data: “User B is typing…” }</p><p>Client → Server: WS Frame { data: “How are you?” }</p><p>No waiting. No polling. No overhead. Pure bidirectional messaging.</p><h3>What Is the Keep-Alive Header?</h3><p>You will often see Connection: keep-alive in HTTP requests, and it is worth being clear about what this is — and what it is not.</p><p>HTTP/1.1 introduced keep-alive to allow multiple HTTP request-response cycles to share a single TCP connection. Instead of opening and closing a TCP connection for every asset on a page, the browser reuses one connection to fetch HTML, then CSS, then JavaScript, then images.</p><pre>GET /page HTTP/1.1<br>Connection: keep-alive<br><br>→ 200 OK (TCP stays open)<br><br>GET /style.css HTTP/1.1<br>Connection: keep-alive<br><br>→ 200 OK (TCP still open)<br><br>GET /logo.png HTTP/1.1<br><br>→ 200 OK (TCP eventually closes after idle timeout)</pre><p>This is faster than reopening a TCP connection for every resource. But it is still fundamentally <strong>request-response</strong>. The server cannot send anything unless the client asks first. The connection still eventually times out and closes. It is a performance optimisation, not a real-time communication mechanism.</p><p>WebSocket is categorically different. After the upgrade, the connection is not just reused — it is transformed. The server can push a frame to the client at 2am without any client request triggering it. The connection does not time out on idle (because WebSocket has its own heartbeat mechanism). It stays alive for as long as the application needs it.</p><h3>The Ping/Pong Heartbeat</h3><p>To keep the connection alive through NAT routers, proxies, and load balancers that would otherwise kill “idle” connections, WebSocket has built-in ping/pong frames.</p><p>Every 30 seconds or so, one side sends a Ping frame. The other side must respond with a Pong. This tiny exchange tells every piece of infrastructure between the client and server: &quot;this connection is still in use, do not kill it.&quot; If a pong never arrives, the application knows the connection has died and can reconnect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trZvFrtV_Egw4II2-9LSUA.png" /></figure><h3>Behind the Scenes: What Happens When You Send a Chat Message</h3><p>Let’s ground all of this in a concrete example. You are using a chat app. You type “Hello!” and hit send.</p><p>Here is the complete journey:</p><p><strong>1.</strong> Your JavaScript calls ws.send(&#39;Hello!&#39;). The WebSocket API packages your string into a WebSocket data frame. The frame header is just 2 to 10 bytes — an opcode byte indicating this is a text frame, and a length field.</p><p><strong>2.</strong> The frame travels over the open TCP connection. No new handshake. No new headers. No reconnection. The bytes go straight down the wire.</p><p><strong>3.</strong> The server receives the frame, decodes it, reads &quot;Hello!&quot;. It looks up which chat room you are in and fetches the list of other users currently connected to that room.</p><p><strong>4.</strong> For each user in the room, the server calls socket.send(&#39;Hello!&#39;) on their individual WebSocket connections. These are separate TCP connections to those specific users&#39; browsers.</p><p><strong>5.</strong> User B’s browser receives the frame. Their onmessage event fires. The UI updates. The message appears on their screen.</p><p>The total round-trip — from you pressing send to User B seeing the message — is typically 5 to 20 milliseconds on a local network, and 50 to 150 milliseconds across the internet. Compare that to long polling where you add the residual wait time of the polling cycle on top of network latency.</p><h3>When Should You Actually Use WebSockets?</h3><p>WebSockets are not always the right tool. They add complexity — you need to handle reconnection logic, authentication on the socket level, and message ordering. For simple cases, a well-designed REST API or Server-Sent Events (SSE) might be sufficient.</p><p>Use WebSockets when you need:</p><ul><li><strong>Chat and messaging</strong> — Slack, WhatsApp Web, Discord. Any UI where messages arrive unpredictably and must appear instantly.</li><li><strong>Live collaboration</strong> — Google Docs, Figma, Notion. Multiple users editing the same document, seeing each other’s cursors in real time.</li><li><strong>Real-time dashboards</strong> — Trading terminals, monitoring systems, live sports scores. Data that changes many times per second.</li><li><strong>Multiplayer games</strong> — Player positions, game state, inputs. Anything where a 200ms delay means you lose.</li><li><strong>Live notifications</strong> — The bell icon in the corner that fills up without you refreshing the page.</li></ul><p>You probably do not need WebSockets for: fetching user profiles, submitting forms, loading product listings, or anything where the user initiates every interaction and waiting a second is perfectly fine.</p><h3>A Quick Note on the Code Side</h3><p>On the client, WebSocket is a browser-native API:</p><pre>const ws = new WebSocket(&#39;wss://example.com/chat&#39;);<br><br>ws.onopen = () =&gt; {<br>  console.log(&#39;Connected&#39;);<br>  ws.send(JSON.stringify({ type: &#39;join&#39;, room: &#39;general&#39; }));<br>};<br><br>ws.onmessage = (event) =&gt; {<br>  const data = JSON.parse(event.data);<br>  renderMessage(data);<br>};<br><br>ws.onclose = () =&gt; {<br>  console.log(&#39;Disconnected — attempting reconnect...&#39;);<br>  setTimeout(connect, 3000); // Simple exponential backoff<br>};<br><br>ws.onerror = (err) =&gt; {<br>  console.error(&#39;WebSocket error:&#39;, err);<br>};</pre><p>On the server, libraries like Socket.IO (Node.js), ws (Node.js), or Django Channels (Python) handle the protocol details. You write application logic; they handle framing, ping/pong, and the upgrade handshake.</p><h3>Summary: The Evolution That Led Here</h3><p>The web needed real-time communication. HTTP’s request-response model made that impossible by design. Engineers worked around it with short polling (wasteful) and long polling (clever but expensive). Neither approach solved the fundamental problem: HTTP is half-duplex.</p><p>WebSocket solves it by performing a one-time HTTP handshake, switching the underlying TCP connection to the WebSocket framing protocol, and then keeping that connection open indefinitely. Both sides can send at any time. The overhead per message drops from hundreds of bytes to two. Latency drops to the speed of your network connection.</p><p>It is one of those protocol decisions that, once you understand how it works, feels obviously correct. Start as HTTP (so existing infrastructure accepts you). Upgrade once (so you only pay the overhead cost at connection time). Then get out of the way and let data flow freely in both directions.</p><p>That is WebSocket. That is why your Slack messages appear instantly. That is why your Google Docs collaborator’s cursor moves in real time. And that is why, for any serious real-time application, there really is no alternative.</p><p>Here’s the polished closing section for your blog:</p><h3>Now It’s Your Turn</h3><p>If you’ve made it this far, you have a solid mental model of how WebSockets work — from the HTTP upgrade handshake all the way down to the TCP socket being reused. But reading about it and <em>building</em> with it are two very different things.</p><p>So close this tab, open your editor, and get your hands dirty.</p><p>Start small. Write a Hello World. Get a WebSocket connection open between a browser and a server, send a single message, and print it on the other side. That first moment where you see your message appear in real time — no polling, no refresh — is the moment it all clicks.</p><p>Once that works, push yourself to build something real. A basic chat app is the perfect first project. Here is the mental model you need to implement:</p><p>Create a <strong>map of rooms</strong>. Each room is just a key in an object or a Map, holding a list of connected users. When a user joins, add their socket to the right room. When they send a message, loop through every socket in that room and broadcast it to all of them. When they disconnect, remove them from the room. That’s it. That’s the core of how Slack, Discord, and every other chat product works under the hood.</p><p>In Node.js you have two great options. <strong>ws</strong> is the raw, unopinionated WebSocket library — close to the metal, great for learning how the protocol actually behaves. <strong>socket.io</strong> adds rooms, namespaces, automatic reconnection, and a nicer API on top — great for building something production-like quickly. Pick whichever feels right and just start.</p><p>User connects → add to room</p><p>User sends message → broadcast to room</p><p>User disconnects → remove from room</p><p>If you can build that loop, you understand WebSockets. Everything else — authentication, message persistence, typing indicators, read receipts — is just layers on top of that same core idea.</p><h3>What’s Next</h3><p>In the next blog, we’ll tackle something significantly harder:</p><p><strong>Scaling a WebSocket server (we will build slack real time communication system with full working prototype)</strong></p><p>A single server handling 10,000 persistent connections is manageable. But what happens when you need to scale horizontally across multiple servers? If User A is connected to Server 1 and User B is connected to Server 2, how does a message from A reach B? The answer involves Redis Pub/Sub, sticky sessions, and some interesting distributed systems thinking — and it’s where most WebSocket architectures get genuinely complex.</p><p>We’ll break it down the same way we did here: from the problem, through the naive solution, to the right answer.</p><p>See you in the next one.</p><p>please follow -&gt;</p><p><a href="https://www.linkedin.com/in/itsprathammehta/">linkedin.com/in/itsprathammehta/</a></p><p><a href="https://x.com/Hi_Prathamm">x.com/Hi_Prathamm</a></p><p>medium.com/@pratham_dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4ca4dcb09a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Journey of SQL Query]]></title>
            <link>https://medium.com/@pratham_dev/the-complete-journey-of-sql-query-1a1a035cee15?source=rss-36307a40de7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a1a035cee15</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Pratham Mehta]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 17:22:15 GMT</pubDate>
            <atom:updated>2026-03-30T17:46:44.502Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you just Connect to your first database connection maybe a PostgreSQL/MySQL/ or XYZ database of your choice , and created a user in the database or fetching the user from the database, but have you ever understand what happens behind the scenes or you are taking everything as a Blackbox . In this article we will understand how actually database stores data on the disk , how it fetches data from the disk.</p><p><strong>The Complete Journey of SQL Query</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Mc-oFG5Wbq2PY0ZUhe4W7Q.png" /></figure><p><strong>Phase 1 -&gt; Parsing (turning text in to tree)</strong></p><p>You Executed Query SELECT name FROM users WHERE age &gt; 25. The database receives this as a raw string</p><p>The <strong>parser</strong> then does three things:</p><p>Lexical Analysis -&gt; the string is broken into tokens: SELECT, name, FROM, users, WHERE, age, &gt;, 25</p><p>Syntax analysis-&gt; the tokens are checked against the SQL grammar rules. If you wrote SELECT name FORM users, this step throws a syntax error. If everything is valid, it builds an <strong>Abstract Syntax Tree (AST)</strong> — a tree structure representing the logical meaning of your query.</p><p><strong>Semantic analysis</strong> — the database checks: does the table users actually exist? Does a column called name exist in it? Do you have permission to read it? This is where “table not found” or “column does not exist” errors come from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*mJA5_2u0Yezw_ZJq0E_qmw.png" /></figure><p><strong>Phase 2 — Query Optimization (the most important phase)</strong></p><p>This is where the database does its “thinking.” The <strong>query optimizer</strong> takes the AST and figures out the <em>best possible way</em> to execute it. This is a genuinely hard problem — a query with 5 joins can have thousands of valid execution strategies.</p><p>The optimizer considers: should it scan the entire table or use an index? Should it filter first and then join, or join first and then filter? Which join algorithm (nested loop, hash join, merge join) is fastest given the data size?</p><p>It uses <strong>statistics</strong> it has collected about the data — how many rows are in the table, what’s the distribution of values in the age column, etc. — to estimate the <em>cost</em> of each strategy. It then picks the lowest cost plan.</p><p>This is why running EXPLAIN before a query is so powerful — it shows you exactly which plan the optimizer chose.</p><h3>Phase 3 — Execution Plan (the blueprint)</h3><p>The optimizer outputs an <strong>execution plan</strong> — a tree of physical operations. For our query it might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Q9Olp_GZQWz-wL-ZCIOI1w.png" /></figure><p>The execution engine then walks this plan tree, executing each node and passing rows upward to the next step.</p><p><strong>Phase 4 — Storage Engine (the real I/O work)</strong></p><p>This is where the actual data lives. The storage engine is responsible for physically reading data from memory or disk.</p><p><strong>Buffer pool / cache first</strong> — the storage engine first checks if the required data pages are already loaded into RAM (the buffer pool). If yes, it reads them there — this is very fast (nanoseconds). If not, it has to go to disk.</p><p><strong>Disk I/O</strong> — data is stored in fixed-size <strong>pages</strong> (typically 8KB or 16KB). The engine reads the relevant pages off disk into the buffer pool. This is the slowest operation in the entire query — disk reads are measured in milliseconds, thousands of times slower than memory.</p><p><strong>Index lookup (if applicable)</strong> — if the optimizer chose an index, the engine first traverses the <strong>B-tree index</strong> to find the physical locations (page numbers + row offsets) of matching rows, then fetches only those pages. Without an index, it reads every single page in the table — a “full table scan.”</p><p><strong>Row format</strong> — in a row-based database (MySQL InnoDB, PostgreSQL), each page contains multiple rows packed together. In a columnar database (Redshift, ClickHouse), each page contains values from a single column. This is why columnar is so fast for analytics — reading age only touches the age pages, skipping everything else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Gs_Lm_zr6f_nrKJACp1PdQ.png" /></figure><p><strong>Phase 5 — Result Assembly &amp; Return</strong></p><p>Once rows start coming out of the execution engine, they’re assembled into a result set. The database applies any final ORDER BY (sort), LIMIT, or aggregate functions (COUNT, SUM) at this stage.</p><p>The result is then serialized into a <strong>wire protocol format</strong> — for PostgreSQL this is the “Frontend/Backend Protocol”, for MySQL it’s the MySQL protocol — and sent over the network (or socket) back to your client. Your client library (psycopg2, JDBC, mysql-connector, etc.) receives the bytes and deserializes them into language-native objects (Python dicts, Java ResultSet, etc.) that you see in your code.</p><p><strong>TLDR;</strong></p><p>Your app</p><p>↓ SQL string over TCP/socket</p><p>Database server</p><p>├─ Parser → AST</p><p>├─ Optimizer → Execution plan (lowest cost strategy)</p><p>├─ Execution engine → Walks the plan, processes rows</p><p>└─ Storage engine</p><p>├─ Check buffer pool (RAM) ← fast path</p><p>└─ Read from disk (I/O) ← slow path</p><p>└─ B-tree index lookup (if index exists)</p><p>↓ Result rows serialized to wire protocol</p><p>Your app ← deserialized into objects</p><p><strong>Thanks for Reading -&gt;</strong></p><p>for more such blogs follow and</p><p><strong>Checkout -&gt;</strong></p><p><a href="https://x.com/Hi_Prathamm"><strong>x.com/Hi_Prathamm</strong></a></p><p><strong>l</strong><a href="https://www.linkedin.com/in/itsprathammehta/"><strong>inkedin.com/in/itsprathammehta</strong></a></p><p><a href="https://github.com/ThePrathamMehta"><strong>github.com/ThePrathamMehta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a1a035cee15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>