<?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 Yash Patel on Medium]]></title>
        <description><![CDATA[Stories by Yash Patel on Medium]]></description>
        <link>https://medium.com/@niceperson2110?source=rss-43125f002298------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ilL5cgywNUfIIkqdZSBWog.jpeg</url>
            <title>Stories by Yash Patel on Medium</title>
            <link>https://medium.com/@niceperson2110?source=rss-43125f002298------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:04:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niceperson2110/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[Stop Using Refresh Tokens Just Because Everyone Else Does — Understand Why They Exist]]></title>
            <link>https://medium.com/@niceperson2110/stop-using-refresh-tokens-just-because-everyone-else-does-understand-why-they-exist-28b24a5e1801?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b24a5e1801</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 14:53:01 GMT</pubDate>
            <atom:updated>2026-07-11T14:53:01.294Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve built authentication using JWT, you’ve probably seen this architecture everywhere:</p><pre>User Login<br>      │<br>      ▼<br>Access Token (15 mins)<br>Refresh Token (30 days)</pre><p>Every tutorial says:</p><blockquote><em>“Use a short-lived access token and a long-lived refresh token.”</em></blockquote><p>But almost nobody answers the most important question:</p><blockquote><strong><em>Why?</em></strong></blockquote><p>Recently, while designing an authentication system for one of my projects, I started asking myself questions that many developers eventually ask but rarely find satisfying answers to.</p><p>This article is that journey.</p><p>By the end, you’ll understand not only <strong>how</strong> refresh tokens work but <strong>why</strong> they exist, when you actually need them, and whether they’re always the best solution.</p><h3>The First Question Everyone Should Ask</h3><p>Let’s imagine a simple authentication system.</p><p>A user logs in.</p><p>The server generates a JWT.</p><p>The client stores it.</p><p>Every API request sends the JWT.</p><p>Simple.</p><p>So why can’t we just keep doing this?</p><pre>Client<br>   │<br>   ▼<br>Access Token<br>   │<br>   ▼<br>API</pre><p>It works.</p><p>Many small applications are built exactly this way.</p><p>So…</p><p><strong>Why introduce another token?</strong></p><h3>Problem #1: How Long Should the Token Live?</h3><p>Suppose your JWT expires after <strong>30 days</strong>.</p><p>Everything feels great.</p><p>The user logs in once.</p><p>No interruptions.</p><p>But now imagine an attacker somehow steals that token.</p><p>Suddenly…</p><p>They also have <strong>30 days of access</strong>.</p><p>Not good.</p><p>So you think:</p><blockquote><em>“Easy. I’ll reduce the expiration.”</em></blockquote><p>Let’s make it <strong>15 minutes</strong>.</p><p>Now security is much better.</p><p>But users now have to log in every 15 minutes.</p><p>Also not good.</p><p>You’ve just discovered one of authentication’s biggest trade-offs:</p><p><strong>Long expiration = Better UX, Worse Security</strong></p><p><strong>Short expiration = Better Security, Worse UX</strong></p><p>So how do companies solve this?</p><h3>Enter Refresh Tokens</h3><p>Instead of giving users one powerful long-lived credential, split responsibilities.</p><pre>Access Token<br>────────────<br>Short-lived<br>Used for APIs</pre><pre>Refresh Token<br>─────────────<br>Long-lived<br>Used only to obtain new access tokens</pre><p>The browser keeps using the access token.</p><p>When it expires…</p><pre>POST /refresh</pre><p>The server verifies the refresh token and issues a new access token.</p><p>The user never notices.</p><p>Problem solved.</p><p>Or is it?</p><h3>Wait…</h3><p>I Had Another Question.</p><p>If an attacker steals my access token…</p><p>Can’t they just steal my refresh token too?</p><p>This question completely changed how I looked at authentication.</p><p>Because if the attacker has both…</p><pre>Access Token ✅</pre><pre>Refresh Token ✅</pre><p>They can simply call</p><pre>POST /refresh</pre><p>and continue the session forever.</p><p>So…</p><p>What’s the point?</p><h3>The Important Assumption Nobody Mentions</h3><p>The authentication model does <strong>not</strong> assume refresh tokens are impossible to steal.</p><p>It assumes something much simpler.</p><blockquote><strong><em>Refresh tokens are harder to steal than access tokens.</em></strong></blockquote><p>Notice the wording.</p><p>Not impossible.</p><p>Just harder.</p><p>Why?</p><p>Because refresh tokens are usually stored differently.</p><p>Instead of JavaScript-accessible storage like Local Storage…</p><p>They’re typically stored in:</p><ul><li>HttpOnly Cookies</li><li>Secure Cookies</li><li>SameSite Cookies</li></ul><p>JavaScript cannot read them.</p><p>That’s a huge security improvement.</p><h3>But I Had Yet Another Question…</h3><p>What if I simply stored my <strong>Access Token</strong> inside an HttpOnly cookie?</p><p>Wouldn’t that solve half the problem?</p><p>Turns out…</p><p>It actually solves quite a lot.</p><p>Now JavaScript cannot steal the access token either.</p><p>Interesting.</p><p>So maybe we don’t even need refresh tokens?</p><h3>My First Alternative Design</h3><p>I thought…</p><p>Why not keep only an access token?</p><p>Whenever a request comes in…</p><p>Check a database flag.</p><pre>isBlocked = false</pre><p>If it’s true…</p><p>Reject the request.</p><p>Logout?</p><p>Just update the database.</p><p>Session revoked instantly.</p><p>No refresh tokens.</p><p>Simple.</p><p>Sounds good.</p><p>Then I realized something.</p><p>Every single API request now requires a database lookup.</p><p>One request?</p><p>No problem.</p><p>One million requests?</p><p>Different story.</p><p>This is exactly why JWT became popular in the first place.</p><p>They’re stateless.</p><p>The server verifies the signature.</p><p>Done.</p><p>No database.</p><h3>My Second Idea</h3><p>This one felt even better.</p><p>Instead of checking the database every time…</p><p>Let’s use Redis.</p><p>Login:</p><pre>Generate Access Token</pre><pre>↓</pre><pre>Store token ID in Redis</pre><p>When the token expires…</p><pre>Expired Token</pre><pre>↓</pre><pre>Lookup Token ID in Redis</pre><pre>↓</pre><pre>Still Exists?</pre><pre>↓</pre><pre>Generate New Access Token</pre><pre>↓</pre><pre>Delete Old Session</pre><pre>↓</pre><pre>Create New Session</pre><p>No refresh token.</p><p>No database.</p><p>Fast Redis lookups.</p><p>Honestly…</p><p>This felt like a great design.</p><p>Until another question appeared.</p><h3>The Hidden Problem</h3><p>Imagine this timeline.</p><pre>9:00 AM<br>Attacker steals Access Token<br><br>9:15 AM<br>Token expires</pre><p>Now both the attacker and the real user possess the same expired token.</p><p>Whoever renews first…</p><p>Wins.</p><p>If the attacker reaches the server first…</p><pre>Generate New Token<br>↓<br>Delete Old Session</pre><p>The legitimate user now gets:</p><pre>401 Unauthorized</pre><p>The attacker has effectively taken over the session.</p><p>This is the subtle problem refresh tokens are designed to reduce.</p><h3>Wait…</h3><p>Wouldn’t The Same Thing Happen With Refresh Tokens?</p><p>Excellent question.</p><p>If an attacker steals:</p><pre>Access Token<br>+<br>Refresh Token</pre><p>Yes.</p><p>Exactly the same thing can happen.</p><p>So refresh tokens aren’t magic.</p><p>They’re just another credential.</p><h3>Then Why Does The Industry Use Them?</h3><p>Because security is about <strong>reducing risk</strong>, not eliminating it.</p><p>Think about your house.</p><p>A lock doesn’t guarantee nobody will ever enter.</p><p>It simply makes unauthorized entry more difficult.</p><p>Refresh tokens do exactly that.</p><p>They reduce the attack surface.</p><p>Access tokens travel with almost every authenticated request.</p><p>Refresh tokens usually don’t.</p><p>Access tokens are constantly used.</p><p>Refresh tokens are used occasionally.</p><p>Access tokens are more exposed.</p><p>Refresh tokens are better protected.</p><p>That’s the real reason.</p><h3>Modern Production Systems Add Even More Protection</h3><p>Large applications rarely stop at refresh tokens.</p><p>They also implement:</p><ul><li>Refresh Token Rotation</li><li>Session Revocation</li><li>Device Tracking</li><li>Suspicious Login Detection</li><li>Multi-Factor Authentication</li><li>HttpOnly Cookies</li><li>Secure Cookies</li><li>SameSite Policies</li><li>Content Security Policy (CSP)</li></ul><p>Authentication isn’t built on one mechanism.</p><p>It’s built on layers.</p><h3>The Biggest Lesson I Learned</h3><p>At first, I thought refresh tokens existed because they were somehow “more secure.”</p><p>That isn’t really true.</p><p>The real insight is much simpler.</p><p>An access token is meant to answer:</p><blockquote><em>“Can this request access the API?”</em></blockquote><p>A refresh token is meant to answer:</p><blockquote><em>“Can this session continue?”</em></blockquote><p>Those are two different privileges.</p><p>Separating them limits what happens if one credential is compromised.</p><p>That’s why access tokens stay short-lived.</p><p>That’s why refresh tokens are protected more aggressively.</p><p>And that’s why most production systems still use both.</p><h3>Final Thoughts</h3><p>The best authentication architecture depends on your application.</p><p>For a small internal tool, a single secure session cookie may be more than enough.</p><p>For a SaaS application with thousands of users, access and refresh tokens often provide a better balance between user experience and security.</p><p>What’s important isn’t copying the latest authentication pattern.</p><p>It’s understanding the trade-offs behind it.</p><p>Once you understand <strong>why</strong> a design exists, you can decide whether it actually fits your own application.</p><p>And that’s far more valuable than following any tutorial blindly.</p><h3>What do you think?</h3><p>Have you ever questioned the need for refresh tokens?</p><p>Or have you designed an authentication flow differently?</p><p>I’d love to hear your approach and discuss the trade-offs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b24a5e1801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full Lifecyle of Browser Request]]></title>
            <link>https://javascript.plainenglish.io/full-lifecyle-of-browser-request-74dd39929d19?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/74dd39929d19</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 04:52:06 GMT</pubDate>
            <atom:updated>2026-07-11T04:52:06.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dV6xU0kSGUd38PpE7T_qZQ.png" /></figure><ul><li><strong>RTT is the real currency, not milliseconds.</strong> TCP costs 1 RTT, TLS 1.3 costs 1 RTT (2 for older TLS 1.2), and the actual request/response is roughly another RTT split in half each way. On a 50ms RTT connection, that’s ~150–200ms burned before your server even sees the request — before it does any work.</li><li><strong>Cold vs warm changes everything.</strong> A cache hit on DNS and a reused (keep-alive) TCP+TLS connection can skip 3 of these 8 stages entirely — that’s the single biggest lever HTTP/1.1 keep-alive and HTTP/2 connection multiplexing pull.</li><li><strong>Server processing time is the only stage you fully control.</strong> Everything above it (DNS, TCP, TLS) is largely network physics — geography and protocol version. This is why edge/CDN placement matters more than code optimization for that portion of total latency.</li><li><strong>Render isn’t “free time” after the response arrives</strong> — parsing, layout, and paint can add as much latency as the entire network round trip, especially with render-blocking JS/CSS.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74dd39929d19" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/full-lifecyle-of-browser-request-74dd39929d19">Full Lifecyle of Browser Request</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[The Crash Course For the networking for web developer.]]></title>
            <link>https://javascript.plainenglish.io/the-crash-course-for-the-networking-for-web-developer-1109d947a23f?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/1109d947a23f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 03:51:22 GMT</pubDate>
            <atom:updated>2026-07-10T03:51:22.967Z</atom:updated>
            <content:encoded><![CDATA[<h4>Performance is a feature. This blog provides a hands-on sheet of what every web developer needs to know about the various types of networks, transport protocols and application protocols for better and reliable user experience.</h4><p>This Blog is a summary of the book written by <a href="https://medium.com/u/2578f746f852">Ilya Grigorik</a>, Web performance engineer at Google. Apart from that in this blog you will find plenty of grammar mistakes, the language that is very simple and sometimes funny. keep up with this as the meaning will not be changed. Let’s dive with the very first topic. Meet you at end of the topic.</p><h3>Chapter 1: Primer on Latency and Bandwidth</h3><p>speed is a feature, faster sites lead to better user engagement, faster sites lead to better user retention, faster sites lead to higher conversions. Simply put, speed is a feature. and to deliver it, we need to understand the many factors and fundamental limitation that are at play.</p><p><strong>Two Critical Factors:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7nYxRECc-vxPYoKwWx_fA.png" /></figure><p><strong><em>Latency</em></strong><em>: The time from the source sending a packet to the destination receiving it.<br></em><strong><em>Bandwidth</em></strong><em>: maximum throughput of a logical or physical communication path.</em></p><p>Let’s take a close look at some common contributing components for a typical router on the internet, which is responsible for relaying a message between client and server.</p><ul><li><em>propagation delay — amount of time required for a message to travel from the sender to receiver, which is a function of distance over speed with which the signal propagates.</em></li><li><em>Transmission Delay — Amount of time required to push all the packet’s bits into the link, which is a function of the packet’s length and data rate of the link.</em></li><li><em>Processing Delay — Amount of time to process the packet header, check for bit-level errors, and determine the packet’s destination.</em></li><li><em>Queuing Delay — Amount of time the packet is waiting in the queue until it can be processed.</em></li></ul><p>The total latency between the client and the server is the sum of all the delays just listed. Propagation delay is the speed is usually within a small constant factor of the speed of light. on the other hand, transmission delay is dictated by the available data rate. e.g. we want to transmit 10MB file over two links: 1 mbps and 100Mbps. It will take 10 seconds to put the entire file on the wire over the 1 mbps link and 0.1 seconds over the 100 Mbps link.</p><p>Next once the packet arrives at the router, the router must examine the packet header to determine the outgoingroute and may run other checks on the data — this takes as well. Much of the logic is now often done at hardware level. so the delays are small. If the packets are coming in more speed then router is capable of then there will be queue for this stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*T9kZXpNpGAdJf6FdE8kITw.png" /></figure><p>Based on the speed of light we are actually going there or reaching there with engineering fiber optics. But this is not the case that signal will only go through the fiber optics there will be different nodes that will transmit this signals. So this latency is also taken care of in creating any system as human have mental context switch time is 1 second. The point is simple, to deliver the best experience and to keep users engaged in the task at hand, we need our applications to respond within hundreds of milliseconds.</p><blockquote>Content delivery networkd (CDN) services provides many benefits, but chief among them is the simple observation that distributing the content around the globe, and serving that content from a nearby location to the client, enables us to significantly reduce the propagation delay of all the data packets.<br>We may not be able to make the packets travel faster, but we can reduce the distance by strategically putting the server closer to the users!</blockquote><h4>Last-Mile Latency</h4><p>Ironically, it is often the last few miles, not the crossing of oceans or continents, where significant latency is introduced: the infamous last-mile problem. To connect your home or office to the Internet, your local ISP needs to route the cables throughout the neighborhood, aggregate the signal, and forward it to a local routing node. In practice, depending on the type of connectivity, routing methodology, and deployed technology, these first few hops alone can take tens of milliseconds.</p><p>The last-mile latencies can vary wildly between ISP’s due to the deployed technology, topology of the network, and even the time of day. As an end user, and if you are looking to improve your web browsing speeds, make sure to measure and compare the last-mile latencies of the various providers available in your area.</p><blockquote>Traceroute is simple networking tool for identifying the routing path of the packets and the latency of each network hops.<br>Linux — traceroute<br>Windows — tracert</blockquote><h4>Bandwidth at the Network Edge</h4><p>The backbones, or the fiber links, that form the core data paths of the Internet are capable of moving hundreds of terabits per second. However, the available capacity at the edges of the network is much, much less, and varies wildly based on deployed technology: dial-up, DSL, cable, a host of wireless technologies, fiber-to-the-home, and even the performance of the local router. The available bandwidth to the user is a function of the lowest capacity link between the client and the destination server</p><p>As a result, to improve performance of our applications, we need to architect and optimize our protocols and networking code with explicit awareness of the limitations of available bandwidth and the speed of light: we need to reduce round trips, move the data closer to the client, and build applications that can hide the latency through caching, pre-fetching, and a variety of similar techniques, as explained in subsequent chapters.</p><p>Hello guys 👋- It was amazing core concepts to excell in the building the tools that are using this network. Now you know how your data flows across the networks and what factors are affecting it. So now we will move forward to the protocols that are used in every communications. see ya at end.</p><h3>Chapter 2: Building Blocks of TCP</h3><h4>1. What is TCP and Why Does It Matter?</h4><p>TCP (Transmission Control Protocol) sits alongside IP to form the Internet’s backbone. Its core job: <strong>provide the abstraction of a reliable network over an unreliable channel.</strong> It handles retransmission of lost data, in-order delivery, congestion control, and data integrity — all transparently from your app’s perspective.</p><p>Key trade-off: TCP is optimized for accurate delivery, rather than a timely one — which directly creates web performance challenges.</p><h4>2. Three-Way Handshake (SYN → SYN-ACK → ACK)</h4><p>Every TCP connection starts with this ritual before a single byte of application data moves:</p><ul><li><strong>SYN</strong> — Client picks a random sequence number x, sends SYN packet</li><li><strong>SYN-ACK</strong> — Server increments x, picks its own sequence number y, replies</li><li><strong>ACK</strong> — Client increments both by 1, handshake complete</li></ul><p><strong>Performance cost:</strong> each new connection will have a full roundtrip of latency before any application data can be transferred. On a New York → London fiber link, that’s a minimum 56 ms just to start.</p><p>This is why <strong>connection reuse</strong> is the most critical TCP optimization.</p><p>TCP Fast Open (TFO)</p><p>An optimization that allows data to be sent inside the SYN packet itself for repeat connections. Based on traffic analysis at Google, TFO can decrease HTTP transaction network latency by 15%, whole-page load times by over 10% on average, and in some cases by up to 40% in high-latency scenarios. Requires support on both client and server.</p><h4>3. Flow Control</h4><p>Prevents the sender from overwhelming the receiver. Each side advertises its <strong>receive window (rwnd)</strong> — the size of its available buffer.</p><ul><li>Both sides adjust rwnd dynamically with every ACK packet</li><li>If rwnd hits 0, the sender must pause until the receiver clears its buffer</li></ul><p>Window Scaling (RFC 1323)</p><p>The original TCP spec capped the receive window at <strong>65,535 bytes</strong> (16-bit field). RFC 1323 provides a “TCP window scaling” option, which allows us to raise the maximum receive window size from 65,535 bytes to 1 gigabyte. This is negotiated during the handshake and is on by default in modern OS, but routers/firewalls can silently strip it.</p><h4>4. Congestion Control — Slow-Start</h4><p>Flow control protects the receiver; <strong>congestion control protects the network itself.</strong> In 1986, congestion collapse brought ARPANET to its knees — capacity dropped by a factor of 1,000 in some cases.</p><p>The solution: <strong>slow-start</strong>, introduced by Van Jacobson and Michael Karels in 1988.</p><p><strong>How it works:</strong></p><ul><li>Server maintains a <strong>congestion window (cwnd)</strong> — a private sender-side limit</li><li>max data in-flight = min(rwnd, cwnd)</li><li>Starts conservatively: 10 segments (per RFC 6928, updated from 4 in 1999)</li><li>For every ACK received, cwnd grows by 1 segment → <strong>exponential growth</strong></li></ul><p><strong>Real-world impact</strong> (New York ↔ London, 56ms RTT, 64 KB file):</p><ul><li>Over a <strong>new</strong> TCP connection → <strong>264 ms</strong></li><li>Over an <strong>existing</strong> TCP connection (no handshake, no slow-start) → <strong>96 ms</strong></li><li>That’s a <strong>275% performance difference</strong> — same bandwidth, same machines.</li></ul><p>For short HTTP transfers (which are most web requests), slow-start often means the transfer ends <em>before</em> the window even reaches maximum size.</p><p>Slow-Start Restart (SSR)</p><p>TCP also resets cwnd on idle connections, since network conditions may have changed. It is generally recommended to disable SSR on the server to help improve performance of long-lived HTTP connections. On Linux: sysctl -w net.ipv4.tcp_slow_start_after_idle=0</p><h4>5. Congestion Avoidance</h4><p>Once cwnd grows past a threshold (ssthresh) or a packet is lost, congestion avoidance kicks in. The implicit assumption in congestion avoidance is that packet loss is indicative of network congestion.</p><p>This produces the classic <strong>sawtooth pattern</strong> in TCP throughput traces — the window grows, a packet drops, it resets, repeat.</p><p>Proportional Rate Reduction (PRR)</p><p>The original algorithm (AIMD — Multiplicative Decrease, Additive Increase) was too conservative. PRR, specified by RFC 6937, provides a 3–10% reduction in average latency for connections with packet loss. It’s the default in Linux 3.2+ kernels.</p><h4>6. Bandwidth-Delay Product (BDP)</h4><p>A critical concept: <strong>the bottleneck is often not bandwidth — it’s RTT.</strong></p><p>BDP = Bandwidth × RTT = max unacknowledged data in-flight</p><p>Example: with a 16 KB window and 100ms RTT, regardless of your pipe size, the connection caps out at <strong>~1.31 Mbps</strong>. To hit 10 Mbps on the same RTT, you’d need a window of at least <strong>122 KB</strong> — which requires window scaling.</p><p>The window size must be “just big enough” that the sender never has to stop and wait for ACKs. Too small → gaps in data flow → wasted bandwidth.</p><h4>7. Head-of-Line (HOL) Blocking</h4><p>TCP delivers packets <strong>in order</strong>. If packet #4 is lost, packets #5, #6, #7… wait in the receiver’s buffer until #4 is retransmitted and arrives.</p><p>The application has no visibility into the TCP retransmissions or the queued packet buffers, and must wait for the full sequence before it is able to access the data. This effect is known as TCP head-of-line (HOL) blocking. <a href="https://hpbn.co/building-blocks-of-tcp/">hpbn</a></p><p>The cost: <strong>unpredictable latency variation (jitter)</strong>. For apps like audio, video, or real-time gaming — where a slightly stale packet is worse than no packet — this makes TCP a poor fit. That’s why WebRTC and similar technologies use <strong>UDP</strong> instead.</p><h4>8. Optimizing for TCP — The Checklist</h4><p>In most cases, latency, not bandwidth, is the bottleneck for TCP. Key server-side and application-level levers: <a href="https://hpbn.co/building-blocks-of-tcp/">hpbn</a></p><p><strong>Server config:</strong></p><ul><li>Upgrade to latest kernel (IW10 default in Linux 2.6.39+; PRR in 3.2+)</li><li>Set initial cwnd to 10 segments</li><li>Enable window scaling (RFC 1323)</li><li>Disable slow-start after idle</li><li>Enable TCP Fast Open where possible</li></ul><p><strong>Application behavior:</strong></p><ul><li><strong>Send fewer bits</strong> — compress, eliminate unnecessary transfers</li><li><strong>Move bits closer</strong> — use CDNs, geo-distribute servers to reduce RTT</li><li><strong>Reuse TCP connections</strong> — avoid handshake + slow-start on every request (keepalive, connection pooling, HTTP/2 multiplexing all exploit this)</li></ul><h4>Key Takeaway for Engineers</h4><p>The four immovable truths of TCP performance:</p><ol><li>The three-way handshake costs <strong>1 full RTT</strong> before any data flows</li><li>Slow-start applies to <strong>every new connection</strong></li><li>Flow and congestion control <strong>cap throughput</strong> on all connections</li><li>Throughput is governed by <strong>current cwnd size</strong>, not just available bandwidth</li></ol><p>This is the foundational reason why techniques like connection pooling, CDNs, HTTP/2 multiplexing, and persistent connections exist — they’re all working around these TCP fundamentals.</p><h3>Chapter 3: Building Blocks of UDP</h3><h4>1. What is UDP and Why Does It Exist?</h4><p>UDP was added to the core network protocol suite in August of 1980 by Jon Postel — right at the time when TCP and IP specifications were being split into two separate RFCs.</p><p>The key insight: <strong>UDP’s appeal is not what it adds, but what it deliberately leaves out.</strong> UDP is colloquially referred to as a “null protocol,” and RFC 768, which describes its operation, could indeed fit on a napkin.</p><p>A <strong>datagram</strong> (UDP’s unit of data) is different from a generic “packet” — the term “datagram” is often reserved for packets delivered via an unreliable service — no delivery guarantees, no failure notifications. That’s why you’ll also hear UDP called “Unreliable Datagram Protocol.”</p><p><strong>Where you already use UDP without knowing it:</strong> DNS. Every time your browser resolves google.com to an IP address, it&#39;s using UDP under the hood. And now with <strong>WebRTC</strong>, UDP is a first-class browser transport for real-time voice, video, and P2P communication.</p><h4>2. Null Protocol Services — What UDP Actually Does (and Doesn’t Do)</h4><p>UDP sits on top of IP just like TCP does. IP’s job: route packets from source to destination. But IP gives zero guarantees — if a router drops your packet, it’s gone, no notification.</p><p>UDP adds only <strong>4 fields on top of IP</strong>: source port, destination port, length, and checksum. That’s it — an 8-byte header total. Even the checksum and source port are optional.</p><p><strong>The complete list of things UDP does NOT do:</strong></p><ul><li>❌ No guarantee of message delivery (no ACKs, no retransmission, no timeouts)</li><li>❌ No guarantee of order (no sequence numbers, no reordering, no HOL blocking)</li><li>❌ No connection state (no handshake, no teardown)</li><li>❌ No congestion control (no cwnd, no feedback mechanisms)</li></ul><p>What UDP <em>does</em> provide: application multiplexing on top of IP by embedding the source and the target application ports of the communicating hosts.</p><p><strong>TCP vs UDP packet model:</strong> TCP is a byte-stream — a message can span multiple packets with no defined boundary. UDP datagrams have definitive boundaries: each datagram is carried in a single IP packet, and each application read yields the full message; datagrams cannot be fragmented.</p><p><strong>Warning before you roll your own protocol:</strong> Without careful engineering and planning, it is not uncommon to start with a bright idea for a new protocol but end up with a poorly implemented version of TCP. The algorithms and state machines in TCP have been honed and improved over decades.</p><h4>3. UDP and NAT (Network Address Translators)</h4><p>This is where UDP gets complicated in the real world.</p><p><strong>Why NAT exists:</strong> IPv4 addresses are only 32 bits long, providing a maximum of 4.29 billion unique IPs. NAT was introduced in 1994 as an interim solution to the looming IPv4 address depletion problem. NAT devices maintain a translation table mapping private IP:port pairs to a shared public IP:port — so many devices can share one public IP.</p><p>What was meant to be temporary became permanent: NAT devices are now baked into routers, firewalls, corporate proxies, and security appliances everywhere.</p><p><strong>Private IP ranges reserved by IANA</strong> (behind NAT):</p><ul><li>10.0.0.0/8</li><li>172.16.0.0/12</li><li>192.168.0.0/16</li></ul><h4>4. Connection-State Timeouts</h4><p>TCP and NAT work fine together — TCP’s handshake and termination sequences tell the NAT exactly when to create and delete translation records.</p><p>UDP has no such signals. Translators have to keep state about each UDP flow, which itself is stateless. Even worse, the translator is also tasked with figuring out when to drop the translation record, but since UDP has no connection termination sequence, either peer could just stop transmitting at any point without notice. To address this, UDP routing records are expired on a timer.</p><p>How long is the timer? It varies wildly by vendor, router model, and configuration — completely unpredictable.</p><p><strong>Best practice:</strong> For long-running sessions over UDP, introduce bidirectional keepalive packets to periodically reset the timers for the translation records in all the NAT devices along the path. Typical interval: every 15–30 seconds.</p><h4>5. NAT Traversal</h4><p>NAT is fine when <em>you</em> initiate an outbound connection — your router creates the translation record automatically. The problem is <strong>inbound connections</strong>: if a peer on another network tries to reach you directly (P2P apps — VoIP, games, file sharing), the NAT blocks it because there’s no existing translation record for that inbound traffic.</p><p>Three techniques to work around this, in order of preference:</p><p>STUN — Session Traversal Utilities for NAT (RFC 5389)</p><p>STUN is a protocol that allows the host application to discover the presence of a network address translator on the network, and when present, to obtain the allocated public IP and port tuple for the current connection.</p><p>Think of it like asking a public server: “What’s my public IP and port from your perspective?” Both peers do this, exchange their public addresses, then attempt a direct connection. Works 92% of the time in the real world.</p><p>TURN — Traversal Using Relays around NAT (RFC 5766)</p><p>When direct connection fails (symmetric NAT, strict firewalls), traffic is routed through a relay server. TURN is the most reliable way to provide connectivity between any two peers on any network, but it carries a very high cost of operating the TURN server — at the very least, the relay must have enough capacity to service all the data flows. As a result, TURN is best used as a last resort fallback.</p><p>According to Google’s libjingle library data: 92% of connections succeed via STUN (direct), only 8% need TURN (relay).</p><p>ICE — Interactive Connectivity Establishment (RFC 5245)</p><p>ICE is a protocol that ties it all together for the participants: direct connection where possible, leveraging STUN negotiation where needed, and finally fallback to TURN if all else fails.</p><p>ICE is what WebRTC uses under the hood to establish peer connections.</p><h4>6. Optimizing for UDP</h4><p>Since UDP gives you nothing for free, everything is your responsibility at the application layer. Key principles:</p><ul><li><strong>Implement your own error handling</strong> if your app needs it — UDP won’t do it for you</li><li><strong>Add keepalives</strong> to prevent NAT translation records from expiring mid-session</li><li><strong>Handle packet loss gracefully</strong> — for real-time apps (audio, video, gaming), missing a packet and moving on is better than waiting for retransmission</li><li><strong>Use STUN/TURN/ICE</strong> if you need P2P connectivity across NATs</li><li><strong>Don’t implement congestion control wrong</strong> — a poorly behaved UDP app can flood the network and harm other users. If you need reliable delivery, use TCP; if you need real-time delivery, design your loss-tolerance carefully</li></ul><h4>TCP vs UDP — The Core Trade-off</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*3EhLZrv_yefS-bk2AMnRFQ.png" /></figure><h4>Key Takeaway</h4><p>UDP is not “broken TCP” — it’s a <strong>deliberate design choice</strong>. For latency-sensitive real-time applications, TCP’s reliability guarantees become a liability (HOL blocking, slow-start, retransmissions add unpredictable delay). UDP hands all that control to the application, which can make smarter, context-aware decisions — like skipping a stale audio frame rather than waiting for it to be retransmitted. That’s exactly why WebRTC, DNS, online games, and video streaming all run on UDP.</p><h3>Chapter 4: Transport Layer Security (TLS)</h3><ol><li><strong>What is TLS and where did it come from ?<br></strong>The SSL protocol was originally developed at NetScape to enable e-commerce transaction security on web — requiring encryption to protect personal data, plus authentication and integrity guarantees to ensure safe transactions.<br>SSL was implemented above TCP so that protocols like HTTP, SMTP and messaging could run unchanged while gaining security.</li></ol><p><strong>SSL → TLS timeline:</strong></p><ul><li>SSL 2.0 → first public version, quickly replaced due to flows</li><li>SSL 3.0 → fixed those flows</li><li>TSL 1.0 → ietf standardized it and renamed it</li><li>TLS 1.1, TLS 1.2, TLS 1.3 → in the market</li></ul><p>Many use TLS and SSL names interchangeably, but technically they are different, since each describes a different version of the protocol.</p><p>Simple Rule: Always use the latest TLS version. Some features like HTTP/2 explicitly requires TLS 1.2+ and will refuse to connect otherwise.</p><p>2. <strong>Three Goals of TLS: Encryption, Authentication, Integrity</strong></p><p>The TLS protocol is designed to provide three essential services: encryption (Obfuscates what is sent), authentication ( verifies the identity of who you’re talking to). and data integrity ( detects message tampering and forging ).</p><p>Think of it like a sealed, signed, tamper — proof envelope:</p><ul><li>Encryption — no one can read what’s inside</li><li>Authentication — the sender’s identity is verified</li><li>Integrity — You can tell if anyone tampered with it in transit</li></ul><p>TLS achieves integrity using a MAC (Message Authentication Code) — a cryptographic checksum attached to every message. If even one bit changes in transit, the MAC check fails.</p><p>3.<strong> The TLS Handshake — The Most Expensive Part</strong></p><p>Before any HTTPS data flows, client and server must negotiate which cipher to use, exchange keys, and verify identity. This costs 2 full round-trips (on top of TCP’s 1 RTT).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*s0cwjHdimo0oyYCPBUrIfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7cvKUyDhGOKcFinBlF_How.png" /></figure><p>That’s 168ms of pure overhead before a single byte of your page loads. This why TLS optimization matters enormously.</p><p><strong>TLS False Start</strong><br>An optimization where the client and server start transmitting encrypted application data when the handshake in only partially complete — reducing handshake overhead for new TLS connection to one roundtrip.</p><p><strong>TLS 1.3 Goal</strong><br>The design target for TLS 1.3: 1-RTT for new connections and 0-RTT for resumed sessions — a massive improvement.</p><h4>4. RSA vs Diffie-Hellman — and Why Forward Secrecy Matters</h4><p><strong>RSA (old way):</strong><br> Client generates a secret key → encrypts it with server’s public key → sends it. Server decrypts with its private key. Done.</p><p><strong>The fatal weakness:</strong> If an attacker gains access to the server’s private key and has been recording encrypted sessions, they can decrypt the entire session — even sessions recorded years ago.</p><p><strong>Diffie-Hellman (DH, the better way):</strong><br> DH allows the client and server to negotiate a shared secret without explicitly communicating it in the handshake. The server’s private key is used only to sign and verify, but the established symmetric key never leaves the client or server and cannot be intercepted even if the attacker has the private key.</p><p><strong>Perfect Forward Secrecy (PFS):</strong> With DH, a new ephemeral key is generated for every session and immediately discarded. The compromise of long-term keys does not compromise past session keys and does not allow an attacker to decrypt previously recorded sessions.</p><p><strong>Bottom line:</strong> RSA is now being actively phased out. All popular browsers prefer ciphers that enable forward secrecy, and some protocol optimizations like TLS False Start are only available when forward secrecy is enabled.</p><p>Public Key vs Symmetric Key Performance</p><p>Public-key cryptography is used only during initial TLS tunnel setup. Symmetric key cryptography is then used for all further communication — because public-key operations (like ECDH) are dramatically more CPU-expensive than symmetric encryption (like AES).</p><h4>5. ALPN — Negotiating the Application Protocol Inside TLS</h4><p>Problem: new protocols like HTTP/2, WebSocket, etc. need to negotiate <em>which protocol</em> to use. But:</p><ul><li>Port 80 (plain HTTP) is unreliable due to nosy proxies and firewalls</li><li>Doing a separate negotiation round-trip wastes latency</li></ul><p>Solution: <strong>ALPN (Application Layer Protocol Negotiation)</strong> — a TLS extension that piggybacks protocol negotiation onto the TLS handshake itself with zero extra round-trips:</p><ul><li>Client’s ClientHello includes a list of supported protocols</li><li>Server’s ServerHello picks one and confirms it</li><li>By the time the TLS tunnel opens, both sides already know which protocol to speak</li></ul><p>This is why HTTPS (port 443) became the universal deployment vehicle for HTTP/2, WebSockets, and other modern protocols.</p><h4>6. SNI — Multiple Sites on One IP Address</h4><p>Problem: a server can host thousands of domains (e.g. shared hosting), each needing its own TLS certificate. But TLS handshake happens <em>before</em> HTTP, so the server doesn’t know which site you want — and can’t pick the right certificate.</p><p>Solution: <strong>SNI (Server Name Indication)</strong> — the client indicates the hostname it is attempting to connect to as part of the TLS handshake, allowing the server to select the appropriate certificate. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p>Without SNI, every domain needs its own dedicated IP address — which was expensive and wasteful. SNI is the reason virtual hosting works with HTTPS.</p><h4>7. TLS Session Resumption — Avoiding the Full Handshake</h4><p>The full TLS handshake is expensive. For returning users, TLS provides two ways to skip it:</p><p>Session Identifiers (Session Caching)</p><p>The server creates and sends a 32-byte session ID as part of its ServerHello message. On subsequent connections, the client includes this ID in its ClientHello. If the server finds the matching session in its cache, an abbreviated 1-RTT handshake replaces the full 2-RTT handshake. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p><strong>Limitation:</strong> The server must store session state for every client — problematic at scale with millions of users and multiple load-balanced servers.</p><p>Session Tickets (Stateless Resumption)</p><p>Instead of the server maintaining a cache, it sends the client a “New Session Ticket” — an encrypted blob containing all session data, encrypted with a secret key only the server knows. The client stores it and presents it on the next connection. All session state is on the client side. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p><strong>Trade-off:</strong> For load-balanced multi-server deployments, all servers must share the same ticket encryption key, which needs to be rotated periodically and securely.</p><h4>8. Chain of Trust and Certificate Authorities</h4><p>How do you know the server is really who it claims to be? TLS uses a <strong>chain of trust</strong>:</p><p>Simple analogy: Alice trusts Bob. Bob has met Charlie and vouches for him by signing Charlie’s ID with his own signature. Alice hasn’t met Charlie, but because she trusts Bob and Bob trusts Charlie — she can trust Charlie too.</p><p>On the web:</p><ul><li><strong>Certificate Authorities (CAs)</strong> = the “Bobs” of the internet — trusted third parties that verify and sign website certificates</li><li><strong>Your browser/OS</strong> ships with a pre-installed list of ~100+ trusted root CAs</li><li>When you visit https://bank.com, your browser walks the certificate chain all the way up to a trusted root CA to verify the site is legitimate</li></ul><p>Every browser allows you to inspect the chain of trust, usually accessible by clicking on the lock icon beside the URL. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p><strong>Let’s Encrypt</strong> (2015): Solved the problem of certificates costing money. Now anyone can get a free, auto-renewing, browser-trusted certificate — eliminating the biggest excuse for not using HTTPS.</p><h4>9. Certificate Revocation — What if a Certificate Gets Compromised?</h4><p>Sometimes a certificate needs to be invalidated early (private key stolen, CA compromised, etc.). Two mechanisms:</p><p>CRL (Certificate Revocation List)</p><p>Each CA publishes a list of revoked certificate serial numbers. Browser downloads the list and checks it.</p><p><strong>Problems:</strong> The list keeps growing. Checking it adds latency. If the cache is stale, a revoked cert looks valid. If the fetch fails, most browsers “soft fail” — meaning they let it through anyway.</p><p>OCSP (Online Certificate Status Protocol)</p><p>Instead of a list, the client queries the CA directly for the specific certificate’s status in real-time.</p><p><strong>Problems:</strong> Real-time OCSP requests impair the client’s privacy because the CA knows which sites the client is visiting. Firefox telemetry shows OCSP requests time out up to 15% of the time, and add approximately 350ms to the TLS handshake when successful. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p>OCSP Stapling — The Best Solution</p><p>Instead of the client making the OCSP request, the server periodically retrieves the signed, timestamped OCSP response from the CA and appends (“staples”) it to the TLS handshake. The client validates both the certificate and the attached OCSP response signed by the CA. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p>Result: No extra latency, no privacy leak, no CA dependency at handshake time. <strong>Enable OCSP stapling on your server.</strong></p><h4>10. Why HTTPS Everywhere?</h4><p>Unencrypted HTTP is susceptible to interception, manipulation, and impersonation. Each unprotected request can reveal sensitive information about the user, and when aggregated across many sessions, can be used to de-anonymize their identities. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><p>HTTPS also unlocks browser features — geolocation, camera, microphone, service workers, push notifications, and more all <strong>require</strong> HTTPS. No HTTPS = no modern web.</p><p>And it’s why protocols like WebSocket and HTTP/2 are almost always deployed over HTTPS — the encrypted tunnel obfuscates the data from all intermediaries, providing a reliable deployment model even in the presence of middleboxes and proxies. <a href="https://www.ietf.org/proceedings/69/slides/mmusic-10.pdf">ietf</a></p><h4>11. Optimizing TLS — The Checklist</h4><p>The key items to optimize TLS performance: enable and configure session caching and stateless resumption; monitor session cache hit rates; configure forward secrecy ciphers to enable TLS False Start; terminate TLS sessions closer to the user to minimize round-trip latencies; use dynamic TLS record sizing to optimize latency and throughput; audit and optimize the size of your certificate chain; configure OCSP stapling. <a href="https://hpbn.co/transport-layer-security-tls/">hpbn</a></p><p>The single biggest win: <strong>terminate TLS close to the user.</strong> Use a CDN or edge servers to end the TLS connection nearby, cutting RTT from hundreds of milliseconds to single digits. Dynamic content can then be fetched over an already-warm persistent connection from the edge to your origin.</p><h4>TLS at a Glance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*yHti9y0yBcIhVFbJYvUqjQ.png" /></figure><p><strong>Core insight:</strong> Good security and good performance are not opposites — they go hand in hand. TLS 1.2+ with the right configuration (DH, session tickets, ALPN, OCSP stapling, False Start) is both <em>more secure</em> and <em>faster</em> than an older, weaker TLS setup.</p><h3>Chapter 5: Performance of Wireless Networks</h3><blockquote><strong>Everything a web developer needs to know about wifi, 4G, 3G and building apps that don’t drain you battery or destroy users’ patience.</strong></blockquote><h4>Chapter 1: Introduction — Why Wireless is Different</h4><p>You’re probably reading this on phone. Or you’ll switch to one soon. Here’s the uncomfortable truth: wireless is not a faster version of your home ethernet cable. It’s a fundamentally different beast.</p><p>We now expect to be able to access online services regardless of location, time, or circumstance — on the run, while standing in line, at the office, on a subway, while in flight, and everywhere in between. But that convenience comes with physics-level trade-offs that no amount of software engineering can fully eliminate.</p><p>The Good News? Most wireless technologies operate on common principles, have common trade-offs, and are subject to common performance criteria and constraints. Learn the fundamentals once, and everything else clicks into place.</p><p><strong>Chapter 2: The Three Laws of Wireless Performance</strong><br>Every wireless technology — Wifi, 4G, Bluetooth, you name it — is governed by one formula: Shannon’s Law.</p><pre>Channel Capacity = Bandwidth × log₂(1 + Signal/Noise)  </pre><p>In plain English: Your wireless speed is limited by two things, and only two things:</p><ol><li><strong>How much frequency range you get (Bandwidth)<br></strong>Think of radio frequencies like lanes on a highway. More lanes = more cars can move simultaneously. The overall channel bitrate is directly proportional to the assigned frequency range — doubling available frequency bandwidth can double the data rate, which is exactly how 802.11 improved performance over earlier WIFI standards.<br>Who decides which lanes you get? Governments. In the US, this process is governed by the Federal Communication Commision ( FCC ). Due to different government regulations, some wireless technologies can work in one part of the world, but not in others.<br><strong>Fun Fact: </strong>Wifi’s 2.4 GHz band was auctioned by the FCC — and the 700 MHz spectrum alone sold for $19.592 billion in 2008. Bandwidth is literally worth billions.</li></ol><p><strong>Low vs High frequency trade-off:</strong></p><ul><li>Low frequency ( like 700 MHz ) → signals travel far, covers large areas, but slower and more congested</li><li>High frequency ( like 5 GHz WIFI ) → faster speeds, but shorter distance, needs more towers/routers</li></ul><p>2. <strong>How strong your signal is vs background noise ( SNR )<br></strong>By its very nature, all radio communication is done over a shared medium, which means other devices generate unwanted interference. For example, a microwave open operating at 2.5 GHz may overlap with the frequency range used by Wifi.</p><p>Imagine you’re at a crowded party trying to have a conversation:</p><ul><li>In an empty room ( no noise ) → you can talk quietly from 20 feet away.</li><li>In a packed party ( high noise ) → you have to lean in and almost shout.</li></ul><p>That’s exactly SNR. This creates two real-world effects in wireless networks.</p><ul><li>Near-far problem: A strong nearby signa drowns out weaker signals from farther away — like someone shouting right next to your ear making it impossible to hear someone across the room</li><li>Cell breathing: The coverage area expands and shrinks based on cumulative noise and interference levels — your router’s effective range literally shrinks when your neighbor&#39;s devices turn on.</li></ul><p>3. <strong>Modulation — The Encoding Trick <br></strong>Your data is 1s and os. Radio waves are analog. Modulation is the translator between them. <br>Different “modulation alphabets” can be used to encode the digital signal with different efficiency. The combination of the alphabet and the symbol rate determines the final throughput of the channel.</p><p>Simple Example:</p><ul><li>sender and receiver process 1000 pulses/second</li><li>with a 2-bit alphabet ( 4 symbols: 00, 01, 10 ,11 ) — you get 2000bits/seconds</li><li>with a 4 bit- 4000</li></ul><p>Catch: higher-order alphabets are more fragile — a higer-order modulation alphabet comes at cost of reduced robustness to noisee and interference. So when your wifi signal is weark, your device automatically drops to a simpler, slower modulation to stay reliable. That’s why moving further from your router makes it slower — not just because of signal loss, but because devices switches to a less efficient encoding mode.</p><p><strong>The Reality Check: </strong>Every wifi spec advertises peak speeds “in ideal conditions.” Idea conditions mean maximum allocated bandwidth, exclusive use of the frequency spectrum, minimum background noise, highest-throughput modulation, and multiple radio steams transmitting in parallel. What you see on the label and what you experience in the real world will be very different.</p><h4>Chapter 3: WiFi — The Network You Think You Understand</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*PX_aWDPSrOjHw6YHSvHLKA.png" /></figure><p>Wifi seems simple. You connect. you browse. What’s there to know? Quite a lot actually.<br>Wifi is a shared medium — every device on your network is essentially shouting into the same room and hoping others listen only when it’s their turn. This is called CSMA/CA Before transmitting, a device must listen to confirm nobody else is sending. This works fine with a few devices but falls apart in high-density environments like conference halls or apartment buildings.</p><p><strong>Packet Loss on wifi is different from packet loss on mobile: <br></strong>On mobile networks, packet loss usually means congestion. On wifi, packet loss often means signal interference or noise — and TCP doesn’t know the difference. TCP sees a dropeed packet and thinks “network is congested!” and triggers slow-start, cutting your speed in half — when the real problem was just a neighour’s microwave brieifly firing up.</p><p><strong>Optimizing for wifi:</strong></p><ul><li><strong>Leverage unmetered bandwidth</strong> — you’re not paying per byte on WiFi, so pre-fetch aggressively, pre-cache assets, sync large files in the background</li><li><strong>Adapt to variable bandwidth</strong> — use adaptive bitrate streaming for video; don’t assume WiFi = fast</li><li><strong>Adapt to variable latency</strong> — WiFi latency can spike unpredictably due to interference; build UIs that are tolerant of occasional slow responses rather than assuming consistent sub-10ms RTTs</li></ul><h4>Chapter 4: Mobile Networks — The G’s Explained Simply</h4><p>Every few years a new “G” shows up and carriers go wild with marketing. Here’s what they actually mean for your app’s performance:</p><p><strong>The evolution:</strong></p><ul><li><strong>1G</strong> → Analog voice. No data. A phone that just called people. Wild concept.</li><li><strong>2G (GSM/CDMA)</strong> → Digital voice + first data. GPRS gave us ~50 Kbps. Painfully slow.</li><li><strong>3G (UMTS/HSPA)</strong> → Real broadband on mobile. HSPA+ hits ~21 Mbps. The era of mobile internet.</li><li><strong>4G LTE</strong> → True broadband. 100+ Mbps theoretical, 10–50 Mbps real-world. Low latency.</li></ul><p>But here’s the thing developers often miss: <strong>raw speed is not the only number that matters on mobile.</strong> The architecture of mobile networks introduces a hidden performance cost that doesn’t exist on WiFi or wired networks.</p><h4>Chapter 5: The RRC — The Hidden Latency Villain Nobody Talks About</h4><p>This is the most important thing in this entire section that most developers don’t know about.</p><p>Your phone’s radio doesn’t stay on full-blast all the time — that would drain the battery in hours. Instead, the mobile network manages a state machine for every device called the <strong>Radio Resource Controller (RRC).</strong></p><p>RRC state promotions to high power occur when data must be transferred. RRC state demotions to lower power occur on network-configured timeouts. <a href="https://hpbn.co/introduction-to-wireless-networks/">High Performance Browser Networking</a></p><p>Think of it like a car’s <strong>auto stop-start</strong> engine — it shuts off when idle and restarts when needed. Except restarting takes time, and that time costs you latency.</p><p><strong>The three states (simplified):</strong></p><pre>IDLE (radio off, battery saving)<br>  ↓ need to send data → costs 200–2500ms to wake up!<br>CONNECTED - LOW POWER (light activity)<br>  ↓ need more bandwidth<br>CONNECTED - HIGH POWER (full radio blast)<br>  ↓ no activity for ~5–10 seconds<br>CONNECTED - LOW POWER<br>  ↓ no activity for ~12 seconds<br>IDLE</pre><p><strong>Real-world cost on 3G</strong> (100ms RTT network):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*gFULZloRXDb8zNs1NKRC-A.png" /></figure><p>That 2500ms isn’t your app’s code. It isn’t your server. It’s the phone’s radio waking up from sleep. And every time your app makes a small, periodic request — a background analytics ping, a polling heartbeat, a tiny sync — it can trigger this entire wake-up cycle.</p><p>The RRC is a fact of life on mobile networks — there is no way around it — and if you want to build optimized applications for the mobile web, you must design with the RRC in mind.</p><h4>Chapter 6: Battery Life is a Performance Metric</h4><p>On mobile, battery and performance are the same problem.</p><p>Radio use at full power can drain a full battery in a matter of hours. Radio power requirements are going up with every wireless generation. Radio is often second in power consumption only to the screen. Radio use has a nonlinear energy profile with respect to data transferred.</p><p>Here’s the brutal math of <strong>polling every minute</strong>:</p><ul><li>10 joules to wake radio from idle to connected and back</li><li>1 minute polling = 600 joules/hour wasted</li><li>That’s ~3% of total battery capacity <strong>per hour, per app</strong></li><li>Two apps doing this with offset intervals = dead phone by lunch</li></ul><p>There is no such thing as a “small request” as far as the battery is concerned. Intermittent network access is a performance anti-pattern on mobile networks.</p><h4>Chapter 7: Optimizing for Mobile — The Practical Checklist</h4><p>All of this theory boils down to concrete rules for developers:</p><p><strong>① Burst data, then go idle</strong><br> Mobile applications should maximize the amount of transferred data while the radio is on, then seek to minimize the number of additional data transfers. Send everything at once, then let the radio sleep. Don’t trickle-feed small requests.</p><p><strong>② Kill the polling. Use push.</strong><br> Polling is exceptionally expensive on mobile networks. Where possible, push delivery and notifications should be used. Outbound and inbound requests should be coalesced and aggregated. Non-critical requests should be deferred until the radio is already active.</p><p><strong>③ Stop unnecessary keepalives</strong><br> The application does not need to keep the radio “active” to ensure connections are not dropped. Unnecessary application keepalives can have an enormous negative impact on battery life and are often put in place due to simple misunderstanding of how the mobile radio works. Most carriers set 5–30 minute NAT timeouts — a keepalive every 5 minutes is plenty.</p><p><strong>④ Account for RRC state transition latency</strong><br> Every “cold” request on mobile can cost 200–2500ms before your server even sees it. Pre-fetch content before the user needs it, keep connections warm when interactions are expected, and decouple UI interactions from network calls so the UI never blocks on a network response.</p><p><strong>⑤ Offload to WiFi whenever possible</strong><br> WiFi has fundamentally better latency, throughput, and battery characteristics than any cellular technology. When designing sync strategies, large downloads, or background updates — prefer WiFi and let the user configure when heavy operations run.</p><p><strong>⑥ All previous TCP/TLS optimizations matter even more here</strong><br> Minimizing latency by reusing keepalive connections, geo-positioning servers and data closer to the client, and optimizing TLS deployments are even more important on mobile networks, where roundtrip latencies are high and bandwidth is always at a premium. <a href="https://hpbn.co/building-blocks-of-udp/">hpbn</a></p><h4>The Big Takeaway</h4><p>Wireless networks are not slow wired networks. They are fundamentally different systems with their own physics, their own state machines, and their own performance constraints. The developers who build great mobile experiences are the ones who design <em>with</em> these constraints — not the ones who assume mobile is just a slower laptop.</p><p><strong>The three rules to tattoo on your brain:</strong></p><ol><li><strong>Bandwidth ≠ Performance</strong> — latency and SNR matter more than raw speed</li><li><strong>Every idle radio wakeup costs you</strong> — batch, burst, then let it sleep</li><li><strong>The RRC is invisible but brutal</strong> — design around it or pay in latency and battery drain</li></ol><h3>Chapter 6: Brief History of HTTP</h3><p>How a one-line protocol built in 1991 became the language of the entire internet.</p><ol><li><strong>The Starting Point: What even is HTTP?</strong><br>The Hypertext Transfer Protocol (HTTP) is one of the most ubiquitous and widely adopted application protocols on the internet: It is the common language between the clients and servers, enabling the modern web. From its simple beginnings as a single keyword and document path, it has become the protocol of choice not just for browsers, but for virtually Internet-connected software and hardware application. <br>Think about that for a second, your browser, your mobile app, your smart TV, your IOT sensor, the coffee machine in your office — they all communicate using a protocol whose first version was a single line of text. The story of HTTP is the story of the web itself.</li><li><strong>HTTP 0.9 — The One-Line Protocol (1991)<br></strong>The Original HTTP proposal by TIM Berners-Lee was designed with simplicity in mind as to help with the adoption of his other nascent idea: The World Wide Web.<br>He set out to build a protocol that would run the internet. He was trying to make it easy for physicists at CERN to share document with each other. The protocol he designed reflected that goal — it was gloriously, almost absurdly, simple.</li></ol><pre>GET /about/ </pre><p>That’s it. One line. The server responds with HTML and closes the connection. No headers, no status code, no metadata. Just raw HTML flowing back.</p><p>The request consists of single line: the GET method and the path of the requested document. The response is a single hypertext document — no headers or any other metadata, just the HTML.</p><p><strong>What HTTP 0.9 could do:</strong></p><ul><li>Client-Server request-response over TCP</li><li>Transfer HTML documents</li></ul><p><strong>What it couldn&#39;t do: </strong>Images, CSS, authentication, caching, content types, error codes — basically everything you associate with the modern web.</p><p><strong>3. HTTP/1.0 — The internet Boom Arrives ( 1996 )</strong><br>Between 1991 an 1996, something explosive happened.</p><p>A team at the National Center of Supercomputing Applications decided to build their own browser. With that, the first popular browser was born: NCSA Mosaic. One of the programmers on the NCSA team, Marc Andreessen, partnered with Jim Clark to found Mosaic Communications in October 1994. The company was later renamed to Netscape.</p><p>At the same time, CompuServe, AOL, and Prodigy began providing dial-up internet access to the public within the same 1994–95 time frame, Riding on this wave of rapid adoption. Netscape made history with a wildly successful IPO — the internet boom arrives.</p><p>Suddenly, HTTP 0.9’s limitation were glaring. The web needed to serve images, not just text. It needed to know if a request succeeded or failed. It needed to negotiate what kind of content to send. Developers started building and experimenting on their own.</p><p>In 1996, the HTTP working group published RFC 1945, which documented the “common usage” of the many HTTP/1.0 implementations found in the wild. Note that this was only an informational RFC: HTTP/1.0 as we know it is not a formal specification or an internet standard!</p><p>HTTP/1.0 was basically the internet crows — sourcing a protocol upgrade, and then writing down what everyone was already doing.</p><p>What HTTP/1.0 added over 0.9:</p><ul><li>Request Headers — tell the server who you are, what you accept</li><li>Response Status Code — 200 OK, 404 Not found, etc.</li><li>Response headers — content-type, content-length, expiry info</li><li>Any content type — not just HTML, but images, plain text, anything</li></ul><pre>GET /rfc/rfc1945.txt HTTP/1.0<br>User-Agent: CERN-LineMode/2.15<br>Accept: */*<br><br>HTTP/1.0 200 OK<br>Content-Type: text/plain<br>Content-Length: 137582<br>(content)<br>(connection closed)</pre><p>This looks almost like modern HTTP. But there’s one massive problem hiding at the end: connection closed. Every single request required a brand new TCP connection — meaning a full 3-way handshake + slow-start panelty for every image, every css file, every resource on the page. On a page with 10 resources, that’s 10 handshakes. Requiring a new TCP connection per request imposes a significant performance penalty on HTTP/1.0</p><p>4. <strong>HTTP/1.1 — The Real Internet Standard(1997–99)</strong></p><p>The work on turning HTTP info into an official IETF internet standard happened over a period of roughly four years.</p><p>HTTP/1.1 is the version of HTTP that powered the web for the next 15+ years — and it’s still what most of the internet speaks today. ITs biggest contributers weren’t new features. They were performance fixes for the mess HTTP/1.0 left behind.</p><p><strong>The Key upgrades:</strong></p><p><strong>① Persistent Connections (Keepalive) — the biggest win</strong></p><p>Http/1.1 changed the semantics of the HTTP protocol to use connection keepalive by default, unless told otherwise via connection:close header,the server should keep the connection open by default.</p><p>Instead of opening and closing a TCP connection for every single resource, HTTP/1.1 keeps the connection alive and reuse it. You pay the handshake cost once, then fire multiple requests down the same pipe. For a page with 50 resources, this is a massive speed-up.</p><p><strong>② Chunked Transfer Encoding</strong></p><p>The server no longer needs to know the full size of the resonse before it starts sending. It can stream the response in chunkz — perfect for dynamically generated content. Each chunk is prefixed with its size in hex, and a 0 marks the end.</p><p><strong>③ Request Pipelining</strong></p><p>In theory, clients could send multiple requests without waiting for each response — like a one-way fire-and-forget. In practice, this turned out to be buggy and poorly supported.</p><p><strong>④ Better Caching and Content Negotiation</strong></p><p>HTTP/1.1 added content encoding, character set, and language negotiation, transfer encoding, caching directives, client cookies, plus a dozen other capabilities that can be negotiated on each request.</p><p>Here’s what a real HTTP/1.1 session looks like — notice two requests over one tcp connection:</p><pre>GET /index.html HTTP/1.1<br>Host: website.org<br>Accept-Encoding: gzip, deflate<br><br>HTTP/1.1 200 OK<br>Transfer-Encoding: chunked<br>Connection: keep-alive<br>...chunks of HTML...<br><br>GET /favicon.ico HTTP/1.1     ← second request, SAME connection<br>Host: website.org<br>Connection: close             ← signal we&#39;re done<br><br>HTTP/1.1 200 OK<br>Content-Length: 3638<br>(icon data)<br>(connection closed)</pre><p>HTTP/1.1 — limitations (which HTTP/2.0 would later fix)</p><ul><li>still fundamentally text-based and verbose</li><li>Headers sent uncompressed with each request — cookies alone can add kilobytes of overhead per request</li><li>Pipelining was broken in practice</li><li>Head-of-line blocking — requests on a single connection must be processed in order</li><li>No server push — server can only respond, never proactively send</li></ul><p>4. <strong>HTTP/2 — The performance revolution ( 2012+ )</strong></p><p>Since its publication, RFC2616 has served as a foundation ofr the unprecedented growth of the internet. Billions of devices of all shapes and sizes, from Desktop computers to the tiny web devices in our pockets, speak HTTP every day to deliver news, video, and millions of other web applications.</p><p>But by 2012, the web was straining under HTTP/1.1’s weight. Pages that once had a handful of resources now had hundreds. Single-page apps made dozens of API calls. Video streaming, real-time collaboration, live notifications — none of this mapped well onto a request-response protocol designed in 1997.</p><p>The HTTPbis working group announced a new initiative for HTTP/2 in early 2012 — a protocol that retains the semantics of HTTP without the legacy of HTTP/1.x message framing and syntax, which had been identified as hampering performance and encouraging misuse of the underlying transport.</p><p><strong>The key goals of HTTP/2:</strong></p><ul><li>Lower latency</li><li>Higher throughput</li><li>fix head-of-line blocking</li><li>eliminate redundant header overhead</li><li>enable server push</li></ul><p><strong>The crucial thing to understand:</strong> The primary focus of HTTP/2 is on improving transport performance. None of the high-level protocol semantics are affected — all HTTP headers, values, and use cases are the same. Any existing website or application can and will be delivered over HTTP/2 without modification: you do not need to modify your application markup to take advantage of HTTP/2.</p><h4>he Core Insight</h4><p>Every version of HTTP solved the problems <em>created by the success of the previous version.</em> HTTP 0.9 worked great for sharing CERN documents — but couldn’t handle images. HTTP/1.0 handled images — but choked on connection overhead. HTTP/1.1 fixed connections — but buckled under modern page complexity. HTTP/2 fixes transport performance — while keeping everything you already know about HTTP intact.</p><p>The lesson for any developer: <strong>protocols evolve around real-world usage patterns.</strong> The internet didn’t plan HTTP/2 in advance. It emerged from watching millions of websites struggle with HTTP/1.1’s limits, and then engineering a precise, targeted fix — without breaking anything that already worked.</p><h3>Chapter 7: Primer on Web Performance</h3><p>If you’ve been following this series, the previous chapters were deep dives into physical delivery, TCP, TLS and transport protocols. This chapter step back and asks the bigger question: How do all these layers interact in a real web application, and what actually makes the web feel fast or slow? <br> — The answer is probably not what most developers expect.</p><h4>The Web Evolved — And So Did the Performance Problem</h4><p>The web didn’t always look like it does today. Grigorik breaks its evolution into three distinct eras:</p><p><strong>Hypertext documents — </strong>Plain text with hyperlinks, HTTP/0.9, one request, one TCP connection, done.<br><strong>Web Pages — </strong>HTML enriched with images, audio, and layout. HTTP/1.0 introduced headers: HTTP/1.1 added caching, keepalives, and persistent connections. The key metric shifted from document load time to page load time (PLT) — The moment the browser spinner stops.<br><strong>Web Applications — </strong>JavaScript, AJAX, and DHTML transformed static pages into dynamic apps with complex dependency graphs: markup →CSSOM →render tree → JavaScript execution, all tightly coupled.</p><p>This matters because PLT alone is no longer a useful benchmark. For a modern web app. you need to ask:</p><ul><li>When does the user first see something meaningful?</li><li>When can they first interact?</li><li>What are the conversion and engagement rates at each step?</li></ul><p>Application-specific metrics always beats generic ones. PLT is a starting point, not the finish line.</p><p><strong>The DOM, CSSOM, and the JavaScript Trap<br></strong>Here’s the pipeline every browser runs:</p><ol><li>Parse HTML → build the DOM</li><li>Parse CSS → build the CSSOM</li><li>combine both → create the render tree</li><li>Layout + paint → pixels on screen</li></ol><p>JavaScript complicates everything. A document.write() call blocks DOM construction. Querying a computed style forces the browser to wait on the CSSOM. The result: DOM and CSSOM construction are tightly coupled through JavaScript, and a delay in any one of them delays the reset.</p><p>This is exactly why the “styles at the top, scripts at the bottom” rule exists — CSS blocks rendering, so get it to the browser as fast as possible. Scripts can usually wait.</p><p><strong>What Does an Average Web App Actually Look like? <br></strong>Based on HTTP Archive data from early 2013 (and the trend has only gotten worse since):</p><ul><li>~90 HTTP requests</li><li>Fetched from ~15 different hosts</li><li>~1.3 MB total transfer size</li><li>Breakdown: 55 image requests, 15 JS, 5 CSS, 10 HTML, 5 other</li></ul><p>Every single page load is essentially a fresh “installation” — DNS lookups, TCP handshakes, resource downloads, DOM/CSSOM construction, JS execution. All in hundreds of milliseconds. This is why web performance is such a competitive field.</p><h4>Speed Is Perception, and Perception Has Deadlines</h4><p>Human reaction times don’t change regardless of how fast our devices get. Grigorik cites these thresholds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*U07HBYQI45TLrqIhvC1yCw.png" /></figure><p>The informal rule in the web performance community: render something useful in under 250ms to keep users engaged.</p><p>Now add up a DNS lookup, TCP handshake, possible TLS negotiation, and the first HTTP request — and you’ve potentially spent your entire latency budget before a single byte of content arrives. This is the core problem.</p><p><strong>The Resource WaterFall: Your most useful Tool</strong></p><p>Every Browser has a network waterfall panel. Tools like WebPageTest make this even more powerful by runnng tests from geo-distributed locations with configurable browsers and connection profiles.</p><p>Every HTTP request consist of distinct stages: DNS resolution → TCP handshake → TLS negotiation → request dispatch → content download. The waterfall makes these visible.</p><p>Two keys observations from analyzing a real page</p><ol><li>HTML is parsed incrementally — the browser doesn’t wait for the full document. It discovers resources early and dispatches requests in parallel, which is why the structure of your markup directly impacts load performance.</li><li>First render fires well before all resources are loaded — “Start Render”. “Document Complete”, and “All Resources fetched” are three separate events. Smart apps optimize for the first two, letting non-critical content load asynchronously.</li></ol><p>The connection view reveals something even more surprising: actual download time is a tiny fraction of total latency. Most time is spent in DNS lookup, TCP handshakes, and waiting for the first byte. The network pipe itself is underutilized — it’s not the bottleneck.</p><p><strong>The Bandwidth vs. Latency Debate — Settled</strong></p><p>Mike Belshe (one of SPDY’s creators) ran a study comparing the effect of bandwidth vs. latency on page load times. The results become a foundational argument for building SPDY and later HTTP/2:</p><ol><li>Bandwidth: Doubling from 1 to 2 Mbps nearly halves load time. Going from 5 to 10 Mbps? only a ~5% improvement. Beyond ~5 Mbps, you’re in diminishing returns territory for typical web browsing.</li><li>Latency: Every 20ms improvement in RTT produces a linear improvement in page load time. No diminishing returns.</li></ol><p>The Practical conclusion: an average US user with 5Mbps + bandwidth would benefit far more from a 20ms latency reduction than from a speed upgrades to 1 Gbps. Bandwidth is saturated for web workloads. Latency is the real bottleneck — and it’s especially brutal on mobile.</p><p>This is the direct consequence of how TCP works: slow start, flow control, congestion control, and head-of-line blcoking all mean that small bursty HTTP requests never fully utilize available bandwidth. They’re latency-bound from the start.</p><p><strong>Measuring What Actually Matters: Synthetic vs. Real-User Measurement</strong></p><p>If you can’t measure it, you can’t fix it. Grigorik argues for two complementary approaches:</p><p>Synthetic testing — controlled environments ( webpagetest, local performance suites, load testing). Great for catching regressions and establishing baselines. Set a “performance budget” per metric and alert when it’s breached.</p><p>Real User Monitoring — Capture actual performance from real users on real devices across real networks. This is where the W3C’s navigation timing api shines: it exposes dns time, tcp connection time, request/response times, and dom construction timing via performance.timing, with microsecond precision.</p><p>Two additional APIs round out the toolkit:</p><ul><li>Resources Timing — per resource performance data (not just the root document)</li><li>User Timing — performance.mark () / performance.measure() for custom application specific milestones.</li></ul><p>A critical note on analyzing RUM data: never look at averages. Page load time distributions are almost always skewed or multimodal. User histograms, meidans, and percentiles (p77, p95, p99) instead. An average hides the outliers that are killing your conversion rate.</p><p><strong>Browser Optimizations You should know about</strong></p><p>Modern browsers are doing a lot of performance work automatically:</p><p><strong>Document-aware optimization</strong> — parsers communicate resource priorities to the network stack. Render-blocking resources get high priority; low-priority requests are queued.</p><p><strong>Speculative optimization</strong> — browsers learn navigation patterns over time and proactively:</p><ul><li>Pre-resolve likely DNS hostnames</li><li>Pre-connect to likely destinations (eliminate the TCP handshake RTT)</li><li>Pre-fetch anticipated resources</li><li>Pre-render the likely next page in a hidden tab</li></ul><p>You can assist the browser with HTML hints:</p><pre>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;//cdn.example.com&quot;&gt;<br>&lt;link rel=&quot;subresource&quot; href=&quot;/app/critical.js&quot;&gt;<br>&lt;link rel=&quot;prefetch&quot; href=&quot;/images/hero-next.jpg&quot;&gt;<br>&lt;link rel=&quot;prerender&quot; href=&quot;//example.com/next-page&quot;&gt;</pre><p>These are treated as hints, not guarantees — browsers that don’t support a hint simply ignore it safely.</p><p><strong>Structural best practices the browser depends on</strong>:</p><ul><li>Put critical CSS and JS references early in the document so the parser discovers them early</li><li>Deliver CSS as fast as possible — it blocks both rendering and JS execution</li><li>Defer non-critical JavaScript to avoid blocking DOM/CSSOM construction</li><li>Flush HTML incrementally from the server — don’t buffer the full response</li></ul><p><strong>Google Search uses this brilliantly</strong>: when a search request arrives, the server immediately flushes the static page header before even running the query. While the browser is parsing that header and fetching CSS/fonts, the search engine is processing the query. The dynamic results fill in when ready.</p><h4><strong>Key Takeaways</strong></h4><ol><li><strong>Latency beats bandwidth</strong> for typical web workloads. Optimizing RTT is almost always higher-leverage than more bandwidth.</li><li><strong>PLT is not enough</strong>. Define application-specific metrics: time to first meaningful paint, time to interactive, conversion events.</li><li><strong>The resource waterfall is your best diagnostic tool</strong>. Use WebPageTest regularly.</li><li><strong>Measure both synthetically and with RUM</strong>. Use medians and percentiles, never averages.</li><li><strong>Help the browser help you</strong>: put CSS early, defer JS, use resource hints, and flush HTML incrementally.</li><li><strong>Performance is not just an engineering metric</strong> — a 1-second delay in page load time causes a 7% drop in conversions. Speed is a product feature.</li></ol><h3>Chapter 8: HTTP/1.X</h3><p>For improving HTTP/1.0 &gt; deployed with the HTTP/1.1; end of story.</p><p>HTTP/1.1 Provides:</p><ul><li>Persistent Connections to allow connection resuse</li><li>Chunked transfer encoding to allow response streaming</li><li>Request pipelining to allow parallel request processing</li><li>Byte serving to allow range — based resource requests</li><li>Improved and much better — specified caching mechanisms</li></ul><p>Networking Optimizations :</p><ul><li>Reduce DNS lookups — Every hostname resolution requires a network roundtrip, imposing latency on the request and blocking the request while the lookup in the progress.</li><li>Make fewer HTTP requests — No request is faster than a request not made: eliminate unnecessary resources on your pages.</li><li>Use a Content Delivery Network — Locating the data geographically close to the client can significantly reduce the network latency of every TCP connection and improve throughput.</li><li>Add an Expires header and configure Etags — Relevant resources should be cached to avoid re-requesting the same bytes on each and every page. An Expires header can be used to specify the cache lifetime of the project.</li><li>Gzip assets — All text based assets should be compressed with Gzip when transferred between the client and the server. On average, Gzip will reduce the file size by 60 to 70 percent. which makes it one of the simpler and high benefit optimizations you can do.</li><li>Avoid HTTP redirects — HTTP redirects can be extremely costly, especially when they redirect the client to a different hostname, which results in additonal DNS lookup, TCP connection latency, and so no.</li></ul><blockquote>At WWDC 2012, Apple gives the benefits of HTTP optimizations. Apple engineers saw 300% performance improvement for users on slower networks once they made better use of existing TCP connections within iTunes, via HTTP keepalive and pipelining!</blockquote><h4>Benefits of KeepAlive Connections</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*QDxJHndtTnejtHWybWJg6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*q0z2YSQeWsKgCFHCcTC9vg.png" /></figure><p>We cannot predict the server processing time, since that will vary by resource and the back-end behind it, but it is worth highlighting that the minimum total time for an HTTP request delivered via a new TCP connection is two network roundtrips: one for the handshake, one for the request-response cycle. This is a fixed cost imposed on all non-persistent HTTP sessions.</p><blockquote>The Faster your server processing time, the higher the impact of the fixed latency overhead of every network request! To prove this, try changing the roundtrip and server times in this previous examples.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*nvm6PhxRZw7HWGaJZ5LJxw.png" /></figure><p>Hence a simple optimization is to reuse the underlying connection!</p><h4>HTTP Pipelining</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Z-AaKzU-mPEkquDV6kd67g.png" /></figure><blockquote>Eliminating the wait time imposed by response and request propogation latencies is one of the primary benefits of HTTP/1.1 pipelining. However, the ability to process the requests in parallel can have just as big, if not bigger, impact on the performance of your application.</blockquote><ul><li>* Larger the application, Larger the bene</li><li>fit of the network optimization</li></ul><h4>Using HTTP Pipelining Outside the Browser</h4><p>Before we discount the benefits of HTTP pipelining entirely, it is important to note that it can still be used, and with great results, in situations where you control the capabilities of both the client and the server. In fact, Apple’s iTunes case study is a case in point: <a href="https://hpbn.co/http1x/#delivering-3-performance-improvement-for-itunes-users">Delivering 3× Performance Improvement for iTunes Users</a>. This performance feat was accomplished by switching to persistent HTTP and enabling HTTP pipelining both on the server and within the custom iTunes client.</p><p>A quick checklist for enabling pipelining in your own application:</p><ul><li>Your HTTP client must support pipelining.</li><li>Your HTTP server must support pipelining.</li><li>Your application must handle aborted connections and retries.</li><li>Your application must handle idempotency concerns of aborted requests.</li><li>Your application must protect itself from broken intermediaries.</li></ul><p>In practice, the best way to deploy HTTP pipelining is to create a secure (HTTPS) tunnel between the client and server. That’s the most reliable way to avoid interference from intermediaries that may not understand or support pipelined requests.</p><h4>Using Multiple TCP Connections</h4><p>Since HTTP/1.x has no multiplexing, sending requests one-by-one over a single connection is too slow. So browsers work around this by opening up to 6 parallel TCP connections per host.</p><p>Why this helps:</p><ul><li>Up to 6 requests dispatched simultaneously</li><li>Effectively multiplies the TCP congestion window (cwnd) by 6, bypassing slow-start limits</li></ul><p>Why It’s a bad long-term fix:</p><ul><li>Extra memory, CPU, and resource overhead on both client and server</li><li>Parallel TCP streams compete with each other for bandwidth</li><li>Higher Implementation complexity</li><li>Still provided only limited parallelism</li></ul><p>Why 6 specifically? It’s a pragmatic middle ground — enough parallelism to help, not so many connections that overhead becomes prohibitive.</p><p>Ultimately, opening multiple TCP connections is a workaround for three HTTP/1.x shortcoming: lack of multiplexing, small initial cwnd, and clients that can’t use TCP window scalling. The TCP issues (cwnd, window scalling) can be fixed with OS kernal upgrades. The multiplexing problem cannot — it requires a protocol-level fix, which is exactly what HTTP/2 delivers.</p><h4>Domain Sharding: The Hack that became Standard Practice</h4><p>You’ve already seen how browsers work around HTTP/1.x’s lack of multiplexing by opening up to 6 parallel connection per host. Six feels like a lot — until you remember that an average web page makes 90+ resource requests. With 6 connections and 90n resources, you’re still queuing 84 requests behind the first batch. Your users are waiting in line.</p><p>So developers got creative. If the browser gives you 6 connections per host — what if you had more hosts?</p><p>Enter domain sharding.</p><p><strong>The Idea is Almost Embarrassingly simple.</strong><br>Instead of serving everything from <a href="http://www.example.com/">www.example.com</a>, you split your assets across multiple subdomains:</p><pre>shard1.example.com → images<br>shard2.example.com → CSS and JS<br>shard3.example.com → fonts</pre><p>All Three hostnames point to the same physical server — usually just CNAME records in DNS. The browser doesn’t know or care. All it sees is three different hostnames, which means three separate connections pools of 6 each. Suddenly you’ve gone from 6 parallel connections to 18.</p><p>The browser’s connections limit is enforced per hostname, not per IP address. That one quirk is the entire foundation the hack is built on.</p><h4>Why It works — And Why it’s still a hack</h4><p>Domain sharding genuinely helps in the right conditions. If you have dozens of small assets — Image,icons, script files — that need to be downloaded in parallel, spreading them across shards gets more of them in-flight simultaneously. The thoughput improvement can be real and measureable.</p><p>But here’s what you’re actually paying for every shard you add:</p><p>An extra DNS lookup. Before the browser can even open a TCP connection to shard2.example.com, it has to resolve that hostname. that’s another network roundtrip, adding latency before a single byte is transferred.</p><p>Another TCP slow-start cycle. Every new connection start with a congestion window of ~10 packets and has to ramp up. If your assets are small, the connection may never fully escape slow-start before it’s done — meaning you never actually get the throughput you were hoping for.</p><p>TLS overhead (if you’re on HTTPS). Add a full TLS handshake on top of the TCP handshake for each shard, and you’ve now burned 2–3 extra roundtrips per hostname just to get started.</p><p>More sockets, more resource usage. On both client and server — memory buffers, CPU, file descriptors. all multiplied by your shard count.</p><h4>The Trap: More shards is not equal to More Performance</h4><p>This is where domain sharding gets dengerous. The optimization is intuitive enough that developers often overshoot it badly.</p><p>The book puts it painly: In practice, domain sharding is often overused, resulting in tens of underutilized TCP connections — many of them never escaping slow-start — and in the worst case, actually slowing the page down.</p><p>There’s no clean formula for the “right” number of shards because the answer depends on things that vary per user and per page: number of reousrces, their sizes, client bandwidths, client latency. What works for a fiber user in a data center city may actively hurt a 3G user in a high-latecy region.</p><p>And mobile users — who are already dealing with significalntly higher latency — are hit hardest by the overhead of each extra shard. The very users you’re trying to help on slow networks are the ones most penalized by going overboard.</p><p><strong>The Practical Rule</strong></p><p>Grigorik’s advice is refreshingly direct: start with zero shards. Let the Browser’s built in 6 connections per host do their job first. Then, if you have profiling data showing queuing is a genuine bottleneck, add shard one at a time and measure the actual impact on your performance metrics.</p><p>In practice, very few sties benefit from more than a dozen total connections. And if you find yourself reaching for a high shard count, that’ usually a signal that the real fix is reducing the number of resources, not splitting them across more hostnames.</p><p><strong>The Bigger Picture</strong></p><p>Domain sharding is a prefect encapsulation of what HTTP/1.x optimization actually looked like in practice: developers reverse — engineering protocol constraints and building elaborate workarounds that introduce their own tradeoffs. It works, but it makes codebases messier, DNS configs more complex, and deployments harder to reason about.</p><p>The right long-term answer was not more shards. It was a better protocol. HTTP/2’s multiplexing — sending multiple requests and responses over a single TCP connection simultaneously — makes domain sharding not just unnecessary, but actively harmful. More on that when we get to that chapter.</p><p>for now, if you’re still on http/1.x shard carefully, measure everything, and remember that every new hostname has a price.</p><h3>Chapter 9: HTTP/2 — The Protocol That Said “We Need to Talk” to HTTP/1.x</h3><p>Remember everything we’ve complained about in the past few chapters? The multiple TCP connections, the domain sharding hacks, the head-of-line blocking, the bloated headers sent on every single request? What if i told you that someone sat down, looked at all of it, and said “nope, we’re fixing the whole thing”?</p><p>That’s HTTP/2. And it’s kind of glorious.</p><h4><strong>A quick Origin story:</strong></h4><p>Before HTTP/2, there was SPDY — an experimental protocol that google quietly launched in 2009 with one goal: make the web 50% faster without enforcing anyone to rewrite their apps.</p><p>Early results were wild, In lab conditions, pages loaded up to 55% faster. Chrome adopted it. The Firefox. Then Opera. By 2012 it was quietly running on Twitter, Facebook and google. the web standards community watched this and basically said “…okay we should probably make this official.”</p><p>So the HTTP working group took SPDY. spent three years of testing, debating and refining it in the open, and in May 2015 published RFC 7540 — the official HTTP/2 standard. SPDY was retired shortly after its job done.</p><p>The best part ? Your existing apps needed zero changes to work on HTTP/2. Same HTTP methods, same status codes, same urls. HTTP/2 only changed how data is packaged and sent under the hood. The API stayed identical.</p><h4>The Root Cause of All HTTP/1.x Pain: Plain Text</h4><p>HTTP/1.x communicates in plain text. Every request and response is a human — readable string. with newlines separating fields. Great for debugging in 1991. Not great for performance in 2015.</p><p>HTTP/2 introduces a binary framing layer — everything gets encoded in compact binary format before it leaves your machine. The browser and server handle this transparently: you never see it. But the impact is massive.</p><p>Think of it like switching from mailing handwritten letters to sending digital packets. same content, completely different transmission mechanism.</p><p>( You’ll need tools like Wireshark to inspect HTTP/2 traffic now. But honestly, you already need Wireshark to inspect TLS-encrypted HTTP/1.x traffic, so this changes nothing for most developers. )</p><h4>The Three Core Concepts: Streams, Messages, Frames</h4><p>HTTP/2 introdces a vocabulary worth knowing:</p><p>Frame → The smaller unit. A tiny binary chunk with a 9-byte header containing its type, length, flags and which steam it belongs to.</p><p>Message → A complete HTTP request or response, made up of one or more frames.</p><p>Stream → A bidirectional channel within the connection. Many streams can exist simultaneously on the same TCP connection, each with a unique ID.</p><p>Here’s the key insight: frames from different streams can be interleaved freely. Stream 1’s frames, stream 3’s frames and 5’s frames — all shuffled together on the wire, all reassembled correctly at other end using the stream IDS embeded in each frame header. It’s like having conversation where then people are talking at once but everyone’s words are color-coded so you can follow each thread.</p><h4>The Main Event: Multiplexing</h4><p>This is the feature that kills every HTTP/1.x hack in one shot.</p><p>In HTTP/1.x, each TCP connection could handle one request at a time. Want parallelism? Open more connections. Hence the six-connections-per-host limit, the domain sharding, all of it.</p><p>HTTP/2 says: one connection, unlimited parallel streams. The browser can dispatch all 90 requests that moment the moment it discovers them. The server interleaves responses back. No queuing. No blocking. No fake hostnames in DNS.</p><p>Practically, this means you can undo all the HTTP/1.x workarounds your codebase probably has:</p><ul><li>❌domain shading → unnecessary ( actually harmful on HTTP/2 )</li><li>❌CSS/JS file concatenation → unnecessary</li><li>❌Image sprites → unnecessary</li><li>❌Resource in lining just to avoid a round trip → unnecessary</li></ul><p>HTTP/2 didn’t just improve performance. It made the codebase cleanup it allowed for.</p><h4>One Connection Per Origin ( And Why That’s Big Deal )</h4><p>Because of multiplexing, HTTP/2 needs just one TCP connection per origin — forever. Compare that to HTTP/1.x where 74% connections carried only a single HTTP transaction. You were paying the full cost of a TCP handshake, slow start, and TLS negotiation just to fetch one resource.</p><p>In HTTP/2, that number drops by 25%. You amortize all the connection setup cost across dozens or hundreds of requests on the same connection. This is especially huge for HTTPS — fewer connections means fewer TLS handshakes, and the ones you do establish get warm and fast with session reuse.</p><p>There’s one honest catch worth mentioning: HTTP-level head-of-line blocking is gone, but TCP-level head-of-line blocking still exists. If a single packet is lost, all streams on that connection stall while TCP retransmits. With HTTP/1.x, that only affected one of your six connections. With HTTP/2’s single connection, it affects everything. In practice, real-world testing showed that the compression and prioritization benefits still outweigh this — but it’s why QUIC (HTTP/3’s transport) eventually moved away from TCP entirely.</p><h4>Stream Prioritization: Telling the server What matters</h4><p>Not all resources are equal. Your CSS blocks rendering. Your JavaScript block the DOM. Your hero image matters more than the footer widget. HTTP/2 lets the browser communicate these priorities explicitly to the server.</p><p>Each stream can have:</p><ul><li>A weight ( 1–256) — relative importance among siblings</li><li>A Dependency — only start on me after stream X is done</li></ul><p>The Browser builds a priority tree and sends it to the server. The server can use this to allocate bandwidth and CPU accordingly — push the CSS response out first, hold back the low-priority analytics script.</p><p>And these priorities are dynamic. User scrolled? Hovering over a link? The browser can update priorities in real time.</p><p>With HTTP/1.x, the browser’s only lever was which requests to dispatch first. Now it can have a full conversation with the server about what matters.</p><h4>Server Push: “You will need this too”</h4><p>Here’s the fun one. In HTTP/1.x, the browser has to discover resources reactively: parse HTML, find a &lt;link&gt; tag, request the CSS, parse the CSS, find a font reference, request the font… It’s chain of round trips.</p><p>Server Push breaks the chain. When the server sends you index.html, it can simultaneously push style.css, app.js and logo.png — before you even asked for them. It already knows you’ll need them. Why wait?</p><p>The key advantage over HTTP/1.x’s hacky equivalent (resource inlining) is that pushed resources are:</p><ul><li>✅cacheable — if the browser already has it, it sends RST_STREAM to cancel the push</li><li>✅reusable across pages — not baked into one document</li><li>✅cancellable — the client stays in control, unlike forced inlining</li></ul><p>The mechanism uses a PUSH_PROMISE frame: the server announces its intent before actually sending the data, giving the client a chance to say “Actually, I have that cached, don’t bother.” Clean, efficient, and nothing like HTTP/1.x’s” just embed it and hope.”</p><h4>Header Compression: HPACK</h4><p>Every HTTP/1.x request ships the same headers, over and over again. user-agent, accept, cookie — hundreds to thousands of bytes, repeated with every single request, completely uncompressed.</p><p>HTTP/2 fixes this with HPACK:</p><ol><li>Huffman encoding: common header values are compressed using a static code table.</li><li>Header Indexing: Both client and server maintain a shared table of previously seen headers. After the first request, user-agent:Mozilla/5.0… becomes just an index number like 42</li></ol><p>The savings were 85–88% reduction in header data size in early SPDY testing — with measurable page load improvements even over low-bandwidth connections.</p><h4>Upgrading to HTTP/2: How does It even negotiate ?</h4><p>Since HTTP/1.x and HTTP/2 share port 80/443, clients and servers need a way to agree on which protocol to use. There are three mechanisms:</p><p><strong>The standard path ( recommended ): </strong>TLS + ALPN. During the TLS handshake, client and server negotiate the protocol in a dedicated extension field. No extra round trips. This is why Firefox and Chrome only support HTTP/2 over TLS in practice — they get ALPN for free.</p><p><strong>The Plain Text Path: </strong>The client sends an HTTP/1.1 request with an upgrade: h2c header. The server can respond with 101 switching protocols to accept, or just reply in HTTP/1.1 to decline. Works, but not supported by major browsers.</p><p><strong>Prior Knowledge: </strong>If the client already knows the server supports HTTP/2 ( from DNS, config or a previous visit) , it can just send HTTP/2 frames immediately and hope for the best. Falls back gracefully if it fails.</p><p>The Practice Takeaways: get TLS, get HTTP/2. They’re a package deal in the browser.</p><h4>What HTTP/2 actually is (and Isn’t)</h4><p>HTTP/2 is not replacement for HTTP. It’s a performance upgrade to the transmission layer. The semantics — Get, Post, 200,404, headers, cookies, caching — all unchanged. Your APIs stay the same. Your CDN configs mostly stay the same.</p><p>What changes is everything underneath: framing, compression, multiplexing, prioritization, and push. The browser and server handle it all. You just… benefit.</p><p>It’s the rare protocol change where the upgrade path is genuinely “turn it on, watch things get faster, delete some old hacks.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*vsUawY4LsWJ48kOuwG1WWw.png" /></figure><h3>Chapter 10: Optimizing Application Delivery: Everything You Know About HTTP/1.x Is Now Technical Debt</h3><p>We’ve spent the last few chapters building up a picture of why the web is slow and what protocols like HTTP/2 offer to fix it.</p><p>Fair warning: some of what’s in here will make you want to go back and delete code you wrote last year. That’s normal. That means it’s working.</p><h4>The one rule that never changes</h4><p>Before diving into protocol-specific tricks, Grigorik establishes a principle that applies regardless of whether you’re on HTTP/1.x, HTTP/2 or whatever comes next:</p><blockquote>Eliminate unnecessary latency. Minimize transferred bytes.</blockquote><p>That’s it. That’s the whole chapter in one sentence. Everything else is just a different way of applying thosee two rules in different contexts. Keep this in mind because it’ll explain why some HTTP/1.x “best practices” become anti-patterns on HTTP/2.</p><h4>Layer zero: You can’t optimize what physics controls</h4><p>Here’s a humbling thought to start: you cannot make light travel faster. The propogation delay between a server in singapore and a user in sao paulo is deteremined by the speed of light and the curvature of the earth. No amount of code changes will fix that.</p><p>What you can do is:</p><p><strong>Get your servers closer to your users. </strong>CDNs exist for this exact reason. A request that travels 50ms round-trip instead of 200ms changes the entire feel of your app — especially for anything that requires multiple round trips ( TLS, TCP slow start, API Calls )</p><p><strong>Stop pretending wireless networks behave like wired ones. </strong>At the API layer, they look identical. At the network layer, 4G latency on a crowded cell tower is nothing like a fibre connection. How and when you schedule downloads, analytics beacons, and prefetch requests can have outsized impact on mobile performance and battery life.</p><p>You cannot control the network. You can control where you put the server, and you can be thoughtful about how much network activity you trigger.</p><h4>The Evergreen checklist: These never expires</h4><p>These apply regardless of protocol version, network type, or what framework you’re using. Engrave them somewhere:</p><p><strong>Reduce DNS lookups. </strong>Every Unique hostname is a network round trip before a single byte of content moves. Count your origins.</p><p><strong>Reuse TCP connections. </strong>Connection keepalive eliminates the handshake + slow-start tax. This should be enabled on every server you run.</p><p><strong>Kill Redirects. </strong>One redirect to a different origin can cost you DNS + TCP + TLS + request/response — hundreds of milliseconds — before you’ve even started serving your page. The ideal number of redirects is zero.</p><p><strong>Eliminate unnecessary resources. </strong>No request is faster than a request not made. Audit your pages. The average site is still carrying resources it doesn’t actually need</p><p><strong>Cache Aggressively. </strong>Specify both a cache lifetime and a validation mechanism ( ETag or Last-Modified). Missing either one is a common mistake: one causes redundant download, the other causes redundant validation round trips. you need both.</p><p><strong>Compress everything. </strong>Text assets ( HTML, CSS, JS) compress 60% 80% with gzip. For images, strip metadata, size them to display width, pick the right format, and consider lossy compression where it makes sense. Images are over half the bytes on an average page — this is not optional.</p><h4>The Cookie problem Nobody Talks about.</h4><p>Here’s a sneaky part. HTTP cookies are automatically attached to every request to their origin. Every Image. Every CSS file. Every font. Every API call.</p><p>You can associate tens of hundreds of kilobytes of cookie data per origin, across multiple cookies. And since cookies are part of the HTTP header:</p><ul><li>In HTTP/1.x: completely uncompressed, every request</li><li>In HTTP/2: HPACK compressed, but still transferred in full on the first request.</li></ul><p>In the worst case, bloated cookies push your request headers past the initial TCP congestion window, requiring extra round trips before your request even arrives. The fix: transfer only what you absolutely need (A session token, not your entire user object), and serve static assets from a cookie-free origin. where client-specific state is irrelevant.</p><p>The rule is: If a resource doesn’t need to know who the user is, it shouldn’t be carrying proof of who they are.</p><h4>HTTP/1.x Optimizations: A field guide to necessary evils</h4><p>If you’re still supporting HTTP/1.x clients (and you probably are for now), here’s the playbook. These are workarounds for protocol limitation, not elegant solutions. Apply them knowing that.</p><p><strong>Domain shading: </strong>Split your assets across multiple subdomains to get more parallel connections. Remember: this adds DNS overhead and hurts HTTP/2 clients. Use it carefully. Measure the impact.</p><p><strong>Concatenation and Spriting — </strong>Bundle your JS file, combine your css, pack your icons into sprites. The goal is fewer HTTP requests, because each request is expensive. The downside: One byte changes invalidates the whole bundle.</p><p><strong>Resource Inlining — </strong>Embed small images as data URLS or CSS directly in html to save a round trip. Saves latency, kills caching, increase document size.</p><p><strong>Pipelining — </strong>Send multiple requests without waiting for responses. Helps, but has limited server support and is notoriously finicky.</p><p>All of these exist for one reason: limited parallelism in HTTP/1.x. They are workarounds. treat them like medication — take the minimum dose needed, with awareness of side effects, and stop when you no longer need them.</p><h4>HTTP/2 : Time to unlearn everything</h4><p>Here’s where the chapter gets cathartic. With HTTP/2 in play. the optimization strategy does a 180. The things you worked hard to build become the things you need to tear down.</p><p><strong>Undo domain sharding: </strong>HTTP/2 wants one connection per origin, Domain sharding defeats this. Each extra origin resets the connection pool, loses header compression state, and forces new TLS handshakes. ON Http/2, sharding is actively harmful.</p><p>Reconsider concatenation. With multiplexing, request count isn’t the bottleneck anymore. Bundling everything into one giant JS file means:</p><ul><li>Users download code they don’t need on every page.</li><li>One changed file invalidates the entire bundle from cache</li><li>Execution is delayed until the whole file is received</li></ul><p>HTTP/2 rewards smaller, granular resources with individual caching policies. A component that doesn’t change can be cached for a year. A component that changes daily gets its own file with a short TTL. You can’t do that a monolithic bundle.</p><p><strong>Replace inlining with server push. </strong>Inlining a resource into your HTML saves a round trip but kills cacheability. Server push does the same thing — eliminates the round trip — while keeping the resource independently cacheble, reusable across pages, and cacnellable by the client if it already has a copy cached. If you’re using data: URIs or &lt;style&gt; blocks with inlined css, server push is the HTTP/2 upgrade path.</p><h4>The Connection Coalescing Trick (For the Migration Period)</h4><p>Here’s a clever detail for teams running mixed HTTP/1.x + HTTP/2 deployments.</p><p>HTTP/2 lets the client reuse a single connection for requests to <em>different origins</em>, if two conditions are met:</p><ol><li>Both origins are covered by the <strong>same TLS certificate</strong> (wildcard or Subject Alternative Names)</li><li>Both origins resolve to the <strong>same server IP address</strong></li></ol><p>So static.example.com and www.example.com can share one HTTP/2 connection if your wildcard cert covers both and they point to the same box. HTTP/1.x clients get their sharded parallel connections. HTTP/2 clients coalesce onto one. Everyone wins without serving different markup.</p><p>This is the rare optimization that works for both protocol versions simultaneously, making the migration period less painful.</p><h4>Prioritization: Trust the Server (But Verify)</h4><p>HTTP/2 lets the client send priority information to the server — which resources are render-blocking, which can wait, which are high-value vs. nice-to-have. The browser builds a priority tree and trusts the server to honor it.</p><p>The problem: a naive HTTP/2 implementation might “speak” HTTP/2 but completely ignore stream priorities. It’ll happily saturate your bandwidth serving low-priority images while the browser sits blocked waiting for the CSS that enables rendering.</p><p>This is not theoretical — it’s a common failure mode in early HTTP/2 server implementations.</p><p><strong>Test your server’s HTTP/2 quality explicitly.</strong> Standard throughput benchmarks (requests/sec, transfer speed) don’t capture this. Use Webpage Test&#39;s waterfall view with a simulated slow connection to see whether your server is actually respecting priorities.</p><h4>The Mental Model Shift</h4><p>HTTP/1.x optimization was about <strong>fighting the protocol</strong> — working around its limitations with hacks that had their own costs.</p><p>HTTP/2 optimization is about <strong>working with the protocol</strong> — letting multiplexing, prioritization, compression, and Push do what they were designed to do, and getting out of the way.</p><p>The rule of thumb Grigorik leaves you with:</p><blockquote><strong><em>More, smaller resources. Fewer origins. Better caching. Let the protocol do the work.</em></strong></blockquote><p>The best HTTP/1.x optimization was always to deploy HTTP/2. And the best HTTP/2 optimization is to stop thinking like you’re on HTTP/1.x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*M09hw5ZwgYxB6YamJ8QLAA.png" /></figure><h3>Chapter 11: Primer On Browser Networking — The Browser’s Hidden Network Brain ( And why it’s your best friend )</h3><p>You think of the browser as a rendering engine. A JavaScript VM. A tab-hoarder. But somewhere under all of that is something most developers barely think about: <strong>a full-blown networking platform</strong> with its own optimization engine, security sandbox, caching layer, and protocol stack.</p><p>Understanding the hidden layer is what separates developers who just write fetch() calls from developers who write fast applications.</p><h4>The Browser Is Doing More Than You Think</h4><p>Every time your app makes an HTTP request, the browser is quietly doing a mountain of work behind the scenes:</p><ul><li>Managing TCP connection pools (organized by origin)</li><li>Prioritizing which pending requests get dispatched first</li><li>Proactively opening sockets <em>before</em> you even ask</li><li>Negotiating HTTP protocol versions (HTTP/1.1 vs HTTP/2)</li><li>Handling caching, compression, redirects, and authentication</li><li>Enforcing security rules you never have to think about</li></ul><p>You write fetch(&#39;/api/data&#39;). The browser does about 15 things. That&#39;s a good deal.</p><h4>Socket Pools: The Invisible Connection Manager</h4><p>Here’s something most developers don’t realize: <strong>you never manage sockets directly in the browser — and that’s intentional</strong>.</p><p>Sockets are organized into <em>pools</em>, grouped by origin (protocol + domain + port). Each pool is capped at six sockets. When your app makes requests, they queue up and get assigned to available sockets in the pool. When a response is done, the socket goes back into the pool for the next request. No teardown. No new handshake. Just reuse.</p><p>This automatic pooling gives you TCP keepalive benefits for free. But it also means the browser has visibility into all your requests at once, which enables something even more powerful: <strong>intelligent prioritization</strong>. Your render-blocking CSS gets a socket first. Your analytics beacon can wait.</p><h4>Security Sandboxing: The Browser as Bouncer</h4><p>The browser doesn’t give JavaScript raw socket access. If it did, a malicious script could port-scan your local network, talk to your mail server, or impersonate you to any server. Instead, the browser exposes <em>just enough</em> — and enforces these constraints at the network level:</p><ul><li><strong>Connection limits</strong> — prevents resource exhaustion attacks</li><li><strong>Same-origin policy</strong> — no cross-origin requests without explicit opt-in</li><li><strong>TLS verification</strong> — certificate checks with visible warnings on failure</li><li><strong>Request formatting</strong> — you supply the URL and data; the browser writes the actual HTTP request</li></ul><p>This is the principle of <em>least privilege</em> at work. You get a clean, safe API. The browser handles the dangerous parts.</p><h4>Cache? What Cache?</h4><p>The browser’s resource cache is another thing developers hand-wave past. It’s actually doing real work for you:</p><ul><li>Checking every outgoing request against its cache first</li><li>Evaluating Cache-Control, ETag, and Last-Modified headers</li><li>Revalidating stale resources automatically</li><li>Managing eviction so the cache doesn’t grow forever</li></ul><p>If you’re not sending proper caching headers on your responses, you’re throwing away one of the best free performance wins available. The browser wants to help. Give it the headers it needs.</p><h4>The Networking API Menu: Pick the Right Tool</h4><p>Not all data is the same. Not all communication is the same. The browser gives you four different networking APIs, each optimized for a different pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*TjJxy6FFo_CzoLyObiMLGw.png" /></figure><p>The browser’s networking layer powers all four. But each has its own performance profile, overhead, and tradeoffs. The next chapters cover each one.</p><p><strong>The point</strong>: before you even write your first API call, the browser has already set up connection pools, checked the cache, planned a priority queue, and enforced your security constraints. Your job isn’t to fight this machinery — it’s to understand it well enough to work with it.</p><h3>Chapter 12: XMLHttpRequest ( XHR: The Old Workhorse That Still Runs the web)</h3><p>In the beginning, there was page reload. You submitted a form, the whole page refreshed, and you sat there watching a blank screen for half a second. That was just how the web worked.</p><p>Then, in 1999, Microsoft crammed a networking object into Internet Explorer 5 as part of their Outlook Web Access team’s effort to build something that <em>felt</em> like a desktop app. They needed to fetch data without reloading the page. They bolted it onto the MSXML library, gave it an awkward name, and shipped it.</p><p><strong>XMLHttpRequest</strong> — or XHR — was born. And it quietly changed everything.</p><h4>What XHR Actually Does</h4><p>The name is misleading. XHR has nothing specifically to do with XML. The “XML” prefix is just a vestige of which library it hitchhiked on at birth. What XHR actually is: <strong>a browser API that lets JavaScript initiate HTTP requests and handle responses asynchronously</strong>.</p><p>That’s it. But in 1999, that was revolutionary.</p><p>Before XHR: user action → full page reload → wait → see result.<br> After XHR: user action → background request → update just the part that changed.</p><p>Google Maps. Gmail. Facebook Chat in 2008. All built on XHR. It’s the technology that enabled us to build <em>applications</em> in the browser instead of just <em>documents</em>.</p><p>And the best part? The browser still does all the hard work:</p><ul><li>Formats the HTTP request</li><li>Handles caching, redirects, compression</li><li>Enforces security and same-origin rules</li><li>Manages the connection lifecycle</li></ul><p>You just write a few lines of JavaScript.</p><h4>Upload, Download, Everything In Between</h4><p>XHR can handle all data types natively — text, JSON, binary blobs, files, typed arrays. Want to download an image without base64 tricks?</p><pre>var xhr = new XMLHttpRequest();<br>xhr.open(&#39;GET&#39;, &#39;/images/photo.webp&#39;);<br>xhr.responseType = &#39;blob&#39;;<br>xhr.onload = function() {<br>  var img = document.createElement(&#39;img&#39;);<br>  img.src = window.URL.createObjectURL(this.response);<br>  document.body.appendChild(img);<br>};<br>xhr.send();</pre><p>No encoding overhead. No data URIs. Just a blob, directly from the network to the DOM.</p><p>Uploads are just as elegant. Pass a string, a FormData object, a File, or an ArrayBuffer into send(). Need to upload a 500MB file? Slice it into 1MB chunks, upload each independently. If one fails, retry just that chunk.</p><p>You also get <strong>progress events</strong>: loadstart, progress, load, error, abort, loadend. Build a proper progress bar. Set timeouts. Handle failures gracefully. XHR gives you the hooks.</p><h4>CORS: The Cross-Origin Conversation</h4><p>The same-origin policy means XHR can’t just talk to any server. If your code at example.com tries to fetch from thirdparty.com, the browser blocks it by default.</p><p><strong>CORS</strong> (Cross-Origin Resource Sharing) is the opt-in mechanism that unlocks this. When you make a cross-origin request, the browser automatically adds an Origin header. The server responds with Access-Control-Allow-Origin. If the headers line up, the request goes through. If not, the browser blocks it.</p><p>For non-simple requests (custom headers, PUT/DELETE methods), the browser sends a <strong>preflight</strong> — an OPTIONS request that asks permission before the real request. It adds a round trip, but the result can be cached.</p><p>The gotcha: CORS is opt-in on the <em>server</em> side. If the server you’re calling doesn’t know about CORS, your request will fail, regardless of your intentions.</p><h4>The Real-Time Problem: Polling vs. Long Polling</h4><p>HTTP is fundamentally request-response. The server can’t push data to you — you have to ask for it. So how do you build real-time notifications on top of XHR?</p><p><strong>Option 1: Polling</strong>. Check the server every N seconds. Simple, but brutal.</p><p>With 10,000 clients polling every 60 seconds, each adding ~850 bytes of request overhead, you’re looking at <strong>1.13 Mbps of sustained ingress traffic</strong> — just for empty responses. Add cookies and auth tokens, or drop the interval to 1 second, and that 60 Mbps of traffic is doing nothing.</p><p><strong>Option 2: Long Polling</strong> (a.k.a. Comet). Instead of returning an empty response immediately, the server <em>holds the connection open</em> until data is available. The moment new data exists, the response is sent, and the client immediately opens a new long-poll request.</p><p>Facebook Chat was built on this in 2008. Lower latency than polling, no empty responses. Still creates one HTTP request per message, but at least each request carries actual data.</p><p>It works. It’s still used as a fallback in production today. But it’s not elegant — and it’s not what you’d build fresh if you had better options.</p><h4>Where XHR Falls Short</h4><p>Streaming is the big one. XHR buffers the entire response before handing it to you. There’s no clean API for processing data incrementally as it arrives. You can hack around this with readyState checks and responseText slicing, but it&#39;s browser-inconsistent, memory-inefficient, and generally unpleasant.</p><p>The summary is blunt: <strong>XHR is excellent for request-response HTTP. For streaming, real-time push, or anything requiring low overhead repeated updates, it’s the wrong tool.</strong> That’s exactly what the next two chapters address.</p><p><strong>Bottom line</strong>: XHR is 25 years old and still runs half the web. Know it well, use it for what it’s good at — clean HTTP calls with full browser services (caching, auth, compression) — and reach for SSE or WebSocket when the use case demands it.</p><h3>Chapter 13: Server-Sent Events, where the server finally gets to do the talking.</h3><p>Here’s a problem XHR doesn’t solve cleanly: <strong>the server has new data, and it needs to tell the client</strong>.</p><p>You could poll. You could long-poll. You could build an elaborate timeout-and-retry dance in JavaScript. Or you could use the API that was literally designed for this exact problem and require approximately four lines of code to set up.</p><p>That’s Server-Sent Events. It’s been in the HTML5 spec for years. It’s supported by every modern browser. And somehow, most developers still reach for WebSocket when SSE would be the better choice.</p><pre>var source = new EventSource(&quot;/event-stream&quot;);<br><br>source.onmessage = function(event) {<br>  console.log(event.data);<br>};<br><br>source.addEventListener(&quot;notification&quot;, function(event) {<br>  showNotification(event.data);<br>});</pre><p>That’s the entire client-side implementation. Open a connection. Register callbacks. The browser handles everything else:</p><ul><li>Establishing and maintaining the persistent connection</li><li>Parsing the incoming stream</li><li>Identifying message boundaries</li><li>Firing DOM events for each message</li><li><strong>Automatically reconnecting</strong> if the connection drops</li><li><strong>Tracking the last received message ID</strong> and sending it on reconnect, so the server can resume the stream</li></ul><p>You didn’t write any reconnection logic. You didn’t manage any state. The browser did it for you.</p><h4>What’s Actually Happening Under the Hood</h4><p>SSE is regular HTTP. The client makes a GET request, and the server responds with Content-Type: text/event-stream. Instead of closing the response, the server just... keeps writing to it. One long, streaming response.</p><p>The event stream protocol is dead simple:</p><pre>data: First message is a simple string.<br><br>data: {&quot;message&quot;: &quot;JSON payload&quot;}<br><br>event: notification<br>data: This is a named event<br><br>id: 42<br>event: update<br>data: Multi-line<br>data: message here<br><br>retry: 15000</pre><p>Rules:</p><ul><li>data: field carries the payload</li><li>Blank line marks the end of a message</li><li>Optional event: gives the message a type</li><li>Optional id: lets the server checkpoint the stream</li><li>retry: sets the client reconnect interval in milliseconds</li></ul><p>That’s the whole protocol. Text-based, human-readable, trivial to generate on any backend.</p><h4>The Auto-Reconnect Is the Killer Feature</h4><p>Drop the connection? SSE reconnects automatically. And when it reconnects, it sends Last-Event-ID: 42 (or whatever the last received ID was), letting the server know exactly where to resume.</p><p>This gives you built-in resilience with no client-side logic:</p><ul><li>If lost messages are acceptable: ignore the ID, just resume the stream</li><li>If message recovery matters: server keeps a short buffer and retransmits anything after the last known ID</li></ul><p>Your chat app, live dashboard, or notification system suddenly handles network hiccups gracefully — for free.</p><h4>Why SSE Beats XHR Long-Polling (In the Right Scenario)</h4><p>The comparison is instructive:</p><p><strong>Long-polling</strong>: every message is a new HTTP request. New TCP connection (or reused, but still new request). New headers sent. 500–800 bytes of overhead per message.</p><p><strong>SSE</strong>: one persistent HTTP connection. Messages arrive over that connection with as little as 5 bytes overhead per message. The connection is already warm. There’s no queuing latency.</p><p>For live feeds, notifications, sports scores, stock tickers, chat messages, progress updates, log streaming — SSE is almost always the right choice over polling.</p><h4>The Limits (And They’re Real)</h4><p>SSE has two firm constraints:</p><p><strong>Server-to-client only.</strong> Once the connection is established, the client can’t send data back. If you need bidirectional communication, SSE won’t cut it.</p><p><strong>Text only.</strong> The event stream protocol is UTF-8. You can base64-encode binary data, but that adds 33% overhead. If you need binary streaming, use WebSocket.</p><p>A practical workaround for the binary case: use SSE to send a notification that a new binary asset is available, then trigger an XHR to actually fetch it. You get the push behavior of SSE with the full caching, compression, and content-negotiation of HTTP for the actual asset. Best of both worlds.</p><p>One more gotcha: <strong>proxy servers</strong>. Some intermediaries buffer streaming responses, which can break SSE. If you see unexpected latency or broken connections, move the SSE endpoint to TLS. Encrypted traffic passes through proxies without buffering.</p><p><strong>When to use SSE</strong>: server needs to push text-based updates to the client. Notifications, live feeds, log streams, progress indicators, real-time dashboards. Simple, efficient, and auto-reconnects.</p><p><strong>When not to</strong>: you need to send data <em>from</em> the client in the same connection, or you need binary streaming. That’s WebSocket territory.</p><h3>Chapter 14: WebSocket</h3><p>XHR is a walkie-talkie. Press to talk, release to listen, one message at a time.</p><p>SSE is a radio broadcast. Server talks, client listens, continuous stream in one direction.</p><p>WebSocket is a <strong>phone call</strong>. Both sides can talk at the same time, whenever they want, over the same persistent connection.</p><p>If your application needs real-time, bidirectional communication — live collaboration, multiplayer gaming, chat, trading platforms, interactive dashboards — WebSocket is where you land.</p><h4>The API: Surprisingly Small</h4><pre>var ws = new WebSocket(&#39;wss://example.com/socket&#39;);<br><br>ws.onopen = function() {<br>  ws.send(&quot;Hello server!&quot;);<br>};<br><br>ws.onmessage = function(msg) {<br>  if (msg.data instanceof Blob) {<br>    processBlob(msg.data);<br>  } else {<br>    processText(msg.data);<br>  }<br>};<br><br>ws.onerror = function(error) { ... };<br>ws.onclose = function() { ... };</pre><p>That’s it. Four callbacks. One send() method. The browser handles connection management, message framing, and all the low-level details. You just send and receive messages.</p><p>What you can send: strings (UTF-8), ArrayBuffers, ArrayBufferViews, Blobs. Text and binary both work natively — no base64 encoding required.</p><h4>The Handshake: Born From HTTP, Escapes to Something Better</h4><p>WebSocket starts life as an HTTP request:</p><pre>GET /socket HTTP/1.1<br>Connection: Upgrade<br>Upgrade: websocket<br>Sec-WebSocket-Version: 13<br>Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==</pre><p>The server responds with 101 Switching Protocols, and from that moment on, the HTTP protocol is done. The connection is now WebSocket&#39;s. No more headers. No more request-response cycles. Just a stream of binary frames flowing in both directions.</p><p>This HTTP-based handshake is intentional and clever — it means WebSocket works on ports 80 and 443, which are almost always open, and it’s compatible with existing HTTP infrastructure.</p><h4>Binary Framing: Tiny Overhead, Maximum Flexibility</h4><p>Once the handshake is done, all communication is via WebSocket frames. Each frame has 2–14 bytes of overhead — orders of magnitude less than HTTP’s 500–800 bytes per request.</p><p>A frame carries:</p><ul><li>A FIN bit (is this the last fragment of a message?)</li><li>An opcode (text, binary, ping, pong, close)</li><li>A masking key (client-to-server messages are masked, to prevent cache-poisoning attacks)</li><li>A variable-length payload length field</li><li>The payload</li></ul><p>Unlike HTTP, there’s no metadata, no content-type headers, no cookies. The framing is lean by design. The tradeoff: you’re responsible for encoding any metadata into the payload itself. WebSocket gives you a raw, bidirectional pipe; what you put through it is your problem.</p><h4>Subprotocols and Message Formats</h4><p>Because WebSocket is so bare-bones, client and server need to agree on a communication format. WebSocket formalizes this with <strong>subprotocol negotiation</strong>:</p><pre>var ws = new WebSocket(&#39;wss://example.com/socket&#39;, [&#39;appProtocol-v2&#39;, &#39;appProtocol-v1&#39;]);<br><br>ws.onopen = function() {<br>  console.log(&quot;Agreed protocol:&quot;, ws.protocol); // &#39;appProtocol-v2&#39;<br>};</pre><p>The client advertises what it speaks. The server picks one. If there’s no match, the connection is rejected. Clean, explicit, no guessing.</p><h4>The Head-of-Line Blocking Gotcha</h4><p>WebSocket frames don’t have stream IDs. That means <strong>frames from different messages can’t be interleaved</strong>. A large message blocks everything queued behind it — even if it’s split into multiple frames.</p><p>This is different from HTTP/2, which solves this with stream multiplexing. WebSocket has no equivalent.</p><p>The practical fix: split large messages into multiple smaller <em>application</em> messages at the application layer. Keep each message small, especially for latency-sensitive data. Monitor bufferedAmount to avoid accidentally queuing a backlog that stalls high-priority messages.</p><h4>The Real Performance Story</h4><p>WebSocket’s low per-message overhead makes it ideal for high-frequency, small-message applications. But it comes with hidden costs that are easy to overlook:</p><p><strong>No browser caching.</strong> Data flowing through a WebSocket is opaque to the browser. No CDN, no cache. Every byte comes from your server. For static or semi-static assets, XHR is often better — the browser can cache them.</p><p><strong>No automatic compression.</strong> HTTP has gzip negotiation built in. SSE can be gzip’d. WebSocket has no compression by default. You have to implement it yourself (or wait for the per-message compression extension to land everywhere). Binary payloads may already be compressed, but UTF-8 messages are sent raw.</p><p><strong>Infrastructure headaches.</strong> WebSocket connections are long-lived. Your load balancers, proxies, and servers are probably configured to timeout idle connections aggressively. Nginx defaults to 60 seconds. HAProxy needs a dedicated tunnel timeout setting. Every piece of infrastructure in the serving path needs to be tuned.</p><p><strong>Always use WSS.</strong> Transparent proxies on the network — especially common on mobile — may buffer or mangle unencrypted WebSocket frames. TLS creates an end-to-end tunnel that passes through without interference.</p><h4>XHR vs SSE vs WebSocket: The Decision Tree</h4><ul><li>Need to fetch or upload a resource? <strong>XHR</strong>.</li><li>Need the server to push text updates to the client? <strong>SSE</strong>.</li><li>Need bidirectional, low-latency, text or binary communication? <strong>WebSocket</strong>.</li></ul><p>WebSocket is not a replacement for XHR or SSE. It’s the tool for the specific cases where bidirectional streaming over a persistent connection is what the application actually needs. Use the right one.</p><h3>Chapter 15: WebRTC</h3><p>Every other API we’ve covered in this series talks to a server. You’re the client. There’s a server. HTTP flows between you. Even WebSocket, for all its bidirectional power, still connects client to server.</p><p>WebRTC breaks that model completely.</p><p><strong>WebRTC lets browsers talk directly to each other.</strong> No server in the middle. Peer-to-peer audio, video, and arbitrary data, over UDP, with encryption baked in. You can build a video call, a multiplayer game’s data sync, or a file transfer tool — in the browser, in JavaScript, without any proprietary software.</p><p>That’s the promise. The reality is that getting there requires one of the most complex protocol stacks in all of web development. Let’s unpack it.</p><h4>Three APIs, One Platform</h4><p>WebRTC surfaces its functionality through three primary JavaScript APIs:</p><p><strong>getUserMedia</strong> — Access the user&#39;s camera and microphone. Acquire audio and video streams with configurable constraints: minimum resolution, frame rate, which camera to use.</p><p><strong>RTCPeerConnection</strong> — The core workhorse. Manages the full lifecycle of a peer-to-peer connection: NAT traversal, stream negotiation, keepalives, and automatic renegotiation when streams change.</p><p><strong>RTCDataChannel</strong> — Bidirectional data transfer between peers. Think WebSocket, but peer-to-peer, and with configurable reliability and ordering semantics.</p><p>The browser’s built-in audio and video engines handle noise cancellation, echo suppression, codec optimization (Opus for audio, VP8 for video), jitter buffering, and adaptive bitrate adjustment. Your code never touches any of that.</p><pre>Application layer:  getUserMedia | RTCPeerConnection | DataChannel<br>                    ↓                    ↓                  ↓<br>Media layer:              SRTP / SRTCP           SCTP<br>Security layer:                   DTLS<br>Transport layer:                   UDP</pre><ul><li><strong>ICE + STUN + TURN</strong> — Figure out how to reach the other peer through NATs and firewalls</li><li><strong>DTLS</strong> — TLS, but adapted for UDP. Encrypts everything</li><li><strong>SRTP/SRTCP</strong> — Secure, real-time delivery of audio and video</li><li><strong>SCTP</strong> — Reliable (or partially reliable) delivery of application data through DataChannel</li></ul><p>The good news: the browser implements all of this. You configure it with a few parameters. The machinery runs invisibly.</p><h4>The Hard Part: Getting Two Peers to Find Each Other</h4><p>Here’s the dirty secret: WebRTC is peer-to-peer, but it needs a server to get started.</p><p>Most browsers live behind NATs. They don’t have a public IP address. Peer A doesn’t know how to reach Peer B directly. So before any peer-to-peer connection exists, both peers need to exchange information through an intermediary — a <strong>signaling server</strong>.</p><p>WebRTC deliberately doesn’t specify what the signaling server looks like or what protocol it uses. That’s your problem. You can use WebSocket, SSE, long-polling, a carrier pigeon, whatever. The point is that both peers need to exchange <strong>SDP offers</strong> (a text description of what streams they want to share and what they support) through some out-of-band channel.</p><p>The flow looks like this:</p><ol><li>Amy calls createOffer(), gets an SDP description of her streams</li><li>Amy sends that SDP to Bob via your signaling server</li><li>Bob calls createAnswer(), sends his SDP back to Amy via signaling</li><li>Both peers now know what the other side looks like — but still can’t reach each other</li></ol><h4>ICE: The NAT Traversal Engine</h4><p>This is where it gets clever. Each peer runs an <strong>ICE agent</strong> that automatically discovers all the possible ways to reach it:</p><ol><li>Local IP addresses (direct LAN connections)</li><li>Public IP and port, discovered via a <strong>STUN server</strong> (like asking “what’s my public IP?” from inside the browser)</li><li>A <strong>TURN relay server</strong> as a last resort (if all else fails, relay through a middleman)</li></ol><p>The ICE agent collects all these <em>candidates</em>, sends them to the other peer via the signaling channel, and both sides run connectivity checks. Whichever path works — local IP, public IP, or TURN relay — becomes the connection.</p><p>About 92% of peer connections succeed via direct or STUN-assisted paths. About 8% need TURN relay. Plan for it.</p><p><strong>Trickle ICE</strong> is the performance optimization: instead of waiting for all candidates to be gathered before sending the SDP offer, candidates are trickled to the other peer as they’re discovered. This parallelizes discovery and connectivity checks, cutting connection setup time significantly.</p><h4>DTLS: Because Even Peer-to-Peer Needs Encryption</h4><p>Once a routing path exists, the peers perform a <strong>DTLS handshake</strong> — essentially TLS, but designed for UDP’s unreliable, unordered delivery. WebRTC generates self-signed certificates for each peer automatically.</p><p>DTLS adds 2 extra round trips for the handshake. The result: an encrypted tunnel. All subsequent data — audio, video, DataChannel messages — flows through this tunnel.</p><h4>Audio and Video: SRTP Takes Over</h4><p>Media streams flow over <strong>SRTP</strong> (Secure Real-Time Transport Protocol), which adds a packet header containing sequence numbers, timestamps, and stream identifiers — just enough metadata for the receiving engine to reconstruct and play the stream in real time.</p><p>The companion <strong>SRTCP</strong> provides a feedback channel: both peers periodically exchange statistics (packets sent, packets lost, jitter) and use that data to adjust bitrate, encoding quality, and other parameters dynamically. WebRTC implements its own adaptive bitrate streaming, down to the wire.</p><p>The browser’s video engine will happily trade resolution for smoothness if the network demands it. Set a 720p constraint; get 360p under network pressure. That’s intentional. Smooth playback beats stalled HD every time.</p><h4>DataChannel: WebSocket, But Peer-to-Peer</h4><p>DataChannel uses <strong>SCTP</strong> — a transport protocol that gives you the best features of TCP and UDP combined:</p><ul><li>Message-oriented (not stream-oriented like TCP)</li><li>Multiple independent streams multiplexed over one connection</li><li>Configurable reliability: fully reliable, partially reliable (N retransmits), or unreliable (raw UDP semantics)</li><li>Configurable ordering: in-order or out-of-order</li></ul><p>The API mirrors WebSocket almost exactly:</p><pre>var dc = pc.createDataChannel(&quot;gameState&quot;, { ordered: false, maxRetransmits: 0 });<br><br>dc.onopen = function() {<br>  dc.send(JSON.stringify(gameState));<br>};<br><br>dc.onmessage = function(msg) {<br>  updateFromPeer(JSON.parse(msg.data));<br>};</pre><p>The ordered: false, maxRetransmits: 0 configuration gives you UDP semantics: fire and forget, no ordering guarantees. Perfect for game state updates where old data is useless anyway. Increase maxRetransmits or set maxRetransmitTime for more reliability.</p><p><strong>Critical gotcha</strong>: for unreliable channels, keep messages under ~1,150 bytes. A 120KB message splits into 107 packets. With 1% packet loss, the probability of losing at least one is very high — and losing any fragment means losing the whole message. Design your message format around this constraint.</p><h4>The Infrastructure You Still Need</h4><p>WebRTC is peer-to-peer, but it’s not infrastructure-free:</p><ul><li><strong>Signaling server</strong> — required to initiate every connection. Use WebSocket or SSE for low latency.</li><li><strong>STUN server</strong> — required for NAT traversal. Without it, most connections fail. Google provides a public one for development; run your own for production.</li><li><strong>TURN server</strong> — required as a relay for the ~8% of connections that can’t punch through NATs. Expensive to operate (full media relay), but necessary for reliability.</li></ul><p>Multiparty calls get even more complex. Full mesh (everyone connects to everyone) is simple to set up but doesn’t scale — N peers means N(N-1)/2 connections and each peer uploads N-1 streams. For anything more than 3–4 participants, you need a <strong>selective forwarding unit</strong> (SFU) — a server that receives all streams and forwards the right ones to the right peers.</p><h4>Is WebRTC Overkill for Your Use Case?</h4><p>Be honest with yourself before reaching for WebRTC:</p><ul><li>Need real-time chat? <strong>SSE + XHR</strong> is simpler and server-hosted, so no NAT issues.</li><li>Need bidirectional data without media? <strong>WebSocket</strong> is simpler to operate.</li><li>Need video calling or peer-to-peer file transfers where bypassing the server matters? <strong>WebRTC</strong>.</li></ul><p>WebRTC’s connection setup is significantly more complex than XHR, SSE, or WebSocket. You’re adding ICE negotiation, SDP exchange, DTLS handshakes, STUN/TURN infrastructure, and your own signaling layer. That complexity is worth it when you need what WebRTC offers. It’s not worth it otherwise.</p><h4>The Quick Summary</h4><p>WebRTC is arguably the most ambitious API ever shipped in a web browser. It turns real-time peer-to-peer communication — video calls, game data, file transfers — into a platform feature that requires nothing but JavaScript. Under the hood it’s coordinating a half-dozen protocols, NAT traversal, encrypted UDP tunnels, and adaptive media engines.</p><p>The complexity is real. But the browser absorbs almost all of it. You configure a few objects, handle a signaling channel, and let the machinery do the rest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1109d947a23f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-crash-course-for-the-networking-for-web-developer-1109d947a23f">The Crash Course For the networking for web developer.</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[The Complete Networking Cheat Sheet: Everything You Need to Know About How Browsers Talk to Servers]]></title>
            <link>https://javascript.plainenglish.io/the-complete-networking-cheat-sheet-everything-you-need-to-know-about-how-browsers-talk-to-servers-e55ca7dad75c?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55ca7dad75c</guid>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 18:53:21 GMT</pubDate>
            <atom:updated>2026-07-10T07:42:03.625Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One blog to rule them all — a complete summary of High Performance Browser Networking by Ilya Grigorik</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*TQx6AWrH75IJSPI7DyiOCA.jpeg" /></figure><h3>Part I: Networking Fundamentals</h3><h3>Chapter 1 — Latency and Bandwidth: The Two Numbers That Explain Everything</h3><p>Before any web performance optimization makes sense, you need to internalize two numbers:</p><p><strong>Bandwidth</strong> = how much data you can push per second. <strong>Latency</strong> = how long it takes a single bit to travel from A to B.</p><p>Bandwidth gets all the marketing attention. Your ISP advertises “up to 1 Gbps!” Latency barely gets mentioned. But here’s the uncomfortable truth: <strong>for typical web browsing, latency is almost always the bottleneck — not bandwidth</strong>.</p><p>Why? An average web page makes ~90 requests. Each request needs a round trip (or several) before data even starts flowing. When you’re making 90 round trips, a 50ms RTT adds 4.5 seconds to your load time regardless of your bandwidth. Upgrading from 5 Mbps to 1 Gbps won’t change that.</p><p>The four sources of latency:</p><ul><li><strong>Propagation delay</strong> — physics. Light takes time. You cannot fix this.</li><li><strong>Transmission delay</strong> — time to push bits onto the wire. Shrinks with bandwidth.</li><li><strong>Processing delay</strong> — routers examining and forwarding packets.</li><li><strong>Queuing delay</strong> — packets waiting in buffers when links are congested.</li></ul><p>The speed of light means a round trip from New York to London takes a minimum of ~70ms. No software optimization changes that. The only fix is putting servers closer to users.</p><h3>Chapter 2 — TCP: The Reliable Workhorse With Hidden Performance Costs</h3><p>HTTP runs on TCP. Everything about HTTP performance is downstream of how TCP works. Here’s what every web developer needs to know:</p><p><strong>Three-way handshake</strong>: Every new TCP connection costs a full round trip before any data moves. Client sends SYN, server sends SYN-ACK, client sends ACK + data. That’s 1 RTT of pure setup cost before HTTP even starts.</p><p><strong>Slow start</strong>: TCP doesn’t blast data at full speed from the beginning. It starts with a small congestion window (cwnd — about 10 packets in modern systems) and doubles it with each acknowledged segment until it hits the network’s limit or detects loss. A short HTTP request may <em>never</em> escape slow start, meaning it never uses the bandwidth you have available. The fix: keep TCP connections alive and reuse them.</p><p><strong>Congestion control</strong>: When packets are lost, TCP assumes network congestion and dramatically cuts its sending rate. On lossy wireless networks, this is especially brutal — what’s actually radio interference looks to TCP like congestion, triggering unnecessary slowdowns.</p><p><strong>Head-of-line blocking</strong>: TCP delivers data in order. A lost packet at position 5 stalls everything after it — even if packets 6, 7, 8 have already arrived. They wait in the buffer until 5 is retransmitted and arrives. Your application sees a stall.</p><p><strong>The takeaway</strong>: TCP was designed for reliability, not low-latency web workloads. The protocol does its best, but every new connection, every packet loss, every cold start is a performance tax. Modern TCP optimizations (larger initial cwnd, TCP Fast Open, window scaling) help, but the fundamental design creates a ceiling.</p><h3>Chapter 3 — UDP: The “Just Send It” Protocol</h3><p>UDP drops everything TCP does for reliability:</p><ul><li>No handshake</li><li>No ordering guarantees</li><li>No acknowledgements</li><li>No congestion control</li></ul><p>That sounds bad. For web browsing, it mostly is. But for real-time audio, video, and gaming — where a delayed packet is <em>worse</em> than a lost one — UDP is exactly right. You’d rather skip a video frame than freeze for 200ms waiting for a retransmit.</p><p>WebRTC (peer-to-peer video/data in browsers) is built on UDP for exactly this reason. The browser layers its own reliability and security protocols on top (DTLS, SRTP) to get encryption and some delivery guarantees where needed, while keeping latency low where it matters.</p><h3>Chapter 4 — TLS: Security That Costs Round Trips</h3><p>HTTPS is no longer optional. TLS encrypts everything, preventing eavesdropping, tampering, and impersonation. But it has a performance cost: <strong>the TLS handshake adds 1–2 extra round trips before the first HTTP request can be sent</strong>.</p><p>The TLS handshake:</p><ol><li>Client sends supported cipher suites and TLS version</li><li>Server sends chosen cipher, its certificate, and a server hello</li><li>Client verifies the certificate, generates session keys</li><li>Both sides confirm they’re ready</li></ol><p>That’s 2 RTTs added on top of TCP’s 1 RTT — so a fresh HTTPS connection costs 3 RTTs before your first byte of content.</p><p><strong>The optimizations that matter</strong>:</p><ul><li><strong>Session resumption</strong>: if client and server have talked before, they can skip most of the handshake. 0-RTT or 1-RTT resumption instead of 2-RTT full handshake.</li><li><strong>TLS False Start</strong>: send application data immediately after sending the client’s handshake message, without waiting for server confirmation. Cuts 1 RTT.</li><li><strong>OCSP stapling</strong>: instead of the client fetching a certificate revocation check separately, the server includes (“staples”) a fresh signed OCSP response in the handshake. Saves a round trip and a DNS lookup.</li><li><strong>Elliptic Curve Cryptography (ECC)</strong>: smaller keys, faster handshakes, equivalent security to RSA at much lower computational cost.</li></ul><p>The bottom line: TLS is mandatory, and the 1–2 RTT overhead is real. Mitigate it with session resumption, False Start, OCSP stapling, and keeping connections alive so you amortize the cost across many requests.</p><h3>Part II: Wireless Networks</h3><h3>Chapters 5–8 — WiFi, Mobile, and the Brutal Reality of Wireless Latency</h3><p>Wireless networks introduce a variable that doesn’t exist on wired connections: <strong>the radio environment is shared, noisy, and unpredictable</strong>.</p><p><strong>WiFi</strong>: Multiple devices share the same radio channel. They negotiate access using carrier sense and collision avoidance, which adds overhead. Signal interference from neighboring networks, walls, and microwave ovens causes packet loss that TCP interprets as congestion — triggering unnecessary slowdowns. The practical advice: sit closer to the router, minimize interference, and don’t assume office WiFi performs like a wired connection.</p><p><strong>Mobile networks (3G/4G/LTE)</strong>: The latency story here is genuinely painful. A 3G connection might have 100–500ms of latency just at the radio layer, before the packet even hits the internet backbone. LTE improved this dramatically (20–60ms typical), but it introduced new complexity: the radio is powered down when idle to save battery, and waking it up adds latency. That’s why the first request after a pause always feels slower on mobile — you’re paying the radio wake-up cost.</p><p><strong>The key insight for mobile optimization</strong>:</p><ul><li>Bundle requests where possible (fewer connections = fewer radio wake-ups)</li><li>Be aggressive about caching — a cached response is infinitely faster than any radio connection</li><li>Use connection keepalive to avoid repeated radio wake-ups</li><li>Offline-first design patterns (service workers) pay outsized dividends on mobile</li></ul><h3>Part III: HTTP</h3><h3>Chapter 9 — HTTP/1.x: The Protocol That Powered the Web (And Its Dirty Secrets)</h3><p>HTTP/1.1 is still the most-deployed version of HTTP. It introduced persistent connections, caching headers, chunked transfer encoding, and content negotiation. For its era, it was excellent.</p><p>Its problems only became apparent as web pages grew from 10KB documents to 1MB+ application bundles with 90+ resources:</p><p><strong>No multiplexing</strong>: one request at a time per TCP connection. While waiting for a response, the connection sits idle. This is called <strong>head-of-line blocking at the HTTP layer</strong> — a blocked request blocks everything behind it on that connection.</p><p><strong>Verbose, uncompressed headers</strong>: every request ships the same User-Agent, Accept, Cookie, Referer headers — hundreds to thousands of bytes, uncompressed, repeated on every single request. On a page with 90 requests, that&#39;s 90 copies of the same bloated header.</p><p><strong>No server push</strong>: the server can only respond to requests. It can’t proactively send resources the client will need. The browser discovers them reactively by parsing HTML, then CSS, then finding font references in CSS — a chain of sequential round trips.</p><p><strong>The workarounds HTTP/1.x forced developers to build</strong>:</p><ul><li><strong>Multiple TCP connections</strong> (up to 6 per host): browsers work around the no-multiplexing problem by opening parallel connections. Six connections = six parallel request slots. But each connection has its own TCP slow-start, its own handshake cost, and they compete with each other for bandwidth.</li><li><strong>Domain sharding</strong>: split assets across multiple subdomains (shard1.example.com, shard2.example.com) to get more than 6 parallel connections. Each shard is just a DNS alias for the same server. It works, but adds DNS overhead, extra TCP slow-starts, and TLS handshakes per shard. Easy to overdo and make things worse.</li><li><strong>Concatenation</strong>: bundle all your JS files into one, all CSS into one. Fewer requests. But one changed line invalidates the whole bundle from cache, and users download code they don’t need.</li><li><strong>Image sprites</strong>: pack dozens of icons into one image, use CSS background positioning to show the right piece. Saves requests. Makes individual icon caching impossible.</li><li><strong>Resource inlining</strong>: embed small images as base64 data URIs, inline critical CSS directly in &lt;style&gt; tags. Saves round trips. Kills cacheability.</li></ul><p>All of these are workarounds for protocol limitations. They have real costs. And they all become harmful when you move to HTTP/2.</p><h3>Chapter 10 — Primer on Web Performance: Why Latency Beats Bandwidth</h3><p>This chapter establishes the mental models that make everything else make sense.</p><p><strong>The web’s three eras</strong>:</p><ul><li><em>Hypertext</em>: one document, one TCP connection. PLT = document load time.</li><li><em>Web pages</em>: HTML + images + CSS. PLT = time until spinner stops.</li><li><em>Web applications</em>: complex dependency graphs of JS, CSS, markup. PLT is no longer sufficient.</li></ul><p>For modern apps, the metrics that matter are application-specific: time to first meaningful paint, time to interactive, conversion rate at each step. Generic PLT hides too much.</p><p><strong>The human perception thresholds</strong>:</p><ul><li>0–100ms: feels instant</li><li>100–300ms: perceptible but acceptable</li><li>300–1000ms: the machine is working</li><li>1000ms+: mental context switch</li><li>10000ms+: task abandoned</li></ul><p>The web performance community’s rule: render something useful in under 250ms.</p><p><strong>Bandwidth vs. latency — the definitive answer</strong>: Mike Belshe’s study (the one that directly motivated SPDY and HTTP/2) compared the effect of bandwidth increases vs. latency reductions on page load time:</p><ul><li>Doubling bandwidth from 1 to 2 Mbps nearly halves load time. Good.</li><li>Going from 5 to 10 Mbps: only ~5% improvement. Diminishing returns.</li><li>Beyond 5 Mbps, more bandwidth barely moves the needle.</li><li>But every 20ms reduction in RTT produces a <em>linear</em> improvement in PLT with no diminishing returns.</li></ul><p>The conclusion: for a typical US user already on 5 Mbps+, a 20ms latency improvement helps more than upgrading to 1 Gbps. Bandwidth is saturated. <strong>Latency is the real bottleneck.</strong></p><p><strong>The resource waterfall</strong>: your single most powerful diagnostic tool. DNS resolution → TCP handshake → TLS → request → download. The connection view in WebPageTest reveals the dirty secret: actual download time (blue) is tiny. The vast majority of time is spent in DNS lookups, handshakes, and waiting for the first byte. The pipe is nearly idle. You’re not bandwidth-limited — you’re latency-limited.</p><p><strong>Measurement strategy</strong>: synthetic testing (WebPageTest, controlled environments) catches regressions. Real-user measurement (RUM) via the Navigation Timing API captures what actually happens on real devices over real networks. Never look at averages — use medians, p75, p95, p99. Distributions are always skewed; averages lie.</p><h3>Chapter 11 — HTTP/1.x Optimizations: The Art of Working Around a Protocol</h3><p>Given the constraints of HTTP/1.x, the optimization playbook looks like this:</p><p><strong>Reduce DNS lookups</strong>: fewer unique hostnames = fewer DNS round trips.</p><p><strong>Reuse TCP connections</strong>: connection keepalive amortizes the TCP handshake across multiple requests. Should be on everywhere.</p><p><strong>Kill redirects</strong>: one redirect can cost DNS + TCP + TLS + request/response = hundreds of milliseconds before you’ve served anything.</p><p><strong>Compress everything</strong>: gzip reduces text assets 60–80%. Images should be sized to display width, metadata-stripped, and format-appropriate.</p><p><strong>Cache aggressively, validate correctly</strong>: set Cache-Control for lifetime AND provide ETag/Last-Modified for validation. Missing either one causes unnecessary downloads or unnecessary network requests.</p><p><strong>Trim cookies on static assets</strong>: cookies are sent on every request to their origin, uncompressed. Static assets (images, fonts, JS) don’t need cookies. Serve them from a cookie-free subdomain.</p><p><strong>Domain sharding (carefully)</strong>: use when profiling shows queuing is the bottleneck. More than 2–3 shards usually hurts. Always measure before and after.</p><p>The chapter on domain sharding deserves a special callout: it <em>works</em>, but it’s a hack. Every shard adds a DNS lookup, a TCP slow-start, and (on HTTPS) a TLS handshake. Overdoing it — 10+ shards — can actually slow pages down, especially on high-latency mobile connections. The rule: start with zero shards, add carefully, measure everything.</p><h3>Chapter 12 — HTTP/2: The Protocol That Fixed Everything at Once</h3><p>HTTP/2 didn’t change HTTP’s semantics. Same methods, same status codes, same URLs, same headers. It changed <em>how</em> HTTP is transmitted. And that change was enormous.</p><p><strong>Origin story</strong>: Google’s experimental SPDY protocol (2009) proved the concept with up to 55% page load improvement in lab conditions. After wide deployment and testing, the HTTP Working Group formalized SPDY into HTTP/2, published as RFC 7540 in May 2015.</p><p><strong>Binary framing</strong>: HTTP/1.x sends plain text. HTTP/2 encodes everything as binary frames. Every frame has a 9-byte header: type, flags, length, and stream ID. Human-readability is sacrificed; parsing speed and compactness are gained.</p><p><strong>Multiplexing</strong>: the single biggest feature. Multiple requests and responses are interleaved as frames on a <em>single</em> TCP connection. The browser dispatches all 90 requests the moment it discovers them. Frames from different streams are labeled with stream IDs and reassembled at the other end. No queuing. No head-of-line blocking at the HTTP layer. This single feature makes every HTTP/1.x workaround unnecessary:</p><ul><li>Domain sharding → gone (actually harmful now — defeats connection coalescing)</li><li>Concatenation → gone (granular resources with individual cache TTLs are better)</li><li>Image sprites → gone</li><li>Resource inlining → gone (replaced by Server Push, which is cacheable)</li></ul><p><strong>Stream prioritization</strong>: the browser sends an explicit priority tree to the server — weights (1–256) and dependency relationships between streams. The server allocates bandwidth accordingly: render-blocking CSS first, low-priority analytics last. Priorities are dynamic and can be updated in real time as the user scrolls or interacts.</p><p><strong>Server Push</strong>: instead of the browser discovering a resource by parsing HTML, the server can proactively push it before being asked. When serving index.html, the server simultaneously pushes style.css and app.js. The browser receives them before it even knew it needed them. Unlike inlining, pushed resources are independently cacheable — if the browser already has a cached copy, it sends RST_STREAM to cancel the push.</p><p><strong>HPACK header compression</strong>: a shared table of previously-seen headers means user-agent: Mozilla/5.0... becomes a single index number after the first request. Combined with Huffman encoding for common values, header data shrinks by 85–88%. Hundreds of bytes of repeated headers per request become tens of bytes.</p><p><strong>Negotiation via ALPN</strong>: HTTP/2 is negotiated during the TLS handshake using the Application-Layer Protocol Negotiation extension. No extra round trips. This is why Chrome and Firefox only support HTTP/2 over TLS in practice — they get ALPN for free.</p><p>One honest caveat: HTTP/2 eliminates HTTP-level head-of-line blocking but TCP-level head-of-line blocking remains. A lost packet stalls all streams on the connection. With HTTP/1.x and 6 connections, a loss only affects one connection. This is ultimately why HTTP/3 moved to QUIC (UDP-based), but that’s a future chapter.</p><h3>Chapter 13 — Optimizing Application Delivery: The New Playbook</h3><p>The optimization strategy flips on HTTP/2. What was required on HTTP/1.x is harmful on HTTP/2.</p><p><strong>The eternal principles (never expire)</strong>:</p><ul><li>Eliminate unnecessary latency</li><li>Minimize transferred bytes</li><li>Get servers close to users (CDN)</li><li>Respect wireless network constraints</li><li>Kill redirects</li><li>Cache aggressively with proper validation</li><li>Compress everything</li><li>Trim cookies on static origins</li></ul><p><strong>HTTP/1.x specific (apply, but know they’re workarounds)</strong>:</p><ul><li>Domain shard (carefully, with measurement)</li><li>Concatenate JS/CSS bundles</li><li>Sprite images</li><li>Inline small resources</li></ul><p><strong>HTTP/2 specific (undo the HTTP/1.x hacks)</strong>:</p><ul><li>One origin. Undo sharding — it defeats connection coalescing and HPACK compression state.</li><li>Granular resources with individual cache TTLs instead of monolithic bundles</li><li>Server Push over inlining</li><li>Verify your server actually respects stream priorities — many early implementations ignored them</li><li>Connection coalescing: if multiple origins share a wildcard TLS cert AND resolve to the same IP, HTTP/2 clients will share one connection. HTTP/1.x clients still get their sharded connections. Both work without changing markup.</li></ul><p>The mental model shift: HTTP/1.x optimization was fighting the protocol. HTTP/2 optimization is getting out of the way and letting the protocol do its job.</p><h3>Part IV: Browser APIs</h3><h3>Chapter 14 — Primer on Browser Networking: The Hidden Network Engine</h3><p>The browser isn’t just a rendering engine. It’s a full networking platform with its own connection pool manager, caching layer, security sandbox, and protocol negotiator.</p><p><strong>Socket pools</strong> are organized by origin (protocol + host + port), each capped at 6 sockets on HTTP/1.x. Requests queue and are assigned to available sockets. Sockets return to the pool after each response. This gives you keepalive for free.</p><p><strong>Security sandboxing</strong>: JavaScript never touches raw sockets. The browser enforces connection limits, same-origin policy, TLS certificate verification, and request formatting on your behalf.</p><p><strong>Speculative optimizations</strong>: browsers pre-resolve DNS for hostnames in the document, pre-connect to likely destinations, pre-fetch anticipated resources, and pre-render likely next pages. You can assist with hints:</p><pre>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;//cdn.example.com&quot;&gt;<br>&lt;link rel=&quot;preconnect&quot; href=&quot;//api.example.com&quot;&gt;<br>&lt;link rel=&quot;prefetch&quot; href=&quot;/next-page.html&quot;&gt;<br>&lt;link rel=&quot;prerender&quot; href=&quot;//example.com/next&quot;&gt;</pre><p><strong>The four networking APIs</strong>:</p><p>API Direction Format Best For XHR / Fetch Request-response Text + Binary HTTP calls, uploads SSE Server → Client Text Live feeds, notifications WebSocket Bidirectional Text + Binary Chat, gaming, collaboration WebRTC Peer-to-peer Audio/Video/Data Video calls, file sharing</p><h3>Chapter 15 — XMLHttpRequest: The Old Workhorse</h3><p>XHR was born in 1999 inside Internet Explorer 5, created by the Outlook Web Access team. It enabled JavaScript to make background HTTP requests — transforming static documents into interactive applications. It’s the technology that made Google Maps, Gmail, and AJAX possible.</p><p><strong>What XHR does well</strong>:</p><ul><li>Full HTTP request/response cycle with browser services (caching, auth, compression, redirects)</li><li>Supports all data types: text, JSON, blobs, typed arrays</li><li>Upload progress events (loadstart, progress, load, error, abort)</li><li>Chunked file uploads (slice a 500MB file into 1MB chunks, retry individual chunks on failure)</li><li>CORS for cross-origin requests</li></ul><p><strong>The polling problem</strong>: HTTP is request-response. The server can’t push to you. To build real-time updates with XHR, you have two options:</p><ul><li><em>Polling</em>: check every N seconds. Simple but generates enormous wasted traffic — 10,000 clients polling every 60 seconds with ~850 bytes of headers = 1.13 Mbps of requests returning empty responses.</li><li><em>Long polling</em>: hold the connection open server-side until data is available. Much more efficient. Still creates one HTTP request per message. Facebook Chat was built on this in 2008.</li></ul><p><strong>Where XHR falls short</strong>: no clean streaming API. Responses are buffered. No way to process data incrementally without browser-inconsistent hacks. For streaming, SSE is cleaner. For bidirectional real-time, use WebSocket.</p><h3>Chapter 16 — Server-Sent Events: The Underrated API</h3><p>SSE is one of the most underused APIs in the browser. It does exactly one thing, perfectly: <strong>the server pushes text events to the client over a persistent HTTP connection</strong>.</p><pre>var source = new EventSource(&quot;/stream&quot;);<br>source.onmessage = function(event) { console.log(event.data); };<br>source.addEventListener(&quot;update&quot;, function(event) { handleUpdate(event.data); });</pre><p>That’s the entire client implementation. The browser handles:</p><ul><li>Connection establishment</li><li>Message parsing and boundary detection</li><li><strong>Automatic reconnection on drop</strong></li><li><strong>Last-Event-ID tracking</strong> — on reconnect, sends the last received event ID so the server can resume</li></ul><p><strong>The wire protocol</strong>: regular HTTP with Content-Type: text/event-stream. The server keeps the response open and writes:</p><pre>data: Simple message</pre><pre>event: update<br>id: 42<br>data: {&quot;type&quot;: &quot;stock&quot;, &quot;price&quot;: 182.50}</pre><pre>retry: 15000</pre><p>Blank line = end of message. Human-readable. Trivial to generate on any backend.</p><p><strong>Why SSE beats long polling</strong>: one persistent connection vs. a new HTTP request per message. Per-message overhead drops from 500–800 bytes (HTTP headers) to as little as 5 bytes. Already-warm connection means no queuing latency.</p><p><strong>The limits</strong>: server-to-client only, text only. Need binary? Use WebSocket. Need the client to send data on the same connection? Use WebSocket.</p><p><strong>Hidden gotcha</strong>: transparent HTTP proxies may buffer streaming responses. Move SSE to TLS — encrypted traffic passes through proxies without buffering.</p><h3>Chapter 17 — WebSocket: The Phone Call</h3><p>WebSocket is a full-duplex, persistent connection between browser and server. Both sides can send at any time, in both directions, simultaneously.</p><p><strong>The handshake starts as HTTP</strong>:</p><pre>GET /socket HTTP/1.1<br>Connection: Upgrade<br>Upgrade: websocket<br>Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==</pre><p>Server responds 101 Switching Protocols. HTTP is done. The connection is now a binary framing channel.</p><p><strong>Per-message overhead</strong>: 2–14 bytes per frame, vs. 500–800 bytes per HTTP request. Transformative for high-frequency, small-message applications.</p><p><strong>Supports both text and binary natively</strong>: strings (UTF-8), ArrayBuffers, Blobs — no base64 encoding needed.</p><p><strong>What WebSocket doesn’t give you for free</strong>:</p><ul><li><em>No browser caching</em>: WebSocket data is opaque to the browser cache. Every byte comes from your server.</li><li><em>No compression</em>: HTTP has built-in gzip negotiation. WebSocket has none by default — implement it yourself.</li><li><em>No stream multiplexing</em>: unlike HTTP/2, frames can’t be interleaved from different logical streams. A large message blocks everything behind it.</li><li><em>Infrastructure headaches</em>: long-lived connections conflict with aggressive load-balancer timeouts (Nginx defaults to 60s). Every proxy and LB in the serving path needs to be configured for WebSocket.</li></ul><p><strong>Always use WSS</strong> (WebSocket over TLS). Transparent proxies on mobile networks may mangle unencrypted WS traffic. TLS creates an end-to-end encrypted tunnel that passes through untouched.</p><p><strong>The decision tree</strong>:</p><ul><li>Fetching or uploading a resource? <strong>XHR/Fetch</strong></li><li>Server needs to push text updates? <strong>SSE</strong></li><li>Bidirectional, low-latency, text or binary? <strong>WebSocket</strong></li></ul><h3>Chapter 18 — WebRTC: Browsers Talking Directly to Each Other</h3><p>WebRTC is the most ambitious browser API ever shipped. It enables peer-to-peer audio, video, and data transfer — directly between browsers, without routing through a server.</p><p><strong>Three JavaScript APIs</strong>:</p><ul><li>getUserMedia — camera and microphone access</li><li>RTCPeerConnection — manages the peer-to-peer connection lifecycle</li><li>RTCDataChannel — bidirectional data transfer between peers</li></ul><p><strong>Runs on UDP, not TCP</strong>: for real-time media, a late packet is worse than a lost one. UDP lets WebRTC skip the packet it loses and continue. The browser layers security and some reliability on top:</p><ul><li><strong>ICE</strong> — discovers how to reach the other peer through NATs</li><li><strong>STUN</strong> — “what’s my public IP?” service for NAT traversal</li><li><strong>TURN</strong> — relay server of last resort when direct connection fails (~8% of cases)</li><li><strong>DTLS</strong> — TLS adapted for UDP, encrypts everything</li><li><strong>SRTP/SRTCP</strong> — encrypted, real-time media delivery with adaptive bitrate</li><li><strong>SCTP</strong> — DataChannel transport with configurable reliability and ordering</li></ul><p><strong>The dirty secret: it still needs a server to start</strong>. Browsers behind NATs can’t find each other directly. A <em>signaling server</em> (WebSocket or SSE, your choice) exchanges SDP offers and ICE candidates between peers before the peer-to-peer connection is established. WebRTC doesn’t specify the signaling protocol — that’s your problem.</p><p><strong>The connection flow</strong>:</p><ol><li>Amy creates an SDP offer describing her streams</li><li>Amy sends it to Bob via your signaling server</li><li>Bob creates an SDP answer, sends it back via signaling</li><li>ICE agents on both sides gather address candidates (local, STUN, TURN)</li><li>Connectivity checks run. Best path wins.</li><li>DTLS handshake encrypts the connection</li><li>Media flows via SRTP. Data flows via SCTP.</li></ol><p><strong>DataChannel</strong>: peer-to-peer data with configurable semantics. ordered: false, maxRetransmits: 0 gives UDP-like fire-and-forget. Perfect for game state where old data is useless. Increase reliability for file transfer.</p><p><strong>Infrastructure you still need</strong>: a signaling server, a STUN server, and a TURN relay. For more than 3–4 participants, you need an SFU (Selective Forwarding Unit) — a server that receives all streams and routes the right ones to the right peers.</p><p><strong>Be honest about whether you need it</strong>: WebRTC’s setup complexity is significant. For chat without video, SSE + XHR is simpler. For bidirectional data without peer-to-peer requirement, WebSocket is simpler. Reach for WebRTC when peer-to-peer genuinely matters — video calls, large file transfers, low-latency multiplayer.</p><h3>The Master Cheat Sheet</h3><h3>What Actually Makes Web Pages Slow</h3><ol><li><strong>Latency, not bandwidth</strong>. Every 20ms RTT improvement = linear PLT gain. Beyond 5 Mbps bandwidth, more bandwidth barely helps.</li><li><strong>Round trips</strong>: each one costs RTT. DNS lookup + TCP handshake + TLS + HTTP request = 3–4 RTTs before first byte.</li><li><strong>Head-of-line blocking</strong>: HTTP/1.x can only serve one request per connection at a time.</li><li><strong>TCP slow start</strong>: new connections ramp up slowly. Short resources never reach full throughput.</li><li><strong>Repeated uncompressed headers</strong>: hundreds of bytes, every request, in HTTP/1.x.</li></ol><h3>The Optimization Hierarchy</h3><p><strong>Always (protocol-agnostic)</strong>:</p><ul><li>Use a CDN. Get servers close to users.</li><li>Cache aggressively. Cache-Control + ETag.</li><li>Compress everything. gzip text, optimize images.</li><li>Kill redirects.</li><li>Reuse connections. Keepalive.</li><li>Trim cookies on static origins.</li><li>Measure with RUM (Navigation Timing API). Use p95, never averages.</li></ul><p><strong>HTTP/1.x specific (workarounds)</strong>:</p><ul><li>6 parallel connections per host</li><li>Domain sharding (carefully — 2–3 shards max, always measure)</li><li>Bundle CSS/JS (fewer requests)</li><li>Sprite images</li><li>Inline critical CSS, small images</li></ul><p><strong>HTTP/2 specific (undo the hacks)</strong>:</p><ul><li>One connection per origin</li><li>Undo domain sharding</li><li>Granular, individually-cached resources</li><li>Server Push over inlining</li><li>Verify priority support in your server</li></ul><h3>Which API to Use</h3><p>Use case API Fetch data, upload files XHR or Fetch Server pushes live text (notifications, feeds, scores) Server-Sent Events Bidirectional real-time (chat, gaming, collaboration) WebSocket Peer-to-peer video/audio/data WebRTC All of the above with offline support Service Worker + any of the above</p><h3>The Hierarchy of What to Fix First</h3><ol><li><strong>Reduce latency</strong>: CDN, server location, fewer round trips</li><li><strong>Reduce connections</strong>: HTTP/2, keepalive, consolidate origins</li><li><strong>Reduce size</strong>: compress, optimize images, eliminate unused code</li><li><strong>Parallelize</strong>: multiplex with HTTP/2, priority hints, preload</li><li><strong>Push proactively</strong>: Server Push, prefetch, prerender hints</li><li><strong>Measure</strong>: synthetic + RUM, waterfall analysis, p95/p99</li></ol><h3>The One Paragraph Summary</h3><p>The web is slow because of round trips, not bytes. DNS lookups, TCP handshakes, TLS negotiations, and HTTP requests each cost at least one RTT, and those costs stack. HTTP/1.x forced developers to build elaborate workarounds — domain sharding, bundling, inlining — to squeeze more parallelism out of a protocol never designed for it. HTTP/2 fixed the protocol: binary framing, multiplexing, header compression, and Server Push eliminate the need for every one of those hacks. Above the protocol, the browser exposes four APIs — XHR for request-response, SSE for server-push, WebSocket for bidirectional streaming, WebRTC for peer-to-peer — each optimized for a different communication pattern. The skill is knowing which layer your bottleneck is at and choosing the right tool for the job. Measure first. Optimize the right thing.</p><p><em>This post summarizes High Performance Browser Networking by Ilya Grigorik (O’Reilly). If you’ve found this series useful, the full book is available free at hpbn.co — it goes deeper on every topic covered here.</em></p><p><em>Follow for more engineering deep-dives as I work through more foundational CS/networking books.</em></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55ca7dad75c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-complete-networking-cheat-sheet-everything-you-need-to-know-about-how-browsers-talk-to-servers-e55ca7dad75c">The Complete Networking Cheat Sheet: Everything You Need to Know About How Browsers Talk to Servers</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[Master Back-of-the-Envelope Calculations for System Design Interviews (With a Real Instagram…]]></title>
            <link>https://javascript.plainenglish.io/master-back-of-the-envelope-calculations-for-system-design-interviews-with-a-real-instagram-706d242a7df8?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/706d242a7df8</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[instagram-system-design]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 14:28:16 GMT</pubDate>
            <atom:updated>2026-06-23T14:28:16.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Master Back-of-the-Envelope Calculations for System Design Interviews (With a Real Instagram Example)</h3><p><em>The skill that separates average System Design candidates from senior engineers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*rZ-3jtSUR79-WgJo" /></figure><p>Imagine you’re sitting in a System Design interview at a top tech company.</p><p>The interviewer says:</p><blockquote><em>“Design Instagram.</em></blockquote><p>Many engineers immediately start drawing databases, microservices, message queues, and caching layers.</p><p>That’s a mistake.</p><p>Before choosing technologies, you need to understand one thing:</p><p><strong>How big is the problem?</strong></p><p>A system serving 10,000 users looks completely different from a system serving 200 million daily active users.</p><p>This is why experienced engineers always begin with <strong>Back-of-the-Envelope (BotE) calculations</strong>.</p><p>These quick estimations help you understand traffic, storage, bandwidth, and scaling requirements before making any architectural decisions.</p><p>In this article, we’ll walk through a complete example using an Instagram-like photo-sharing application and learn how these numbers influence the final design.</p><h3>What Are Back-of-the-Envelope Calculations?</h3><p>Back-of-the-Envelope calculations are rough estimations used to determine the scale of a system.</p><p>The goal is not perfect accuracy.</p><p>The goal is to quickly answer questions like:</p><ul><li>How many requests will the system receive?</li><li>How much storage will we need?</li><li>What bandwidth requirements should we expect?</li><li>Can a single database handle the load?</li><li>Do we need sharding or caching?</li></ul><p>Interviewers are not checking whether your math is perfect.</p><p>They’re checking whether you can think like a systems engineer.</p><h3>Three Shortcuts Every Engineer Should Remember</h3><h3>1. The 100,000 Seconds Rule</h3><p>A day contains:</p><pre>86,400 seconds</pre><p>For quick calculations, round it to:</p><pre>100,000 seconds (10⁵)</pre><p>This makes QPS calculations incredibly fast.</p><h3>Formula</h3><pre>QPS = Daily Requests ÷ 100,000</pre><pre>Example:</pre><pre>1 Billion requests/day</pre><pre>1,000,000,000 ÷ 100,000</pre><pre>= 10,000 QPS</pre><h3>2. Use Powers of 10 for Storage</h3><p>Instead of using 1024-based conversions, use simple decimal units.</p><p>UnitValueKB1⁰³ BytesMB1⁰⁶ BytesGB1⁰⁹ BytesTB1⁰¹² BytesPB1⁰¹⁵ Bytes</p><p>This keeps calculations quick during interviews.</p><h3>3. Always Estimate Peak Traffic</h3><p>Traffic is never evenly distributed.</p><p>People use applications at different times of the day, and traffic spikes during major events.</p><p>A common interview assumption is:</p><pre>Peak Traffic ≈ 2 × Average Traffic</pre><p>This simple rule helps avoid underestimating infrastructure requirements.</p><h3>Example: Designing an Instagram-Like Application</h3><p>Let’s estimate the scale of a global photo-sharing platform.</p><h3>Assumptions</h3><p>We’ll start by defining a few assumptions.</p><h3>User Activity</h3><ul><li>Daily Active Users (DAU): 200 Million</li><li>Photos Viewed per User per Day: 50</li><li>Photos Uploaded per User per Day: 2</li></ul><h3>Data Size</h3><ul><li>Average Photo Size: 2 MB</li><li>Metadata per Photo: 2 KB</li></ul><p>Always state your assumptions clearly during interviews.</p><p>Interviewers care more about reasonable assumptions than exact numbers.</p><h3>Step 1: Calculate Write Traffic</h3><p>Each user uploads:</p><pre>2 photos/day</pre><p>Total uploads per day:</p><pre>200M × 2</pre><pre>= 400 Million uploads/day</pre><p>Average write QPS:</p><pre>400M ÷ 100,000</pre><pre>= 4,000 requests/sec</pre><p>Peak write traffic:</p><pre>4,000 × 2</pre><pre>= 8,000 requests/sec</pre><h3>Result</h3><ul><li>Average Write QPS = 4K</li><li>Peak Write QPS = 8K</li></ul><h3>Step 2: Calculate Read Traffic</h3><p>Each user views:</p><pre>50 photos/day</pre><p>Total views per day:</p><pre>200M × 50</pre><pre>= 10 Billion views/day</pre><p>Average read QPS:</p><pre>10B ÷ 100,000</pre><pre>= 100,000 requests/sec</pre><p>Peak read QPS:</p><pre>100,000 × 2</pre><pre>= 200,000 requests/sec</pre><h3>Result</h3><ul><li>Average Read QPS = 100K</li><li>Peak Read QPS = 200K</li></ul><h3>A Critical Observation</h3><p>Look at the ratio:</p><pre>Reads = 100K QPS</pre><pre>Writes = 4K QPS</pre><p>The system is heavily read-dominant.</p><p>This immediately suggests:</p><ul><li>Aggressive caching</li><li>Content Delivery Networks (CDNs)</li><li>Read-optimized storage</li></ul><p>Without doing any architecture discussion, we’ve already identified major design requirements.</p><h3>Step 3: Calculate Storage Requirements</h3><h3>Photo Storage</h3><p>Daily uploads:</p><pre>400 Million photos/day</pre><p>Average size:</p><pre>2 MB/photo</pre><p>Daily storage:</p><pre>400M × 2 MB</pre><pre>= 800 Million MB/day</pre><pre>= 800 TB/day</pre><h3>Metadata Storage</h3><p>Metadata size:</p><pre>2 KB/photo</pre><p>Daily metadata growth:</p><pre>400M × 2 KB</pre><pre>= 800 Million KB/day</pre><pre>≈ 800 GB/day</pre><h3>Step 4: Estimate Three-Year Storage Growth</h3><p>Media storage:</p><pre>800 TB/day</pre><p>Over three years:</p><pre>800 × 365 × 3</pre><pre>≈ 876,000 TB</pre><pre>= 876 PB</pre><p>That’s nearly an exabyte of media data.</p><h3>Don’t Forget Replication</h3><p>Production systems replicate data for durability and availability.</p><p>Assume:</p><pre>Replication Factor = 3</pre><p>Total storage:</p><pre>876 PB × 3</pre><pre>≈ 2.6 EB</pre><h3>Final Storage Requirement</h3><pre>≈ 2.6 Exabytes</pre><p>At this scale, traditional storage solutions are no longer practical.</p><h3>Step 5: Estimate Network Bandwidth</h3><p>Bandwidth calculations reveal another important bottleneck.</p><h3>Upload Bandwidth (Ingress)</h3><p>Average write traffic:</p><pre>4,000 uploads/sec</pre><p>Photo size:</p><pre>2 MB</pre><p>Bandwidth:</p><pre>4,000 × 2 MB</pre><pre>= 8,000 MB/sec</pre><pre>= 8 GB/sec</pre><h3>Download Bandwidth (Egress)</h3><p>Average read traffic:</p><pre>100,000 requests/sec</pre><p>Photo size:</p><pre>2 MB</pre><p>Bandwidth:</p><pre>100,000 × 2 MB</pre><pre>= 200,000 MB/sec</pre><pre>= 200 GB/sec</pre><p>Converting to bits:</p><pre>200 × 8</pre><pre>= 1.6 Tbps</pre><h3>How These Numbers Drive Architecture Decisions</h3><p>Now comes the important part.</p><p>Numbers should influence design choices.</p><h3>1. Massive Read Traffic → CDN</h3><p>We discovered:</p><pre>Peak Read QPS = 200K</pre><p>and</p><pre>Egress = 1.6 Tbps</pre><p>Serving all this traffic directly from your primary data center would be extremely expensive and inefficient.</p><h3>Solution</h3><p>Use a globally distributed CDN.</p><p>Benefits:</p><ul><li>Reduced latency</li><li>Lower bandwidth costs</li><li>Improved availability</li><li>Better user experience</li></ul><p>Popular images can be cached close to users worldwide.</p><h3>2. Exabyte-Scale Media → Object Storage</h3><p>We estimated:</p><pre>2.6 EB of replicated storage</pre><p>No relational database should store image binaries.</p><h3>Solution</h3><p>Store photos in object storage systems such as:</p><ul><li>Amazon S3</li><li>Google Cloud Storage</li><li>Azure Blob Storage</li></ul><p>Object storage is designed to scale efficiently to petabytes and beyond.</p><h3>3. Billions of Metadata Records → Sharding</h3><p>Daily metadata growth:</p><pre>400 Million records/day</pre><pre>years, this becomes hundreds of billions of rows.</pre><p>A single database instance will eventually become a bottleneck.</p><h3>Solution</h3><p>Use:</p><ul><li>Database sharding</li><li>Cassandra</li><li>DynamoDB</li><li>Partitioned PostgreSQL/MySQL clusters</li></ul><p>Sharding by User ID is often a practical strategy.</p><h3>A Simple Framework for Every System Design Interview</h3><p>Whenever you’re asked to design a large-scale system, calculate these six things first:</p><h3>1. Daily Active Users</h3><p>How many users are interacting with the system?</p><h3>2. Read QPS</h3><p>How many read requests occur every second?</p><h3>3. Write QPS</h3><p>How many write requests occur every second?</p><h3>4. Storage Growth</h3><p>How much data is generated daily, monthly, and yearly?</p><h3>5. Peak Traffic</h3><p>How much higher is peak traffic than average traffic?</p><h3>6. Bandwidth</h3><p>How much network throughput is required?</p><p>These six numbers often reveal 80% of your architectural decisions.</p><h3>Final Thoughts</h3><p>Back-of-the-envelope calculations are not just an interview trick.</p><p>They are how experienced engineers think about systems.</p><p>Before discussing microservices, Kafka, Redis, Cassandra, or Kubernetes, first answer a simpler question:</p><blockquote><em>How big is the system?</em></blockquote><p>Once you understand the scale, the architecture starts designing itself.</p><p>The next time you’re asked to design Instagram, YouTube, WhatsApp, Uber, or Dropbox, resist the urge to jump directly into technology choices.</p><p>Start with the numbers.</p><p>Because in System Design, <strong>good architecture is usually just good math applied early.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=706d242a7df8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/master-back-of-the-envelope-calculations-for-system-design-interviews-with-a-real-instagram-706d242a7df8">Master Back-of-the-Envelope Calculations for System Design Interviews (With a Real Instagram…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[How to Build a Real-Time Stock Price Pipeline: WebSocket + Redis Pub/Sub in Node.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-build-a-real-time-stock-price-pipeline-websocket-redis-pub-sub-in-node-js-03043f535820?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/03043f535820</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 11:22:32 GMT</pubDate>
            <atom:updated>2026-06-04T11:22:32.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pushing live market data to 100 browsers simultaneously — without making 1,000 API calls per second or writing a single polling loop on the client.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5maBIgwSkrap6Nylt31P2g.jpeg" /></figure><blockquote><strong><em>TL;DR:</em></strong><em> Server polls Yahoo Finance once every 10 seconds using parallel requests. Engine publishes price ticks to Redis pub/sub. A dedicated WebSocket service relays ticks to browsers. Frontend maintains one persistent connection per tab. Result: ~300–600ms latency, zero client-side rate limiting, load that doesn’t grow with user count</em></blockquote><p>When I built <strong>NexTrade</strong> — a paper trading platform for India’s Nifty 50 — I needed live stock prices in every browser tab, updating in near real-time, without hammering Yahoo Finance’s API into a rate-limit wall.</p><p>Below are the previous blogs of this series of building <strong>NexTrade</strong> in public.<br>1. <a href="https://medium.com/javascript-in-plain-english/why-i-added-kafka-to-my-trading-platform-even-though-redis-was-already-doing-the-job-c28ed49ba5ca"><em>https://medium.com/@niceperson2110/building-nextrade-a-high-concurrency-nifty-50-paper-trading-engine-with-microservices-70e404ee965a</em></a><br>2. <a href="https://medium.com/javascript-in-plain-english/why-i-added-kafka-to-my-trading-platform-even-though-redis-was-already-doing-the-job-c28ed49ba5ca"><em>https://medium.com/javascript-in-plain-english/why-i-added-kafka-to-my-trading-platform-even-though-redis-was-already-doing-the-job-c28ed49ba5ca</em></a></p><p>This is the architecture I ended up with, why each piece exists, and the duplication bug that would have sent every price update 10× if I hadn’t caught it.</p><h3>The Problem With the Obvious Approach</h3><p>The first idea most developers reach for: have each browser tab fetch prices directly.</p><pre>// Don&#39;t do this<br>setInterval(() =&gt; {<br>  const prices = await fetch(&#39;https://yahoo-finance.../RELIANCE.NS&#39;);<br>  updateChart(prices);<br>}, 5000);</pre><p>Simple. Works for one user. Fails immediately at scale.</p><p><strong>The math:</strong> 50 stocks × 100 users × a request every 5 seconds = <strong>1,000 outbound HTTP requests per second</strong> from browser tabs. Yahoo Finance will rate-limit or silently drop you well before that. You’d also be leaking your users’ IP addresses to a third-party API — every tab, every poll, every second.</p><p>The core problem is architectural: <strong>you’re distributing the polling responsibility to clients who can’t coordinate with each other.</strong> Each tab doesn’t know the other 99 tabs are polling the same data.</p><p>The right solution: poll once at the server. Distribute to everyone.</p><h3>Architecture Overview</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                       NexTrade Pipeline                          │<br>│                                                                  │<br>│                       Yahoo Finance API                          │<br>│                              │ (1 batched request / 10s)         │<br>│                              ▼                                   │<br>│   ┌──────────┐  PUBLISH stock:*.NS  ┌─────────────────────┐     │<br>│   │  Engine  │ ────────────────────▶│       Redis         │     │<br>│   │ Service  │                      │  (pub/sub broker)   │     │<br>│   └──────────┘                      └──────────┬──────────┘     │<br>│                                                │ SUBSCRIBE       │<br>│                                                ▼                 │<br>│                                     ┌─────────────────────┐     │<br>│                                     │  WebSocket Server   │     │<br>│                                     │   (relay only)      │     │<br>│                                     └──────────┬──────────┘     │<br>│                                                │ ws://           │<br>│                              ┌─────────────────┼─────────────┐   │<br>│                              ▼                 ▼             ▼   │<br>│                          Browser           Browser       Browser │<br>└─────────────────────────────────────────────────────────────────┘</pre><p>Four distinct layers: <strong>poller → broker → relay → client.</strong> Each layer has exactly one responsibility.</p><h3>Step 1: Parallel Server-Side Polling</h3><p>The Engine service is responsible for market data. It runs a single setInterval that fires every 10 seconds:</p><pre>// backend/engine/src/marketPoller.ts<br>const SYMBOLS = [<br>  &#39;RELIANCE.NS&#39;, &#39;TCS.NS&#39;, &#39;INFY.NS&#39;, &#39;HDFCBANK.NS&#39;,<br>  // … 46 more Nifty 50 symbols<br>];<br><br>async function pollAllSymbols(): Promise&lt;Record&lt;string, Quote&gt;&gt; {<br>  // Yahoo Finance supports batched multi-symbol queries<br>  const results = await Promise.all(<br>    SYMBOLS.map(symbol =&gt; yahooFinance.quote(symbol))<br>  );<br>  return Object.fromEntries(<br>    results.map((quote, i) =&gt; [SYMBOLS[i], quote])<br>  );<br>}<br>setInterval(async () =&gt; {<br>  const quotes = await pollAllSymbols();<br>  await publishToRedis(quotes);<br>}, 10_000);</pre><p><strong>Why </strong><strong>Promise.all matters here:</strong></p><p>Before parallelising, I had 50 sequential API calls. Each call takes roughly 80–120ms over the network. Sequential execution: <strong>50 × 100ms = 5 seconds of network IO per cycle.</strong> By the time you finish fetching the 50th stock, the first one’s data is already 5 seconds old — half your polling interval gone just on fetching.</p><p>Promise.all runs all 50 requests concurrently. Total time: ~300ms — the time of the single slowest request, not the sum of all of them.</p><p>The batched Yahoo Finance API (quote with multiple symbols) cuts this further — you can fetch all 50 in a single HTTP request rather than 50 separate ones.</p><h3>Step 2: Redis Pub/Sub Fan-Out</h3><p>After each poll, the Engine publishes each stock’s data to its own Redis channel:</p><pre>async function publishToRedis(quotes: Record&lt;string, Quote&gt;): Promise&lt;void&gt; {<br>  const pipeline = redisClient.pipeline();<br><br>for (const [symbol, quote] of Object.entries(quotes)) {<br>    const payload = JSON.stringify({<br>      symbol,<br>      price:         quote.regularMarketPrice,<br>      change:        quote.regularMarketChange,<br>      changePercent: quote.regularMarketChangePercent,<br>      dayHigh:       quote.regularMarketDayHigh,<br>      dayLow:        quote.regularMarketDayLow,<br>      volume:        quote.regularMarketVolume,<br>      timestamp:     Date.now(),<br>    });<br>    pipeline.publish(`stock:${symbol}`, payload);<br>  }<br>  await pipeline.exec();<br>}</pre><p>Using a Redis pipeline batches all 50 PUBLISH commands into a single network round-trip to Redis.</p><p><strong>Why Redis pub/sub for this layer?</strong></p><p>Price ticks are ephemeral. If a subscriber misses one tick, the next one arrives in 10 seconds with fresh data. There’s no business-critical state here — no money moves, no order fills. Redis pub/sub’s fire-and-forget semantics are exactly right: low latency, zero overhead, no durability required.</p><blockquote><em>For order fill events — where losing a message means a user’s balance never updates — I use Kafka instead. The data type determines the tool. (More on that in a follow-up post.</em></blockquote><p>Each stock gets its own channel: stock:RELIANCE.NS, stock:TCS.NS, etc. This means the WebSocket server can subscribe to only the channels that active browser tabs are watching, rather than receiving the entire 50-symbol flood and filtering client-side.</p><h3>Step 3: WebSocket Server as a Stateless Relay</h3><p>The WebSocket server is deliberately minimal. It has no database connection, no business logic, no authentication beyond a basic token check. Its only job is:</p><ol><li>Accept browser connections</li><li>Track which ticker(s) each connection is watching</li><li>Subscribe to the corresponding Redis channel</li><li>Forward every Redis message to the watching browsers</li></ol><p>typescript</p><pre>// backend/websocket/src/server.ts<br>wss.on(&#39;connection&#39;, (ws: WebSocket) =&gt; {<br>  const clientId = generateId();<br>  subscriptions.set(clientId, new Set());<br><br>ws.on(&#39;message&#39;, (raw) =&gt; {<br>    const msg = JSON.parse(raw.toString());<br>    if (msg.action === &#39;SUBSCRIBE&#39;) {<br>      const ticker = msg.ticker; // e.g. &quot;RELIANCE.NS&quot;<br>      // Track this client → ticker mapping<br>      subscriptions.get(clientId)!.add(ticker);<br>      // Subscribe to Redis only if nobody else is already watching<br>      if (!anyClientWatching(ticker)) {<br>        redisSubscriber.subscribe(`stock:${ticker}`, (message) =&gt; {<br>          broadcastToWatchers(ticker, message);<br>        });<br>      }<br>    }<br>    if (msg.action === &#39;UNSUBSCRIBE&#39;) {<br>      const ticker = msg.ticker;<br>      subscriptions.get(clientId)!.delete(ticker);<br>      // Clean up Redis subscription if last watcher disconnected<br>      if (!anyClientWatching(ticker)) {<br>        redisSubscriber.unsubscribe(`stock:${ticker}`);<br>      }<br>    }<br>  });<br>  ws.on(&#39;close&#39;, () =&gt; {<br>    // Clean up all subscriptions for this client<br>    const watched = subscriptions.get(clientId) ?? new Set();<br>    for (const ticker of watched) {<br>      subscriptions.get(clientId)!.delete(ticker);<br>      if (!anyClientWatching(ticker)) {<br>        redisSubscriber.unsubscribe(`stock:${ticker}`);<br>      }<br>    }<br>    subscriptions.delete(clientId);<br>  });<br>});</pre><p>The key property: <strong>the Redis subscription layer grows with the number of distinct tickers being watched, not the number of connected users.</strong> With 50 stocks and 1,000 users all watching the same Nifty 50 stocks, there are still only 50 Redis subscriptions.</p><h3>Step 4: The Frontend Hook</h3><p>On the React side, a custom useWebSocket hook manages one persistent connection per browser tab:</p><pre>// frontend/hooks/use-websockets.ts<br>export function useWebSocket(tickers: string[]) {<br>  const wsRef = useRef&lt;WebSocket | null&gt;(null);<br>  const tickData = useRef&lt;Record&lt;string, TickPayload&gt;&gt;({});<br>  const [, forceUpdate] = useReducer(x =&gt; x + 1, 0);<br><br>useEffect(() =&gt; {<br>    const ws = new WebSocket(process.env.NEXT_PUBLIC_WS_URL!);<br>    wsRef.current = ws;<br>    ws.onopen = () =&gt; {<br>      tickers.forEach(ticker =&gt; {<br>        ws.send(JSON.stringify({ action: &#39;SUBSCRIBE&#39;, ticker }));<br>      });<br>    };<br>    ws.onmessage = (event) =&gt; {<br>      const data: TickPayload = JSON.parse(event.data);<br>      tickData.current[data.symbol] = data;<br>      forceUpdate(); // trigger re-render with new tick<br>    };<br>    ws.onclose = () =&gt; {<br>      // Reconnect after 3s backoff<br>      setTimeout(() =&gt; wsRef.current = null, 3000);<br>    };<br>    return () =&gt; {<br>      tickers.forEach(ticker =&gt; {<br>        ws.send(JSON.stringify({ action: &#39;UNSUBSCRIBE&#39;, ticker }));<br>      });<br>      ws.close();<br>    };<br>  }, [tickers.join(&#39;,&#39;)]);<br>  return { tickData: tickData.current };<br>}</pre><p>The tick data lives in a useRef, not useState. This matters: React state triggers re-renders synchronously throughout the tree. For high-frequency data like price ticks, you want to batch updates. useRef + manual forceUpdate() gives you control over when re-renders fire.</p><p>The live price chart is a Recharts LineChart reading from a circular buffer of the last 120 ticks — roughly 10 minutes of price history at a 5-second tick rate.</p><h3>The Bug That Made Prices Move 10× Too Fast</h3><p>Show Image <em>Photo by </em><a href="https://unsplash.com/@markusspiske"><em>Markus Spiske</em></a><em> on Unsplash</em></p><p>Here’s the production bug I almost shipped.</p><p>The subscription tracking inside the WebSocket server had a subtle ordering problem:</p><pre>// ❌ The buggy version<br>function handleSubscribe(clientId: string, ticker: string) {<br>  subscriptions.get(clientId)!.add(ticker);   // ← adds client FIRST<br>  <br>  if (anyClientWatching(ticker)) {            // ← always true now (we just added ourselves)<br>    redisSubscriber.subscribe(`stock:${ticker}`, callback);<br>  }<br>}</pre><p>The condition anyClientWatching(ticker) checks whether any client is watching a given ticker. But I was calling it <em>after</em> adding the current client to the subscription map — so it was always true.</p><p><strong>The effect:</strong> Every time a new browser tab subscribed to RELIANCE, the WS server called redisSubscriber.subscribe(&#39;stock:RELIANCE.NS&#39;, …) again — creating a new, independent Redis listener. With 10 tabs open for the same stock, there were 10 Redis subscription handlers, each independently receiving the tick and forwarding it to the client.</p><p>Each price update was being sent <strong>10 times</strong> to every connected browser. The chart appeared to update 10× per tick. Numbers jumped faster than they should have. The 10-second polling interval effectively looked like 1 second.</p><p>The fix is one reordering:</p><pre>// ✅ The correct version<br>function handleSubscribe(clientId: string, ticker: string) {<br>  // Check BEFORE adding this client<br>  const alreadyWatched = anyClientWatching(ticker);<br>  subscriptions.get(clientId)!.add(ticker);   // ← add client SECOND<br>if (!alreadyWatched) {                       // ← now correctly false if first watcher<br>    redisSubscriber.subscribe(`stock:${ticker}`, callback);<br>  }<br>}</pre><p>Check first. Add second. The condition is now !alreadyWatched — subscribe to Redis only when we&#39;re the <em>first</em> client to watch a given ticker.</p><p><strong>The lesson:</strong> Any time you have a conditional that depends on a data structure you’re about to mutate, the order of operations matters. In this case: “is anyone watching?” needs to be answered before you change the answer.</p><h3>Performance Profile</h3><p>MetricValueYahoo Finance calls per second0.1 (one every 10s)Redis PUBLISH operations per poll50 (one per stock)Redis SUBSCRIBE operations (total)≤ 50 (one per watched ticker, deduplicated)End-to-end latency (Yahoo → Browser)300–600msServer load scaling factorO(tickers watched), not O(users)</p><p>The load profile is almost entirely determined by the number of distinct tickers being watched, not the number of connected users. 100 users all watching the same 50 stocks produce the same Redis load as 1 user watching 50 stocks.</p><h3>Key Takeaways</h3><p><strong>1. Never poll external APIs from the browser.</strong> Rate limits exist. Your users’ IP addresses shouldn’t be hitting a data provider’s servers. Move all external polling to the server.</p><p><strong>2. Match the tool to the data’s durability requirements.</strong> Price ticks are ephemeral — Redis pub/sub’s fire-and-forget is exactly right. If you miss one tick, the next one corrects it. For order fill events where loss is unacceptable, use Kafka.</p><p><strong>3. Deduplicate subscriptions at the broker layer, not the message layer.</strong> Don’t let multiple clients create multiple broker subscriptions for the same data. One subscription per distinct data stream, shared across all interested clients.</p><p><strong>4. The ordering of your mutation and your condition always matters.</strong> Read the state you’re about to change <em>before</em> you change it. This applies to subscription tracking, React state updates, database transactions — anywhere you have a check-then-modify pattern.</p><p><strong>5. Parallel requests at the ingestion layer are non-negotiable.</strong> Sequential fetching of independent data sources is usually a bug waiting to be reported as a feature. If the requests are independent, run them concurrently.</p><h3>What’s Next</h3><p>The current implementation has one known limitation: if the Engine service restarts, the in-memory order book loses all open orders. For the price pipeline specifically, this is fine — the Engine reconnects to Yahoo Finance and resumes publishing within seconds.</p><p>For production, I’d add:</p><ul><li><strong>Heartbeat messages</strong> from the WS server so clients can detect silent disconnections faster</li><li><strong>Reconnection with exponential backoff</strong> on the client</li><li><strong>Redis Streams</strong> instead of pub/sub if tick history (for chart replay) becomes a requirement</li></ul><p>But for a paper trading platform where 600ms latency and occasional reconnects are perfectly acceptable — this architecture is solid, and the operational complexity is manageable.</p><p><em>If you found this useful, the full NexTrade series covers Kafka vs Redis for order events, the AI coaching system, and the portfolio analytics math. Follow me here on Medium so you don’t miss the next post — and clap 👏 if this saved you from learning the 10× bug the hard way.</em></p><p><strong>Tags:</strong> nodejs · websocket · redis · system-design · real-time · typescript · backend · building-in-public</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03043f535820" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-build-a-real-time-stock-price-pipeline-websocket-redis-pub-sub-in-node-js-03043f535820">How to Build a Real-Time Stock Price Pipeline: WebSocket + Redis Pub/Sub in Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[Why I Added Kafka to My Trading Platform (Even Though Redis Was Already Doing the Job)]]></title>
            <link>https://javascript.plainenglish.io/why-i-added-kafka-to-my-trading-platform-even-though-redis-was-already-doing-the-job-c28ed49ba5ca?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/c28ed49ba5ca</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Sun, 17 May 2026 14:38:13 GMT</pubDate>
            <atom:updated>2026-05-17T14:38:13.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>A real-world look at when fire-and-forget messaging breaks your system — and why Redis Pub/Sub and Kafka aren’t the same tool wearing different clothes.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*7h2kaCdQF2ZHdjX0hrbBDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wj1HUursZl3yXSIr" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@nampoh"><em>Maxim Hopman</em></a><em> on Unsplash</em></p><h3>TL;DR</h3><p>I’m building <strong>NexTrade</strong>, a virtual stock trading platform, in public. In the last refactor, I added Apache Kafka alongside Redis — not to replace it, but because Redis Pub/Sub physically cannot deliver the guarantee that order fill events need. This post walks through the problem I ran into, why Kafka solved it, when Redis Pub/Sub is still the right call, and the one mental model I now use to pick between them.</p><p>If you’ve ever wondered <em>“Why would I run two message brokers when Redis already has Pub/Sub?”</em> — this one’s for you.</p><p>Before moving forward checkout this blog post on initial system design of the papertrading platform — <a href="https://medium.com/javascript-in-plain-english/building-nextrade-a-high-concurrency-nifty-50-paper-trading-engine-with-microservices-70e404ee965a">https://medium.com/javascript-in-plain-english/building-nextrade-a-high-concurrency-nifty-50-paper-trading-engine-with-microservices-70e404ee965a</a></p><h3>The setup: NexTrade</h3><p>NexTrade is a virtual trading platform. Users start with fake money, place buy and sell orders on real-world stocks, and watch their portfolio move with live prices. Think Robinhood, but the money isn’t real and the engine is mine.</p><p>Under the hood, the v1 stack was simple:</p><ul><li><strong>Node.js</strong> for the matching engine and API server</li><li><strong>PostgreSQL</strong> for the source of truth (users, orders, holdings, trades)</li><li><strong>Redis</strong> for caching and Pub/Sub messaging</li><li><strong>WebSockets</strong> for pushing live data to the browser</li></ul><p>It worked. Until I sat down to implement the order matching path properly and realized I was about to ship a quiet, expensive bug.</p><h3>The problem nobody talks about until it bites them</h3><p>Here’s the flow that broke my brain:</p><ol><li>A user places a buy order</li><li>The matching engine finds a sell order at the same price</li><li>The engine “fills” both orders and emits a fill event</li><li>The API server catches that event and updates the database — releases the locked balance, credits the holding, marks the order as filled</li></ol><p>Simple, right? I had Redis Pub/Sub already running. I’d just publish the fill event on a channel, the API would subscribe, and we’d call it a day.</p><p>Except Redis Pub/Sub has one property that turns this into a time bomb:</p><blockquote><strong><em>If the subscriber isn’t connected at the exact moment the message is published, the message is gone. Forever. No queue. No retry. No record it ever existed.</em></strong></blockquote><p>Read that again. Because in production, “the subscriber isn’t connected” happens all the time:</p><ul><li>During a deployment (the API server restarts)</li><li>During a brief network blip between services</li><li>When the consumer is busy processing a slow message and misses the next one</li><li>When you scale down or roll a container</li></ul><p>And here’s the kicker: <strong>the engine has no idea the message was lost</strong>. It publishes happily. Redis returns success. The fill event evaporates into the void.</p><p>Meanwhile, the engine’s internal state says the order is filled. The database still says it’s open. The user&#39;s money is locked. Their portfolio is wrong. The two systems have silently diverged — and nothing will reconcile them unless you build that reconciliation yourself (which, congratulations, is now a second project).</p><p>“It usually works” is a perfectly fine guarantee for many things in software. It is not a fine guarantee when the data is money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0fQhWwddPLuNPkhX" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@tvick"><em>Taylor Vick</em></a><em> on Unsplash</em></p><h3>What Redis Pub/Sub actually is (and isn’t)</h3><p>Here’s the part most tutorials skip past: Redis Pub/Sub is a <strong>broadcast primitive</strong>, not a message queue.</p><p>When you publish to a channel:</p><ul><li>Redis looks at who’s currently subscribed <em>right now</em></li><li>It pushes the message to each of them</li><li>Then it forgets the message existed</li></ul><p>That’s it. There’s no storage. There’s no acknowledgment. There’s no “I’ll hold this until someone picks it up.” It’s a megaphone in a public square — if you’re in the crowd, you hear it. If you stepped away for coffee, tough luck.</p><p>This is not a flaw in Redis. It’s the <em>design</em>. Pub/Sub is meant for ephemeral signals — “the user came online,” “this cache key was invalidated,” “here’s the latest price tick.” Things where if you miss it, another one is right behind it.</p><p>The flaw is using it for events where missing one means corrupted state.</p><h3>Enter Kafka</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U_gSGxj8llIby6nh" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@markusspiske"><em>Markus Spiske</em></a><em> on Unsplash</em></p><p>Kafka looks similar to Pub/Sub on the surface. Same vocabulary — publishers, subscribers, topics, messages. The first time you use it, you’ll think “this is just fancier Redis.”</p><p>It isn’t. The model is fundamentally different.</p><p>Kafka is a <strong>persistent, ordered log on disk</strong>. When the engine publishes a fill event:</p><ul><li>Kafka writes it to disk immediately</li><li>The message stays there, in order, for as long as your retention policy says (days, weeks, months)</li><li>Each consumer tracks its own <strong>offset</strong> — basically a bookmark for “I’ve read up to message #4,729”</li><li>If the consumer goes down and comes back, Kafka says “great, here’s #4,730 onwards”</li><li>You can even rewind the offset and replay history if you ever need to</li></ul><p>The mental shift: <strong>Redis Pub/Sub is a megaphone. Kafka is a mailbox.</strong></p><p>The megaphone is loud, fast, and ephemeral. The mailbox is patient — it doesn’t care if you check it now, in five minutes, or tomorrow morning. Your mail is still there.</p><p>For order fill events, I need a mailbox.</p><h3>So why not just use Kafka for everything?</h3><p>This is the question that separates senior thinking from “I just learned about Kafka and now I want to use it everywhere” thinking.</p><p>Running Kafka isn’t free. Here’s what you’re actually signing up for:</p><ul><li><strong>Another service</strong> to deploy, monitor, and maintain</li><li><strong>Disk space and retention policies</strong> to manage (it’s a log on disk — that disk fills up)</li><li><strong>Consumer offset management</strong> — committing offsets, handling rebalances when consumers join or leave</li><li><strong>Partition strategy</strong> — how do you spread messages across partitions for parallelism?</li><li><strong>Higher per-message latency</strong> — Kafka does fsync to disk; Redis hands you a memory pointer</li><li><strong>More moving parts</strong> that can fail in production</li></ul><p>For a solo project, none of that is trivial. And for some data, all of it is wasted effort.</p><p>Take <strong>price ticks</strong> in NexTrade. Every 10 seconds, the engine emits the current price of 50 stocks. The frontend uses these to update the live chart.</p><p>What happens if one tick gets dropped? Literally nothing. The next tick arrives 10 seconds later and the UI catches up. The user might see a slightly stale price for a few seconds — nobody dies.</p><p>Persisting these to disk would be absurd. We’d be writing data we’ll never read, that’s replaced before anyone could even query the history. It would make the system slower for zero benefit.</p><p>For price ticks, <strong>Redis Pub/Sub is genuinely the better tool</strong>. Low latency. Zero ceremony. Exactly the broadcast pattern it was designed for.</p><h3>The one question I now ask before every cross-service message</h3><p>After working through this, I landed on a single mental model. Before I send any message between services, I ask:</p><blockquote><strong><em>“What’s the cost if this message is lost?”</em></strong></blockquote><p>The answer tells me which tool to use:</p><p>Cost of loss Tool Why Negligible — fresh data is coming <strong>Redis Pub/Sub</strong> Low latency, no overhead, ephemeral by design Money, user state, or correctness <strong>Kafka</strong> Persistent, replayable, survives outages Need to query it later <strong>PostgreSQL</strong> Strong consistency, queryable, permanent Just need fast lookup <strong>Redis (key-value)</strong> TTL-based, blazing fast reads</p><p>Four tools. Four different guarantees. They aren’t competitors. They’re complements.</p><p>The trap I want every developer to avoid: <strong>picking a tool because it’s already in your stack, rather than because it matches the guarantee your data needs.</strong></p><p>“We already have Redis, let’s use Pub/Sub” feels efficient. It saves a deployment. It saves cognitive load. But it’s actually risk transfer — you’re trading operational simplicity for correctness risk. Sometimes that’s the right trade. For order fills on a trading platform, it absolutely isn’t.</p><h3>The new NexTrade architecture</h3><p>After the refactor, here’s how messages flow:</p><pre>┌─────────────────┐<br>│ Matching Engine │<br>└────────┬────────┘<br>         │<br>         ├──── Kafka topic: order.events ─────► API Consumer ────► PostgreSQL<br>         │     (fills, cancels, partials)        (durable)         (balance, holdings)<br>         │<br>         └──── Redis Pub/Sub: price.ticks ─────► WebSocket Server ────► Browser clients<br>               (every 10s, 50 stocks)              (ephemeral)</pre><p>Two paths. Two guarantees. One architecture.</p><p>If the API server crashes mid-deployment, Kafka holds the unprocessed fill events. When the consumer reconnects, it picks up from its last committed offset. <strong>Zero data loss on the path that matters.</strong></p><p>If the WebSocket layer drops a price tick, clients get the next one 10 seconds later. <strong>Nobody notices, nobody cares.</strong></p><p>That’s the whole point. Right tool, right job, right tradeoff.</p><h3>Things I’d tell my past self</h3><p>A few hard-won notes from doing this:</p><p><strong>1. Read the docs for the messaging tool you’re already using.</strong> Not the marketing page. The actual semantics page. “Pub/Sub” means wildly different things in Redis, RabbitMQ, Kafka, Google Cloud Pub/Sub, and AWS SNS. Same word, completely different guarantees.</p><p><strong>2. “It works on my machine” is the most expensive lie in distributed systems.</strong> A single-process app where the publisher and subscriber start together will never expose Pub/Sub’s at-most-once nature. The bug only appears when you deploy, scale, or restart anything. By then, it’s in production.</p><p><strong>3. Don’t reach for Kafka just because it sounds impressive.</strong> Kafka is genuinely complex operationally. If you’re shipping a side project and your data tolerates loss, Redis Pub/Sub or even an in-process event emitter is fine. Use Kafka when the guarantee is worth the cost.</p><p><strong>4. Ask the loss question early.</strong> “What happens if this message is lost?” is the cheapest sentence in distributed systems. Asking it during design costs you a minute. Discovering the answer in production costs you a week.</p><h3>What’s next</h3><p>Next refactor on the queue: moving the matching engine off a single-threaded event loop. JavaScript’s event loop served me well for v1, but as I scale order volume, I’m running into the limits of doing matching, persistence, and event publishing on one thread.</p><p>Concurrency edge cases incoming. I’ll post about whatever breaks.</p><p>If you want to follow along as I build NexTrade in public — architectural decisions, refactors, the occasional self-inflicted disaster — give this post a clap and follow me on Medium. The fun part of building in public is that the bugs are the lesson, not the embarrassment.</p><h3>Related reads</h3><ul><li><a href="https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">The Log: What every software engineer should know about real-time data’s unifying abstraction</a> — Jay Kreps’ original Kafka manifesto, still the best explanation of why logs are powerful</li><li><a href="https://dataintensive.net/">Designing Data-Intensive Applications</a> by Martin Kleppmann — chapter 11 on stream processing is required reading</li><li>Apache Kafka and Redis official documentation</li></ul><p><em>Tags: Kafka, Redis, System Design, Backend Development, Microservices, Distributed Systems, Software Engineering, Build In Public, Node.js, FinTech</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c28ed49ba5ca" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-i-added-kafka-to-my-trading-platform-even-though-redis-was-already-doing-the-job-c28ed49ba5ca">Why I Added Kafka to My Trading Platform (Even Though Redis Was Already Doing the Job)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[Building NexTrade: A High-Concurrency Nifty 50 Paper Trading Engine with Microservices]]></title>
            <link>https://medium.com/@niceperson2110/building-nextrade-a-high-concurrency-nifty-50-paper-trading-engine-with-microservices-70e404ee965a?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e404ee965a</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 13:46:10 GMT</pubDate>
            <atom:updated>2026-04-05T13:46:10.953Z</atom:updated>
            <content:encoded><![CDATA[<p>In the high-stakes world of the Indian Stock Market, speed isn’t just a feature — it’s the entire product. When I set out to build <strong>NexTrade</strong>, a paper trading platform for Nifty 50 stocks, I knew I couldn’t build a standard “CRUD” app. I needed a distributed system that could simulate the chaos of the NSE in real-time.</p><p><strong>Market Page:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBgDDJK4jp9KmScKQ_aemw.png" /></figure><p><strong>Trade Page:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50XWq3snU8suTGHiPr_64A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwydmAI14ztS5xY9BvsWMQ.png" /></figure><p><strong>Portfolio Page:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdN8li3IzQSfa9btzuy-Ew.png" /></figure><p><strong>AI Insights Page: <br></strong>- we will do something about this page if we can give anything related to ai.</p><h3>🎯 The Purpose: Why NexTrade?</h3><p>The idea for NexTrade was born out of a personal frustration. While studying technical analysis for the Indian equity markets, I wanted a sandbox to test my strategies in real-time. I turned to popular platforms like TradingView, only to discover a major hurdle: <strong>native paper trading for Indian stocks was restricted or unavailable.</strong></p><p>Instead of letting that stop my learning journey, I decided to build my own solution. NexTrade is a custom-engineered environment designed to simulate the Nifty 50 market, allowing developers and aspiring traders to validate their technical analysis and logic without risking a single Rupee. It’s a project built for learners, by a learner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*1Q2yWXtdrMfzTMCCRfPgEA.png" /></figure><h3>🏗️ The Blueprint: A 5-Pillar Architecture</h3><p>To handle thousands of concurrent users and real-time price ticks, NexTrade is split into five decoupled services.</p><h3>1. The Engine Server (The Heart) 🫀</h3><p>The Engine is where the magic happens. It’s a high-performance service that:</p><ul><li><strong>Polls Market Data:</strong> Fetches Nifty 50 data from the Yahoo Finance API (configurable intervals).</li><li><strong>In-Memory Order Book:</strong> Stores all active trades in a high-speed memory map.</li><li><strong>The Matchmaker:</strong> On every tick, it scans the order book. If a stock hits your price, it executes the trade, wipes it from memory, and screams the news to Redis.</li></ul><h3>2. Redis (The Central Nervous System) 🧠</h3><p>Using Redis <strong>Pub/Sub</strong>, we ensure that our services aren’t just “talking” — they’re synchronized.</p><ul><li><strong>Channels:</strong> Every stock has its own channel (e.g., stock:RELIANCE.NS).</li><li><strong>Events:</strong> When an order is filled, a unique event ID is published, triggering updates across the entire ecosystem instantly.</li></ul><h3>3. The API Server (The Brain) 👔</h3><p>The API is the gatekeeper. Built with Node.js and Express, it handles:</p><ul><li><strong>Authentication:</strong> Secure registration and login.</li><li><strong>Consistency:</strong> Implements locking mechanisms for stock quantities and user balances to prevent “double-spending” during high volatility.</li><li><strong>Persistence:</strong> It listens to Redis and commits every successful trade to the <strong>PostgreSQL</strong> database.</li></ul><h3>4. WebSocket Server (The Megaphone) 📢</h3><p>The WS server exists for one reason: to keep the frontend “alive.” It subscribes to Redis channels and pushes live price ticks directly to the user’s dashboard.</p><h3>5. PostgreSQL (The Memory) 💾</h3><p>Our source of truth. It stores user profiles, historical trades, and the state of every “Open” order.</p><h3>⚡ Handling the “Boom” Scenarios (Resilience)</h3><p>A system is only as good as its worst day. Here’s how NexTrade survives the “Bombshell” moments:</p><ul><li><strong>“What if the Engine dies?”</strong> 🧨 If the Engine crashes, the in-memory order book vanishes. <strong>The Fix:</strong> Upon reboot, the Engine queries the Postgres DB for all “Open” orders and repopulates its memory. Consistency is preserved.</li><li><strong>“What if the API is dead while the Engine is matching?”</strong> 📉 The Engine keeps matching, but the listeners are gone. <strong>The Fix:</strong> We reset the Engine state and re-run all pending requests from the DB.</li></ul><blockquote><strong><em>Pro Tip:</em></strong><em> In a real-world scenario, you’d want a </em><strong><em>Message Queue (like RabbitMQ or Kafka)</em></strong><em> to act as a buffer so no event is ever truly lost.</em></blockquote><h3>🧐 The Critic’s Corner: The Good, The Bad, and The Ugly</h3><h3>The Good ✅</h3><ul><li><strong>Scaling:</strong> Decoupling the WS and API servers means we can scale them independently. With a load balancer and some vertical scaling on Redis, this architecture can handle it.</li><li><strong>Speed:</strong> In-memory matching is <em>orders of magnitude</em> faster than querying a DB on every tick.</li></ul><h3>The Bad ❌</h3><ul><li><strong>The “WS Don’t Care” Fallacy:</strong> You mentioned if WS is down, it’s fine. In trading, <strong>if the WS is down, the user is blind.</strong> A 5-second lag is the difference between a profit and a loss.</li><li><strong>Client-Side Weight:</strong> Using too many hooks on the frontend can make the UI sluggish. For a dashboard this data-heavy, <strong>Server-Side Rendering (SSR)</strong> or <strong>Incremental Static Regeneration (ISR)</strong> for the “Markets” page would boost SEO and performance significantly.</li></ul><h3>🚀 Get Started in Seconds</h3><p>Deployment shouldn’t be a headache. NexTrade is fully Dockerized.</p><p>Bash</p><pre># Clone the repo<br>git clone https://github.com/yashpatel21102002/papertrading</pre><pre># Spin up the entire microservice cluster<br>docker-compose up -d</pre><p><em>That’s it. Your local NSE is live.</em></p><h3>🎯 Final Thoughts</h3><p>NexTrade was built with a “Ship Fast, Ship More” mentality, but the underlying architecture is ready for battle. By separating the matching logic from the data persistence, we’ve created a system that is both simple and effective.</p><p><strong>What do you think?</strong> Could this handle the madness of a Budget Day or a major Market Crash? Let’s discuss in the comments!</p><h3>⚠️ Important Disclaimer &amp; Cautions</h3><p><strong>Please read this carefully before using or interacting with the platform:</strong></p><p><strong>Educational Simulation Only:</strong> NexTrade is a <strong>simulation tool</strong> and should be treated as an educational game. There is no real money involved, and “profits” or “losses” within this app have no real-world financial value.</p><p><strong>No NSE Affiliation:</strong> This project is <strong>not affiliated with, authorized, or endorsed by</strong> the National Stock Exchange of India (NSE) or any other financial regulatory body. All stock data is fetched via third-party APIs (Yahoo Finance) for simulation purposes only.</p><p><strong>Not Financial Advice:</strong> The data, charts, and “insights” provided by this platform are for informational and testing purposes. Do not use this application to make real-world investment decisions. Always consult with a certified financial advisor for actual trading.</p><p><strong>No Liability:</strong> The developer (Yash Patel) is not responsible for any financial losses, data inaccuracies, or technical glitches resulting from the use of this software. This project is provided “as-is” for portfolio and demonstration purposes.</p><p><strong>Data Accuracy:</strong> Since this is a simulation, price ticks and order execution may not perfectly mirror the live NSE market due to API latency or polling intervals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e404ee965a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Real-Time Chat App with React, Node.js & WebSockets (and deploying on AWS EC2)]]></title>
            <link>https://javascript.plainenglish.io/building-a-real-time-chat-app-with-react-node-js-websockets-and-deploying-on-aws-ec2-770e3978dfe8?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/770e3978dfe8</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 14:09:07 GMT</pubDate>
            <atom:updated>2025-09-15T00:20:26.863Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Building a Real-Time Chat App with Next, Node.js &amp; WebSockets (and deploying on AWS EC2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slk3KAgdfSZqIk6vTSONgw.png" /></figure><p>👋 Hey friends, ever wondered what <em>really</em> goes on behind the scenes of a real-time chat app? You type “hi” and magically, someone on the other side sees it instantly. No Gmail-style refresh. No polling every 5 seconds. Just ✨ real-time ✨.</p><p>That magic is called <strong>WebSockets</strong>, and in this post, I’ll walk you through how I built a <strong>room-based chat server</strong> using Node.js, Express, and ws.<br> 👉 I’ll explain <strong>the thinking, the architecture, the low-level design</strong>, and yes — how to actually deploy it on AWS EC2.</p><p>You’ll also get the <strong>live demo link</strong> (running on my EC2 — yes, direct IP, no fancy domain yet 😅) + GitHub code.</p><h3>🧐 What are WebSockets (and why should you care)?</h3><p>Imagine HTTP as that friend who only answers when you ask:</p><blockquote><em>You: “Hey, got any new messages?”<br> HTTP: “Nope.”<br> You: “What about now?”<br> HTTP: “Still nope.”</em></blockquote><p>Now imagine WebSocket as the <em>cool friend</em> who just texts you the moment something happens. No asking, no refreshing, just push.</p><p>🔬 <strong>Low-level magic</strong>:</p><ul><li>WebSocket starts as HTTP (Upgrade: websocket) → server replies 101 Switching Protocols.</li><li>After handshake, the TCP connection is hijacked into a <strong>bi-directional pipe</strong>.</li><li>Messages travel as <strong>frames</strong> (tiny binary or text packets).</li><li>Server can send, client can send — no waiting.</li></ul><p>👉 Result: Low-latency, persistent connection. Perfect for chat, gaming, stock tickers, or collaborative apps.</p><h3>🏗 Architecture of Our Chat Server</h3><p>Let’s break down the mental model:</p><p>🖥 <strong>HTTP Layer (Express)</strong> → Handles normal routes (health check, etc.).<br>🔗 <strong>WebSocket Server (</strong><strong>ws)</strong> → Lives on top of HTTP, upgrades connections.<br>📦 <strong>Room Store (</strong><strong>Map&lt;string, Set&lt;ws&gt;&gt;)</strong> → Each room ID maps to a set of client connections.<br> 🆔 <strong>UUIDs</strong> → Generate unique IDs short codes for rooms.<br> 🧹 <strong>Cleanup Logic</strong> → When a client leaves, server removes it from the room. If room is empty → delete it.</p><h3><strong>🧑‍💻 Code Walkthrough</strong></h3><p>Here’s the gist (with commentary).</p><pre>// Setup HTTP + Express<br>const app = express()<br>const server = http.createServer(app)<br>const wss = new WebSocketServer({ server })<br><br>// Room store<br>const rooms = new Map()<br>// Helper: send typed JSON<br>function sendMessage(ws, type, payload) {<br>  ws.send(JSON.stringify({ type, ...payload }))<br>}</pre><p>👆 This sets the stage: Express handles /, and ws upgrades to persistent sockets.</p><h3>🔑 Connection Lifecycle</h3><p>Every socket = a “mini user object”:</p><pre>wss.on(&quot;connection&quot;, (ws) =&gt; {<br>  ws.id = uuidv4()     // unique client ID<br>  ws.room = null       // no room yet<br>  ws.name = null<br>})</pre><p>Think of ws like a little human: they don’t have a name or room when they’re born, but we’ll assign them later.</p><h3>🏠 Create a Room</h3><pre>case &#39;create-room&#39;:<br>  const newRoom = uuidv4().slice(0, 6) // short 6-char code<br>  rooms.set(newRoom, new Set([ws]))<br>  ws.room = newRoom; <br>  ws.name = name<br>  sendMessage(ws, &#39;room-created&#39;, { roomId: newRoom })</pre><p>Here the server becomes an <strong>Airbnb host</strong>. It creates a room, assigns the client, and gives them the keys.</p><h3>🚪 Join a Room</h3><pre>case &#39;join-room&#39;:<br>  if (!rooms.has(roomId)) {<br>    sendMessage(ws, &#39;error&#39;, { message: &#39;Room not found!&#39; })<br>  }<br>  const room = rooms.get(roomId)<br>  room.add(ws); ws.room = roomId; ws.name = name<br>  sendMessage(ws, &#39;room-joined&#39;, { roomId })</pre><p>If the room exists, you’re in. Otherwise, error. (Pro tip: always check for null rooms, or you’ll get ghosts 👻).</p><h3>💬 Chat in a Room</h3><pre>case &#39;chat&#39;:<br>  const room = rooms.get(ws.room)<br>  room.forEach((client) =&gt; {<br>    if (client.readyState === ws.OPEN) {<br>      sendMessage(client, &#39;chat&#39;, { name: ws.name, message })<br>    }<br>  })</pre><p>This is the “broadcast to everyone except the wall” part.</p><h3>👋 Disconnect</h3><pre>ws.on(&#39;close&#39;, () =&gt; {<br>  const room = rooms.get(ws.room)<br>  room.delete(ws)<br>  if (room.size === 0) rooms.delete(ws.room)<br>})</pre><p>Cleanup is essential. Otherwise you’ll have zombie sockets eating memory like 🍕 at a LAN party.</p><h3>⚙️ How This Works Internally (The Geeky Bits)</h3><ul><li><strong>Handshake</strong>: Browser → HTTP GET with upgrade → server replies → socket becomes bi-directional.</li><li><strong>Frames</strong>: Small packets. Chat messages = text frames.</li><li><strong>Ping/Pong</strong>: Keepalive. Prevent zombie connections.</li><li><strong>Backpressure</strong>: If client is slow, buffer grows. Use bufferedAmount to monitor.</li><li><strong>Room cleanup</strong>: Avoid memory leaks.</li></ul><p><em>[Insert flow diagram: Connect → Join → Chat → Disconnect → Cleanup]</em></p><h3>🚨 Production Considerations</h3><p>If you scale:</p><ul><li>Use <strong>Redis Pub/Sub</strong> for cross-instance messaging.</li><li>Add <strong>auth tokens</strong> in handshake.</li><li>Use <strong>TLS (wss://)</strong>.</li><li>Add <strong>rate limiting</strong> (avoid spam).</li><li>Monitor pm2 monit, heap, and event loop lag.</li></ul><p>Scaling WebSockets = sticky sessions or Redis → choose based on traffic.</p><h3>☁️ Deploying to EC2 (Step by Step)</h3><p>1️⃣ Launch EC2 (Ubuntu). Open ports 22, 8080.<br>2️⃣ SSH in:</p><pre>ssh -i &quot;key.pem&quot; ubuntu@&lt;EC2-IP&gt;</pre><p>3️⃣ Install Node.js + Git:</p><pre>curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -<br>sudo apt install -y nodejs git</pre><p>4️⃣ Clone your repo &amp; install:</p><pre>git clone &lt;your-repo&gt;<br>cd chat-server<br>npm install</pre><p>5️⃣ Run with PM2:</p><pre>sudo npm install -g pm2<br>pm2 start dist/server.js --name chat-server<br>pm2 save</pre><p>6️⃣ Test 🎉:</p><pre>curl http://&lt;EC2-IP&gt;:808</pre><h3>🎯 Final Thoughts</h3><p>You now understand not just <em>the code</em>, but the <strong>thinking behind it</strong> — from handshake internals to cleanup logic.</p><p>The server is the unsung hero: it creates rooms, broadcasts messages, cleans up, and scales when you need it. With this, you can host your own chat party on EC2 and say, “I run my own Slack” (without spending $8 per seat).</p><p>👉 Live demo: <a href="http://52.66.212.92/">http://52.66.212.92/</a><br>👉 Code [Frontend]: <a href="https://github.com/yashpatel21102002/simple-chat-client">https://github.com/yashpatel21102002/simple-chat-client</a><br>👉 Code [Backend]: <a href="https://github.com/yashpatel21102002/simple-chat-server">https://github.com/yashpatel21102002/simple-chat-server</a></p><p>Checkout the app, add the suggestions/issues Or code review points for this projects in the github so we can improve the project, thank you guys for reading the blog till now. 🌝</p><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=770e3978dfe8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-real-time-chat-app-with-react-node-js-websockets-and-deploying-on-aws-ec2-770e3978dfe8">🚀 Building a Real-Time Chat App with React, Node.js &amp; WebSockets (and deploying on AWS EC2)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript 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[ Build a High-Performance Caching Proxy Server with Redis, Express, and Node.js]]></title>
            <link>https://javascript.plainenglish.io/build-a-high-performance-caching-proxy-server-with-redis-express-and-node-js-481808210a58?source=rss-43125f002298------2</link>
            <guid isPermaLink="false">https://medium.com/p/481808210a58</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Yash Patel]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 17:46:23 GMT</pubDate>
            <atom:updated>2025-09-05T00:25:57.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naMTvBSJTCtjBUfLszfaNw.png" /></figure><h3>🔥 Introduction</h3><p>Modern web apps rely heavily on APIs, and hitting the database for every request can slow things down.<br>Caching is the answer: by storing frequently accessed data in memory, you can <strong>reduce response time from milliseconds to microseconds</strong> and save on expensive compute resources.</p><p>In this article, we’ll build a <strong>Node.js reverse proxy with Redis caching</strong> that:<br>1. Caches GET requests for fast performance<br>2. Supports <strong>configurable cache TTL</strong> (Time-to-Live)<br>3. Adds <strong>rate limiting</strong> to protect from abuse<br>4. Implements <strong>security best practices</strong> (Helmet, CORS, Compression)<br>5. Uses a <strong>CLI</strong> to run the server with custom parameters</p><p>Let’s dive into the code.</p><p>below is the github link for the reference: <a href="https://github.com/yashpatel21102002/Caching-Server">https://github.com/yashpatel21102002/Caching-Server</a></p><h3>🛠️ Tech Stack</h3><p>Node.js + Express → Lightweight web framework<br>Redis → In-memory caching<br>Axios → HTTP request forwarding<br>Helmet, CORS, Compression → Security &amp; performance<br>express-rate-limit → Request rate limiting<br>Commander.js → CLI for running the server</p><h3>📦 Project Setup</h3><p>Install dependencies:</p><pre>npm init -y<br>npm install express helmet cors compression express-rate-limit commander axios redis</pre><h3>🧩 Understanding the Code</h3><h4>1. app.ts – Core Proxy Logic</h4><pre>import express from &#39;express&#39;<br>import helmet from &#39;helmet&#39;<br>import cors from &#39;cors&#39;<br>import compression from &#39;compression&#39;<br>import rateLimit from &#39;express-rate-limit&#39;<br>import logger from &#39;./utils/logger&#39;<br>import { Command } from &#39;commander&#39;;<br>import { RedisConfig } from &#39;./config/redis&#39;<br>import axios from &#39;axios&#39;</pre><p>Here, we import all required modules.</p><p>helmet → Secures headers.<br>cors → Enables Cross-Origin Resource Sharing.<br>compression → Gzip compression for faster responses.<br>express-rate-limit → Limits API abuse.<br>axios → Makes HTTP calls to target servers.<br>RedisConfig → Custom Redis connection wrapper.<br>commander → CLI tool for passing arguments like target URL and TTL.</p><h4>2. CLI Arguments</h4><pre>const program = new Command();<br>program<br>  .option(&#39;-t, --target &lt;url&gt;&#39;, &#39;Target server URL&#39;, &#39;http://localhost:5000&#39;)<br>  .option(&#39;-c, --cache-ttl &lt;seconds&gt;&#39;, &#39;Cache TTL in seconds&#39;, &#39;60&#39;);<br><br>program.parse(process.argv);<br>const options = program.opts();</pre><p>We allow users to run the proxy server like this:</p><pre>node server.js --target http://api.example.com --cache-ttl 120</pre><p>This sets the <strong>target server</strong> and <strong>cache expiration time</strong>.</p><h4>3. Express Middleware</h4><pre>app.use(compression());<br>app.use(helmet());<br>app.use(cors());<br>app.use(express.json());<br>app.use(express.urlencoded({ extended: true }));</pre><p>We add essential middleware:</p><p><strong>Compression</strong>: Reduces response size.<br><strong>Helmet</strong>: Secures headers against attacks.<br><strong>CORS</strong>: Allows cross-origin requests.<br><strong>Body Parser</strong>: Handles JSON and form data.</p><h4>4. Rate Limiting</h4><pre>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,<br>  max: 100,<br>  message: &#39;Too many requests from this IP, please try again after 15 minutes&#39;,<br>  handler: (req, res, next, options) =&gt; {<br>    logger.info(options.message);<br>    res.status(options.statusCode).json({ error: options.message });<br>  }<br>});<br>app.use(limiter);</pre><p>This ensures no single client can spam your API with requests.</p><h4>5. Proxy Request Handling</h4><pre>app.use(async (req, res) =&gt; {<br>  const cacheKey = `cache:${req.method}:${req.originalUrl}`;<br>  const redis = RedisConfig.getInstance().client;<br><br>try {<br>    if (req.method === &#39;GET&#39;) {<br>      const cached = await redis.get(cacheKey);<br>      if (cached) {<br>        logger.info(`Cache hit: ${cacheKey}`);<br>        return res.json(JSON.parse(cached));<br>      }<br>    }<br>    const targetUrl = `${options.target}${req.originalUrl}`;<br>    const response = await axios({<br>      method: req.method,<br>      url: targetUrl,<br>      data: req.body,<br>      headers: { ...req.headers, host: undefined },<br>    });<br>    if (req.method === &#39;GET&#39;) {<br>      await redis.set(cacheKey, JSON.stringify(response.data), { EX: parseInt(options.cacheTtl) });<br>    }<br>    res.json(response.data);<br>  } catch (error) {<br>    logger.error(&#39;Error in the caching logic&#39;, error);<br>    res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>  }<br>});</pre><p>🔑 <strong>Key points:</strong></p><p>We generate a unique cache key using request method + URL.</p><p>If it’s a <strong>GET request</strong> and found in Redis, we return cached data immediately.</p><p>If not cached, we <strong>forward the request</strong> to the target server using Axios.</p><p>Response is stored in Redis with a configurable <strong>TTL</strong>.</p><p>Errors are logged and handled gracefully.</p><h4>6. server.ts – Entry Point</h4><pre>#!/usr/bin/env node<br>import logger from &quot;./utils/logger&quot;;<br>import app from &#39;./app&#39;<br><br>function startServer() {<br>  const PORT = process.env.PORT || 8989;<br>  try {<br>    app.listen(PORT, () =&gt; {<br>      logger.info(`Server is listening on the PORT:${PORT}`);<br>    });<br>  } catch (e) {<br>    logger.error(e);<br>  }<br>}<br>startServer();</pre><p>This script starts the server on <strong>port 8989</strong> (or process.env.PORT).</p><h3>🚀 How It Works</h3><ol><li>The proxy intercepts requests.</li><li>If cached in Redis → returns immediately (Cache Hit).</li><li>if not cached → forwards request to the target server (Cache Miss).</li><li>Caches response for future requests.</li></ol><p>This <strong>reduces latency</strong> and <strong>saves bandwidth</strong> for frequently accessed endpoints.</p><h3>🔒 Security &amp; Performance Features</h3><p>✅ <strong>Helmet</strong> for security headers.<br> ✅ <strong>Rate Limiting</strong> prevents abuse.<br> ✅ <strong>Compression</strong> saves bandwidth.<br> ✅ <strong>CORS</strong> ensures controlled access.<br> ✅ <strong>CLI</strong> for flexible deployment.</p><h3>📈 When to Use This</h3><ul><li>Microservices needing centralized caching.</li><li>Frontend apps calling a single proxy endpoint.</li><li>High-traffic APIs with repeated GET requests.</li><li>Edge caching layer in front of your backend.</li></ul><h3>🔥 Next Steps (Advanced)</h3><ul><li>Implement <strong>cache invalidation</strong> policies.</li><li>Use <strong>Redis Cluster</strong> for horizontal scaling.</li><li>Add <strong>monitoring with RedisInsight</strong> or Grafana.</li><li>Add <strong>authentication middleware</strong>.</li><li>Deploy with <strong>Docker + Kubernetes</strong>.</li></ul><h3>🎯 Conclusion</h3><p>You now have a <strong>production-ready caching proxy</strong> powered by Redis and Express.<br> This setup improves performance, saves resources, and introduces best practices for security and scalability.</p><p>If you want to explore <strong>Redis Lua scripting, message queues, or pub/sub patterns</strong>, this project is the perfect starting point.</p><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=481808210a58" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/build-a-high-performance-caching-proxy-server-with-redis-express-and-node-js-481808210a58">🚀 Build a High-Performance Caching Proxy Server with Redis, Express, and Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>