<?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 Mr Madhukar on Medium]]></title>
        <description><![CDATA[Stories by Mr Madhukar on Medium]]></description>
        <link>https://medium.com/@mrmadhukar?source=rss-5f0d1e5b962c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7RNTprTd6NdB4dK7jhJbGg.jpeg</url>
            <title>Stories by Mr Madhukar on Medium</title>
            <link>https://medium.com/@mrmadhukar?source=rss-5f0d1e5b962c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:17:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrmadhukar/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[How Authentication and Authorization Work]]></title>
            <link>https://towardsdev.com/how-authentication-and-authorization-work-6438c57302fe?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6438c57302fe</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 20:11:01 GMT</pubDate>
            <atom:updated>2026-11-08T20:11:01.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cprxEmtmmc-aZine5jiog.png" /></figure><h3>Who you are versus what you can do: login, sessions, OAuth, and role-based access, explained with one e-commerce example.</h3><p>You log in once and open ten pages. How does the server know it’s still you, and how does it know you can’t open someone else’s account?</p><p>Those are two different questions, and mixing them up causes real security bugs. Authentication and authorization are the pair of ideas behind every login screen and every “access denied” message. This guide takes them one at a time, then follows a single e-commerce app from signup to role-based access.</p><h3>Key Takeaways</h3><ul><li>Authentication asks “who are you?”; authorization asks “what are you allowed to do?”</li><li>Authentication always comes first, and each protects against different failures</li><li>Passwords must be hashed, and multi-factor authentication adds a strong second layer</li><li>Sessions and tokens keep you logged in; OAuth delegates access; OIDC adds identity on top</li><li>Hiding a button is not security: every permission must be enforced on the server</li></ul><h3>1. Why Applications Need to Know Who You Are and What You Can Do</h3><p><strong>Problem:</strong> Apps hold private data: messages, orders, payments. Without checks, anyone could read or change anyone else’s data.</p><p><strong>Two separate questions:</strong> <em>who are you?</em> and <em>what are you allowed to do?</em> A person can be correctly identified and still not be allowed to open another customer’s order.</p><p><strong>Consequences of weak access control:</strong> data breaches and account takeovers. Both come from the same root: the system trusted someone it should not have.</p><p><strong>The journey, at a glance:</strong> identity (who you are), session (staying logged in), permissions (what you can do).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jPYonIL3mo5VngpFhHDqw.png" /></figure><p>Our running example is an e-commerce app with customers, sellers, and admins.</p><p><strong>Tradeoff:</strong> Every check adds friction and code. The goal is the right amount of friction in the right places.</p><h3>2. Authentication vs Authorization: The Core Concepts</h3><p><strong>Concepts:</strong></p><ul><li><strong>Authentication (AuthN):</strong> proving identity</li><li><strong>Authorization (AuthZ):</strong> deciding permissions</li><li><strong>Identification:</strong> claiming an identity (“I am user 42”)</li><li><strong>Authentication:</strong> proving the claim is true</li></ul><p>AuthN comes before AuthZ because you cannot decide what someone may do until you know who they are.</p><p><strong>The airport analogy:</strong> the passport check is authentication. The boarding pass is authorization: it says which flight you may board. It breaks down because an airport checks you once, while a web app must re-check on every request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOQFpF6VsVLKKiUvIinuxg.png" /></figure><p><strong>401 vs 403:</strong> <strong>401 Unauthorized</strong> really means “not authenticated” (missing or invalid credentials), despite the name. <strong>403 Forbidden</strong> means “authenticated, but not allowed.”</p><p><strong>Common confusion:</strong> people say “unauthorized” when they mean “forbidden,” and use “auth” for both. Be precise in design discussions and code reviews.</p><h3>3. How Authentication Works: Proving Who You Are</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcLEq3J0epA5vSylaUKRcw.png" /></figure><p><strong>Factors:</strong> something you <strong>know</strong> (password), something you <strong>have</strong> (phone, hardware key), and something you <strong>are</strong> (fingerprint, face).</p><p><strong>Password login flow:</strong> the user submits credentials, the server finds the user, compares the password to a stored <strong>hash</strong>, and on success starts a session.</p><p><strong>Hashing and salting:</strong> never store passwords in plain text, since a database leak would expose every account. Store a slow, one-way hash instead. A <strong>salt</strong> is random data added per user, so identical passwords produce different hashes. Purpose-built algorithms such as bcrypt or Argon2 are designed for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh9gBTxR0g-vFwXQD-hLsA.png" /></figure><pre>const bcrypt = require(&quot;bcrypt&quot;);<br><br>const hash = await bcrypt.hash(password, 12);          // at signup<br>const ok = await bcrypt.compare(password, hash);        // at login</pre><p>This hashes at signup and checks the password at login. bcrypt stores the salt inside the hash.</p><p><strong>Multi-factor authentication (MFA):</strong> combines factors, such as a password plus a one-time code from an authenticator app, an SMS code, or a hardware key. Hardware keys resist phishing better than codes you type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWFhHCe8BsjjXc5TRq-kwA.png" /></figure><p><strong>Passwordless options (brief):</strong> magic links sent by email, <strong>passkeys</strong> (based on public-key cryptography), and device biometrics that unlock them.</p><p><strong>Common attacks:</strong></p><ul><li><strong>Brute force:</strong> guessing many passwords</li><li><strong>Credential stuffing:</strong> trying leaked username and password pairs from other sites, which works because people reuse passwords</li><li><strong>Phishing:</strong> tricking users into entering credentials on a fake site</li></ul><p><strong>Tradeoff:</strong> Stronger authentication adds friction. Rate limiting, MFA, and breached-password checks balance security against convenience.</p><h3>4. Staying Logged In: Sessions, Cookies, and Tokens</h3><p><strong>Problem:</strong> HTTP is stateless, so identity must be carried on every request.</p><p><strong>Session-based:</strong> after login, the server stores session data and gives the browser a <strong>session ID</strong> in a cookie. Each request carries the cookie, and the server looks it up.</p><p><strong>Token-based:</strong> the server issues a signed token, such as a <strong>JWT</strong>, with short-lived <strong>access tokens</strong> and longer-lived <strong>refresh tokens</strong>. The client sends it in the Authorization header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZopQEFQRg7hYOL4XXkWQQ.png" /></figure><p><strong>Where credentials travel:</strong> cookies are sent automatically by the browser, which helps convenience and raises CSRF concerns. The Authorization header is set by your code, so it is not sent automatically.</p><p><strong>Logout, expiry, revocation:</strong> sessions are easy to cancel by deleting the server record. Tokens stay valid until they expire unless you add a blocklist, which is why access tokens are kept short.</p><p><strong>Security basics:</strong> use <strong>HTTPS</strong>, and set cookies with <strong>HttpOnly</strong>, <strong>Secure</strong>, and <strong>SameSite</strong>. Remember that a JWT is signed, not encrypted, so do not put secrets in it.</p><p><strong>Tradeoff:</strong> Sessions give control but need storage; tokens scale easily but are harder to revoke.</p><h3>5. Third-Party and Delegated Authentication: OAuth 2.0, OIDC, SSO</h3><p><strong>Problem:</strong> Sharing your password with another app is dangerous: it gets full access, with no limits and no easy way to take it back.</p><p><strong>OAuth 2.0:</strong> a framework for <strong>delegated access</strong>. A user lets an app access limited resources on their behalf, without sharing the password. Key roles: the <strong>resource owner</strong> (user), the <strong>client</strong> (the app), the <strong>authorization server</strong>, and the <strong>resource server</strong>. <strong>Scopes</strong> limit what the app may do.</p><p><strong>Authorization code flow (conceptual):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFXVq3F9tsH9mviw8WIhow.png" /></figure><p>For single-page and mobile apps, the code flow is used with <strong>PKCE</strong>, which protects the code from interception.</p><p><strong>OpenID Connect (OIDC):</strong> a layer on top of OAuth that adds <strong>identity</strong>. It provides an <strong>ID token</strong> that says who the user is, plus standard user info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyIyfwnfflss988SJUVqGQ.png" /></figure><p><strong>“Login with Google” walkthrough:</strong> your app redirects to Google, the user signs in and consents, Google returns a code, and your backend exchanges it for tokens. The ID token tells you who logged in.</p><p><strong>SSO:</strong> single sign-on lets one login work across several apps, using a central <strong>identity provider</strong>.</p><p><strong>Key rule:</strong> OAuth is for authorization, and OIDC is for authentication. Using plain OAuth as a login system is a classic mistake.</p><p><strong>Tradeoff:</strong> Delegation avoids password sharing, but adds redirects, configuration, and a dependency on the provider.</p><h3>6. How Authorization Works: Deciding What You Can Do</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbrGAPHOb00jyhpO1pYGlg.png" /></figure><p><strong>Concepts:</strong> <strong>permissions</strong> are actions (edit product), <strong>roles</strong> group permissions (seller), and <strong>resources</strong> are the things protected (an order).</p><p><strong>Where checks happen:</strong> at the API gateway, in middleware, in the service, or in the database. The most important rule is that the <strong>server enforces</strong> them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apkI21NguRRdS2IgbVSiKA.png" /></figure><p><strong>Least privilege:</strong> give each user and service only the access it needs.</p><p><strong>Frontend hiding is not security.</strong> Hiding the “Delete” button only changes what users see. Anyone can send the request directly, so the backend must check.</p><p><strong>Ownership checks:</strong> a user may edit only their own data.</p><pre>function requireRole(role) {<br>  return (req, res, next) =&gt;<br>    req.user &amp;&amp; req.user.role === role ? next() : res.status(403).json({ error: &quot;Forbidden&quot; });<br>}<br><br>app.delete(&quot;/products/:id&quot;, requireAuth, requireRole(&quot;admin&quot;), deleteProduct);</pre><p>This allows only admins to delete products, and rejects everyone else with 403.</p><p><strong>Common failures:</strong> <strong>IDOR</strong> (insecure direct object reference) happens when a user changes an ID in a request (/orders/101 to /orders/102) and the server returns another person&#39;s order because it never checked ownership. This is part of <strong>broken access control</strong>, which has ranked at the top of recent OWASP Top 10 lists [verify current edition].</p><p><strong>Tradeoff:</strong> Fine-grained checks are safer and take more design work.</p><h3>7. Authorization Models: RBAC, ABAC, ACL and Beyond</h3><ul><li><strong>ACL (Access Control List):</strong> each resource lists who can do what. Simple and direct, but hard to manage at scale.</li><li><strong>RBAC (Role-Based Access Control):</strong> users get roles, and roles get permissions. Easy to understand, though roles can multiply.</li><li><strong>ABAC (Attribute-Based Access Control):</strong> decisions use attributes of the user, resource, and context (department, time, ownership). Flexible, but more complex to write and test.</li><li><strong>Relationship-based access (brief):</strong> permissions follow relationships, such as “owner” or “shared with,” as in document sharing with view and edit rights.</li><li><strong>Policy engines and permission-as-code (brief):</strong> tools such as Open Policy Agent keep rules in one place, separate from app code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvqW5DiBflCdpMji3fkgdw.png" /></figure><p><strong>Strengths and weaknesses:</strong> ACLs are simple but scattered. RBAC is readable but coarse. ABAC is precise but complex. Relationship-based models fit sharing, and policy engines help centralize.</p><h3>8. Authentication and Authorization Across Architectures</h3><ul><li><strong>Monolith:</strong> server-side sessions fit well.</li><li><strong>SPA plus REST API:</strong> tokens, with an auth middleware on the API.</li><li><strong>Microservices:</strong> an <strong>API gateway</strong> authenticates at the edge, <strong>token propagation</strong> passes identity to services, and services also authorize their own data. <strong>Service-to-service</strong> auth uses credentials for the services themselves.</li><li><strong>Mobile apps and API keys:</strong> an API key identifies an app, not a person, so do not treat it as user authentication, and do not ship secrets inside frontend or mobile code.</li><li><strong>Machine-to-machine (brief):</strong> the OAuth <strong>client credentials</strong> flow, or <strong>mTLS</strong>, where both sides present certificates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8H4PPVqHtfmyPnCj5YAlLA.png" /></figure><p><strong>MERN example:</strong> signup stores a bcrypt hash in MongoDB, login issues a token or session, a requireAuth middleware protects routes, and a requireRole middleware limits admin routes.</p><pre>function requireAuth(req, res, next) {<br>  const token = (req.headers.authorization || &quot;&quot;).split(&quot; &quot;)[1];<br>  try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); }<br>  catch { res.status(401).json({ error: &quot;Unauthenticated&quot; }); }<br>}</pre><p>This verifies the token and returns 401 if it is invalid.</p><h3>9. Comparing Approaches, Tradeoffs, and Common Pitfalls</h3><p><strong>Sessions vs JWT vs OAuth/OIDC:</strong></p><ul><li>Sessions: server-held state, easy revocation, need shared storage when scaling</li><li>JWT: signed token, stateless verification, harder revocation</li><li>OAuth/OIDC: delegated access and third-party login, more moving parts</li></ul><p><strong>RBAC vs ABAC:</strong> RBAC is simpler and works for most apps; ABAC is more flexible for complex rules.</p><p><strong>Build your own vs use a provider:</strong> providers such as Auth0, Firebase Auth, Clerk, and Keycloak (self-hosted), or libraries like NextAuth, handle hard parts such as password storage, MFA, and social login. Using a trusted provider is often safer than building from scratch, though it adds cost, lock-in, and configuration. Check each provider’s current features before choosing [verify].</p><p><strong>Usability vs security:</strong> more steps stop more attacks and annoy more users.</p><p><strong>Most common mistakes:</strong></p><ul><li>Weak password storage</li><li>Missing server-side checks</li><li>Long-lived tokens</li><li>Secrets in frontend code</li><li>Treating OAuth as login, or JWT as encryption</li><li>Assuming HTTPS replaces authorization checks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FFTzPO_KYzDULr0OavnBA.png" /></figure><p><strong>OWASP-style checklist:</strong> hash passwords, enforce server-side access control, use MFA, limit login attempts, set secure cookie flags, keep tokens short-lived, log and monitor.</p><h3>10. Choosing the Right Approach</h3><p>Consider:</p><ul><li><strong>Project size:</strong> small projects can use a provider or sessions; enterprises need audit trails and SSO</li><li><strong>Clients:</strong> web only favors sessions; web plus mobile favors tokens</li><li><strong>Features:</strong> social login, SSO, or MFA push you toward OAuth/OIDC or a provider</li><li><strong>Compliance and audit needs:</strong> may require specific controls and logs</li><li><strong>Team experience and maintenance cost</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdiTL7hdYD1Hf6RL9tENXA.png" /></figure><p><strong>Practical checklist:</strong> pick the simplest approach that fits, use a trusted library or provider, and enforce permissions on the server. <strong>Next steps:</strong> an OAuth deep dive, the OWASP Top 10, and zero trust.</p><h3>Try It Yourself</h3><p>Open DevTools. In the <strong>Application</strong> tab, inspect Cookies and Local Storage for a site you use, and check the HttpOnly and Secure flags. In the <strong>Network</strong> tab, log in and find the Set-Cookie header or the token. Then request a page without being logged in, and look for a <strong>401</strong>. Try a page you are logged in for but not allowed to use, and look for a <strong>403</strong>.</p><h3>Security Checklist</h3><ul><li>Hash passwords with bcrypt or Argon2</li><li>Offer or require MFA</li><li>Rate limit login attempts</li><li>Use HTTPS, with HttpOnly, Secure, and SameSite cookies</li><li>Keep access tokens short-lived</li><li>Check permissions and ownership on the server</li><li>Never put secrets in frontend code</li></ul><h3>Interview Q&amp;A</h3><p><strong>Q: Authentication vs authorization?</strong></p><p>A: Authentication proves who you are; authorization decides what you may do. Authentication comes first.</p><p><strong>Q: 401 vs 403?</strong></p><p>A: 401 means not authenticated; 403 means authenticated but not allowed.</p><p><strong>Q: Is OAuth an authentication protocol?</strong></p><p>A: No. It delegates authorization. OpenID Connect adds authentication on top.</p><p><strong>Q: Why is hiding a button not security?</strong></p><p>A: Anyone can send the request directly, so the server must enforce access.</p><p><strong>Q: What is IDOR?</strong></p><p>A: Accessing another user’s resource by changing an ID, because ownership was not checked.</p><h3>FAQ</h3><p><strong>Is JWT encrypted?</strong> <br>&gt; Not by default. A signed JWT can be read by anyone who has it.</p><p><strong>Does HTTPS handle authorization?</strong> <br>&gt; No. HTTPS protects data in transit, and you still need server-side access checks.</p><p><strong>Should I build my own login system?</strong> <br>&gt; Often a trusted provider or library is safer, since password storage and MFA are easy to get wrong.</p><p><strong>What is the difference between RBAC and ABAC?</strong> <br>&gt; RBAC grants access by role; ABAC decides using attributes of the user, resource, and context.</p><p><strong>What is passwordless login?</strong> <br>&gt; Logging in without a typed password, for example with a magic link or a passkey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6438c57302fe" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-authentication-and-authorization-work-6438c57302fe">How Authentication and Authorization Work</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSockets vs HTTP: When Should You Use Each?]]></title>
            <link>https://towardsdev.com/websockets-vs-http-when-should-you-use-each-64d82ab37cc2?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d82ab37cc2</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-11-05T21:06:01.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFzcFxpPeo0Rs-2NlyVCUw.png" /></figure><h3>Why HTTP can’t push, how polling and SSE work around it, and when WebSockets are worth their cost.</h3><p>When your friend sends a WhatsApp message, how does your phone know instantly, when the web was designed to wait for you to ask?</p><p>That question is the heart of WebSockets vs HTTP. HTTP is built so the client asks and the server answers. Live features break that model, because the server has news and nobody has asked. This guide follows the story in order: the need for real time, HTTP’s limits, the workarounds (polling and SSE), and then WebSockets, using one running example, a chat app.</p><h3>Key Takeaways</h3><ul><li>HTTP is request-response: the client always starts, and the server cannot push on its own</li><li>Polling and long polling fake “live” with repeated requests; SSE streams one way from server to client</li><li>WebSockets keep one persistent, two-way connection, and it starts as an HTTP request</li><li>WebSockets are not always faster, and they do not replace REST</li><li>Persistent connections cost memory and make scaling harder, so most apps need only HTTP</li></ul><h3>1. Why Real-Time Features Challenge the Web</h3><p><strong>Problem:</strong> Some features are only useful if they are instant: chat messages, live scores, stock tickers, delivery tracking. Users now expect that kind of experience.</p><p><strong>Cause:</strong> The original web was built for <strong>documents</strong>. You request a page, you get a page. Nobody designed it for a server that has something new to say.</p><p><strong>The core question:</strong> how does the server tell the client something new, when the client has not asked?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGh13o6WmqzIXB88TRUFiQ.png" /></figure><p><strong>Tradeoff:</strong> Making the web feel live means adding machinery that plain HTTP never needed.</p><h3>2. How HTTP Works: The Request-Response Model</h3><p><strong>Concept:</strong> HTTP follows the <strong>client-server model</strong>. The client always initiates, and the server only responds. Each request is <strong>stateless</strong>: the server treats it on its own.</p><p>A request has a method (GET, POST, PUT, DELETE), headers, and sometimes a body. A response has a <strong>status code</strong>, headers, and a body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d01IwFvSHJW_sQkZsuUIrQ.png" /></figure><p><strong>Connections:</strong> HTTP/1.1 supports <strong>keep-alive</strong>, which reuses a TCP connection for several requests. HTTP/2 adds multiplexing, so several requests share one connection at once. Both still follow request-response.</p><p><strong>What HTTP does very well:</strong> it is simple, cacheable, works with CDNs and every proxy, is easy to test, and scales with stateless servers. Pages, APIs, and CRUD operations fit it perfectly.</p><p><strong>Tradeoff:</strong> The model that makes HTTP simple is the same one that limits live updates.</p><h3>3. Limits of HTTP for Live Updates</h3><p><strong>Problem list:</strong></p><ul><li><strong>No server push:</strong> the server must wait to be asked</li><li><strong>Header overhead:</strong> every request repeats headers such as cookies and user agent, even for a tiny message</li><li><strong>Wasted requests:</strong> asking “anything new?” over and over costs bandwidth and, on phones, battery</li><li><strong>Latency:</strong> an event can wait until the next request before the client learns about it</li></ul><p><strong>Polling tradeoff:</strong> a short interval gives fresher data but more load; a long interval saves load but feels slow. You can’t win both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wmj9TfenCsTky06-ePK6Lw.png" /></figure><p><strong>Tradeoff:</strong> Plain HTTP can be stretched to feel live, but the cost shows up as traffic or delay.</p><h3>4. Workarounds Built on HTTP: Polling, Long Polling, SSE</h3><p><strong>Short polling:</strong> the client asks on a timer. It is simple and works everywhere, but most responses are empty.</p><p><strong>Long polling:</strong> the client sends a request, and the server <strong>holds it open</strong> until it has data (or a timeout), then responds. The client immediately asks again. It reduces empty responses, but each message still costs a full request cycle, and held requests use server resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVVQrsZ4BPZS6TdrOMH_bg.png" /></figure><p><strong>Server-Sent Events (SSE):</strong> the server streams events one way to the client over a single HTTP response. In browsers you use EventSource. SSE has <strong>automatic reconnect</strong>, and events can carry <strong>IDs</strong> so a reconnecting client can say where it left off (via the Last-Event-ID header).</p><pre>const source = new EventSource(&quot;/events&quot;);<br>source.onmessage = (e) =&gt; console.log(e.data);</pre><p>This listens for a stream of server events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ln_QJynTpz5DKj9FvFzCHw.png" /></figure><p><strong>Strengths and weaknesses:</strong></p><ul><li>Short polling: simplest, but wasteful</li><li>Long polling: broad compatibility, but heavier per message</li><li>SSE: easy and efficient for one-way updates, but the client cannot send over the same channel</li></ul><p><strong>Why they were not enough:</strong> a chat needs both directions, low overhead, and fast delivery. These workarounds are one-way or request-heavy.</p><h3>5. What Are WebSockets?</h3><p><strong>Concept:</strong> A <strong>WebSocket</strong> is a persistent, <strong>full-duplex</strong> connection: both sides can send at any time over the same connection, without a new request each time. The analogy: HTTP is sending letters through the post, and WebSockets are a phone call. It breaks down because a phone call between two people is private and simple, while a server may hold thousands of calls at once.</p><p><strong>The handshake starts as HTTP.</strong> The client sends a normal HTTP request asking to <strong>Upgrade</strong>, and the server replies <strong>101 Switching Protocols</strong>. After that, the same connection carries WebSocket data instead of HTTP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GIge7WeEhDpsn9rX08TMA.png" /></figure><p><strong>Secure connections:</strong> ws:// is unencrypted, and wss:// runs over TLS, like HTTPS. Use wss:// in production.</p><p><strong>Frames and messages:</strong> data travels in small <strong>frames</strong> with little overhead compared with a full HTTP request and its headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqU76u03UUnobOJLFNQ9Yg.png" /></figure><p><strong>Heartbeats and closing:</strong> <strong>ping/pong</strong> frames check that the other side is alive, and a close frame ends the connection cleanly.</p><p><strong>Tradeoff:</strong> You gain low-latency two-way messaging, and you take on a long-lived, stateful connection to manage.</p><h3>6. WebSocket Lifecycle and Message Flow</h3><p><strong>Events in the browser:</strong> open (connected), message (data arrived), error, and close.</p><pre>const ws = new WebSocket(&quot;wss://example.com/chat&quot;);<br>ws.onopen = () =&gt; ws.send(&quot;hello&quot;);<br>ws.onmessage = (e) =&gt; console.log(e.data);<br>ws.onclose = () =&gt; console.log(&quot;closed&quot;);</pre><p>This opens a connection, sends a message, and logs incoming ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uqy9spx9DNQ7XzGsLJhaLg.png" /></figure><p><strong>Broadcasting:</strong> a server can send one message to many connected clients, as in a chat room. <strong>Rooms and channels</strong> group clients so messages reach only the right ones.</p><p><strong>Reconnection and missed messages:</strong> connections drop on mobile networks. The client must reconnect, and the app must decide how to recover messages sent in between, for example by asking over HTTP for anything newer than the last seen ID.</p><p><strong>Libraries:</strong> the ws package is a lean WebSocket implementation for Node.js. <strong>Socket.IO</strong> is a higher-level library that adds rooms, automatic reconnection, and fallbacks. It uses its own protocol on top, so a plain WebSocket client cannot talk to a Socket.IO server directly.</p><pre>const { Server } = require(&quot;socket.io&quot;);<br>const io = new Server(httpServer, { cors: { origin: &quot;http://localhost:3000&quot; } });<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  socket.on(&quot;chat&quot;, (msg) =&gt; io.emit(&quot;chat&quot;, msg)); // broadcast to everyone<br>});</pre><p>This receives a chat message and broadcasts it to all connected clients.</p><p><strong>Tradeoff:</strong> Libraries save effort, but add abstraction and their own protocol.</p><h3>7. Scaling and Operating WebSockets</h3><p><strong>Problem:</strong> HTTP is stateless, so any server can answer any request. A WebSocket is <strong>stateful</strong>: one client is tied to one server for the life of the connection.</p><p><strong>Costs and issues:</strong></p><ul><li><strong>Memory:</strong> every open connection uses memory and a socket, so thousands of users means thousands of connections held open</li><li><strong>Load balancers and sticky sessions:</strong> the balancer must keep a connection on one server. Some libraries that fall back to long polling also need requests from one client to reach the same server</li><li><strong>Multi-server broadcast:</strong> if user A is on server 1 and user B is on server 2, server 1 cannot message B directly. A shared <strong>pub/sub layer</strong> such as Redis lets servers relay messages to each other</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZORguToPc1HBOvAlt12lQ.png" /></figure><ul><li><strong>Authentication:</strong> the browser WebSocket API cannot set custom headers, so common approaches are cookies sent during the handshake, or a short-lived token passed in the URL or first message. Validate it when the connection opens</li><li><strong>Proxies, firewalls, and timeouts:</strong> some intermediaries close idle connections, so heartbeats help keep them open</li><li><strong>Backpressure and rate control:</strong> a slow client or a flood of messages can pile up on the server, so limit buffer sizes and message rates</li></ul><p><strong>Tradeoff:</strong> Real-time is possible at scale, but needs extra infrastructure and care.</p><h3>8. WebSockets vs HTTP: Side-by-Side Comparison</h3><p>HTTP Polling SSE WebSockets Direction Client asks, server answers Client asks repeatedly Server to client Both ways Connection Short or reused Repeated Long-lived Long-lived Per-message overhead Full headers Full headers Low after setup Low Latency Depends on request Up to the interval Low Low Caching and CDN Excellent Possible Limited Not applicable Scaling Stateless, easy Easy but heavy Moderate Hardest Debugging Easy Easy Fairly easy Needs WS tooling</p><p>Long polling sits between polling and SSE: fewer empty responses than short polling, but a full request per message.</p><p><strong>Myths:</strong> WebSockets are not always faster, since for a rare update a plain request is fine. They do not replace REST, because CRUD still fits HTTP better. Persistent connections are not free.</p><p><strong>Tradeoff:</strong> There is no winner. The right choice follows the data flow.</p><h3>9. Real-World Use Cases and Architectures</h3><ul><li><strong>Chat apps and collaborative editing:</strong> two-way, frequent messages suit WebSockets</li><li><strong>Multiplayer games and live dashboards:</strong> low latency and many updates suit WebSockets, though a read-only dashboard may only need SSE</li><li><strong>Food delivery tracking:</strong> the server pushes location updates, so SSE often works; WebSockets suit it if the app also sends data back</li><li><strong>Notifications and live feeds:</strong> mostly one-way, so SSE or WebSockets fit</li><li><strong>E-commerce product page:</strong> plain HTTP is enough, while live auction bidding benefits from real time</li></ul><p><strong>Hybrid architecture:</strong> use HTTP for CRUD, and WebSockets only for live events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX86_5Vpq3fcCbHf5hsecg.png" /></figure><p><strong>MERN example:</strong> React connects to an Express server with Socket.IO. Chat history loads through a REST endpoint, new messages arrive over the socket, and MongoDB stores them.</p><p><strong>Running chat example:</strong> with polling the client asks every few seconds; with SSE the server streams new messages down, but sends go over normal HTTP POST requests; with WebSockets one connection carries both.</p><h3>10. Choosing the Right Approach</h3><p>Ask:</p><ul><li>Do you actually need real time?</li><li>Is data one-way or two-way?</li><li>How often does it update, and how low must latency be?</li><li>What are your scale and infrastructure limits?</li><li>What can your team maintain?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y13eFzcEsbfhAE69GTkjQg.png" /></figure><p>Be honest: most apps need only HTTP. If a refresh every few seconds is fine, polling is simpler than a new connection layer.</p><p><strong>Next learning steps:</strong> SSE in depth, WebRTC for peer-to-peer media, message queues, and gRPC streaming.</p><h3>Try It Yourself</h3><p>Open DevTools and the <strong>Network</strong> tab. Use the <strong>WS</strong> filter and open a site that uses WebSockets (or build a tiny chat). Click the connection, and open the <strong>Messages</strong> tab to see frames moving both ways. Look at the first request: it should show an Upgrade header and a <strong>101</strong> status.</p><h3>Interview Q&amp;A</h3><p><strong>Q: How does a WebSocket connection start?</strong></p><p>&gt; A: As an HTTP request with an Upgrade header, answered by 101 Switching Protocols.</p><p><strong>Q: SSE or WebSockets for notifications?</strong></p><p>&gt; A: SSE if data only flows from server to client; WebSockets if the client also sends frequent messages.</p><p><strong>Q: Why are WebSockets harder to scale?</strong></p><p>&gt; A: Connections are stateful and long-lived, so they need connection capacity, balancing, and a pub/sub layer across servers.</p><p><strong>Q: Is Socket.IO the same as WebSocket?</strong></p><p>&gt; A: No. It is a library with its own protocol on top, adding rooms and reconnection.</p><p><strong>Q: Do WebSockets replace REST?</strong></p><p>&gt; A: No. Use REST for CRUD and WebSockets for live events.</p><h3>FAQ</h3><p><strong>Are WebSockets faster than HTTP?</strong></p><p>&gt; Per message they have lower overhead, but that only matters when messages are frequent.</p><p><strong>Can WebSockets work through load balancers?</strong></p><p>&gt; Yes, if the balancer supports them and routes a connection to one server, with a pub/sub layer for cross-server messages.</p><p><strong>What is the difference between ws and wss?</strong></p><p>&gt; wss runs over TLS and is encrypted, like HTTPS.</p><p><strong>Do I need WebSockets for notifications?</strong></p><p>&gt; Often not. SSE or even polling may be enough.</p><p><strong>Is long polling obsolete?</strong></p><p>&gt; It is less common, but still used as a fallback when other options are unavailable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d82ab37cc2" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/websockets-vs-http-when-should-you-use-each-64d82ab37cc2">WebSockets vs HTTP: When Should You Use Each?</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CORS Explained: Why Does It Exist?]]></title>
            <link>https://towardsdev.com/cors-explained-why-does-it-exist-2a832b2c2b99?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a832b2c2b99</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 20:06:01 GMT</pubDate>
            <atom:updated>2026-11-03T20:06:01.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ftUX4rUdnAq2WQE7u1Ttg.png" /></figure><h3>Why browsers block cross-origin reads, how the Same-Origin Policy led to CORS, and how to fix the error the right way.</h3><p>Your API works perfectly in Postman. Why does your React app suddenly refuse to talk to it?</p><p>You see a red console message: “blocked by CORS policy.” The server is fine and the code is fine, yet the browser refuses. CORS feels random until you see the problem it was built to solve. This guide builds the story in order: the threat, the Same-Origin Policy, the pain it created, and CORS as a controlled exception. By the end, the error will read like a clear message instead of a mystery.</p><h3>Key Takeaways</h3><ul><li>A browser holds your logged-in sessions, so it must stop one site from reading another site’s data</li><li>The Same-Origin Policy blocks scripts from reading cross-origin responses</li><li>CORS lets a server opt in to sharing with specific origins, and the browser enforces the decision</li><li>Non-simple requests trigger a preflight OPTIONS request before the real one</li><li>CORS is not a server firewall, and it does not stop Postman, curl, or other servers</li></ul><h3>1. Why Browsers Needed a Security Boundary</h3><p><strong>Why:</strong> Every page you open runs code from a stranger, inside your browser. Meanwhile your browser also holds cookies for many sites at once: your email, your bank, your social accounts.</p><p><strong>What:</strong> Without rules, a malicious page could quietly call your bank in the background. Your browser would attach your session cookie automatically, and the bank would treat the request as yours. The malicious page could then read the response, such as your balance or messages.</p><p><strong>How:</strong> Picture the attack. You are logged into your email in one tab. You open an evil site in another. Its script requests your inbox, the browser sends your cookies, and the evil site reads the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asOZQ874LXvLJL5RgYa-gQ.png" /></figure><p>That would be catastrophic, so browsers needed rules about who can talk to whom.</p><p><strong>Tradeoff:</strong> Strict boundaries protect users, but they also block legitimate cross-site communication. The rest of this guide is about that tension.</p><h3>2. Understanding Origins and the Same-Origin Policy</h3><p><strong>Why:</strong> The browser needs a precise definition of “same site” to enforce any rule.</p><p><strong>What:</strong> An <strong>origin</strong> is the combination of <strong>scheme</strong>, <strong>host</strong>, and <strong>port</strong>. Two URLs have the same origin only if all three match.</p><ul><li>http://localhost:3000 and http://localhost:3000/about: same origin</li><li>http://localhost:3000 and http://localhost:5000: different port, so cross-origin</li><li>http://example.com and https://example.com: different scheme, so cross-origin</li><li>https://example.com and https://api.example.com: different host, so cross-origin</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7oKkHDd3O6tBa9XCx_cnw.png" /></figure><p>The <strong>Same-Origin Policy (SOP)</strong> is the browser rule that stops a script from one origin reading responses from another origin.</p><p><strong>How:</strong> SOP blocks <em>reading</em> cross-origin responses from scripts. It does not block everything. Pages can still embed images, load scripts, submit forms, and follow links to other origins. Those actions do not give the embedding page the ability to read the response data.</p><p>SOP protects <strong>users</strong>, not servers. It stops a malicious page from using your browser to read your private data. It applies only in browsers. Postman, curl, and server code do not enforce it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIf0Qg8HwmILuyHoGbtlQw.png" /></figure><p><strong>Tradeoff:</strong> SOP is a blunt default. It is safe, but it stops many valid setups.</p><h3>3. The Problem SOP Created</h3><p><strong>Why:</strong> Modern apps are rarely a single origin. A React frontend runs on localhost:3000, while an Express API runs on localhost:5000. Those are different origins, so the browser blocks the frontend from reading the API&#39;s responses.</p><p><strong>What:</strong> The same pain appears in microservices, CDNs, third-party APIs, and public APIs that are meant to be used by other websites. A weather API wants thousands of sites to call it. SOP would block them all.</p><p><strong>How:</strong> The web needed a controlled way to relax SOP, so servers could say “this origin is allowed.”</p><p>Before that existed, developers used workarounds:</p><ul><li><strong>JSONP:</strong> load data through a script tag, which SOP allows. It only supports GET and runs the response as code, so a hostile server could run arbitrary script on your page.</li><li><strong>Proxies:</strong> route requests through your own server, so the browser only talks to one origin. This still works and is covered later.</li></ul><p><strong>Tradeoff:</strong> Workarounds either created security holes or added infrastructure. A standard, safer mechanism was needed.</p><h3>4. What Is CORS?</h3><p><strong>Why:</strong> Servers needed a standard way to opt in to being read by other origins.</p><p><strong>What:</strong> <strong>CORS</strong> (Cross-Origin Resource Sharing) is a mechanism where the server declares which origins may read its responses, and the browser enforces that declaration. Think of a building security guard with an approved visitor list. The browser is the guard, and the server supplies the list. The analogy breaks down because the guard is not stopping visitors from entering (the request often still reaches the server). The guard decides whether the page is allowed to <em>see</em> the answer.</p><p><strong>How:</strong> The browser adds an <strong>Origin</strong> request header showing where the page came from. The server replies with <strong>Access-Control-Allow-Origin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-fcQgOyDGpP_lMrBLA8LA.png" /></figure><p>If the header is missing or does not match, the browser withholds the response from the script and logs the “blocked by CORS policy” error. That message does not mean the API is broken. It means the browser did not receive permission.</p><pre>// Running example: a fetch call from the React app<br>fetch(&quot;http://localhost:5000/api/products&quot;)<br>  .then((res) =&gt; res.json())<br>  .then(console.log);</pre><p>This request is cross-origin, so the server must include the matching Allow-Origin header.</p><p><strong>Tradeoff:</strong> CORS puts the decision with the server, but a developer can easily grant too much permission. Strictness matters.</p><h3>5. Simple Requests vs Preflighted Requests</h3><p><strong>Why:</strong> Some cross-origin requests can change data on the server. Browsers needed to check first for requests that older servers never expected.</p><p><strong>What:</strong> A <strong>simple request</strong> is limited. It uses a method such as GET, HEAD, or POST, only safelisted headers, and for POST a content type such as application/x-www-form-urlencoded, multipart/form-data, or text/plain.</p><p>Anything else is <strong>preflighted</strong>. A JSON request with Content-Type: application/json, or a request with a custom header such as Authorization, triggers a preflight. So do methods like PUT and DELETE.</p><p><strong>How:</strong> For a preflighted request, the browser first sends an <strong>OPTIONS</strong> request asking permission:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcahi-uGiM2mmnlGaHI1rg.png" /></figure><p>The server answers with <strong>Access-Control-Allow-Methods</strong> and <strong>Access-Control-Allow-Headers</strong>. <strong>Access-Control-Max-Age</strong> lets the browser cache the preflight result, which cuts repeat OPTIONS calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUGVlJpNytaF-mjLBqYvuQ.png" /></figure><p>Why does preflight exist? Legacy servers were built before CORS and never expected a cross-origin DELETE or a JSON POST from another site. The preflight asks first, so those servers are not surprised.</p><p><strong>Tradeoff:</strong> Preflights add an extra round trip. Caching with Max-Age reduces the cost.</p><h3>6. CORS with Credentials and Advanced Headers</h3><p><strong>Why:</strong> Many APIs rely on cookies or auth headers. By default, cross-origin requests do not include them.</p><p><strong>What:</strong> To send cookies, the client must opt in: credentials: &quot;include&quot; in fetch, or withCredentials in XHR. The server must reply with <strong>Access-Control-Allow-Credentials: true</strong>.</p><pre>fetch(&quot;http://localhost:5000/api/me&quot;, {<br>  credentials: &quot;include&quot;,<br>});</pre><p>This sends cookies with the cross-origin request.</p><p><strong>How:</strong> With credentials, the server cannot use the wildcard * for Allow-Origin. It must name the exact origin. The reason is safety: a wildcard means &quot;anyone,&quot; which is unsafe when private cookies are involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwDzdIq-Z2n0LM3ZLdU6mw.png" /></figure><p>Other details:</p><ul><li><strong>Access-Control-Expose-Headers</strong> lets scripts read extra response headers. By default only a small set is visible.</li><li><strong>Vary: Origin</strong> tells caches that the response depends on the Origin header. If the server returns different Allow-Origin values per origin, missing Vary can cause a cache to serve the wrong one.</li></ul><p><strong>Tradeoff:</strong> Credentialed requests are powerful and require tight configuration. This is also where CSRF concerns start to matter.</p><h3>7. Common Misconceptions and Debugging</h3><p><strong>Why:</strong> Most CORS frustration comes from believing something it does not do.</p><p><strong>What, the myths:</strong></p><ul><li><strong>CORS is not server-side security or a firewall.</strong> It is a browser rule.</li><li><strong>CORS does not stop Postman, curl, or other servers.</strong> They do not enforce it.</li><li><strong>The request often still reaches the server.</strong> For a simple request, the server processes it, and the browser only hides the response. A failed preflight stops the real request, but the OPTIONS call still arrived.</li><li><strong>Disabling CORS in the browser is not a fix.</strong> It only hides the problem on your machine.</li></ul><p><strong>CORS vs CSRF vs SOP:</strong></p><ul><li><strong>SOP</strong> is the default rule that blocks cross-origin reads.</li><li><strong>CORS</strong> is the opt-in way to relax SOP for chosen origins.</li><li><strong>CSRF</strong> is an attack where a malicious site causes your browser to send an authenticated request. CORS does not fully prevent it, since the request can still be sent. Defenses include SameSite cookies and CSRF tokens.</li></ul><p><strong>How, debugging:</strong> Open DevTools. In the <strong>Console</strong>, read the error, which usually names the missing header. In the <strong>Network</strong> tab, check whether a preflight ran and what it returned.</p><p>Frequent causes:</p><ul><li>Missing Allow-Origin header</li><li>Origin mismatch (port, scheme, or trailing differences)</li><li>Preflight returning an error status, such as an unhandled OPTIONS route</li><li>A <strong>redirect</strong> during the request or preflight</li><li>Missing Allow-Headers for a custom header</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Kj7ZwL71qV2jrY2L9XXww.png" /></figure><p><strong>Who enforces what:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aWTTJ_CLdmi4VEo1Fa4RQ.png" /></figure><p><strong>Tradeoff:</strong> Understanding the headers takes effort, but it beats trial and error.</p><h3>8. Implementing CORS in Practice</h3><p><strong>Why:</strong> You need a setup that works without opening the door too wide.</p><p><strong>What:</strong> In Express, the common approach is the cors middleware.</p><pre>const cors = require(&quot;cors&quot;);<br><br>app.use(cors({<br>  origin: &quot;http://localhost:3000&quot;,<br>  credentials: true,<br>}));</pre><p>This allows one specific origin and enables credentialed requests.</p><p><strong>How:</strong> For several allowed origins, use an <strong>allowlist</strong>:</p><pre>const allowed = [&quot;https://app.example.com&quot;, &quot;https://admin.example.com&quot;];<br><br>app.use(cors({<br>  origin: (origin, cb) =&gt; cb(null, !origin || allowed.includes(origin)),<br>}));</pre><p>This checks each request’s origin against a fixed list.</p><p>Other options:</p><ul><li><strong>Dev proxy:</strong> tools like Vite can forward /api calls to your backend, so the browser sees one origin during development.</li><li><strong>Reverse proxy or API gateway:</strong> CORS headers can be set once at the edge instead of in each service.</li><li><strong>Serverless and managed services</strong> (API gateways, object storage, Firebase) have their own CORS settings that you configure in their consoles. Check the provider’s documentation for exact fields [verify].</li></ul><p><strong>Common misconfigurations and risks:</strong></p><ul><li><strong>Reflecting any origin:</strong> copying the request’s Origin into the response header allows every site, and with credentials this is dangerous.</li><li><strong>Allowing </strong><strong>null:</strong> the null origin can come from sandboxed or local contexts, so allowing it can open a hole.</li><li><strong>Using </strong><strong>* for private APIs.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRRoAUVRO5pHePmaKw6cgQ.png" /></figure><p><strong>Tradeoff:</strong> A strict allowlist is safer but needs maintenance as origins change.</p><h3>9. CORS vs Alternatives: Comparison and Tradeoffs</h3><p><strong>Why:</strong> CORS is one option, not the only one.</p><p><strong>What and how, side by side:</strong></p><ul><li><strong>Enable CORS:</strong> direct and flexible. It needs correct headers and may add preflights.</li><li><strong>Same-origin proxy:</strong> the browser talks to one origin, and the proxy forwards to the API. It removes CORS but adds a hop and infrastructure.</li><li><strong>One domain for both:</strong> serving the frontend and API under one domain, for example /api paths, avoids cross-origin entirely. It needs routing at the edge.</li><li><strong>Wildcard vs strict allowlist:</strong> a wildcard suits genuinely public, non-credentialed data. A strict allowlist suits private APIs.</li><li><strong>Cookies vs token auth across origins:</strong> cookies need credentialed CORS and SameSite handling. Tokens in an Authorization header avoid cookie rules but trigger preflight and need safe storage.</li><li><strong>JSONP:</strong> obsolete. It only supports GET and executes remote code, so avoid it.</li><li><strong>Performance:</strong> preflights add a round trip, reduced by Max-Age caching.</li></ul><p>No option wins everywhere. The right choice depends on who calls the API and how it is authenticated.</p><h3>10. Choosing the Right Approach</h3><p><strong>Why:</strong> Different setups need different strategies.</p><p><strong>What and how:</strong></p><ul><li><strong>Public API:</strong> allow broad origins, but without credentials.</li><li><strong>Private first-party API:</strong> allow only your own origins with an allowlist.</li><li><strong>SPA plus backend on separate domains (a MERN example):</strong> enable CORS for the exact frontend origin, set credentials if you use cookies, and handle OPTIONS.</li><li><strong>Microservices and multiple frontends:</strong> handle CORS at the gateway, with one allowlist.</li><li><strong>Local development vs production:</strong> a dev proxy is convenient locally, while production often uses a same-domain setup or an explicit allowlist.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ef1ObGLbnFpLpXLpYSevA.png" /></figure><p><strong>Security checklist before deploying:</strong></p><ul><li>Allowlist exact origins, not any origin</li><li>No wildcard with credentials</li><li>Do not reflect arbitrary origins or allow null</li><li>Add Vary: Origin when the header varies</li><li>Handle OPTIONS preflights and set Max-Age</li><li>Combine with CSRF protection for cookie-based auth</li></ul><p><strong>Learning path:</strong> Same-Origin Policy, CSRF, Content Security Policy, then authentication.</p><h3>Try It Yourself</h3><p>Open DevTools and go to the <strong>Network</strong> tab. Trigger a cross-origin fetch with a JSON body. Look for an <strong>OPTIONS</strong> request, then the real request. Click each and compare the request headers (Origin, Access-Control-Request-Method) with the response headers (Access-Control-Allow-Origin, Allow-Methods). Remove a header on your server and watch the console error change.</p><h3>Debugging Checklist</h3><ul><li>Read the console error: which header is named?</li><li>Is there a preflight, and did it return a success status?</li><li>Does the Allow-Origin value match the page’s origin exactly?</li><li>Are credentials used, and is the origin explicit (not *)?</li><li>Is a redirect in the way?</li><li>Does a custom header appear in Allow-Headers?</li></ul><h3>Interview Q&amp;A</h3><p><strong>Q: Why does CORS exist?</strong></p><p>&gt; A: The Same-Origin Policy blocks cross-origin reads to protect users, and CORS lets servers opt in to sharing with chosen origins.</p><p><strong>Q: Who enforces CORS?</strong></p><p>&gt; A: The browser enforces it. The server only declares permission with headers.</p><p><strong>Q: Why does my API work in Postman but not in the browser?</strong></p><p>&gt; A: Postman does not enforce the Same-Origin Policy or CORS, while browsers do.</p><p><strong>Q: Why can’t I use </strong><strong>* with credentials?</strong></p><p>&gt; A: A wildcard means any origin, which is unsafe with private cookies, so the origin must be explicit.</p><p><strong>Q: What triggers a preflight?</strong></p><p>&gt; A: Non-simple methods, custom headers such as Authorization, or content types like application/json.</p><h3>FAQ</h3><p><strong>Is CORS a server security feature?</strong></p><p>&gt; No. It is a browser rule that protects users, and it does not stop non-browser clients.</p><p><strong>Does a CORS error mean the server did not get my request?</strong></p><p>&gt; Not necessarily. Simple requests often reach the server, and the browser then hides the response.</p><p><strong>Can I fix CORS from the frontend?</strong></p><p>&gt; No. The server must send the right headers. A dev proxy can avoid the problem during development.</p><p><strong>Is Access-Control-Allow-Origin: * always unsafe?</strong></p><p>&gt; No. It is fine for public data without credentials, but not for private data.</p><p><strong>What is the difference between CORS and CSRF?</strong> <br>&gt; CORS controls whether scripts can read cross-origin responses. CSRF is an attack that abuses automatically attached credentials, and it needs its own defenses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a832b2c2b99" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/cors-explained-why-does-it-exist-2a832b2c2b99">CORS Explained: Why Does It Exist?</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP vs HTTPS: How the Web Actually Communicates]]></title>
            <link>https://towardsdev.com/http-vs-https-how-the-web-communicates-ed530c892e85?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed530c892e85</guid>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[tsl-hendshek]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[http-status-code]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 21:26:01 GMT</pubDate>
            <atom:updated>2026-10-24T21:26:01.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTpZ-Nfe3aD2Gz2wQk64BQ.png" /></figure><h3>When you log in on café Wi-Fi, what stops the person at the next table from reading your password?</h3><p>Most of the time, the honest answer is HTTPS. Without it, your login request would travel across the network as readable text. This guide explains what HTTP is, why plain HTTP is risky, and how HTTPS fixes that, using a login request as the running example.</p><h3>Key Takeaways</h3><ul><li>HTTP is the agreed language browsers and servers use to exchange requests and responses</li><li>Plain HTTP sends readable text, so anyone on the path can read or change it</li><li>HTTPS is HTTP sent over TLS, which adds encryption, integrity checks, and server identity</li><li>A certificate lets your browser confirm the server is the one it claims to be</li><li>HTTPS does not hide the domain name, and a padlock does not prove a site is trustworthy</li></ul><h3>1. Why the Web Needs a Communication Protocol</h3><p><strong>Why:</strong> A browser and a web server are different machines, often run by different people, with no shared memory or shared context. To cooperate, they need a common language with agreed rules.</p><p><strong>What:</strong> A protocol is that agreed set of rules. The web uses a <strong>client-server model</strong>: the client (usually your browser) sends a request, and the server sends back a response. This pattern is called the <strong>request-response cycle</strong>.</p><p><strong>How:</strong> Each side knows what a valid message looks like, so neither has to guess what the other means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tj1YGxniQfEfxM_V2cWc5g.png" /></figure><p><strong>Tradeoff:</strong> Shared rules make the web interoperable across many browsers and servers, but every rule also has to be designed, maintained, and secured.</p><h3>2. What is HTTP?</h3><p><strong>Why:</strong> Browsing, APIs, and forms all need a single, predictable way to ask for resources and receive them.</p><p><strong>What:</strong> <strong>HTTP</strong> (Hypertext Transfer Protocol) is an application-layer protocol for request-response exchanges. RFC 9110, the IETF standard that defines HTTP semantics, describes it as a stateless application-level protocol. It sits above the transport layer, where TCP normally carries it.</p><p><strong>How:</strong> HTTP messages are human-readable text. Each request names a method and a target, and each response carries a status code. Because HTTP is stateless, each request is understood on its own, and the server does not keep a memory of earlier requests unless something else, such as a cookie or token, carries that context.</p><p><strong>Tradeoff:</strong> Stateless design keeps servers simple and scalable. The cost is that applications must add state explicitly, through cookies, sessions, or tokens.</p><h3>3. Anatomy of an HTTP Request and Response</h3><p><strong>Why:</strong> Knowing the parts of a message makes it easier to read traffic in DevTools and to debug problems.</p><p><strong>What:</strong> A request has a request line (method, path, version), headers (such as Host, User-Agent, Content-Type, and Cookie), and an optional body. A response has a status line (version, status code, reason), headers, and a body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5PZInyuN9YLCUPJmVKcDw.png" /></figure><p><strong>How:</strong> Status codes come in families. <strong>2xx</strong> means success, <strong>3xx</strong> means redirection, <strong>4xx</strong> means the client made an error, and <strong>5xx</strong> means the server failed. RFC 9110 defines the meaning of each code in its status code section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VA6LmnKTIDZf4DTRWe5H2Q.png" /></figure><p><strong>Tradeoff:</strong> Readable text helps humans and debugging tools, but it also means the content is visible to anyone who can see the traffic. That is the problem Section 5 covers.</p><h3>4. HTTP Methods, State, and Everyday Use</h3><p><strong>Why:</strong> Different actions need different verbs, and the browser and servers rely on those meanings to decide what is safe to repeat.</p><p><strong>What:</strong> The common methods are <strong>GET</strong> (retrieve), <strong>POST</strong> (submit data to be processed), <strong>PUT</strong> (replace a resource), <strong>PATCH</strong> (partially change a resource), and <strong>DELETE</strong> (remove a resource). RFC 9110 defines <strong>safe</strong> methods, which should not change server state, and <strong>idempotent</strong> methods, where repeating the request has the same effect as sending it once. GET is safe and idempotent. PUT and DELETE are idempotent but not safe.</p><p><strong>How:</strong> For statefulness, servers use cookies, sessions, or tokens. Caching uses headers such as Cache-Control and ETag. Many REST APIs are simply HTTP methods applied to resources, such as GET /users/42 to read a user.</p><p><strong>Tradeoff:</strong> Choosing the right method matters. Using GET to change data can cause repeated actions when a link is prefetched or retried, so keep GET read-only.</p><h3>5. The Problem with Plain HTTP</h3><p><strong>Why:</strong> Imagine the login request again. On public Wi-Fi, every packet can pass through devices you do not control.</p><p><strong>What:</strong> Plain HTTP has no encryption, so the data travels as readable text. That creates three specific risks: eavesdropping (someone reads the request), tampering (someone changes it in transit), and impersonation (someone pretends to be the server, a man-in-the-middle attack).</p><p><strong>How:</strong> Here is what an attacker on the same network can see with plain HTTP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAxxtWVQ_x3WIJoXG3nhvg.png" /></figure><p>The attacker does not need to break anything. The credentials are simply visible.</p><p><strong>Tradeoff:</strong> Plain HTTP is simpler and has no certificate or encryption cost, which is why it survived for so long. Today, that simplicity is rarely worth the risk for anything private, and browsers warn users about it.</p><h3>6. What is HTTPS?</h3><p><strong>Why:</strong> HTTP needs a way to protect data and to prove who the server is.</p><p><strong>What:</strong> <strong>HTTPS</strong> is HTTP carried over <strong>TLS</strong> (Transport Layer Security). According to RFC 9110, the https scheme identifies a resource on a server that has been authenticated and whose HTTP communication has confidentiality and integrity protection. It is not a different application protocol. The HTTP messages are the same; they just travel through a secure channel. The default port is <strong>443</strong> for HTTPS and <strong>80</strong> for HTTP.</p><p><strong>How:</strong> HTTPS provides three guarantees:</p><ul><li><strong>Confidentiality:</strong> others cannot read the content</li><li><strong>Integrity:</strong> changes in transit can be detected</li><li><strong>Authentication:</strong> the browser can check the server’s identity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*t1chrXU1Z62UxF5sKQTS-A.png" /></figure><p><strong>Tradeoff:</strong> HTTPS does not protect against everything. It does not hide the domain name from the network, it does not stop phishing sites that have valid certificates, and it does not fix bugs on the server.</p><h3>7. How HTTPS Works: TLS Handshake and Certificates</h3><p><strong>Why:</strong> Encrypting data needs a shared secret, but two strangers cannot easily agree on one in public.</p><p><strong>What:</strong> TLS uses two kinds of encryption. <strong>Asymmetric encryption</strong> uses a key pair: a public key anyone can see and a private key only the server holds. It is slower, so it is mainly used to prove identity and agree on a secret. <strong>Symmetric encryption</strong> uses one shared key for both sides. It is fast, so it protects the actual data after the handshake.</p><p><strong>How:</strong> The TLS handshake runs before any HTTP request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWhYqqHCjqfHwORWE3EsYg.png" /></figure><p>The server’s <strong>certificate</strong> contains its domain name, its public key, and a signature from a <strong>certificate authority</strong> (CA). Your browser trusts a list of root CAs. A root CA can sign an intermediate CA’s certificate, which can sign the site’s certificate. This chain is the <strong>chain of trust</strong>. If the chain is valid, the domain matches, and the certificate has not expired, the browser proceeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*_ClqetEj88Y8L2swcuPTjg.png" /></figure><p>Common errors include an <strong>expired</strong> certificate, a <strong>mismatched</strong> domain name (the certificate is for another site), and an unknown issuer. Browsers show warnings for these because the identity check failed.</p><p>TLS 1.2 and TLS 1.3 are both in use. TLS 1.3 completes the handshake with fewer round trips than TLS 1.2. [verify exact round-trip counts before quoting them]</p><p><strong>Tradeoff:</strong> The handshake adds time and CPU work, and it depends on trusting CAs. Compromised or misissued certificates are a real risk, which is why certificate management matters.</p><h3>8. HTTP vs HTTPS: Side-by-Side Comparison</h3><p><strong>Why:</strong> You need to decide when each matters, and what each one costs.</p><p><strong>What:</strong> The main differences are security, port and URL scheme, handshake overhead, and browser trust. HTTP uses http:// and port 80. HTTPS uses https:// and port 443.</p><p><strong>How:</strong> Consider these points as a list, not a verdict:</p><ul><li><strong>Security:</strong> HTTPS encrypts and authenticates. HTTP does neither.</li><li><strong>Performance:</strong> HTTPS adds a handshake, which costs some time on the first connection. Session resumption and newer TLS versions reduce this cost.</li><li><strong>Browser trust:</strong> Browsers mark plain HTTP pages as not secure, and some features such as service workers and geolocation require a secure context.</li><li><strong>Cost and certificates:</strong> HTTPS needs a certificate. Let’s Encrypt issues free, automated certificates.</li><li><strong>Mixed content:</strong> A secure page that loads images or scripts over plain HTTP can be blocked or flagged.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpK2m1IsgklcU3Vt9xt5jA.png" /></figure><p><strong>Tradeoff:</strong> HTTPS is now the standard for most public sites. HTTP still appears in local development and some internal systems, where the threat model is different.</p><h3>9. Beyond the Basics: HTTP Versions and Hardening</h3><p><strong>Why:</strong> Protocol versions and server settings change how fast and how safely a site works.</p><p><strong>What:</strong> HTTP/1.1 sends one request at a time per connection, so browsers open several connections in parallel. HTTP/2 multiplexes many requests on one connection. HTTP/3 runs over QUIC, which uses UDP. RFC 9110 notes that all three share the same semantics, and that they differ mainly in how messages are encoded and carried.</p><p><strong>How:</strong> Hardening usually means:</p><ul><li>Redirecting HTTP to HTTPS with a 301 or 308 response</li><li>Sending <strong>HSTS</strong> (HTTP Strict Transport Security), which tells browsers to use HTTPS only for that domain</li><li>Setting Secure and HttpOnly flags on cookies</li><li>Terminating TLS at a load balancer or CDN, then forwarding to the application server</li></ul><pre>curl -I http://example.com</pre><p>This prints the response headers, so you can check whether the server redirects to HTTPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3IQ68g4FLqhwaGycx9xUA.png" /></figure><p><strong>Tradeoff:</strong> HSTS is powerful but hard to undo quickly, so start with a short duration before a long one. Misconfigured redirects can also cause loops.</p><h3>10. Real-World Usage and Choosing the Right Approach</h3><p><strong>Why:</strong> The right setup depends on what data flows through the site.</p><p><strong>What:</strong> Login and payment pages must use HTTPS. Personal projects and student apps should use HTTPS too, since certificates are free and the setup is short. Internal tools and local development often use HTTP on a private network, but the risk is still real on shared networks. APIs and microservices may use mutual TLS (mTLS), where both sides present certificates.</p><p><strong>How:</strong> A practical deployment checklist:</p><ul><li>Obtain a certificate (for example from Let’s Encrypt)</li><li>Serve the site over HTTPS on port 443</li><li>Redirect all HTTP traffic to HTTPS</li><li>Enable HSTS once redirects work reliably</li><li>Set secure cookie flags</li><li>Check mixed content and certificate expiry</li></ul><p><strong>Tradeoff:</strong> Each step adds operational work, especially certificate renewal and redirect rules. Automating renewal removes most of that burden.</p><p><strong>Next learning steps:</strong> web security basics, networking fundamentals, and DevOps practices for certificates and deployment.</p><h3>Try It Yourself</h3><p>Open your browser’s DevTools. In the <strong>Network</strong> tab, load a page and click the main request to see its headers and status code. In the <strong>Security</strong> tab, inspect the certificate, its issuer, and its validity dates. Compare what you see with the diagrams above.</p><h3>Recap Checklist</h3><ul><li>HTTP carries requests and responses in readable text</li><li>Status codes group into 2xx, 3xx, 4xx, and 5xx</li><li>Plain HTTP exposes data to eavesdropping, tampering, and impersonation</li><li>HTTPS adds TLS for confidentiality, integrity, and authentication</li><li>The handshake uses asymmetric encryption to agree on symmetric session keys</li><li>Certificates form a chain of trust back to a root CA</li><li>HTTPS does not hide the domain name or stop phishing</li></ul><h3>Interview Q&amp;A</h3><p><strong>Q: Is HTTPS a different protocol from HTTP?</strong> A: No. It is HTTP carried over TLS, so the messages are the same and the channel is secured.</p><p><strong>Q: Why use both symmetric and asymmetric encryption?</strong> A: Asymmetric encryption helps establish identity and agree on a secret. Symmetric encryption is faster for the data itself.</p><p><strong>Q: What does a padlock guarantee?</strong> A: That the connection is encrypted and that the server proved control of the domain. It does not guarantee the site is honest.</p><p><strong>Q: What is HTTP stateless?</strong> A: Each request is interpreted on its own. State is added with cookies, sessions, or tokens.</p><p><strong>Q: Which port does HTTPS use by default?</strong> A: Port 443 by default; HTTP uses port 80.</p><h3>FAQ</h3><p><strong>Does HTTPS hide which website I visit?</strong></p><p>&gt; Not fully. The domain name is still visible to the network in common cases, though the page path and content are encrypted.</p><p><strong>Is a site with a padlock safe to use?</strong></p><p>&gt; The padlock means the connection is encrypted and the domain was verified. It does not mean the site is legitimate.</p><p><strong>Why do browsers show “Not Secure” on HTTP pages?</strong></p><p>&gt; Because HTTP sends data without encryption or identity checks, so the browser warns users.</p><p><strong>Is HTTPS slower?</strong></p><p>&gt; The handshake adds some delay on the first connection, but session reuse and newer TLS versions reduce the cost.</p><p><strong>Do I need a paid certificate?</strong></p><p>&gt; Not necessarily. Free, automated certificates are available from Let’s Encrypt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed530c892e85" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/http-vs-https-how-the-web-communicates-ed530c892e85">HTTP vs HTTPS: How the Web Actually Communicates</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Type a URL in Your Browser?]]></title>
            <link>https://towardsdev.com/what-happens-when-you-type-a-url-in-your-browser-97616b52ff17?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/97616b52ff17</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 20:56:01 GMT</pubDate>
            <atom:updated>2026-10-16T20:56:01.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nW0XVvn-DPpqQ5hj9qxuoA.png" /></figure><h3>Follow one request from the address bar to the screen: DNS, TCP, TLS, HTTP, and rendering, explained step by step.</h3><p>Written by Mr Madhukar</p><p>You press Enter on a website’s address. What happens in the next 200 milliseconds before the page appears?</p><p>The honest answer is: a lot. Your browser checks its own memory, looks up a name, opens a connection, secures it, asks for a page, and then turns the reply into pixels. If you have ever wondered what happens when you type a URL in your browser, this guide follows one request from start to finish, in the order things actually happen.</p><p>We will use one running example: opening a shopping site during a sale.</p><h3>Key Takeaways</h3><ul><li>A URL is an address for a resource, and the browser works through a fixed chain of steps to fetch it</li><li>DNS turns a name into an IP address, TCP opens a reliable connection, and TLS secures it</li><li>The server side often involves a CDN, a load balancer, an application server, and a database</li><li>The browser then parses HTML and CSS, builds a render tree, lays it out, and paints it</li><li>Knowing the chain makes debugging and performance work much more systematic</li></ul><h3>1. Why This Question Matters</h3><p><strong>Why:</strong> Most developers use the web every day without seeing its mechanics. Yet this question is a classic interview favorite because the answer touches almost everything: frontend, backend, networking, and DevOps all meet in this one journey.</p><p><strong>What:</strong> It is a map of the web stack. Each stage you will read about (name lookup, connection, security, request, response, rendering) is owned by a different part of the system, and a problem in any one of them can make a site feel slow or broken.</p><p><strong>How:</strong> Think of it as a relay race. The browser hands the baton to DNS, then to the network, then to the server, and finally gets it back to draw the page. When something goes wrong, the useful question is not “why is the site broken?” but “which leg of the relay failed?”</p><p>That framing helps in practice. A DNS error, a timeout, a certificate warning, and a slow render all look like “the page did not load” to a user, but each points to a different place to investigate.</p><p>Here is the order this article follows: names, addresses, connection, security, request, response, and rendering. We finish with a reusable recap checklist and a tour of the browser’s Network tab.</p><p><strong>Tradeoff:</strong> Going deep on every layer can bury you in detail. You do not need to memorize protocol internals. The goal is a mental model you can reason with, not a specification you can recite.</p><h3>2. The Big Picture: Life of a Request</h3><p><strong>Why:</strong> Before zooming into DNS or TLS, you need the overall shape of the journey, otherwise each piece feels disconnected.</p><p><strong>What:</strong> The web follows the <strong>client-server model</strong>. Your browser is the client; a machine somewhere else is the server. A <strong>URL</strong> is the address of a resource on that server. The high-level stages are: URL, DNS, connection, request, response, rendering.</p><p><strong>How:</strong> The work is split across three places. The browser handles URL parsing, cache checks, and rendering. The network carries data between machines. The server builds and sends the response.</p><p>It also helps to think in layers. The <strong>application layer</strong> is where HTTP lives. The <strong>transport layer</strong> is where TCP (or QUIC) lives. The <strong>network layer</strong> is where IP addressing and routing live. Each layer does one job and relies on the one below it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uff3upR0fYeCgmV3kO57w.png" /></figure><p>As for time cost, stages that need a round trip over the network (DNS lookup, connection setup, the request itself) usually cost more than local work like checking a cache. Exact numbers vary by network and distance, so treat any single figure with caution.</p><p>An analogy: the web is like a postal system. DNS is the address book, routing is the sorting offices, and the server is the house. The analogy breaks down because mail is one-way and slow, while a web request is a fast conversation with many back-and-forth steps.</p><p><strong>Tradeoff:</strong> A neat staged model hides the fact that real browsers overlap stages. For example, a browser can start fetching resources before it has finished parsing the page.</p><h3>3. Anatomy of a URL and Browser Pre-Checks</h3><p><strong>Why:</strong> The browser does real work before it touches the network, and understanding it explains why repeat visits feel faster.</p><p><strong>What:</strong> A URL has up to six parts: <strong>scheme</strong> (https), <strong>host</strong> (shop.example.com), <strong>port</strong> (optional), <strong>path</strong> (/sale), <strong>query</strong> (?page=2), and <strong>fragment</strong> (#reviews). The fragment is used by the browser only and is not sent to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1MClB9AJf3FcBlPph32YA.png" /></figure><p><strong>How:</strong> First, the address bar decides whether you typed a URL or a search query. If it looks like a search, it goes to your search engine instead.</p><p>Next, defaults fill in the blanks. If no port is given, HTTP uses port 80 and HTTPS uses port 443.</p><p>Then comes <strong>HSTS</strong> (HTTP Strict Transport Security). If the site has told the browser to use HTTPS only, the browser upgrades http:// to https:// itself, before sending anything.</p><p>Finally, the browser checks its <strong>cache</strong>, and a <strong>service worker</strong> (if the site registered one) can intercept the request and answer it locally. On a repeat visit, a cached copy may mean no network call at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFgNtn-cZL0jvgqZ33E9mQ.png" /></figure><p><strong>Tradeoff:</strong> Caching speeds things up but can serve stale content, which is why sites set cache rules carefully. This is the cold-versus-warm difference: a first visit pays for every step, while a repeat visit may skip many of them.</p><h3>4. Finding the Server: DNS Resolution</h3><p><strong>Why:</strong> Humans remember names like shop.example.com. Machines route traffic using IP addresses. Something has to translate between the two.</p><p><strong>What:</strong> <strong>DNS</strong> is the internet’s phonebook. It maps a domain name to the IP address (or addresses) where the site lives.</p><p><strong>How:</strong> The browser looks for an answer in layers of cache first: the browser’s own cache, then the operating system, then the router, then your ISP’s resolver. Any layer that already knows the answer replies immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgNWUMfW3QYO5iiAq1Gvhg.png" /></figure><p>If nobody knows, a <strong>recursive resolver</strong> does the legwork. It asks a <strong>root server</strong> where to find the top-level domain, asks the <strong>TLD server</strong> (for example .com) where the domain&#39;s name servers are, and finally asks the <strong>authoritative server</strong>, which holds the real answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAnuFjH9yQPDfUrJ1G1I5w.png" /></figure><p>Common record types: an <strong>A</strong> record maps a name to an IPv4 address, an <strong>AAAA</strong> record maps to an IPv6 address, and a <strong>CNAME</strong> record points one name at another name. Each record carries a <strong>TTL</strong> (time to live), which says how long it may be cached. “DNS propagation” is mostly caches expiring at different times after a change.</p><p>Optional snippet to see it yourself:</p><pre>dig example.com</pre><p>This asks a resolver for the records of example.com and prints the answer.</p><p><strong>Tradeoff:</strong> Caching makes DNS fast but means changes are not instant. A long TTL reduces lookups but slows how quickly a change reaches everyone. The phonebook analogy breaks down because DNS is distributed and cached everywhere, not one central book.</p><h3>5. Reaching the Server: IP, Routing, and TCP</h3><p><strong>Why:</strong> Knowing an IP address is not enough. Data must travel across many networks, and it must arrive complete and in order.</p><p><strong>What:</strong> <strong>IP</strong> handles addressing and routing: packets hop from router to router across ISPs until they reach the destination. <strong>Ports</strong> identify which service on a machine should receive the data, and a <strong>socket</strong> is the combination of an IP address and a port. <strong>TCP</strong> sits on top and adds reliability.</p><p><strong>How:</strong> Before sending the request, the browser opens a TCP connection using the <strong>three-way handshake</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8w2ELi-8lQE8aPDSUhBGw.png" /></figure><p>The client says “can we talk?” (SYN), the server says “yes, can you hear me?” (SYN-ACK), and the client confirms (ACK).</p><p>Once connected, TCP provides reliability: it numbers data so it can be put back in order, resends data that was lost, and uses flow control so a fast sender does not overwhelm a slow receiver.</p><p>Every round trip costs <strong>latency</strong>, measured as <strong>round-trip time (RTT)</strong>. Because the handshake needs a round trip before any data flows, distance to the server directly affects how quickly a page starts. This is one reason CDNs, covered later, place servers closer to users.</p><p>Optional snippet:</p><pre>traceroute example.com</pre><p>This shows the hops your packets take toward the destination.</p><p><strong>Tradeoff:</strong> TCP’s guarantees cost time. The handshake and retransmissions add delay, which is acceptable for web pages but is why some real-time apps prefer other transports.</p><h3>6. Securing the Connection: HTTPS, TLS, and Certificates</h3><p><strong>Why:</strong> Plain HTTP sends data in readable form. Anyone on the path (a shared Wi-Fi network, for example) could read or alter it. For a shopping site, that could mean exposed passwords or card details.</p><p><strong>What:</strong> <strong>HTTPS</strong> is HTTP over <strong>TLS</strong>, which encrypts the connection and lets the browser verify the server’s identity. As Cloudflare’s explanation describes it, a TLS handshake happens after the TCP connection is opened, and it is where client and server agree on a cipher suite and exchange what they need to create session keys.</p><p><strong>How:</strong> At a high level, the handshake does three jobs: negotiation (agree on the TLS version and cipher suite), authentication (the server presents a certificate), and key exchange (both sides arrive at shared session keys).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0B0oUKyljrtFa1kQeiqZRQ.png" /></figure><p>The certificate is checked against a <strong>chain of trust</strong>: your browser trusts certain <strong>certificate authorities (CAs)</strong>, a CA signs the site’s certificate, and so the browser can confirm the certificate is genuine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHvAPubAOzd697C7oFDl-w.png" /></figure><p>Conceptually, <strong>asymmetric encryption</strong> (a key pair) is used to prove identity and agree on a secret, and <strong>symmetric encryption</strong> (one shared key) then protects the actual data because it is faster.</p><p>The padlock guarantees that the connection is encrypted and that the server proved it controls that domain. It does not guarantee the site is trustworthy or safe.</p><p>TLS 1.3 shortens the handshake compared with older versions, according to Cloudflare’s overview. [verify exact round-trip counts before quoting them]</p><p><strong>Tradeoff:</strong> Security costs extra round trips and CPU work, which newer TLS versions reduce but do not eliminate.</p><h3>7. The HTTP Request and Server-Side Journey</h3><p><strong>Why:</strong> The secure connection is ready. Now the browser must actually ask for the page, and the server must work out the answer.</p><p><strong>What:</strong> An <strong>HTTP request</strong> has a method, a path, headers, optional cookies, and optionally a body. Common methods: <strong>GET</strong> (read), <strong>POST</strong> (create), <strong>PUT</strong> (update), <strong>DELETE</strong> (remove). The <strong>response</strong> has a status code, headers, and a body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-iiLZqNjF-d0vkGubr4-A.png" /></figure><p><strong>How:</strong> The request rarely reaches a single machine directly. A <strong>CDN</strong> or edge server may answer immediately with a cached copy. If not, a <strong>load balancer</strong> or <strong>reverse proxy</strong> picks a healthy backend. That web server passes the request to an <strong>application server</strong>, which may query a <strong>database</strong>, and the reply travels back the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rd2k8ycPwIYN_c6Rgbh5lQ.png" /></figure><p>Status codes tell the browser what happened: 200 means success, 404 means not found, and 500 means a server error. Headers carry details like content type and caching rules, and the body holds the HTML, JSON, or other data.</p><p>During a sale, this is where the load balancer and CDN matter most: they spread traffic and serve cached pages so the application server is not overwhelmed.</p><p>Optional snippet:</p><pre>curl -I https://example.com</pre><p>This fetches only the response headers so you can see the status code and caching hints.</p><p><strong>Tradeoff:</strong> Each extra layer (CDN, proxy, load balancer) improves scale and resilience but adds another place where things can fail or cache the wrong thing.</p><h3>8. From Bytes to Pixels: Browser Rendering Pipeline</h3><p><strong>Why:</strong> A response full of text is not a page yet. The browser must turn it into something you can see.</p><p><strong>What:</strong> Following web.dev’s description of the critical rendering path, the browser builds the <strong>DOM</strong> from HTML and the <strong>CSSOM</strong> from CSS, combines them into a <strong>render tree</strong>, then performs <strong>layout</strong> (working out sizes and positions) and <strong>paint</strong> (drawing pixels), with compositing assembling the layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*VO2D_jYNRwD9UV5aS9eqjA.png" /></figure><p><strong>How:</strong> As the HTML arrives, the parser builds the DOM and discovers more resources to fetch: stylesheets, scripts, images, fonts, and API calls. CSS is <strong>render-blocking</strong>, because the browser needs styles before it can draw correctly. Scripts can block HTML parsing unless they are marked to load differently.</p><p><strong>Reflow vs repaint:</strong> a <strong>reflow</strong> (layout again) happens when a change affects size or position, which is costly. A <strong>repaint</strong> happens when only appearance changes, such as a color, which is usually cheaper.</p><p>The page also fires load events as it progresses, so scripts can run when the DOM is ready or when everything has finished loading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYs-_rFxiZ8TdI_q2BnjVQ.png" /></figure><p><strong>Tradeoff:</strong> More CSS, JavaScript, and images mean richer pages but more waiting. Deferring non-critical resources speeds up the first paint at the cost of extra planning.</p><h3>9. HTTP/1.1 vs HTTP/2 vs HTTP/3</h3><p><strong>Why:</strong> A modern page needs dozens of resources. How the protocol carries them changes how fast the page feels.</p><p><strong>What:</strong> Three generations of HTTP exist, each tackling a limit of the last. Comparing them is about tradeoffs, not picking a winner.</p><p><strong>How:</strong> <strong>HTTP/1.1</strong> handles one request at a time per connection, so browsers open several connections in parallel. A slow response can hold up the ones behind it, known as <strong>head-of-line blocking</strong>.</p><p><strong>HTTP/2</strong> allows <strong>multiplexing</strong>: many requests and responses share one connection at the same time. It also compresses headers to cut repeated overhead.</p><p><strong>HTTP/3</strong> runs over <strong>QUIC</strong>, which is built on UDP rather than TCP. The aim is to avoid TCP-level head-of-line blocking and speed up connection setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2zYtN3IkE8rIdhbpPwQfA.png" /></figure><p><strong>TCP vs QUIC:</strong> TCP is mature and universally supported. QUIC offers different performance behavior, particularly on lossy networks, but depends on UDP being allowed through networks and on server and client support. [verify performance claims for your own use case]</p><p><strong>Caching:</strong> a <strong>browser cache</strong> stores files on the user’s device, while a <strong>CDN cache</strong> stores them on edge servers near many users. Both cut repeat work, at different layers.</p><p><strong>Cookies, sessions, tokens (briefly):</strong> cookies are small data stored by the browser and sent with requests. A session keeps state on the server, while a token carries it in a signed value the client sends back.</p><p><strong>Tradeoff:</strong> Newer is not automatically better for every site. Adoption depends on browser, server, and network support, so most sites fall back gracefully to older versions.</p><h3>10. Debugging, Performance, and Applying the Knowledge</h3><p><strong>Why:</strong> This knowledge pays off when something is slow or broken, and in interviews and system design.</p><p><strong>What:</strong> The browser’s developer tools show the journey in real time, with a timing breakdown for each request.</p><p><strong>How:</strong> <strong>Try it yourself:</strong> open DevTools, go to the <strong>Network</strong> tab, reload a page, and click any request. Look at its timing breakdown. You will typically see time spent on things like DNS lookup, connecting, TLS, waiting for the first byte, and downloading the content. Compare a first visit against a repeat visit to see caching at work.</p><p>Common failures map to stages: <strong>DNS errors</strong> point to name lookup, <strong>timeouts</strong> to connection or server, <strong>SSL errors</strong> to certificates, <strong>404</strong> to a missing resource, and <strong>500</strong> to a server-side bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgSq30bBmyGP4QPobWYpbg.png" /></figure><p>Quick wins: cache static files, use a CDN, compress responses, and reduce the number of requests.</p><p>Where to optimize: if the delay is before the first byte, look at network and server; if it is after, look at the browser (large scripts, render-blocking CSS, layout work).</p><p><strong>Recap checklist for interviews:</strong></p><ul><li>URL parsed, pre-checks run (HSTS, cache, service worker)</li><li>DNS resolves the name to an IP address</li><li>TCP connection opens with a three-way handshake</li><li>TLS secures the connection and verifies the certificate</li><li>HTTP request is sent, possibly via CDN and load balancer</li><li>Application server and database build the response</li><li>Browser builds DOM and CSSOM, then layout, paint, and composite</li><li>Sub-resources load, and the page finishes</li></ul><p>Next learning steps: networking basics, system design, and web performance.</p><p><strong>Tradeoff:</strong> Speed, security, and simplicity pull in different directions. Every extra optimization or security layer adds complexity, so measure first and fix what the data points to.</p><h3>FAQ</h3><p><strong>What happens first when you type a URL?</strong></p><p>&gt; The browser decides if it is a URL or a search, applies defaults and HSTS, and checks its cache before using the network.</p><p><strong>Why does DNS come before everything else?</strong></p><p>&gt; Because the browser needs an IP address to know which machine to connect to.</p><p><strong>Is HTTPS slower than HTTP?</strong></p><p>&gt; It adds a handshake, but newer TLS versions reduce that cost, and HTTPS is the standard for security reasons.</p><p><strong>What is the difference between DOM and CSSOM?</strong></p><p>&gt; The DOM represents page structure from HTML, and the CSSOM represents styles from CSS. They combine into the render tree.</p><p><strong>Does HTTP/3 replace HTTP/2?</strong></p><p>&gt; Not entirely. Both are in use, and the best choice depends on support and the network conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97616b52ff17" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/what-happens-when-you-type-a-url-in-your-browser-97616b52ff17">What Happens When You Type a URL in Your Browser?</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker vs Kubernetes Explained]]></title>
            <link>https://towardsdev.com/docker-vs-kubernetes-explained-9b68ce220ec2?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b68ce220ec2</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 20:01:02 GMT</pubDate>
            <atom:updated>2026-10-11T20:01:02.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>From a single container to a self-healing cluster</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-DiEPWQn5JLobw3tnUW1Q.png" /></figure><p>Written by Mr Madhukar</p><p>If your app works perfectly on your laptop, why does it break on the server? That question has frustrated developers for decades, and it’s exactly where the Docker vs Kubernetes story begins.</p><p>This is a deployment story, not a tool comparison. Docker solved how to package an application so it runs the same way everywhere. Kubernetes solved what happens once you have many of those packaged applications running across many machines, and something inevitably goes wrong.</p><h3>Key Takeaways</h3><ul><li>The core deployment problem is environment mismatch, not laziness or bad code</li><li>Containers solve packaging; they share the host OS kernel, unlike heavier virtual machines</li><li>Docker builds, ships, and runs containers on a single machine</li><li>Docker Compose coordinates multiple containers, but only on one host</li><li>Kubernetes takes over once you need many containers managed across many servers</li><li>Docker and Kubernetes are different layers of the same stack, not rivals</li></ul><h3>Why Deployment Became a Problem</h3><p>Every developer has shipped code that worked flawlessly on their own machine, only to watch it fail the moment it reached a test or production server. This is the “works on my machine” problem, and it’s rarely about bad code.</p><p>The real cause is environment mismatch. Your laptop has a specific operating system version, specific installed libraries, and specific configuration. The server has its own version of all three. A dependency that behaves one way locally can behave differently once installed on a server with a slightly different setup.</p><p>Version conflicts make this worse. One project needs Node 18, another needs Node 20, and installing both globally on the same machine invites trouble. Multiply this across a real team, and dependency management becomes a genuine source of production incidents, not just an annoyance.</p><p>Manual server setup compounds the problem further. Installing a runtime, configuring environment variables, and setting up a database by hand, one server at a time, is slow and genuinely error-prone. A single missed step can mean a server that looks configured but behaves differently from every other one.</p><p>What teams actually need is consistency: the same application, with the same dependencies, behaving identically regardless of which machine it runs on. That single requirement — consistent, repeatable deployment — is the problem containers were built to solve, and it’s worth holding onto as the thread connecting everything else in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM6b4KQDtDYnJalT-N_chw.png" /></figure><h3>Virtual Machines vs Containers</h3><p>Before containers became the default, <strong>virtual machines</strong> were the standard way to isolate applications from each other. A VM runs a complete, independent operating system on top of a hypervisor, meaning every single VM carries the full weight of its own kernel, its own system processes, and its own memory footprint.</p><p>That full isolation is a real strength, but it’s also expensive. Booting a VM can take minutes. Running several VMs on one machine means running several complete operating systems side by side, each consuming meaningful CPU and memory just to exist, before your actual application has done anything.</p><p><strong>Containers</strong> take a different approach. Instead of packaging a full OS, a container packages just the application and its dependencies, and shares the host machine’s OS kernel with every other container running alongside it. This shared-kernel approach is the core idea that makes containers dramatically lighter.</p><p>The practical difference shows up immediately: containers typically start in seconds, not minutes, and you can run far more containers than VMs on the same hardware, since they aren’t each dragging along a redundant operating system.</p><p>None of this makes VMs obsolete. When you genuinely need strong isolation between workloads — different customers on shared infrastructure, or applications that require entirely different operating systems — a VM’s stronger boundary still makes sense. Containers optimize for speed and density; VMs optimize for isolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZM0SGi51ADOuIiHYd7jBgg.png" /></figure><h3>What Is Docker?</h3><p><strong>Docker</strong> is a platform for packaging an application together with everything it needs to run — code, runtime, system libraries, configuration — into a single, portable unit called a container image.</p><p>The purpose is directness: once an application is packaged this way, it runs the same way on a developer’s laptop, a testing server, or a production machine, because the environment itself travels with the application instead of being recreated by hand each time.</p><p>Under the hood, Docker has a few key pieces. The <strong>Docker daemon</strong> (dockerd) is the background process that actually builds images and runs containers. The <strong>Docker CLI</strong> is how you talk to it — commands like docker build and docker run are sent to the daemon, which does the real work.</p><p>Conceptually, a typical workflow looks like this: you describe how to build your application’s environment, Docker builds that into an image, and then Docker runs that image as a running container. We’ll look at this flow in more detail in the next section.</p><p>Docker became the industry standard largely because it made this packaging approach genuinely easy to adopt. It didn’t invent the underlying container technology in the Linux kernel, but it built an accessible, well-documented toolchain around it that teams of any size could actually use, which is a large part of why “containers” and “Docker” are often used almost interchangeably today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqXVFyCWSYR07uJwpf3OQw.png" /></figure><h3>Core Docker Concepts</h3><p>A <strong>Dockerfile</strong> is the blueprint — a plain text file listing the steps needed to build your application’s environment: which base image to start from, which dependencies to install, which files to copy in, and how to start the application.</p><pre>FROM node:20<br>COPY . .<br>RUN npm install<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>This small Dockerfile starts from an official Node.js base image, copies in the application code, installs dependencies, and defines the startup command.</p><p><strong>Images vs containers</strong> is a distinction worth being precise about. An image is a read-only snapshot — the packaged result of building a Dockerfile. A container is a running instance of that image. One image can be used to start many containers, each an independent running copy.</p><p>Docker builds images in <strong>layers</strong>, and each instruction in a Dockerfile typically creates one layer. Docker caches these layers, so if only your application code changes, Docker can reuse the cached dependency-installation layer instead of reinstalling everything from scratch — a real speed advantage during iterative development.</p><p><strong>Docker Hub</strong>, and container registries generally, are where built images are stored and shared, letting a team push an image once and pull it on any other machine that needs to run it.</p><p>Two more pieces round out the basics. <strong>Volumes</strong> let data persist beyond a container’s own lifecycle — essential for anything like a database, where losing data when a container restarts isn’t acceptable. <strong>Docker networking</strong> lets containers communicate with each other, and with the outside world, in controlled, configurable ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0fQKkWVuxLOSEw3AijRQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihhtSyfIIXjYjIWqtTwZ6Q.png" /></figure><h3>Running Multiple Containers with Docker Compose</h3><p>A single container is rarely the whole picture. A typical web application needs at least three separate pieces running together: a frontend, a backend API, and a database — each with different dependencies, and each better kept in its own container.</p><p><strong>Docker Compose</strong> lets you define this entire multi-container stack in one file, and bring it all up with a single command.</p><pre>services:<br>  frontend:<br>    build: ./frontend<br>    ports: [&quot;3000:3000&quot;]<br>  backend:<br>    build: ./backend<br>    ports: [&quot;4000:4000&quot;]<br>  database:<br>    image: postgres:16</pre><p>This defines three services — frontend, backend, and database — each built or pulled as its own container. Compose also sets up networking automatically, so the backend can reach the database simply by using its service name, database, rather than needing to know its specific IP address.</p><p>This service-to-service communication by name is one of Compose’s more genuinely convenient features. It removes a real source of fragile, hardcoded configuration that manual container networking would otherwise require.</p><p>Compose has a real limit, though: it’s designed to run on a <strong>single machine</strong>. It’s excellent for local development and small deployments, but it has no built-in concept of spreading containers across multiple servers, recovering automatically from a server going down, or distributing traffic across several machines. That gap is exactly where the next section picks up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uYK6_NLlZZdwnb7D1L99g.png" /></figure><h3>The Problem Docker Alone Cannot Solve</h3><p>Imagine a food delivery app during peak dinner hours. Traffic surges, and the handful of backend containers that were comfortably sufficient an hour ago are suddenly overwhelmed. Someone — or something — needs to notice this and add more containers, fast.</p><p>Now imagine one of those containers crashes silently at 2 a.m. Docker itself won’t restart it for you by default, and if nobody’s watching, that’s reduced capacity nobody even knows about until complaints start coming in.</p><p>This is the real gap: <strong>managing hundreds of containers</strong>, reliably, is a fundamentally different problem from running one or a dozen. It requires someone — or something — constantly watching for crashes and restarting them, distributing traffic evenly across many running containers (load balancing), scaling the number of containers up and down as real demand changes, rolling out new versions without dropping any live traffic, and coordinating all of this across multiple physical or virtual servers, not just one.</p><p>Docker, including Docker Compose, was never built to solve this coordination problem at scale. It’s genuinely good at packaging and running containers; it has no built-in concept of a multi-server cluster, continuous health monitoring, or automated scaling decisions.</p><p>This is precisely the gap <strong>container orchestration</strong> exists to fill — and it&#39;s exactly why Kubernetes exists at all. Understanding this gap first is what makes Kubernetes&#39;s complexity feel earned, rather than arbitrary, once we get there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuQavVHDIOMoZNKes1fImg.png" /></figure><h3>What Is Kubernetes?</h3><p><strong>Kubernetes</strong> (often shortened to K8s) is a container orchestration platform — software that manages running containers across a cluster of machines, handling scheduling, scaling, networking, and recovery automatically.</p><p>It originated at Google, based on years of internal experience running containerized workloads at massive scale, and was later open-sourced. Its purpose is directly the gap described above: once you have many containers across many servers, Kubernetes becomes the system that keeps track of all of them.</p><p>The core idea underlying Kubernetes is the relationship between <strong>desired state</strong> and <strong>actual state</strong>. You declare what you want — &quot;three replicas of this application should always be running&quot; — and Kubernetes continuously works to make the cluster&#39;s actual state match that declaration, automatically correcting drift whenever something changes, like a crashed pod.</p><p>A Kubernetes cluster has two broad parts. The <strong>control plane</strong> makes decisions: the <strong>API server</strong> is the entry point for every command sent to the cluster, the <strong>scheduler</strong> decides which machine should run each new workload, <strong>etcd</strong> stores the cluster&#39;s actual current state, and additional controllers continuously reconcile that state against what was declared. <strong>Worker nodes</strong> are where containers actually run, each managed by an agent called the <strong>kubelet</strong>, which talks back to the control plane.</p><p>It&#39;s worth being precise here: Kubernetes is a <strong>manager</strong>, not a replacement for containers themselves. It typically runs on top of Docker or another container runtime — it orchestrates containers; it doesn&#39;t eliminate the need for them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2SGEMwfS4h6dYNiVozosw.png" /></figure><h3>Core Kubernetes Concepts</h3><p>A <strong>Pod</strong> is the smallest deployable unit in Kubernetes — typically wrapping a single container (sometimes a small group of tightly coupled ones), along with shared networking and storage.</p><p>A <strong>Deployment</strong> declares how many replicas of a pod should exist and manages a <strong>ReplicaSet</strong> underneath to keep that number running continuously — if a pod dies, the Deployment notices and starts a replacement automatically.</p><p>A <strong>Service</strong> gives a set of pods one stable network address, even as individual pods are created and destroyed behind the scenes, and load-balances incoming traffic across whichever pods are currently healthy.</p><p><strong>ConfigMaps</strong> and <strong>Secrets</strong> separate configuration and sensitive values (like API keys) from your application&#39;s actual code, so the same container image can be configured differently across environments without being rebuilt.</p><p><strong>Ingress</strong> manages external traffic entering the cluster, typically routing requests to the correct internal Service based on the request&#39;s URL or hostname.</p><p>Two capabilities tie everything together in practice. <strong>Scaling and self-healing</strong> mean Kubernetes can add or remove pod replicas based on demand, and automatically replace pods that fail health checks. <strong>Rolling updates and rollbacks</strong> mean a new version can be deployed gradually, pod by pod, with traffic continuing to flow throughout — and if something goes wrong, Kubernetes can revert to the previous known-good version just as systematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bt3loFm3VYqrb4CYz7HtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWvFjePg6c-xEdb4Z_YCtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*883rYzLglGVuJwDOsRQ2rg.png" /></figure><h3>Docker vs Kubernetes</h3><p>With both tools now explained individually, the comparison itself becomes much simpler — because they aren&#39;t really solving the same problem.</p><ul><li><strong>Different problems, different layers.</strong> Docker handles containerization: packaging and running an application. Kubernetes handles orchestration: coordinating many containers across many machines.</li><li><strong>Scope.</strong> Docker (and Compose) operates comfortably on a single host. Kubernetes is built specifically for a cluster of many machines.</li><li><strong>Scaling and high availability.</strong> Docker alone offers no automatic scaling or multi-server failover. Kubernetes provides both as core, built-in capabilities.</li><li><strong>Learning curve and complexity.</strong> Docker is relatively approachable for an individual developer. Kubernetes has real operational complexity — more concepts, more configuration, more moving parts to understand and maintain.</li><li><strong>Cost and infrastructure.</strong> Running Docker needs one machine. Running Kubernetes well typically needs a cluster of machines, plus the operational effort of managing that cluster, or a managed service that handles it for you.</li><li><strong>Alternatives worth knowing exist.</strong> Docker Swarm is Docker&#39;s own, simpler built-in orchestration option — less powerful than Kubernetes, but considerably easier to adopt for smaller-scale needs.</li></ul><p>The most important point is the last one: <strong>they&#39;re typically used together</strong>, not as competing choices. Kubernetes doesn&#39;t replace Docker — it usually runs containers built with Docker (or a similar container runtime), adding the orchestration layer Docker was never designed to provide on its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rs2PYSaTWrorhlLjuKXgQ.png" /></figure><h3>Real-World Usage and Choosing the Right Approach</h3><p>For a <strong>small project or personal app</strong>, plain Docker — maybe with Docker Compose for a few services — is usually more than enough. The operational overhead of a full Kubernetes cluster isn&#39;t justified when a single server comfortably handles the load.</p><p><strong>Startups and growing products</strong> often begin exactly this way, then introduce Kubernetes once real scaling, reliability, or multi-service coordination needs actually appear — not before those needs are real.</p><p><strong>Large-scale systems</strong> — an e-commerce platform with frontend, API, database, and payment services, or a streaming platform absorbing sudden, large traffic spikes — are where Kubernetes&#39; strengths become genuinely necessary rather than optional: automatic scaling, self-healing, and coordinated rollouts across many servers.</p><p>Most teams don&#39;t run Kubernetes entirely by hand. <strong>Managed options</strong> like Amazon EKS, Google GKE, and Azure AKS handle much of the control plane&#39;s operational burden, letting teams focus on their application rather than cluster maintenance itself.</p><p>Both tools sit naturally inside modern <strong>CI/CD and DevOps pipelines</strong> — code gets built into a Docker image, pushed to a registry, and deployed to Kubernetes automatically, forming the backbone of how many production systems ship changes today.</p><p>For students mapping out a learning path: start with Docker fundamentals and genuinely understand containers first. Move to Docker Compose for multi-container applications. Only then approach Kubernetes — its concepts land far more naturally once the problems it solves feel real to you, rather than abstract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiywyqNmSnHTR5nTFSTq-w.png" /></figure><h3>Frequently Asked Questions</h3><p><strong>Is Kubernetes a replacement for Docker?</strong></p><p>&gt; No. Kubernetes orchestrates containers across a cluster; it typically runs containers built with Docker rather than replacing it.</p><p><strong>Do I need Kubernetes for a small project?</strong></p><p>&gt; Usually not. Docker, or Docker with Compose, is typically sufficient until you have real multi-server scaling or reliability needs.</p><p><strong>What is the main difference between Docker Compose and Kubernetes?</strong></p><p>&gt; Compose coordinates multiple containers on a single machine. Kubernetes coordinates containers across many machines, with automatic scaling and self-healing.</p><p><strong>Why did Kubernetes become so popular?</strong></p><p>&gt; It solves the coordination problem that appears the moment an application runs as many containers across many servers — crash recovery, scaling, and zero-downtime updates — reliably and automatically.</p><p><strong>Should I learn Docker before Kubernetes?</strong></p><p>&gt; Yes. Kubernetes manages containers, so understanding what a container actually is, and the specific problems of running many of them, makes Kubernetes concepts click far more naturally.</p><h3>Conclusion</h3><p>Docker vs Kubernetes isn&#39;t really a rivalry — it&#39;s two different layers of the same deployment story. Docker solved the &quot;works on my machine&quot; problem by packaging an application with everything it needs, so it runs identically anywhere. Kubernetes picked up where Docker&#39;s scope ends, solving the coordination problem that appears once you have many containers spread across many servers: scaling, healing, and deploying without downtime. Understanding both, in that order, is what turns deployment from something mysterious into something you can reason about clearly.</p><p><strong>Mr Madhukar</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b68ce220ec2" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/docker-vs-kubernetes-explained-9b68ce220ec2">Docker vs Kubernetes Explained</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM vs Jev: Understanding AI That Generates and AI That Decides]]></title>
            <link>https://towardsdev.com/llm-vs-jev-understanding-ai-that-thinks-and-acts-e9379a13e856?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9379a13e856</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[genrative-ai]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 20:06:01 GMT</pubDate>
            <atom:updated>2026-10-02T02:17:36.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QL-haIIaWLdZZtz7QpH3XQ.png" /></figure><h3>Answering a question is not the same as making a decision</h3><p>Ask an AI assistant “what’s a good subject line for this email?” and it generates text — a suggestion, nothing more. Ask it “send this email to my client,” and something different has to happen: a decision has to be made about <em>whether</em> to proceed (is this request safe, urgent, authorized?), and then a real action has to be <em>taken</em> by your software. Generating language, making a fast structured decision, and executing an action are three separate jobs.</p><p>This guide is about the first two, and how they fit together. An <strong>LLM</strong> generates language. <strong>Jev</strong> — a model released by TypeSafe AI — makes fast, structured decisions that software can use directly. Your application code and tools then carry out the action.</p><p>A quick note on terminology: Jev is <strong>not</strong> an execution engine, and it does not “act” on anything itself. It is a <strong>System One model</strong>: it reads a piece of context (called a <em>state</em>), answers questions about it, and returns typed answers with probabilities. Your code decides what to do with those answers. Keeping that distinction clear from the start avoids a common confusion this article will return to later.</p><h3>What Is an LLM (Large Language Model)?</h3><p>An <strong>LLM</strong> is a model trained on large amounts of text (and increasingly other data types) to understand and generate human-like language — given an input, it predicts and produces a coherent, contextually relevant response.</p><p>At its core, an LLM’s job is <strong>understanding and generation</strong>: reading a request, drawing on patterns learned during training, and producing text (or, in multimodal models, other content) that responds to it appropriately. This makes LLMs the right tool for open-ended reasoning and writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-KB31qO1Bw40PY1Gw_wCA.png" /></figure><h3>What Is Jev?</h3><p><strong>Jev</strong> is a model released by <strong>TypeSafe AI</strong>. It is <strong>not a traditional LLM and it does not generate text</strong>. TypeSafe AI describes it as a <strong>System One model</strong>: a class of AI models built to make fast, structured decisions that software can use directly.</p><p>Here is how it works in practice:</p><ul><li>You send Jev a <strong>state</strong> — the context to evaluate (a support message, a user request, a tool call, structured data).</li><li>You send it <strong>questions</strong> about that state.</li><li>Jev returns <strong>typed answers with probabilities</strong>, not a paragraph of prose.</li></ul><p>There are three supported question types:</p><ul><li><strong>Choice</strong> — pick from a set of options; returns a probability for each option plus an overall confidence.</li><li><strong>Score</strong> — rate the input against ordered levels such as low, medium, high; returns a continuous score, the underlying distribution, and a confidence value.</li><li><strong>Noul</strong> — answer a yes-or-no question; returns the probability that the statement is true.</li></ul><p>Multiple questions about the same state are evaluated in parallel in one request, so adding questions barely changes response time. Jev is trained with reinforcement learning for calibrated decisions (RLCD), and TypeSafe AI reports up to 200x faster inference and 400x lower cost than comparable LLMs on classification tasks (these are the company’s own reported figures).</p><p>To be precise about scope: Jev is not a drop-in replacement for an LLM. It cannot draft, summarize, or chat. It handles the <strong>classification-style decisions</strong> that agents often use LLMs for today, but faster and cheaper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-a483Z6CVqd57Zsb6NNtQ.png" /></figure><h3>Content Generation vs Fast Structured Decisions: The Core Distinction</h3><h3>The virtual-assistant analogy</h3><p>Picture two different team members. One is a <strong>research assistant</strong> — extremely knowledgeable, great at answering open-ended questions, drafting text, and summarizing information. The other is a <strong>triage desk</strong> — someone who looks at every incoming request and instantly answers a handful of fixed questions: <em>Is this urgent? Which team should handle it? Is this risky?</em> The triage desk never writes a long reply; it just gives quick, reliable labels that the rest of the organization can act on.</p><p>An LLM behaves like the research assistant. Jev behaves like the triage desk: fast, cheap, structured judgments that software can use directly. Neither one is the person who actually books the room or sends the email — that is done by your tools and application code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYmpNNdUiv6ID5Xx2VcHpg.png" /></figure><h3>How LLMs Understand Context and Generate Responses</h3><p>An LLM processes an input request against everything it learned during training (and any additional context provided, like conversation history or retrieved documents), and generates a response by predicting what coherent, relevant text should come next, piece by piece.</p><p>This is genuinely powerful for understanding intent, summarizing information, drafting content, and answering questions — but note carefully: <strong>the LLM itself is not verifying that an action is safe, authorized, or even technically possible</strong> — it’s generating a linguistically appropriate response. Also, if every small decision in an agent requires another full LLM call, the agent loop becomes slow and costly. That gap is exactly what Jev is designed to fill.</p><h3>How Jev Evaluates Inputs and Returns Decisions</h3><p>Jev sits <strong>alongside</strong> the LLM in the agent loop, not after it as an executor. Whenever your agent needs a quick structured judgment, your code sends Jev the relevant state and a few questions:</p><ul><li><strong>Evaluating</strong> the state — a message, a proposed tool call, a user request</li><li><strong>Answering</strong> each question with a typed result and a probability</li><li><strong>Returning</strong> that result to your application, which uses it to route, block, prioritize, or escalate</li></ul><p>A simple example: a support message arrives, and you ask Jev one Noul question, “does this convey urgency?” It might return a probability of 0.99. Your code then decides to push that ticket to the top of the queue. Jev made the judgment; your code took the action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QddiPB_BpPx9XTDuIBdtLQ.png" /></figure><h3>LLM vs Jev: Key Differences and Use Cases</h3><p>LLM Jev (System One model) <strong>Core responsibility</strong> Understanding and generating content Fast, structured decisions about a given state <strong>Output</strong> Text, code, suggestions Typed answers (choice, score, noul) with probabilities <strong>Speed and cost</strong> Slower and costlier per call Much faster and cheaper per decision (company-reported) <strong>Best suited for</strong> Drafting, summarizing, answering, open-ended reasoning Classification, routing, prioritization, risk gating <strong>Performs real actions?</strong> No — it only generates output No — your application and tools perform the action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxPAvT0InnP_hGk0CeZmHA.png" /></figure><h3>How LLMs and Jev Work Together in AI Agents</h3><p>A modern <strong>AI agent</strong> runs in a loop: an LLM decides what to do, a tool executes, the results are evaluated, and the loop continues until the task is done. Jev slots into that loop wherever a fast, structured decision is needed, so the expensive LLM is reserved for open-ended reasoning and generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFr74W1u4tZ387D0VNrhqA.png" /></figure><h3>Traditional chatbot vs action-oriented AI assistant</h3><p>A traditional chatbot stops at generation — it tells you what it thinks you should do, and you do it yourself. An action-oriented AI assistant (an agent) goes further: it can use tools to book the appointment, send the email, or update the record. Fast decision layers like Jev help make that safe and affordable by checking and routing each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B27UlIh8ECDl-ZbdxXamFg.png" /></figure><h3>Role of APIs, Tools, and Structured Outputs</h3><p>Two primitives made it much easier to connect AI models to real software:</p><ul><li><strong>Tool calling</strong> lets a model make structured requests (for example, “call the createBooking tool with these parameters&quot;) and receive structured results.</li><li><strong>Structured outputs</strong> let a model return results in a predictable format instead of loose, free-form text.</li></ul><p>Jev takes the structured idea further: its entire output is typed by design — a probability for a Noul question, a distribution for a Score, per-option probabilities for a Choice — so your code can use it directly without parsing prose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wf9OP_v-NLQBO_9W4zhwFg.png" /></figure><p><strong>Important distinction worth stating plainly:</strong> neither an LLM requesting a tool call nor Jev scoring that call performs anything by itself — a separate execution system has to actually receive the request and act on it. Confusing “the model asked for an action” or “the model approved the action” with “the action happened” is a real source of misunderstanding when building these systems.</p><h3>Real-World Applications in Web Development and Automation</h3><ul><li><strong>Model routing</strong> — Jev can assess an incoming request and pick the cheapest model that can handle it: a fast, inexpensive model for simple lookups, a more capable one for complex debugging or architecture decisions</li><li><strong>Guardrails (auto mode)</strong> — Jev can check proposed tool calls for risky behavior and block them before the tool executes, the same pattern some coding harnesses use internally to build trust in agents</li><li><strong>Triage and prioritization</strong> — urgency, category, or sentiment of tickets and emails, scored cheaply at scale</li><li><strong>LangChain integration</strong> — Jev is exposed through the langchain-typesafe package (a TypeSafeClassifier, plus experimental middleware for routing and guardrails), so it can be called from a node, tool, or middleware hook using context the agent already has</li><li><strong>Integration with existing systems</strong> — connecting an AI layer to systems you already run, rather than replacing them outright</li></ul><h3>Challenges: Hallucinations, Incorrect Decisions, Security, and Reliability</h3><h3>Hallucinations</h3><p>LLMs can generate confident-sounding, plausible text that’s factually incorrect or describes an action that doesn’t correspond to anything real or valid — a genuine reason validation can’t be skipped.</p><h3>Incorrect decisions</h3><p>Jev returns probabilities, not certainty. A classifier can still be wrong, so applications should set sensible thresholds, look at the confidence value, and fall back to a stronger model or a human when confidence is low. Robust systems also limit which actions are possible at all.</p><h3>Security</h3><p>Agents can receive bad instructions, either by accident or from an attacker, and be persuaded to take actions nobody wanted. A cheap classifier layer that screens tool calls helps, but it is one layer, not the whole defense — authentication, authorization, and input validation all remain essential.</p><h3>Reliability</h3><p>Real actions can fail partway — a network call times out, an API returns an error. Production systems need retries, clear error handling, and audit trails, the same production-mindedness that applies to any backend system performing real-world side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYAjBBMe2KBvAw5krn8DLA.png" /></figure><p><strong>Why validation and human approval matter for sensitive actions:</strong> for anything with real consequences — sending money, deleting data, communicating externally on someone’s behalf — an explicit approval step (human-in-the-loop) remains a genuinely sound safeguard, even when a fast classifier says the action looks safe.</p><h3>Practical Examples</h3><ul><li><strong>AI customer support assistant</strong> — Jev scores a message for urgency and category; the LLM drafts the reply; your backend actually creates the ticket</li><li><strong>AI-powered travel booking</strong> — the LLM understands “book me a flight to Delhi next Friday”; Jev can check whether the request is high-stakes enough to need confirmation; your booking API actually reserves and charges, ideally after user approval</li><li><strong>Automated email assistant</strong> — the LLM drafts the email; Jev can classify whether it is sensitive or external; your system sends it, with an approval gate where needed</li><li><strong>AI coding assistant</strong> — the LLM generates code; a Jev-based guardrail checks a risky tool call, such as a shell command, before it runs; your sandbox actually executes it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHK1A6X3uErA2TrYXYbZNw.png" /></figure><h3>Important Comparisons</h3><h3>LLM vs Jev</h3><p>Flexible content generation, versus fast structured decisions — two different responsibilities, not competing alternatives. Jev is not a replacement for an LLM.</p><h3>Reasoning vs Classification</h3><p>Open-ended reasoning and generation (LLM), versus answering fixed typed questions with calibrated probabilities (Jev).</p><h3>Chatbot vs AI Agent</h3><p>Conversational responses only, versus a system that can also use tools and carry out real workflows.</p><h3>Tool Calling vs Tool Execution</h3><p>A model requesting that a specific action be taken, versus a separate execution system actually receiving and carrying out that request. Jev scoring a request does not execute it either.</p><h3>Autonomous vs Human-Approved Actions</h3><p>A system executing independently without a check-in, versus requiring explicit human authorization before a sensitive action proceeds.</p><h3>Developer Connection</h3><ul><li><strong>Web development</strong> — integrating AI assistants meaningfully into real web applications</li><li><strong>Frontend</strong> — chat interfaces, action confirmation prompts, and visualizing results clearly</li><li><strong>Backend</strong> — calling Jev for routing and gating, orchestrating workflows, and the actual tool/API execution layer</li><li><strong>APIs</strong> — sending a state and questions to Jev, and connecting an LLM’s tool calls to real external services</li><li><strong>Databases</strong> — retrieving relevant context for the LLM or Jev, and storing results and audit logs of actions taken</li><li><strong>Security</strong> — authentication, permissions, and input validation apply fully once real actions are on the table</li><li><strong>System design</strong> — deliberately separating AI generation, fast decisions, and execution, rather than blurring them together</li></ul><h3>Production and Real-World Connection</h3><ul><li>Deploying LLM-powered applications typically means using cloud AI services rather than self-hosting large models</li><li>Jev is used through an API (and the LangChain integration), so it needs an API key and the same careful integration work as any other external dependency</li><li>Probabilities and confidence values need thresholds you choose and test — never assumed correct by default</li><li>Queues and workflow engines help manage asynchronous, multi-step tasks reliably</li><li>Authorization and human approval steps matter specifically for sensitive operations</li><li>Monitoring model responses, classification accuracy, execution failures, and API costs is essential operational hygiene, not optional polish</li><li>Retries, clear error handling, and audit logs matter exactly as much here as in any other production backend system</li></ul><h3>Common Mistakes and Misconceptions</h3><ul><li><strong>“LLMs only generate text”</strong> — incomplete; multimodal LLMs can process and generate multiple content types beyond plain text</li><li><strong>“Jev is an AI that executes actions”</strong> — false; Jev doesn’t execute anything. It evaluates a state and returns typed answers with probabilities, and your application and tools perform the action</li><li><strong>“Jev is just another LLM”</strong> — false; Jev doesn’t generate text. It is a System One model built for fast, structured decisions</li><li><strong>“Jev replaces the LLM in an agent”</strong> — false; it complements the LLM. Use an LLM for open-ended reasoning and generation, and Jev for fast structured decisions along the way</li><li><strong>“LLMs cannot make decisions”</strong> — incomplete; they can support decision-making, but every decision costs a full model call, which is why a cheaper decision model can help</li><li><strong>“An AI agent is just a chatbot”</strong> — false; agents can additionally use tools and execute real workflows, not just converse</li><li><strong>“A high probability means the action is safe”</strong> — false; probabilities are inputs to your decision logic, and sensitive actions still need validation or human approval</li><li><strong>“Tool calling automatically performs an action”</strong> — false; a separate execution system must actually receive and carry out the tool call</li><li><strong>“AI agents always require full autonomy”</strong> — false; they can, and often should, operate with human approval for sensitive actions</li></ul><h3>Final Takeaway</h3><p>Generating language, making fast structured decisions, and executing real actions are different responsibilities, even though modern AI systems increasingly combine them into one seamless-feeling experience. An LLM excels at understanding context and generating language — drafting, summarizing, reasoning through open-ended problems. Jev, a System One model from TypeSafe AI, covers a different job: evaluating a state and returning calibrated, typed decisions quickly and cheaply, which makes it useful for routing, prioritization, and risk gating inside the agent loop. Neither replaces the other, and neither one executes anything on its own — your application and tools do that. A genuinely capable AI agent combines all three, connected deliberately through structured outputs, tool calling, and — for anything sensitive — a real validation or approval step in between. For developers building these systems, that separation isn’t a minor implementation detail — it’s the core architectural decision that determines whether an AI system stays a helpful assistant, or becomes something risky the moment it’s given the ability to act.</p><h3>Frequently Asked Questions</h3><p><strong>What is Jev?</strong></p><p>&gt; Jev is a model from TypeSafe AI, described as a System One model. It doesn’t generate text. You give it a state and some questions, and it returns typed answers (choice, score, or yes/no “noul”) with probabilities, so software can use the result directly.</p><p><strong>Is Jev an LLM?</strong></p><p>&gt; No. An LLM generates language. Jev evaluates a state and returns structured decisions. It is best seen as a complement to an LLM, not a replacement.</p><p><strong>Does Jev execute actions?</strong></p><p>&gt; No. Jev only makes judgments. Your application code and tools take the real action, such as sending an email or updating a database.</p><p><strong>Can an LLM be trusted to execute actions directly, without a separate layer?</strong></p><p>&gt; Generally, no — best practice is to keep a distinct validation and execution step between a model’s output and any real-world action, because models can generate plausible-sounding but incorrect or inappropriate proposals. A fast classifier like Jev can be part of that validation, but it shouldn’t be the only safeguard.</p><p><strong>Do all AI agents need human approval for every action?</strong></p><p>&gt; No — the appropriate level of autonomy depends on the action’s sensitivity and reversibility. Low-stakes, easily reversible actions might run autonomously, while sensitive or hard-to-reverse actions (like financial transactions) generally warrant explicit human approval.</p><p><strong>What’s the simplest way to start using Jev in a web application?</strong></p><p>&gt; Pick one decision your agent currently asks an LLM to make, such as “is this message urgent?” or “which model should handle this request?” Send that state and question to Jev (directly through the TypeSafe API or through the langchain-typesafe integration), read the probability, and let your own backend code act on it with a sensible threshold and a fallback for low confidence.</p><p><em>Sources: LangChain’s “Building a Harness with Jev” and TypeSafe AI’s introduction to System One models and Jev.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9379a13e856" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/llm-vs-jev-understanding-ai-that-thinks-and-acts-e9379a13e856">LLM vs Jev: Understanding AI That Generates and AI That Decides</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain vs. LangGraph: A Practical JavaScript Developer’s Guide]]></title>
            <link>https://towardsdev.com/langchain-vs-langgraph-a-practical-javascript-developers-guide-3551e89e7bea?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3551e89e7bea</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[langchain-vs-langgraph]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-10-02T02:34:34.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZoe6nU9NEeq5eH0p8zCww.png" /></figure><h3>The Challenge of Building LLM-Powered Applications</h3><p>Calling a model provider’s API directly — openai.chat.completions.create(...) — works fine for a single question and a single answer. The moment an application needs more than that — reusable prompt templates, retrieving relevant documents before answering, calling external tools, remembering earlier steps in a multi-turn task, or branching based on what the model decided — that raw API call stops being enough, and developers end up rebuilding the same scaffolding: prompt formatting, retries, state tracking, conditional logic.</p><p><strong>LangChain</strong> and <strong>LangGraph</strong>, both available as JavaScript/TypeScript libraries built by LangChain Inc., exist specifically to remove that repeated scaffolding — as two related, complementary frameworks addressing two different layers of the same problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkkMqX6fun9IpIqlW2omKA.png" /></figure><h3>LangChain Fundamentals</h3><p><strong>LangChain</strong> provides high-level, composable building blocks for LLM applications: <strong>models</strong>, <strong>prompts</strong>, <strong>tools</strong>, <strong>retrieval</strong>, and <strong>agents</strong>.</p><h3>Models</h3><p>A consistent interface across model providers (OpenAI, Anthropic, Google, and others), so switching providers means changing an import and a config object, not rewriting application logic.</p><pre>import { ChatAnthropic } from &quot;@langchain/anthropic&quot;;<br><br>const model = new ChatAnthropic({ model: &quot;claude-sonnet-4-5&quot;, temperature: 0 });<br>const response = await model.invoke(&quot;Explain event loops in one sentence.&quot;);</pre><h3>Prompts</h3><p><strong>Prompt templates</strong> let you define reusable, parameterized prompts instead of hardcoding strings everywhere:</p><pre>import { ChatPromptTemplate } from &quot;@langchain/core/prompts&quot;;<br><br>const prompt = ChatPromptTemplate.fromMessages([<br>  [&quot;system&quot;, &quot;You are a {role} expert.&quot;],<br>  [&quot;human&quot;, &quot;{question}&quot;],<br>]);<br><br>const chain = prompt.pipe(model);<br>const response = await chain.invoke({ role: &quot;Node.js&quot;, question: &quot;What is the event loop?&quot; });</pre><h3>Tools</h3><p>Tools let a model request that a specific function be called — the same tool-calling concept covered conceptually in this series’s LLM vs JEV article:</p><pre>import { tool } from &quot;@langchain/core/tools&quot;;<br>import { z } from &quot;zod&quot;;<br><br>const getWeather = tool(<br>  async ({ city }) =&gt; `Sunny in ${city}`,<br>  { name: &quot;getWeather&quot;, description: &quot;Get the weather for a city&quot;, schema: z.object({ city: z.string() }) }<br>);</pre><h3>Retrieval</h3><p><strong>Retrieval-augmented generation (RAG)</strong> lets a model answer using your own documents: loading content, splitting it into chunks, embedding those chunks, storing them in a vector store, and retrieving the most relevant ones for a given question before generating an answer.</p><h3>Agents</h3><p>LangChain also provides prebuilt <strong>agent</strong> abstractions — components that let a model decide, in a loop, which tools to call and when. Worth stating clearly: <strong>modern LangChain agents are built on top of LangGraph</strong> underneath — they aren’t a separate, competing execution model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKg3ttyXHfla_f4kGR0WQQ.png" /></figure><h3>LangGraph Fundamentals</h3><p><strong>LangGraph</strong> provides explicit, low-level control over <strong>stateful, multi-step workflows</strong> — built around three core ideas: <strong>state</strong>, <strong>nodes</strong>, and <strong>edges</strong>.</p><h3>State</h3><p>A shared, typed data structure passed between every step of the workflow, with each node able to read and update it.</p><pre>import { Annotation } from &quot;@langchain/langgraph&quot;;<br><br>const StateAnnotation = Annotation.Root({<br>  messages: Annotation(),<br>  step: Annotation(),<br>});</pre><h3>Nodes</h3><p>Individual processing steps — plain functions that receive the current state and return updates to it.</p><pre>function agentNode(state) {<br>  // run the model, decide what to do next<br>  return { step: &quot;decided&quot; };<br>}</pre><h3>Edges</h3><p>Connections defining execution order — including <strong>conditional edges</strong>, which route execution differently depending on the current state.</p><pre>import { StateGraph, START, END } from &quot;@langchain/langgraph&quot;;<br><br>const graph = new StateGraph(StateAnnotation)<br>  .addNode(&quot;agent&quot;, agentNode)<br>  .addNode(&quot;tool&quot;, toolNode)<br>  .addEdge(START, &quot;agent&quot;)<br>  .addConditionalEdges(&quot;agent&quot;, (state) =&gt; (state.step === &quot;needs_tool&quot; ? &quot;tool&quot; : END))<br>  .addEdge(&quot;tool&quot;, &quot;agent&quot;)<br>  .compile();<br><br>const result = await graph.invoke({ messages: [], step: &quot;start&quot; });</pre><h3>Deterministic vs. Model-Driven Branching</h3><p>Not every branching decision needs to be made by a model. If a workflow has a fixed requirement — for example, every request must retrieve documents before an answer is generated — that routing can remain deterministic in the graph or application code.</p><p>The model becomes useful when the next step depends on the content or meaning of what was retrieved. For example, after retrieving documents, a model might determine whether the evidence is sufficient to answer, whether more information is needed, or which narrower workflow should handle the request.</p><p>A practical rule is: <strong>put predictable workflow requirements in code, and use model judgment where the decision genuinely depends on unstructured or semantic information.</strong></p><h3>Graph execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RmKCniDWkZpse_TB-zx9w.png" /></figure><p>Unlike a straightforward, mostly linear LangChain pipeline, a LangGraph workflow can <strong>cycle</strong> — looping an agent back through a decision repeatedly — which is exactly the pattern most genuine agentic behavior needs: call the model, check if it wants a tool, run the tool, hand the result back, repeat until it’s actually done.</p><h3>LangChain vs. LangGraph: Architecture Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_n0Xqzp21r5k1lfNcaMUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddX0RBtQqvYdnP4m1ShaVg.png" /></figure><p><strong>Important clarification, stated directly:</strong> this comparison doesn’t mean LangChain “can’t” support agents or branching logic — its prebuilt agents genuinely handle tool-calling loops. LangGraph’s distinction is giving you <strong>explicit, fine-grained control</strong> over that same execution, which matters once a workflow’s logic grows complex enough that you need to see and control every step yourself.</p><h3>How LangChain and LangGraph Work Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGoOlIx7t3KGXTgw8fJaLQ.png" /></figure><p>In practice, LangGraph nodes very commonly <strong>use LangChain components internally</strong> — a node might call a LangChain-wrapped model, or run a LangChain retrieval step — while LangGraph handles the surrounding orchestration: what runs next, what state is shared, and whether execution can pause and resume. They aren’t competing choices; they’re two layers of the same stack.</p><h3>Building AI Applications with JavaScript and Node.js: Practical Examples</h3><h3>Example 1: Basic LangChain Chatbot</h3><pre>npm install @langchain/anthropic @langchain/core</pre><pre>import { ChatAnthropic } from &quot;@langchain/anthropic&quot;;<br>import { ChatPromptTemplate } from &quot;@langchain/core/prompts&quot;;<br><br>const model = new ChatAnthropic({ model: &quot;claude-sonnet-4-5&quot; });<br>const prompt = ChatPromptTemplate.fromMessages([<br>  [&quot;system&quot;, &quot;You are a helpful assistant.&quot;],<br>  [&quot;human&quot;, &quot;{input}&quot;],<br>]);<br><br>const chain = prompt.pipe(model);<br>const response = await chain.invoke({ input: &quot;What does npm stand for?&quot; });<br>console.log(response.content);</pre><h3>Example 2: Document Q&amp;A with LangChain (RAG)</h3><pre>import { MemoryVectorStore } from &quot;langchain/vectorstores/memory&quot;;<br>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;;<br><br>const vectorStore = await MemoryVectorStore.fromDocuments(chunks, new OpenAIEmbeddings());<br>const relevantDocs = await vectorStore.similaritySearch(&quot;How does the checkpointer work?&quot;, 3);<br><br>const context = relevantDocs.map(d =&gt; d.pageContent).join(&quot;\n&quot;);<br>const answer = await chain.invoke({ input: `Context: ${context}\n\nQuestion: How does the checkpointer work?` });</pre><h3>Example 3: Stateful LangGraph Workflow</h3><pre>import { StateGraph, Annotation, START, END } from &quot;@langchain/langgraph&quot;;<br><br>const State = Annotation.Root({ count: Annotation() });<br><br>const increment = (state) =&gt; ({ count: state.count + 1 });<br><br>const graph = new StateGraph(State)<br>  .addNode(&quot;increment&quot;, increment)<br>  .addEdge(START, &quot;increment&quot;)<br>  .addEdge(&quot;increment&quot;, END)<br>  .compile();<br><br>const result = await graph.invoke({ count: 0 }); // { count: 1 }</pre><h3>Example 4: Tool-Calling AI Agent</h3><pre>import { StateGraph, Annotation, START, END } from &quot;@langchain/langgraph&quot;;<br><br>const model = new ChatAnthropic({ model: &quot;claude-sonnet-4-5&quot; }).bindTools([getWeather]);<br><br>async function agentNode(state) {<br>  const response = await model.invoke(state.messages);<br>  return { messages: [...state.messages, response] };<br>}<br><br>function shouldCallTool(state) {<br>  const last = state.messages[state.messages.length - 1];<br>  return last.tool_calls?.length ? &quot;tool&quot; : END;<br>}<br><br>const graph = new StateGraph(Annotation.Root({ messages: Annotation() }))<br>  .addNode(&quot;agent&quot;, agentNode)<br>  .addNode(&quot;tool&quot;, toolNode) // runs the requested tool and appends its result<br>  .addEdge(START, &quot;agent&quot;)<br>  .addConditionalEdges(&quot;agent&quot;, shouldCallTool)<br>  .addEdge(&quot;tool&quot;, &quot;agent&quot;)<br>  .compile();</pre><h3>Example 5: Human-in-the-Loop Agent</h3><pre>import { MemorySaver, interrupt } from &quot;@langchain/langgraph&quot;;<br><br>const checkpointer = new MemorySaver();<br><br>function approvalNode(state) {<br>  const approved = interrupt({ question: &quot;Approve this action?&quot;, action: state.pendingAction });<br>  return { approved };<br>}<br><br>const graph = new StateGraph(State)<br>  .addNode(&quot;approval&quot;, approvalNode)<br>  // ...other nodes<br>  .compile({ checkpointer });<br><br>// Execution pauses at the interrupt; resume later with the human&#39;s decision</pre><p>interrupt() pauses graph execution at that exact point, persisting state via the configured checkpointer — execution resumes later, from precisely where it paused, once a human decision is supplied.</p><h3>Full-Stack Integration: Express.js, React, and External APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhYVTVNtInrHBBhmAQx0Zg.png" /></figure><p>A typical production shape: the <strong>frontend</strong> (React/Next.js) sends a user’s message to an <strong>Express.js</strong> endpoint; that endpoint invokes a <strong>LangGraph</strong> workflow, which internally uses <strong>LangChain</strong> components for the actual model calls and retrieval; results (and, where relevant, streamed tokens) flow back to the frontend, while checkpoint and application data persist separately.</p><pre>// Express route exposing the workflow<br>app.post(&quot;/api/chat&quot;, async (req, res) =&gt; {<br>  const result = await graph.invoke({ messages: [new HumanMessage(req.body.message)] });<br>  res.json({ reply: result.messages.at(-1).content });<br>});</pre><h3>Real-World Examples</h3><ul><li><strong>AI Customer Support Chatbot</strong> — LangChain handles model and tool integration; LangGraph manages the conversation’s persistent, multi-turn state</li><li><strong>AI Research Assistant</strong> — LangChain retrieval and search tools, orchestrated through LangGraph’s conditional execution based on what’s actually been found so far</li><li><strong>AI Travel Planning Assistant</strong> — a multi-step workflow (search flights → check dates → confirm budget → book) naturally modeled as a LangGraph graph, calling external APIs via LangChain tools at each step</li><li><strong>GitHub Issue Assistant</strong> — classifies an incoming issue, routes it through different handling paths, and pauses for human approval before taking a sensitive action (like closing or labeling) — a direct application of the human-in-the-loop pattern above</li></ul><h3>Important Comparisons</h3><ul><li><strong>LangChain vs. LangGraph</strong> — high-level application components versus low-level, explicit stateful orchestration</li><li><strong>Chain vs. Graph</strong> — pipeline-style execution versus explicit graph-based execution with cycles and branches</li><li><strong>LangChain Agent vs. Custom LangGraph</strong> — a prebuilt agent abstraction versus a fully customized workflow you design node by node</li><li><strong>Node vs. Edge</strong> — a processing step versus the connection defining what runs next</li><li><strong>State vs. Memory</strong> — the current workflow’s data at this point in execution, versus retained conversational or application context carried across separate interactions</li><li><strong>Conditional Routing vs. Fixed Execution</strong> — paths chosen based on current state, versus a single, predetermined sequence</li><li><strong>Checkpointing vs. Database Storage</strong> — snapshots of workflow execution state for pausing/resuming, versus general-purpose application data storage</li></ul><h3>Developer Connection</h3><ul><li><strong>JavaScript/TypeScript</strong> — build AI applications using familiar tooling and type safety</li><li><strong>Node.js</strong> — execute workflows and integrate model provider SDKs</li><li><strong>Express.js</strong> — expose chatbot and agent functionality as REST endpoints</li><li><strong>React/Next.js</strong> — build interactive interfaces, including streamed token responses</li><li><strong>Databases</strong> — manage application data and conversation records</li><li><strong>Vector Stores</strong> — enable retrieval and semantic search for RAG</li><li><strong>System Design</strong> — deliberately separate frontend, backend, orchestration, and model layers</li></ul><h3>Production Considerations</h3><ul><li>Secure model API keys and external service credentials via environment variables, never hardcoded</li><li>Add authentication and authorization to any exposed AI endpoint</li><li>Use persistent checkpointing (a real database-backed checkpointer, not just in-memory) for genuinely resumable workflows in production</li><li>Handle retries, timeouts, and tool execution failures explicitly — external calls fail, and workflows need to handle that gracefully</li><li>Monitor latency, token usage, and model costs, which can scale unpredictably with usage</li><li>Add tracing and logging across workflow steps for debugging multi-step execution</li><li>Apply rate limiting and request validation on any public-facing AI endpoint</li><li>Deploy Node.js services via containers or cloud platforms, as covered in this series’s deployment-adjacent articles</li><li>Scale stateless API workers independently from persistent workflow state, which typically lives in a shared store</li><li>Add human approval checkpoints before any sensitive external action, exactly as shown in Example 5</li></ul><h3>Common Mistakes and Misconceptions</h3><ul><li><strong>LangChain and LangGraph are not competing language models</strong> — both are frameworks for building LLM-powered applications</li><li><strong>LangGraph does not completely replace LangChain</strong> — they work together, and LangChain’s own agents are built on LangGraph</li><li><strong>LangChain is not limited to linear chains only</strong> — modern LangChain also provides agents with genuine tool-calling capabilities</li><li><strong>Not every chatbot requires LangGraph</strong> — simple applications may only need direct model calls or basic LangChain components</li><li><strong>LangGraph is not exclusively for multi-agent systems</strong> — it supports single-agent and general stateful workflows just as well</li><li><strong>Graph state is not automatically persistent</strong> — durable persistence requires a properly configured checkpointer and storage backend</li><li><strong>Not every workflow needs an autonomous agent</strong> — deterministic, explicitly-defined workflows handle many predictable tasks perfectly well</li><li><strong>Adding tools does not automatically make an agent production-ready</strong> — security, validation, monitoring, and failure handling all remain necessary</li></ul><h3>Conclusion</h3><p>LangChain and LangGraph address two related but distinct layers of building LLM-powered applications: LangChain supplies the high-level components — models, prompts, tools, retrieval — while LangGraph supplies explicit, stateful orchestration for anything more complex than a straightforward pipeline. They’re built to complement each other, not compete — LangChain’s own agents run on top of LangGraph underneath. For JavaScript developers, the practical choice usually isn’t “one or the other,” but recognizing when a workflow’s branching, state, or persistence needs genuinely call for LangGraph’s explicit control, versus when LangChain’s higher-level components are already enough — a decision worth making deliberately, the same way any architectural choice in this series has been, rather than defaulting to the most powerful tool available.</p><h3>Frequently Asked Questions</h3><p><strong>Should I start with LangChain or LangGraph for my first AI project?</strong></p><p>&gt; Start with LangChain’s basic model and prompt integration for a simple use case (Example 1 above) — reach for LangGraph once your workflow genuinely needs branching, cycles, shared state across steps, or pause/resume behavior that a straightforward pipeline can’t express cleanly.</p><p><strong>Do I need LangGraph if I’m only building a simple Q&amp;A chatbot?</strong></p><p>&gt; Probably not — a simple chatbot without multi-step branching or persistent state typically works fine with LangChain’s model and prompt components alone, without the added complexity of explicit graph orchestration.</p><p><strong>Can I use LangGraph without LangChain at all?</strong></p><p>&gt; Yes — LangGraph is built by the same team but designed to be usable independently. In practice, most JavaScript projects still use LangChain components (models, tools) inside LangGraph nodes, since it avoids reimplementing that integration work yourself.</p><p><strong>How do I decide between a LangChain prebuilt agent and a custom LangGraph workflow?</strong></p><p>&gt; Reach for a prebuilt LangChain agent when your use case fits its standard tool-calling loop pattern well. Build a custom LangGraph workflow when you need precise control over specific branches, custom state, human-in-the-loop approval steps, or execution patterns a prebuilt agent doesn’t directly support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3551e89e7bea" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/langchain-vs-langgraph-a-practical-javascript-developers-guide-3551e89e7bea">LangChain vs. LangGraph: A Practical JavaScript Developer’s Guide</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React.js Interview Questions: Beginner to Advanced]]></title>
            <link>https://towardsdev.com/react-js-interview-questions-beginner-to-advanced-fb5b81003910?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb5b81003910</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 21:36:01 GMT</pubDate>
            <atom:updated>2026-10-17T01:48:09.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGz8D_wIDjljA8zjAjnjGA.png" /></figure><p>A practical collection of React.js questions covering fundamentals, Hooks, performance, architecture, and real-world scenarios — organized from Beginner to Advanced, with coding and scenario-based questions kept separate for easier revision. Estimated reading time: 15–25 minutes.</p><h3>React.js Basics</h3><p><strong>Q: What is React, and why is it used?</strong></p><p>&gt; React is a JavaScript library for building user interfaces out of reusable, composable components. It’s used because it lets developers describe <em>what</em> the UI should look like for a given state, and lets React handle efficiently updating the actual browser DOM to match — rather than manually manipulating the DOM by hand.</p><p><strong>Q: What are React’s core features?</strong></p><p>&gt; A component-based architecture, a declarative programming model, the Virtual DOM (covered in depth later), one-directional data flow via props, and — in modern React — Hooks for managing state and side effects inside function components.</p><p><strong>Q: Is React a framework or a library?</strong></p><p>&gt; A library — it focuses specifically on the view layer. Routing, global state management, and other concerns are typically handled by separate, complementary libraries, unlike a full framework that bundles everything together by default.</p><p><strong>Q: What is React DOM, and how is it different from React?</strong></p><p>&gt; React provides the core UI programming model — components, state, the reconciliation algorithm. React DOM is the specific package that takes React’s output and renders it to the actual browser DOM. This distinction matters because React’s core model can target other renderers too (like React Native for mobile).</p><h3>Components &amp; JSX</h3><p><strong>Q: What is JSX?</strong></p><p>&gt; A syntax extension letting you write HTML-like markup directly inside JavaScript, compiled down to React.createElement() calls before it reaches the browser.</p><p><strong>Q: What is a component?</strong></p><p>&gt; A self-contained, reusable function that returns JSX describing a piece of UI — the fundamental building block of a React application.</p><p><strong>Q: What’s the difference between functional and class components?</strong></p><p>&gt; Functional components are plain functions using Hooks for state and lifecycle behavior — the modern, standard approach. Class components use ES6 classes with lifecycle methods (componentDidMount, etc.) and are mostly found in legacy codebases today.</p><p><strong>Q: Why do functional components with Hooks dominate modern React?</strong></p><p>&gt; Less boilerplate, easier logic reuse through custom Hooks, and no this binding confusion — interviewers commonly ask this to check you understand <em>why</em> the ecosystem shifted, not just that it did.</p><h3>Props &amp; State</h3><p><strong>Q: What are props, and what are they used for?</strong></p><p>&gt; Props (“properties”) are data passed <strong>into</strong> a component from its parent — read-only from the receiving component’s perspective, used to configure or supply data to a component.</p><p><strong>Q: What is state?</strong></p><p>&gt; Data a component owns and manages internally, which can change over time in response to user interaction — updating state triggers a re-render.</p><p><strong>Q: Props vs State — what’s the real difference?</strong></p><p>&gt; Props come from outside and are read-only; state is owned internally and mutable via its setter. A simple test: if a component receives the data from its parent, it’s a prop; if the component creates and updates it itself, it’s state.</p><p><strong>Q: Can a child component modify the props it receives?</strong></p><p>&gt; No — props are read-only from the child’s perspective. If a child needs to affect the parent’s data, the parent passes down a function (often via props) that the child calls, and the parent updates its own state in response.</p><p><strong>Q: How does data flow between a parent and child component?</strong></p><p>&gt; One-directionally: parent passes data down via props; a child can request a change by calling a function the parent also passed down — data itself never flows directly upward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1RguQpM69einhmBzabv4g.png" /></figure><h3>Hooks</h3><p><strong>Q: What is useState, and what does it return?</strong></p><p>&gt; A Hook that gives a function component a piece of persistent state. It returns a pair: the current value, and a setter function to update it and trigger a re-render.</p><p><strong>Q: What is useEffect used for?</strong></p><p>&gt; Synchronizing a component with something outside React’s own rendering — data fetching, subscriptions, timers, manual DOM work — running after render, based on its dependency array.</p><p><strong>Q: What does the dependency array in useEffect actually control?</strong></p><p>&gt; When the effect re-runs. An empty array means “run once, after the first render.” Listing specific values means “re-run whenever any of these change.” Omitting the array entirely means “run after every render.”</p><p><strong>Q: Is useEffect required for every piece of logic?</strong></p><p>&gt; No — this is a common misconception. Effects exist specifically for synchronizing with external systems. A value that can be computed directly from existing props or state during render shouldn’t be pushed into useEffect and a separate state variable.</p><p><strong>Q: What is useContext used for?</strong></p><p>&gt; Reading a value from the nearest matching Context Provider higher up the tree, without manually passing it down through every intermediate component as props (avoiding prop drilling).</p><p><strong>Q: What is useRef, and how is it different from useState?</strong></p><p>&gt; useRef returns a mutable object that persists across renders, but <strong>updating it does not trigger a re-render</strong> — commonly used for accessing DOM elements directly, or storing a value you need to persist without causing a re-render. useState is specifically for data that, when changed, should update the UI.</p><p><strong>Q: Does changing a ref’s value cause a re-render?</strong></p><p>&gt; No — this is a frequently tested misconception. Updating ref.current is silent to React&#39;s rendering system entirely; only state updates schedule a re-render.</p><p><strong>Q: What does useMemo do?</strong></p><p>&gt; Caches the <strong>result of an expensive calculation</strong> between renders, recomputing only when its listed dependencies change.</p><p><strong>Q: What does useCallback do?</strong></p><p>&gt; Caches a <strong>function reference</strong> between renders, useful specifically when that function is passed to a React.memo-wrapped child or into another Hook&#39;s dependency array, where a fresh reference every render would defeat memoization or cause unnecessary re-runs.</p><p><strong>Q: useMemo vs useCallback — what’s the actual difference?</strong></p><p>&gt; useMemo caches a <em>value</em>; useCallback caches a <em>function</em>. In fact, useCallback(fn, deps) is functionally equivalent to useMemo(() =&gt; fn, deps) — same underlying mechanism, shaped for two different use cases.</p><p><strong>Q: Should useMemo and useCallback always be used for performance?</strong></p><p>&gt; No — this is a very commonly tested misconception. They carry their own small overhead; apply them where you’ve identified a real, measured performance issue, not as a default habit on every value and function.</p><p><strong>Q: What is a custom Hook, and why would you build one?</strong></p><p>&gt; A plain function (conventionally named useSomething) that itself calls other Hooks internally — used to extract and reuse stateful logic (like a useWindowWidth or useFetch Hook) across multiple components, without duplicating that logic.</p><h3>Rendering &amp; Lifecycle</h3><p><strong>Q: Does every state update immediately change the DOM?</strong></p><p>&gt; No — a commonly tested misconception. React schedules the re-render and updates the real DOM efficiently, often batching multiple updates together, rather than synchronously touching the DOM the instant a state setter is called.</p><p><strong>Q: What causes a component to re-render?</strong></p><p>&gt; Its own state changing, its props changing, or its parent re-rendering — the third case is the most common source of <em>unnecessary</em> re-renders in a large app.</p><p><strong>Q: What is the Virtual DOM?</strong></p><p>&gt; A lightweight, in-memory JavaScript representation of the UI, letting React compare (diff) the previous and new versions cheaply before touching the actual, expensive browser DOM.</p><p><strong>Q: Virtual DOM vs Real DOM?</strong></p><p>&gt; The Real DOM is the browser’s actual, heavyweight live representation of the page. The Virtual DOM is React’s cheap, plain-object approximation used purely to calculate the <em>minimal</em> set of real DOM changes needed — it isn’t a replacement for the real DOM, just an optimization strategy sitting in front of it.</p><p><strong>Q: What is reconciliation?</strong></p><p>&gt; The process React uses to compare the old and new Virtual DOM trees and determine the smallest set of real changes actually needed, using heuristics (matching by type and position, or by key for lists) rather than a theoretically perfect diff.</p><p><strong>Q: What’s the difference between useEffect and useLayoutEffect?</strong></p><p>&gt; useEffect runs asynchronously, after the browser has painted. useLayoutEffect runs synchronously, <em>before</em> the browser paints — used specifically when you need to measure or mutate the DOM and want that change reflected before the user sees anything, at the cost of potentially blocking the paint.</p><h3>Forms &amp; Events</h3><p><strong>Q: How does event handling work in React?</strong></p><p>&gt; React wraps native browser events in its own synthetic event system, providing a consistent API across browsers. Handlers are attached via props like onClick, onChange, matching camelCase JSX conventions.</p><p><strong>Q: What are controlled components?</strong></p><p>&gt; Form inputs whose value is driven entirely by React state — every keystroke updates state, and the input’s displayed value comes from that state, giving React full, single-source-of-truth control over the form’s data.</p><p><strong>Q: What are uncontrolled components?</strong></p><p>&gt; Form inputs that manage their own internal state via the DOM directly, typically accessed through a ref when needed (like on form submission), rather than being synchronized with React state on every change.</p><p><strong>Q: Controlled vs Uncontrolled — when would you choose each?</strong></p><p>&gt; Controlled components are the standard default — needed for validation-as-you-type, conditional rendering based on input value, or keeping multiple inputs in sync. Uncontrolled components can simplify very basic forms where you only need the value at submission time, not on every keystroke.</p><p><strong>Q: How does conditional rendering work in React?</strong></p><p>&gt; Using standard JavaScript — ternaries, &amp;&amp;, or early returns inside the component function — to decide what JSX gets rendered based on the current props or state, rather than a special React-specific templating syntax.</p><p><strong>Q: Why does React need a key prop when rendering a list?</strong></p><p>&gt; Keys give React a stable identity for each list item across renders, letting it correctly match items when the list reorders, grows, or shrinks — not just to silence a console warning, but a genuine input into how reconciliation matches old and new list items correctly.</p><p><strong>Q: Is a key only needed to remove a React warning?</strong></p><p>&gt; No — a common misconception worth correcting directly. Without stable keys (or with array index used carelessly), React can misidentify which item is which across renders, causing real bugs like state or focus jumping to the wrong row.</p><h3>Routing &amp; APIs</h3><p><strong>Q: How does client-side routing work in a React app (e.g., with React Router)?</strong></p><p>&gt; It intercepts navigation, updating the URL and rendered components without a full page reload — matching the current URL against defined routes and rendering the corresponding component tree.</p><p><strong>Q: How do you fetch data in a React component?</strong></p><p>&gt; Typically inside a useEffect, calling fetch or a library like Axios, storing the result in state via useState, so the component re-renders once the data arrives.</p><pre>useEffect(() =&gt; {<br>  fetch(`/api/users/${id}`)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; setUser(data));<br>}, [id]);</pre><p><strong>Q: How do you handle loading and error states for an API call?</strong></p><p>&gt; Track them as additional state variables (loading, error), set appropriately at each stage of the request, and conditionally render UI based on their current value.</p><h3>State Management &amp; Context API</h3><p><strong>Q: What is prop drilling, and why is it a problem?</strong></p><p>&gt; Passing a prop through several intermediate components that don’t use it themselves, purely so it reaches a deeply nested component — it clutters components with irrelevant props and makes refactoring fragile.</p><p><strong>Q: What is the Context API used for?</strong></p><p>&gt; Sharing data across a component tree without manually threading it through every intermediate component as props — well suited to genuinely global, infrequently-changing data like authentication state or theme.</p><p><strong>Q: State vs Context — when do you reach for each?</strong></p><p>&gt; Local useState fits data used by one component or its close children. Context fits data needed broadly across unrelated parts of the tree, and changed relatively infrequently — not a replacement for local state in general.</p><p><strong>Q: Does Context replace the need for a dedicated state management library?</strong></p><p>&gt; Not universally — a common misconception. Context is useful for specific shared-data needs, but every consumer of a Context re-renders when its value changes, which can become a real performance concern for large, frequently-changing shared state.</p><h3>Performance Optimization</h3><p><strong>Q: What does React.memo do?</strong></p><p>&gt; Wraps a component so React skips re-rendering it if its props haven’t actually changed (via shallow comparison), even if its parent just re-rendered.</p><p><strong>Q: React.memo vs useMemo — what’s the distinction?</strong></p><p>&gt; React.memo memoizes an entire <strong>component</strong>, skipping its re-render. useMemo memoizes a <strong>value</strong> computed <em>within</em> a render that still happens — different granularity, solving related but distinct problems.</p><p><strong>Q: When does React.memo not help, or even hurt?</strong></p><p>&gt; On cheap, simple components, the props-comparison cost can outweigh just re-rendering. It also does nothing useful if the component receives new object/array/function references on every render — since those always fail the shallow comparison, regardless of their actual contents.</p><p><strong>Q: What causes unnecessary re-renders in a React app?</strong></p><p>&gt; Most commonly: a parent re-rendering and dragging unrelated children along with it by default, and new object/array/function references being created on every render, defeating memoization further down the tree.</p><p><strong>Q: What is code splitting, and why does it matter for performance?</strong></p><p>&gt; Breaking a JavaScript bundle into smaller chunks loaded on demand, rather than one large bundle loaded upfront — reducing the amount of JavaScript a user has to download before the app becomes interactive.</p><p><strong>Q: What is React.lazy, and how does it relate to Suspense?</strong></p><p>&gt; React.lazy lets you import a component lazily, only when it&#39;s actually needed. Suspense lets you declare a fallback (like a loading spinner) shown while that lazily-loaded component is still being fetched.</p><h3>Advanced Concepts</h3><p><strong>Q: What is a Higher-Order Component (HOC)?</strong></p><p>&gt; A function that takes a component and returns a new, enhanced component — a pattern for reusing component logic, largely predating Hooks, though still encountered in some codebases and libraries.</p><p><strong>Q: What are render props?</strong></p><p>&gt; A pattern where a component takes a function as a prop, which it calls to determine what to render — another pre-Hooks pattern for sharing logic between components, now often replaced by custom Hooks.</p><p><strong>Q: What are Portals used for?</strong></p><p>&gt; Rendering a component’s output into a different part of the actual DOM tree than its logical position in the React component tree — commonly used for modals, tooltips, or dropdowns that need to escape a parent’s overflow or z-index constraints.</p><p><strong>Q: What is Suspense, beyond lazy-loaded components?</strong></p><p>&gt; A mechanism for declaratively handling “this part of the tree isn’t ready yet” — originally for code splitting, and increasingly relevant for data fetching patterns in modern React as well.</p><h3>React Architecture and Organization</h3><p><strong>Q: How would you typically organize a mid-sized React application’s folder structure?</strong></p><p>&gt; Common approaches group by feature (all files for one feature together) or by type (all components, all hooks, all utils, in separate top-level folders) — feature-based organization tends to scale better as an app grows, since related files stay close together.</p><p><strong>Q: How do you decide where a piece of state should live?</strong></p><p>&gt; As close as possible to where it’s used, lifted up only as far as its lowest common ancestor that actually needs it — not defaulted to global state “just in case.”</p><h3>Practical Examples (Used to Frame Discussion Questions)</h3><ul><li><strong>Todo Application</strong> — demonstrates components, state, event handling, list rendering with keys, and controlled form inputs</li><li><strong>E-commerce Product Page</strong> — demonstrates props, state, API-driven data, routing between pages, and component composition</li><li><strong>Dashboard Application</strong> — demonstrates API calls, Context for shared data, reusable components, and performance considerations at scale</li><li><strong>Search/Filter Application</strong> — demonstrates controlled inputs, state management as filters change, re-render behavior, and optimization opportunities</li></ul><p>Interviewers frequently frame questions around scenarios like these directly — expect to be asked to reason through one of them out loud, not just define terms in isolation.</p><h3>Coding / Problem-Solving Questions</h3><p><strong>Q: Write a counter component using useState.</strong></p><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Q: Fix this code — why doesn’t the counter update correctly when clicked rapidly?</strong></p><pre>// Problematic: uses stale `count` from the render&#39;s closure<br>const increment = () =&gt; setCount(count + 1);<br><br>// Fixed: uses the functional update form, always working off the latest state<br>const increment = () =&gt; setCount(prev =&gt; prev + 1);</pre><p><strong>Q: Write a custom Hook that tracks whether the window is above a given width.</strong></p><pre>function useIsWide(minWidth = 768) {<br>  const [isWide, setIsWide] = useState(window.innerWidth &gt;= minWidth);<br><br>  useEffect(() =&gt; {<br>    const handleResize = () =&gt; setIsWide(window.innerWidth &gt;= minWidth);<br>    window.addEventListener(&quot;resize&quot;, handleResize);<br>    return () =&gt; window.removeEventListener(&quot;resize&quot;, handleResize);<br>  }, [minWidth]);<br><br>  return isWide;<br>}</pre><p><strong>Q: Given a list of items, render it correctly with keys, and explain your key choice.</strong></p><pre>{items.map(item =&gt; (<br>  &lt;li key={item.id}&gt;{item.name}&lt;/li&gt; // stable id, not array index<br>))}</pre><h3>Scenario-Based Questions</h3><p><strong>Q: A component re-renders every time its parent updates, even though its own props never change. How would you fix it?</strong></p><p>&gt; Wrap the component in React.memo. If it&#39;s still re-rendering, check whether it&#39;s receiving new object/array/function references as props each time — those need useMemo/useCallback on the parent side to actually stay stable.</p><p><strong>Q: You need to share the logged-in user’s data across many unrelated components. How would you approach it?</strong></p><p>&gt; Use Context for the shared identity — assuming it doesn’t change frequently. If performance becomes an issue as more consumers are added, consider splitting the Context into smaller, more focused pieces to limit unnecessary re-renders.</p><p><strong>Q: A search input feels laggy as the user types, because it triggers an API call on every keystroke. How would you address it?</strong></p><p>&gt; Debounce the input — only firing the actual API call after the user pauses typing for a short interval, rather than on every single keystroke.</p><p><strong>Q: Your app’s initial bundle is large and slows down first load. What would you consider?</strong></p><p>&gt; Code splitting with React.lazy and Suspense, loading routes or heavy components on demand rather than all upfront, and auditing for unnecessarily large dependencies.</p><h3>Common Mistakes and Misconceptions</h3><ul><li><strong>Props can be directly modified by a child</strong> — false; props are read-only from the receiving component’s side</li><li><strong>Every state update immediately changes the DOM</strong> — false; React schedules and batches updates efficiently</li><li><strong>useEffect is required for every piece of logic</strong> — false; it’s specifically for synchronizing with external systems</li><li><strong>useMemo and useCallback should always be used for performance</strong> — false; apply them where they provide a measurable benefit</li><li><strong>key is only needed to remove a warning</strong> — false; keys are a real input into correct reconciliation</li><li><strong>Changing a useRef value causes a re-render</strong> — false; ref updates are invisible to React’s rendering system</li><li><strong>Context automatically replaces every state-management solution</strong> — false; it fits specific shared-data needs, not everything</li><li><strong>React and React DOM are the same thing</strong> — false; React provides the UI model, React DOM handles browser rendering</li></ul><h3>Production Relevance</h3><p>React applications in production are commonly structured around reusable components, consuming dynamic data from APIs, with routing managing navigation between views. State-management patterns (local state, Context, or a dedicated library) handle shared application data at whatever scale the app actually needs. Code splitting and lazy loading help keep production bundles lean, and performance techniques (memoization, avoiding unnecessary re-renders) become genuinely important as component trees grow. Beyond the component code itself, production React applications also need proper error handling, monitoring, and deployment practices — the same production-mindedness covered throughout this series’s backend-focused articles applies just as much on the frontend.</p><h3>Quick Revision Checklist</h3><p>Before a React interview, make sure you can confidently explain:</p><ul><li>[ ] Props vs State, and why props are read-only</li><li>[ ] What each core Hook does: useState, useEffect, useContext, useRef, useMemo, useCallback</li><li>[ ] Why and when a component re-renders</li><li>[ ] Virtual DOM and reconciliation, at a conceptual level</li><li>[ ] Controlled vs Uncontrolled components</li><li>[ ] useMemo vs useCallback vs React.memo</li><li>[ ] useEffect vs useLayoutEffect</li><li>[ ] Why keys matter for list rendering</li><li>[ ] Context API — what it’s for, and its limits</li><li>[ ] Code splitting, React.lazy, and Suspense</li><li>[ ] Be ready to reason through at least one scenario-based performance or architecture question out loud</li></ul><h3>Final Takeaway</h3><p>React interviews tend to reward genuine understanding over memorized definitions — the difference between reciting “useEffect handles side effects” and being able to explain <em>why</em> a specific dependency array choice avoids a bug, or <em>why</em> a component keeps re-rendering unnecessarily. Fundamentals (props, state, JSX, components) build the foundation; Hooks, rendering behavior, and performance are where most modern interviews spend real time; and advanced concepts (HOCs, Portals, Suspense) show up mostly as depth-checks once the fundamentals are solid. Walking through this guide’s comparisons and scenario questions out loud, in your own words, is a far better use of prep time than memorizing definitions verbatim — that’s genuinely what interviewers are listening for.</p><h3>Frequently Asked Questions</h3><p><strong>How should I prioritize my prep time with limited days before an interview?</strong></p><p>&gt; Prioritize Props/State, Hooks (especially useState, useEffect, and the memoization Hooks), and rendering behavior first — these come up in nearly every React interview. Advanced patterns (HOCs, render props, Portals) are worth a lighter pass unless the role specifically calls for deep React expertise.</p><p><strong>Do I need to memorize class component lifecycle methods for modern interviews?</strong></p><p>&gt; Increasingly less critical, but still worth knowing at a conceptual level (mounting, updating, unmounting) since some codebases and some interviewers still reference them, and understanding how they map to useEffect shows genuine depth.</p><p><strong>Are coding questions in React interviews usually about algorithms or React-specific patterns?</strong></p><p>&gt; Typically React-specific — building a small component, fixing a bug involving stale state or incorrect dependencies, or writing a custom Hook — rather than generic algorithm questions, which are more common in separate data-structures-focused rounds.</p><p><strong>What’s the best way to practice scenario-based questions?</strong></p><p>&gt; Take a real feature you’ve built (or one of the practical examples in this guide) and practice explaining your component and state design decisions out loud, including tradeoffs you considered — that’s a very close simulation of how these questions actually get asked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb5b81003910" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/react-js-interview-questions-beginner-to-advanced-fb5b81003910">React.js Interview Questions: Beginner to Advanced</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolithic vs Microservices Architecture: Choosing the Right Approach]]></title>
            <link>https://towardsdev.com/monolithic-vs-microservices-architecture-choosing-the-right-approach-401889110fe5?source=rss-5f0d1e5b962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/401889110fe5</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Mr Madhukar]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 20:46:01 GMT</pubDate>
            <atom:updated>2026-09-29T13:57:57.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N41PIZcu4gswN269pgrUjQ.png" /></figure><h3>Software Architecture Basics</h3><p><strong>Software architecture</strong> is the high-level structure of how an application’s parts fit together — how code is organized, how components communicate, and how the whole system is built, deployed, and scaled. Two components that “work” individually can still form a poorly architected system if the way they’re organized makes the application hard to build on, deploy, or maintain over time.</p><p>Architecture decisions are felt long after they’re made — they shape how easy it is to add a feature, fix a bug, onboard a new developer, or scale under real traffic. <strong>Monolithic</strong> and <strong>Microservices</strong> architecture are two fundamentally different answers to the same underlying question: how should a large application actually be structured? Neither is automatically correct — this guide walks through both, using a single running example — an e-commerce application — throughout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXDYbEYgMwcP7d53PjgcJQ.png" /></figure><h3>What Is Monolithic Architecture?</h3><p>A <strong>monolithic</strong> application is built and deployed as <strong>one single, unified unit</strong> — all the functionality (users, orders, payments, products, in our e-commerce example) lives in one codebase, compiled and deployed together as a single application.</p><h3>Basic structure of a monolithic application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6dGnxNS4vcXEJQAhJ6_rg.png" /></figure><p>Internally, a well-organized monolith is still typically broken into logical modules or layers (as covered in this series’s Spring and Spring Boot article, for instance — Controller, Service, Repository) — but all of it runs as <strong>one process</strong>, deployed as <strong>one unit</strong>, sharing <strong>one database</strong>.</p><h3>The single-building analogy</h3><p>Think of a monolith like one large <strong>department store</strong> — everything (electronics, groceries, clothing) is under one roof, managed by one staff, sharing one set of shelves and one checkout system. It’s simple to walk through and manage as a whole, but expanding just the electronics section still means renovating part of the same single building.</p><h3>What Is Microservices Architecture?</h3><p><strong>Microservices</strong> architecture splits an application into <strong>multiple independent services</strong>, each responsible for one specific piece of functionality, each deployable, scalable, and maintainable <strong>separately</strong> from the others.</p><h3>Basic structure of a microservices-based application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5xtrpM1EVy8RPswce9-uw.png" /></figure><p>Each service in our e-commerce example — Users, Orders, Payments, Products — runs as its <strong>own independent application</strong>, often with its own dedicated database, communicating with the others over the network rather than through direct in-process function calls.</p><h3>The independent shops analogy</h3><p>Think of microservices like a <strong>shopping street</strong> made up of separate, independently run shops — an electronics store, a grocery store, a clothing store — each with its own staff, its own inventory system, its own hours. Expanding the electronics shop doesn’t require touching the grocery store at all. But now a customer buying items from multiple shops has to walk between them, and the street as a whole needs some kind of coordination (signage, shared parking) to feel like one coherent shopping experience.</p><h3>Monolithic vs Microservices: Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TddfM0-yXnb6Q9Qlg82FkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR29B1nql6IUyno1edN81A.png" /></figure><h3>How Communication Works Between Microservices</h3><p>Since microservices don’t share memory or run in the same process, they communicate over the <strong>network</strong> — most commonly through REST APIs (covered extensively elsewhere in this series), or asynchronous messaging systems (like Kafka, also covered in this series) for event-driven communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*357F1NHoe229xUeAYiv6Xg.png" /></figure><p>An <strong>API Gateway</strong> commonly sits in front of all the services, acting as a single entry point for clients — routing incoming requests to the correct internal service, so the client doesn’t need to know the internal structure of the system at all.</p><h3>Advantages and Limitations of Both Architectures</h3><h3>Monolithic: advantages</h3><ul><li>Simpler to develop, test, and deploy, especially early on</li><li>No network latency between internal components — everything communicates in-process</li><li>Easier to reason about as a whole, with fewer moving parts to coordinate</li></ul><h3>Monolithic: limitations</h3><ul><li>Scaling means scaling the <strong>entire</strong> application, even if only one part actually needs more capacity</li><li>A bug or crash in one part can potentially affect the whole application</li><li>Large monoliths can become harder to navigate and modify safely as they grow</li></ul><h3>Microservices: advantages</h3><ul><li>Each service can be scaled, deployed, and updated <strong>independently</strong></li><li>Teams can work on separate services in parallel, with clearer ownership boundaries</li><li>A failure in one service doesn’t necessarily bring down the entire system</li></ul><h3>Microservices: limitations</h3><ul><li>Genuine distributed-system complexity: network calls can fail, latency is introduced, debugging spans multiple services</li><li>Operational overhead: more deployments, more monitoring, more infrastructure to manage</li><li>Data consistency across separate databases becomes a real, non-trivial design concern</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ckp7xu4Yl0IvbN-9nKjx2g.png" /></figure><h3>When Should a Project Use Monolithic Architecture?</h3><ul><li>Early-stage products or startups still figuring out core requirements, where speed of iteration matters most</li><li>Smaller teams, where the coordination overhead of multiple independent services isn’t yet justified</li><li>Applications without dramatically different scaling needs across their different features</li></ul><h3>When Should a Project Consider Microservices?</h3><ul><li>Large, established applications with genuinely different scaling needs across different features (a payments service handling far more load than an admin dashboard, for instance)</li><li>Larger engineering organizations where multiple independent teams need to own and deploy their own services without blocking each other</li><li>Systems where specific parts need independent reliability guarantees or specialized infrastructure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phpI5vymqZWGMgpNgajJuA.png" /></figure><h3>How Architecture Affects Scalability, Deployment, and Maintenance</h3><h3>Scalability</h3><p>A monolith scales <strong>vertically or as a whole unit</strong> — running more copies of the entire application, even if only one feature is under heavy load. Microservices scale <strong>individual services independently</strong> — if the Payment Service is under heavy load during a sale, only it needs additional instances, not the entire application.</p><h3>Deployment</h3><p>A monolith typically means <strong>one deployment pipeline</strong>, releasing the whole application together — simpler, but a small change anywhere requires redeploying everything. Microservices allow <strong>independent deployments</strong> — a Product Service update doesn’t require redeploying the Payment Service at all.</p><h3>Maintenance</h3><p>A monolith’s shared codebase can make it easier to trace a bug across features initially, but harder to safely change as it grows large. Microservices isolate changes to individual services, but require more careful attention to how those services interact and stay compatible with each other.</p><h3>Role of Databases, APIs, Containers, and Cloud in Both Approaches</h3><ul><li><strong>Databases</strong> — a monolith typically shares one database across all its modules; microservices often practice <strong>data ownership</strong>, where each service manages its own dedicated database, chosen specifically for that service’s needs</li><li><strong>APIs</strong> — both approaches use APIs to communicate with external clients; microservices additionally rely heavily on internal APIs for service-to-service communication</li><li><strong>Containers</strong> (like Docker) — commonly used to package and run each microservice consistently and independently; also useful for monoliths, though less essential to the architecture itself</li><li><strong>Cloud platforms</strong> — enable both approaches to run reliably, but microservices particularly benefit from cloud infrastructure’s ability to scale individual services and manage many independent deployments</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzhV-D-31UzDkpduHyVx0w.png" /></figure><h3>Practical Examples</h3><h3>E-commerce Application</h3><ul><li><strong>Monolith:</strong> Users, Orders, Payments, and Products all live in one application, sharing one database — simple to build initially, but a traffic spike during a sale (hitting Orders and Payments hardest) forces scaling the entire application, including parts (like Products browsing) that aren’t under the same pressure.</li><li><strong>Microservices:</strong> Each of Users, Orders, Payments, and Products runs independently — during a sale, only the Order and Payment services need to scale up, while Users and Products stay at normal capacity.</li></ul><h3>Food Delivery Platform</h3><p>A food delivery platform naturally separates into distinct concerns: <strong>Restaurants</strong> (menus, availability), <strong>Orders</strong> (placing and tracking), <strong>Delivery</strong> (driver assignment, live location), and <strong>Payments</strong>. As independent services, Delivery — which needs to handle constant, real-time location updates — can be scaled and optimized separately from something like Restaurant menu browsing, which has very different traffic patterns.</p><h3>Banking Application</h3><p>Banking systems illustrate <strong>service separation for reliability and security</strong> particularly well: a Transactions service handling money movement might have far stricter reliability, auditing, and security requirements than a Customer Support or Notifications service. Microservices let these be developed, secured, and scaled according to their genuinely different requirements, rather than treating every part of the system identically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XW2Dq-xjhrFHLNtn90EjIg.png" /></figure><h3>Important Comparisons</h3><h3>Monolithic vs Microservices</h3><p>A single, unified application versus a set of independently deployable services — the core structural distinction underlying every other comparison in this article.</p><h3>Centralized Database vs Service-Specific Data</h3><p>A monolith typically shares one database across all its modules. Microservices commonly practice independent data ownership — each service manages its own data, chosen and structured specifically for that service’s needs, at the cost of needing careful coordination for data that spans multiple services.</p><h3>Single Deployment vs Independent Deployment</h3><p>A monolith releases as one unit — every change ships together. Microservices allow each service to be released on its own schedule, independently of the others.</p><h3>Vertical Scaling vs Independent Service Scaling</h3><p>A monolith scales by running more copies of the whole application (or a more powerful single instance). Microservices scale by adding capacity specifically to the services that actually need it.</p><h3>Simple Communication vs Distributed Communication</h3><p>A monolith’s components talk to each other through direct, in-process function calls — fast, reliable, no network involved. Microservices communicate over the network, introducing latency, potential failures, and the need for resilience strategies that simply aren’t a concern inside a single process.</p><h3>Simple Operations vs Distributed-System Complexity</h3><p>Running one application is operationally simpler than running, monitoring, and coordinating many independent services — microservices trade that operational simplicity for organizational and scaling flexibility.</p><h3>Developer Connection</h3><ul><li><strong>Backend</strong> — application structure, business logic organization, and how services or modules are divided</li><li><strong>APIs</strong> — the communication layer both within a microservices system and between any architecture and its clients</li><li><strong>Databases</strong> — how data is organized and owned, especially critical in microservices</li><li><strong>Networking</strong> — service-to-service communication becomes a first-class concern in microservices</li><li><strong>DevOps</strong> — independent builds, deployments, and CI/CD pipelines, especially relevant for microservices</li><li><strong>Cloud</strong> — running and scaling individual services or a whole application</li><li><strong>System Design</strong> — the actual decision-making process of choosing an architecture based on real requirements</li><li><strong>Scalability</strong> — understanding precisely which parts of an application genuinely need to scale, and why</li></ul><h3>Production and Real-World Considerations</h3><ul><li>Monolithic applications are commonly deployed as a single application or server unit — straightforward, with well-understood tooling</li><li>Microservices can be deployed and scaled independently, often via containers (Docker) orchestrated across cloud infrastructure</li><li><strong>Load balancing</strong> distributes traffic across multiple instances — of either a monolith or individual microservices</li><li><strong>API gateways</strong> manage and route external requests across multiple internal services in a microservices setup</li><li><strong>Monitoring and logging</strong> become especially critical in distributed systems, where a single user request might span several services, and tracing a problem requires visibility across all of them</li><li><strong>Database design</strong> grows more important the moment services have separate data ownership — decisions about consistency, duplication, and cross-service queries all become real architectural questions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lK0rB5zJ5tPX3DdgZGqDw.png" /></figure><h3>Common Mistakes and Misconceptions</h3><ul><li><strong>Microservices are not always better than monoliths</strong> — architecture should match the project’s actual requirements, not follow a trend</li><li><strong>A monolith does not mean bad architecture</strong> — a well-designed monolith can be genuinely effective and maintainable</li><li><strong>Microservices don’t automatically make an application faster</strong> — their real benefits are organizational, deployment, and scaling flexibility, not raw speed</li><li><strong>Microservices are not simply “many small classes or modules”</strong> — they are independently deployable services communicating over a network, a fundamentally different concern from internal code organization</li><li><strong>Not every small project needs microservices</strong> — they can add unnecessary complexity to applications that don’t actually need that level of independence</li><li><strong>Splitting into services doesn’t eliminate complexity</strong> — it often moves complexity into networking, deployment, monitoring, and data management instead</li><li><strong>Microservices don’t always require completely separate databases</strong> — data ownership and database strategy depend on the specific system’s design, not a fixed rule</li></ul><h3>Choosing the Right Approach</h3><p>There’s no universally correct answer — the right architecture depends on your team’s size, your application’s actual scaling needs, and how much operational complexity you’re genuinely prepared to take on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*paakkFXiq7sCG15Z8_abJg.png" /></figure><p>Many successful systems also <strong>start as a monolith</strong> and evolve toward microservices only once genuine, specific pain points (scaling bottlenecks, team coordination friction) actually emerge — rather than starting with microservices’ full complexity before the project has earned the need for it.</p><h3>Final Takeaway</h3><p>Monolithic and microservices architecture answer the same fundamental question — how should an application be structured — with two genuinely different, valid tradeoffs. A monolith keeps everything unified: simpler to build, deploy, and reason about, at the cost of scaling and deploying as one indivisible unit. Microservices split functionality into independent, separately scalable and deployable services, at the cost of real distributed-system complexity — network communication, data ownership, and significantly more operational overhead. Neither is a mark of “good” or “bad” engineering on its own; the right choice depends entirely on your team, your application’s actual requirements, and how much complexity your project has genuinely earned the need to take on. Understanding both deeply — not favoring one as automatically superior — is what actually lets you make that call well.</p><h3>Frequently Asked Questions</h3><p><strong>Should every new project start with microservices to avoid rewriting later?</strong></p><p>&gt; Not necessarily — many successful systems deliberately start as a monolith, since it’s faster to build and iterate on early, and migrate toward microservices only once specific, genuine pain points justify the added complexity. Starting with microservices before that need exists often just adds overhead without a corresponding benefit.</p><p><strong>Can a monolith and microservices coexist in the same system?</strong></p><p>&gt; Yes — many real-world systems are genuinely a hybrid, with a core monolith handling most functionality and select high-scale or independently-owned features split out as separate services, rather than a strict, all-or-nothing choice.</p><p><strong>Do microservices always need Docker or Kubernetes?</strong></p><p>&gt; Not strictly required, but containers (like Docker) are extremely commonly used to package microservices consistently, and orchestration tools (like Kubernetes) help manage many independent services at scale — they’re a natural fit for the architecture, even if not an absolute technical requirement.</p><p><strong>Is it harder to test a microservices-based application than a monolith?</strong></p><p>&gt; Generally, yes, in certain ways — testing interactions across independent services (integration and end-to-end testing) introduces complexity that doesn’t exist when everything runs in a single process, even though testing each individual service in isolation can actually be simpler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401889110fe5" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/monolithic-vs-microservices-architecture-choosing-the-right-approach-401889110fe5">Monolithic vs Microservices Architecture: Choosing the Right Approach</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>