<?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 Animesh Mishra on Medium]]></title>
        <description><![CDATA[Stories by Animesh Mishra on Medium]]></description>
        <link>https://medium.com/@ani05?source=rss-127ea839ba82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fXJEqoxIPJseJy2AATtu6Q.jpeg</url>
            <title>Stories by Animesh Mishra on Medium</title>
            <link>https://medium.com/@ani05?source=rss-127ea839ba82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:03:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ani05/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[Cors]]></title>
            <link>https://medium.com/@ani05/cors-7bda3a34ade5?source=rss-127ea839ba82------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bda3a34ade5</guid>
            <dc:creator><![CDATA[Animesh Mishra]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 16:59:51 GMT</pubDate>
            <atom:updated>2026-06-15T16:59:51.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>Browsers enforce the Same-Origin Policy by default — scripts on domain A cannot access resources on domain B. This protects users from malicious cross-site requests, but blocks legitimate API calls between domains.</p><h3>Core Idea</h3><p>CORS (Cross-Origin Resource Sharing) is a mechanism that lets servers explicitly declare which domains (origins) can access their resources and under what conditions.</p><h3>How It Works</h3><h3>Simple Request Flow</h3><p>For simple requests (GET/POST/HEAD with standard headers):</p><ol><li>Client sends request with Origin header</li><li>Server checks policy, responds with Access-Control-Allow-Origin</li><li>Browser allows/blocks response based on header</li></ol><h3>Pre-flight Request Flow</h3><p>For non-simple requests (PUT, DELETE, custom headers, non-standard Content-Type):</p><ol><li>Browser sends OPTIONS request first (pre-flight)</li><li>Server responds with allowed methods, headers, and origins</li><li>Browser caches this (via Access-Control-Max-Age)</li><li>Then sends actual request</li></ol><h3>Key Headers</h3><p>Header Purpose Origin Client&#39;s domain (sent by browser) Access-Control-Allow-Origin Allowed origins (server) Access-Control-Allow-Methods Allowed methods (server) Access-Control-Allow-Headers Allowed headers (server) Access-Control-Max-Age Cache duration for pre-flight</p><pre>@Configuration<br>public class CorsConfig implements WebMvcConfigurer {<br>    @Override<br>    public void addCorsMappings(CorsRegistry registry) {<br>        registry.addMapping(&quot;/api/**&quot;)<br>            .allowedOrigins(&quot;http://localhost:5173&quot;)<br>            .allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;)<br>            .allowedHeaders(&quot;*&quot;)<br>            .allowCredentials(true);<br>    }<br>}</pre><h3>Key Properties</h3><ul><li>Server controls access — not the client</li><li>Pre-flight caching reduces overhead</li><li>Credentials require specific origin (not ‘*’)</li></ul><h3>Connections</h3><ul><li><strong>Related to:</strong> <a href="https://medium.com/http-headers">HTTP Headers</a> (uses headers for negotiation: Access-Control-Allow-Origin)</li><li><strong>Builds on:</strong> <a href="https://medium.com/http-methods">HTTP Methods</a> (OPTIONS is the pre-flight method)</li><li><strong>Related to:</strong> HTTP Status Codes (401, 403 errors appear in CORS failures)</li><li><strong>Related to:</strong> Statelessness (CORS requests must include all auth per request)</li></ul><h3>Edge Cases &amp; Gotchas</h3><ul><li>CORS errors in browser console ≠ server error; request reached server</li><li>Preflight required for PUT, DELETE, PATCH methods</li><li>Authorization header triggers pre-flight (custom header)</li><li>Misconfiguration appears as “blocked by CORS policy”</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bda3a34ade5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[curl]]></title>
            <link>https://medium.com/@ani05/curl-3e5f8fcf404a?source=rss-127ea839ba82------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5f8fcf404a</guid>
            <dc:creator><![CDATA[Animesh Mishra]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 16:58:35 GMT</pubDate>
            <atom:updated>2026-06-15T16:58:35.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>How do you test backend APIs directly without building a front end? How do you inspect what’s actually sent over the wire? curl provides a CLI interface to speak HTTP directly — essential for backend development and debugging.</p><h3>Core Idea</h3><p>curl is a command-line tool that sends HTTP requests and prints the response. It bypasses browsers — you can directly test endpoints, inspect headers, send POST data. It’s the backend developer’s direct connection to the server.</p><h3>How It Works</h3><ol><li><strong>Parse URL</strong>: curl extracts protocol, domain, port, path from the URL</li><li><strong>DNS Lookup</strong>: Resolves domain to IP address</li><li><strong>Socket Connection</strong>: Opens TCP socket to IP:port</li><li><strong>TLS Handshake</strong>: For HTTPS, establishes encrypted connection</li><li><strong>Send Request</strong>: Writes raw HTTP request text to socket</li><li><strong>Receive Response</strong>: Reads response from server and prints to terminal</li></ol><p>Example: curl https://example.com sends GET / HTTP/1.1 and prints the HTML response.</p><h3>Key Properties</h3><ul><li>CLI tool available on all major operating systems</li><li>Supports multiple protocols: HTTP, HTTPS, FTP, etc.</li><li>Options: -X (method), -H (headers), -d (body), -v (verbose)</li><li>Great for API testing: curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;:&quot;ani&quot;}&#39; <a href="https://api.example.com/">https://api.example.com</a></li><li>-v flag shows full request/response headers and connection details</li><li>Does not execute JavaScript like browsers do</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5f8fcf404a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend from First Principles: Part 2 :- API and server]]></title>
            <link>https://medium.com/@ani05/backend-from-first-principles-part-2-api-and-server-5a5e2669b298?source=rss-127ea839ba82------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5e2669b298</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Animesh Mishra]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 09:55:10 GMT</pubDate>
            <atom:updated>2026-03-16T04:49:42.688Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Backend from First Principles: Part 2 :- API and server</strong></p><p><em>Date: 2026 | Estimated Reading Time: around 20 min | Author: Animesh Mishra</em></p><p><strong>Table of Contents</strong></p><ol><li>What is an API</li><li>REST</li><li>SOAP</li><li>GraphQL</li><li>gRPC</li><li>WebSockets</li><li>WebRTC</li><li>How a Server Actually Handles Requests</li><li>The Event Loop vs. Threaded Concurrency</li><li>The Internal Journey of a Request</li><li>Summary</li></ol><p>In Part 1, we traced how data travels from a browser across the internet to a server. We covered TCP, DNS, HTTP, TLS, and headers. We understood the rules of the road.</p><p>But we stopped right at the edge of the server. We never asked: what happens when a request actually arrives? What does a server do with it? And more importantly, what is a server even doing when thousands of requests arrive at the same moment?</p><p>This part answers those questions. It also expands backward to cover something I skimmed past in Part 1: the different styles of communication an API can use, and why each one was invented. Most backend tutorials start with REST and stop there. That is a significant gap because REST is one answer to a question that has at least six different serious answers, each designed for a different problem.</p><p>I want to understand all of them properly, and I want to understand how a server handles all of it at scale.</p><p>took a lot of time to post this, but it took me a lot of time and I procastinated too so.I am writing So I myself will be using this when I’ll be revising APIs. Let’s continue</p><p>An API, or Application Programming Interface, is a defined set of rules through which one system exposes functionality or data to another system in a controlled way.</p><p>The keyword is controlled. A system’s internal database, business logic, and infrastructure are private by design. An API creates a deliberate boundary: here is what you are allowed to ask for, here is the format you must use to ask, and here is what you will receive in return.</p><p>The most important property an API provides is decoupling. Consider a company that exposes user account data to a mobile application. Internally, the company might store this data across five different database tables, in a format optimized for storage rather than retrieval. The API abstracts all of that. The mobile app sends a request for user data, the API gathers what it needs from wherever it needs it, and returns a clean, well-shaped response. If the company later migrates its entire database to a different system, the mobile app notices nothing as long as the API’s external behavior stays the same.</p><p>This separation between internal reality and external contract is the fundamental value of an API. Everything else is implementation detail.</p><p>There are several distinct communication styles used to build APIs. They are not interchangeable. Each emerged to solve a specific class of problem, and choosing the wrong one for a given situation creates real pain at scale. I want to go through each one properly.</p><p><strong>2. REST: Constraints That Won the Web</strong></p><p><strong>2.1 Origin and Intent</strong></p><p>REST is not a protocol or a technology. It is a set of architectural constraints on how communication should be designed. Roy Fielding, who had co-designed the HTTP protocol itself, published REST as part of his doctoral dissertation in 2000 [1]. His argument was that the web had an elegant, scalable architecture already, and that API design should follow the same principles rather than inventing new ones.</p><p>The name, Representational State Transfer, is academic and confusing. The idea is clean: every piece of data a server manages is a resource, each resource has a unique address, and you interact with resources using the HTTP verbs that already exist.</p><p><strong>2.2 The Six Constraints</strong></p><p>Fielding defined six constraints that make a system RESTful. They are worth knowing properly because most developers learn REST by syntax rather than by principle.</p><p><strong>Statelessness</strong> is the most important constraint and the most commonly misunderstood. Every request from a client to a server must contain all information needed to process that request. The server must not store any session state between requests. <em>If you make a request to retrieve your orders, that request must carry your authentication credentials. The server does not remember that you authenticated five minutes ago.</em></p><p>This constraint is what makes REST systems horizontally scalable. If the server remembers nothing about past requests, then any server in a cluster can handle any request from any client. You can add ten more machines tomorrow and route traffic between them freely.</p><p><strong>Uniform Interface</strong> enforces consistent conventions across all resources. Resources are identified by URI. Resources are manipulated through their representations, not directly. Messages are self-descriptive. This predictability is why a developer who has never seen a particular REST API can usually figure out how to use it in minutes.</p><p><strong>Client-Server Separation</strong> enforces that client and server evolve independently. The client does not know how the server stores data. The server does not know how the client displays it. This separation lets both sides be developed, deployed, and scaled independently.</p><p><strong>Cacheability</strong> requires that responses explicitly declare whether they can be cached. This allows clients and intermediaries to store responses and avoid repeating identical requests. GET requests for resources that rarely change can be cached aggressively, dramatically reducing server load.</p><p><strong>Layered System</strong> means the client does not need to know if it is speaking directly to the server or to an intermediary like a load balancer or a CDN. This invisibility allows infrastructure layers to be added, removed, or modified without affecting clients.</p><p><strong>Code on Demand</strong> (optional) allows servers to send executable code to clients. This constraint is rarely used in practice and is the only optional one.</p><p><strong>2.3 How It Works</strong></p><p>A REST API structures communication around nouns (resources) and uses HTTP verbs to express actions on those nouns.</p><p><em>Fetching user 42: GET /users/42</em> <em>Creating a new user: POST /users</em> <em>Updating user 42: PUT /users/42</em> <em>Deleting user 42: DELETE /users/42</em></p><p>The response carries an HTTP status code indicating what happened, headers with metadata, and a body with the resource representation, usually JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*xCrwW4jw8KcDfgp4YMgXrw.png" /><figcaption>REST architecture</figcaption></figure><p><strong>2.4 Where REST Breaks Down</strong></p><p>REST works well when the shape of data needed by every client is predictable and consistent. It struggles when different clients need radically different shapes of the same data, because each endpoint returns a fixed structure regardless of what the client actually needs. It also has no native mechanism for the server to push data to the client. Every interaction is client-initiated. For anything requiring real-time updates, REST requires the client to poll, which is wasteful.</p><p><strong>3. SOAP: The Protocol Built for Contracts</strong></p><p><strong>3.1 Origin and Intent</strong></p><p>SOAP predates REST as a widely adopted standard. The first SOAP specification was published in 2000, though an earlier version released in 1998 was known as XML-RPC. It was designed for enterprise environments where the cost of ambiguity was high: banking, healthcare, government, insurance. Places where two systems exchanging data need absolute certainty about every field, every type, and every error case.</p><p>Where REST treats communication as resource access, SOAP treats it as procedure calls. You are not fetching a resource. You are calling a named function on a remote machine and receiving a structured result. This model is called Remote Procedure Call, and SOAP is a highly structured XML-based implementation of it [2].</p><p><strong>3.2 Message Structure</strong></p><p>A SOAP message consists of an optional SOAP header and a mandatory SOAP body, both incorporated into the SOAP envelope. Every SOAP message, regardless of what it contains, follows this structure exactly.</p><p>The <strong>Envelope</strong> is the root element of every message. It declares the document as a SOAP message and defines the namespaces in use.</p><p>The <strong>Header</strong> carries metadata about the message: authentication tokens, routing instructions, transaction identifiers. It is optional but commonly used in enterprise integrations.</p><p>The <strong>Body</strong> contains the actual payload, the function call and its parameters, or the response and its values. It is mandatory.</p><p>The <strong>Fault</strong> element appears inside the Body when something goes wrong. It carries a standardized error code, a human-readable description, and optionally additional detail. Error handling is built into the protocol itself, not left to convention.</p><p><strong>3.3 WSDL: The Machine-Readable Contract</strong></p><p>SOAP services publish a document called a WSDL, Web Services Description Language. A WSDL is machine-readable and describes how to call a web service, defines the operations available, and specifies what input and output fields to expect. A client reads this document before sending a single request and knows exactly what it is allowed to do.</p><p>This strict contractual definition is SOAP’s greatest strength in enterprise contexts. When a bank connects to a payment processor via SOAP, both sides have read the same WSDL. There is no ambiguity about field names, types, or error formats. The contract is enforced at the protocol level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*K08qIRpFY7TYCV80f-IdrA.png" /><figcaption>SOAP architecture</figcaption></figure><p><strong>3.4 The Tradeoff</strong></p><p>The absence of overhead text in plain JSON compared to bulky XML in SOAP results in substantial size reduction. A REST API’s JSON file is easier and faster to process and transfer. A SOAP message carrying ten bytes of actual data might wrap it in hundreds of bytes of XML envelope. At massive scale, this overhead becomes a real cost in bandwidth and parsing time.</p><p>SOAP is rarely used in new systems today. It is deeply embedded in legacy enterprise infrastructure and you will encounter it in banking integrations, healthcare systems, and government services. Understanding it is about not being lost when you find it, which you will.</p><p><strong>4. GraphQL</strong></p><p><strong>4.1 Origin and Intent</strong></p><p>GraphQL was developed internally at Facebook in 2012 and open-sourced in 2015 [3]. The problem it solved was specific: Facebook’s mobile apps were running on slow connections, and the data needs of each screen were so different from one another that REST’s fixed resource structure was actively hurting performance.</p><p><em>A news feed screen needs post content, author names, comment counts, and reaction totals. A profile screen needs bio, follower count, recent posts, and tagged photos. A notification screen needs actor names, action types, and timestamps.</em> In REST, each of these screens would need multiple round trips, and each response would return far more data than the screen actually needed.</p><p>GraphQL inverts the control model. Instead of the server deciding what each endpoint returns, the client sends a precise description of exactly what it needs and receives exactly that, nothing more and nothing less.</p><p><strong>4.2 How It Works</strong></p><p>A GraphQL server exposes a single endpoint, typically POST /graphql. The server publishes a schema: a complete description of every type of data it knows about, the fields on each type, and the relationships between types.</p><p>The client writes a query against this schema. <em>“Give me the name, profile photo, and last three post titles for user 42.”</em> The server receives this query, resolves it by pulling from whatever data sources it needs, assembles exactly the shape requested, and returns it in a single response.</p><p>The <strong>resolver</strong> is the unit of work in GraphQL. Every field in the schema has a corresponding resolver function that knows how to fetch that specific piece of data. When a query arrives, the server calls the appropriate resolvers, assembles their results into the requested shape, and returns the whole thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1x4uo3WNXurZisqhDislQ.png" /><figcaption>GraphQL architecture</figcaption></figure><p><strong>4.3 Where GraphQL Excels and Where It Does Not</strong></p><p>GraphQL is most valuable when many different clients with different data needs talk to the same backend. A web app, a mobile app, and a third-party integration can all query the same GraphQL API and each receive precisely what they need.</p><p>The management challenge is the schema. It becomes the central contract that everything depends on. Changing a field name or removing a field has downstream effects on every client that uses it. Schema versioning and deprecation require careful process. GraphQL is overkill for a simple internal service that does five predictable things.</p><p><strong>5. gRPC: Binary Speed for Internal Systems</strong></p><p><strong>5.1 Origin and Intent</strong></p><p>gRPC was built by Google and open-sourced in 2015 [4]. The motivation was performance between internal services. Google passes billions of messages per day between its systems. The size and parsing cost of JSON at that scale adds up to real latency and real infrastructure cost.</p><p>gRPC makes two fundamental changes to how communication works: it replaces JSON with a binary encoding format called Protocol Buffers, and it runs over HTTP/2 instead of HTTP/1.1. Both changes compound to produce communication that is measurably faster and cheaper at scale.</p><p><strong>5.2 Protocol Buffers</strong></p><p>Protocol Buffers, or Protobuf, is a binary serialization format. You define your data structures in a schema file with a .proto extension. The Protobuf compiler reads this file and generates code in your target language that can serialize and deserialize messages in binary format.</p><p><em>The word “false” in JSON takes 5 bytes. In Protobuf it takes 1 bit.</em> A message that weighs 200 bytes as JSON might weigh 20 bytes as Protobuf. Ten times smaller means ten times faster to transmit and ten times faster to parse.</p><p>The schema file also generates client and server stubs automatically. From the developer’s perspective, calling a remote function over gRPC looks exactly like calling a local function. The network is nearly invisible.</p><p><strong>5.3 HTTP/2 Multiplexing</strong></p><p>gRPC runs over HTTP/2, which supports multiplexing: multiple requests and responses travel over a single connection simultaneously. In HTTP/1.1, requests on a single connection are sequential. If request one is waiting for a slow response, request two must wait behind it. HTTP/2 sends both at once and matches responses to requests as they arrive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xN6mfWQcYh9Z99NShDwkw.png" /><figcaption>grpc architecture</figcaption></figure><p><strong>5.4 Streaming</strong></p><p>gRPC supports four communication patterns, which is a significant advantage over REST.</p><p><strong>Unary</strong>: client sends one request, server sends one response. This is equivalent to a standard REST call.</p><p><strong>Server streaming</strong>: client sends one request, server sends a stream of responses. <em>Useful for fetching a large dataset in chunks or receiving live updates.</em></p><p><strong>Client streaming</strong>: client sends a stream of requests, server sends one response. <em>Useful for uploading a large file in chunks.</em></p><p><strong>Bidirectional streaming</strong>: both sides send streams simultaneously. <em>Useful for real-time communication between services.</em></p><p><strong>5.5 Where gRPC Belongs</strong></p><p>gRPC is almost exclusively used for service-to-service communication inside an infrastructure, not for public-facing APIs. The primary reason is that browsers cannot natively use gRPC because they cannot access HTTP/2 at the level gRPC requires. There are workarounds like gRPC-Web, but they add complexity. For internal microservices communicating at high frequency, gRPC is the clear choice.</p><p><strong>6. WebSockets</strong></p><p><strong>6.1 The Problem REST Cannot Solve</strong></p><p>Every communication style we have covered so far follows the same fundamental pattern: the client speaks, the server responds, the conversation ends. For the majority of use cases this is correct. For a specific class of use cases it is a fundamental mismatch.</p><p><em>You are using a live chat application. A friend sends you a message.</em> In a purely REST model, how would your browser know? It would have to ask the server every few seconds: any new messages? This is called polling. Most of those requests return empty. You are spending bandwidth and server capacity asking a question whose answer is almost always no.</p><p>The deeper version of this problem is that the server has no mechanism to speak first. It can only respond. For applications where the server has information the client needs as soon as it exists, this is architecturally broken.</p><p>WebSockets solve this by keeping the connection open permanently and making it bidirectional.</p><p><strong>6.2 How the Handshake Works</strong></p><p>A WebSocket connection begins as a regular HTTP request. The client sends a special header: <em>Upgrade: websocket.</em> This is the client saying: I want to switch this connection from HTTP to WebSocket. The server, if it supports WebSockets, responds with status 101 Switching Protocols. At this moment, the connection stops behaving like HTTP entirely and becomes a persistent, full-duplex channel [5].</p><p>Both sides can now send messages to the other at any time, independently, without one waiting for the other to speak first. The connection remains open until one side explicitly sends a close frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IAnEX2k8KWOqoJzKZvmLg.png" /><figcaption>Websocket Lifecycle</figcaption></figure><p><strong>6.3 Infrastructure Cost</strong></p><p>WebSockets introduce a resource challenge that REST does not have. A REST server can handle enormous traffic efficiently because each connection is brief. A WebSocket server must hold an open connection for every active client for the duration of their session. <em>A chat application with one million simultaneous users requires one million open file descriptors in memory at all times.</em></p><p>This is why dedicated WebSocket infrastructure services exist. Running WebSockets at scale is its own engineering problem, separate from your application logic.</p><p><strong>6.4 Use Cases</strong></p><p>WebSockets are appropriate when the server needs to push data to the client without the client asking, and when the latency between an event occurring and the client seeing it must be very low. <em>Live collaborative documents, real-time location tracking, live sports scores, multiplayer game state synchronization, live financial data feeds.</em> The defining pattern is: the server has something to say, and it cannot wait for the client to ask.</p><p><strong>7. WebRTC</strong></p><p><strong>7.1 The Peer-to-Peer Problem</strong></p><p>Every API style covered so far involves a client talking to a server. WebRTC is architecturally different at its foundation. It establishes direct communication between two clients, with no server involved in the actual data exchange [6].</p><p>The motivation is latency and cost. <em>In a video call, your camera feed needs to reach another person’s screen with as close to zero delay as possible.</em> If that video stream traveled from your browser up to a server and back down to theirs, you would have double the latency of a direct path. For video this is perceptible. For real-time gaming it is the difference between playable and broken. For a company serving millions of video minutes per day, routing all that media through its own servers is also an enormous infrastructure cost.</p><p><strong>7.2 The Signaling Phase</strong></p><p>Establishing a direct connection between two browsers is harder than it sounds. Both devices are behind routers, behind NAT layers, possibly behind firewalls. Neither has a public IP address that the other can simply connect to.</p><p>WebRTC solves this through a signaling phase. Both devices connect to a small signaling server and exchange information about themselves: their network topology, the addresses they might be reachable at, the media formats they support. This process uses a protocol called ICE, Interactive Connectivity Establishment, which tries multiple possible connection paths and selects the best one.</p><p>Once the two peers have exchanged enough information to find each other, the signaling server’s job is done. The actual media flows directly between the two browsers.</p><p><em>The signaling server is a matchmaker. It introduces the two parties, helps them find each other’s address, and then steps aside. The conversation happens without it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*tWHZim1mScS07bqWtWRK6w.png" /><figcaption>WebRTC flow</figcaption></figure><p><strong>7.3 Why UDP</strong></p><p>WebRTC uses UDP for its media streams rather than TCP. TCP guarantees delivery: if a packet is lost, it waits and retransmits it. For video and audio, this behavior is wrong. <em>A single lost video frame is invisible if you simply move past it. A frozen screen while you wait for TCP to retransmit that frame is not.</em> UDP sacrifices guaranteed delivery for speed, which is exactly the right tradeoff for real-time media.</p><p>WebRTC is the technology behind browser-based video calls, screen sharing, peer-to-peer file transfers, and real-time collaborative drawing tools.</p><p><strong>8. How a Server Actually Handles Requests</strong></p><p><strong>8.1 What a Server Is</strong></p><p>A server is a program. It runs on a machine, consumes real CPU and real memory, and operates in a permanent loop listening on a port. When a request arrives at that port, the operating system intercepts it at the network level and hands it to the program. This is worth being explicit about because the “server in the cloud” abstraction hides the fact that all of the physical constraints of a single process apply.</p><p>The interesting engineering problem emerges from concurrency. If your server is one process, and requests arrive simultaneously from thousands of clients, how does it handle them all? There are two fundamentally different answers to this question.</p><p><strong>9. The Event Loop vs. Threaded Concurrency</strong></p><p><strong>9.1 The Threaded Model</strong></p><p>The classic approach, which servers like Apache popularized, assigns each incoming connection its own thread. A thread is an independent unit of execution within a process, with its own call stack and memory space.</p><p><em>Request one arrives, thread one handles it. Request two arrives, thread two handles it.</em> This model is intuitive and it works well at low concurrency.</p><p>The cost is in resource consumption and waiting. Each thread consumes memory simply by existing, typically one to eight megabytes for its stack alone. At five thousand concurrent threads, that is potentially forty gigabytes of memory consumed by threads that are mostly idle. The additional cost is context switching: when the CPU moves from one thread to another, it must save the complete state of the current thread and load the state of the next. At high thread counts, the CPU spends a significant fraction of its time on this bookkeeping rather than on actual work.</p><p>The deeper problem is the nature of server workloads. Most of what a server does is wait. It sends a database query and waits. It calls an external API and waits. It reads from disk and waits. <em>While a thread waits, it occupies memory and a slot in the scheduler while producing nothing.</em> In a workload that is ninety percent waiting and ten percent processing, the threaded model is enormously wasteful.</p><p><strong>9.2 The Event Loop Model</strong></p><p>Node.js introduced many developers, including me, to an entirely different concurrency model: a single thread that never blocks [7].</p><p>The core insight is that waiting does not require a thread. Waiting is fundamentally an operating system concern. When you ask the OS to read from a network socket, the OS can notify you when the data is ready rather than requiring you to sit there watching. This is called non-blocking I/O, and it is the foundation of the event loop.</p><p>In the event loop model, when a request triggers a database query, the server registers a callback function saying “when this result arrives, call this function,” and immediately moves on to handle the next incoming request. The operating system manages the actual waiting at the kernel level. When the database responds, the result is placed in an event queue. The event loop checks this queue continuously and executes callbacks as their results become available.</p><p>The result is a server that is always doing something useful. No thread sits idle waiting for a database. No memory is wasted on parked execution contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuwvRKzw7M9PJvSqrs4FZQ.png" /><figcaption>Concurrency models..</figcaption></figure><p><strong>9.3 The Tradeoff</strong></p><p>The event loop model has one critical weakness. If the single thread encounters a task that requires intensive computation, every other request is frozen for the duration of that computation. <em>A two-second mathematical calculation blocks the entire server.</em> There is no other thread to handle incoming requests while this one is occupied.</p><p>This is why Node.js is excellent for I/O-heavy workloads where most time is spent waiting on databases, external APIs, or network responses, and genuinely poor for CPU-heavy workloads like image processing, video encoding, or machine learning inference. CPU-heavy work must be offloaded to worker threads or a separate service.</p><p>Threaded Model Event Loop Model Concurrency mechanism One thread per connection Single thread, non-blocking I/O Memory cost High at scale (per-thread stack) Low (single thread) Best for CPU-intensive work I/O-intensive work Failure mode Thread exhaustion at high load CPU blocking freezes all requests Examples Apache, Java servers Node.js, Nginx (event-driven)</p><p><strong>10. The Internal Journey of a Request</strong></p><p>Once a request enters your server application, it passes through a structured sequence of stages before a response is generated. This sequence is more deliberate than most tutorials convey.</p><p><strong>10.1 The Middleware Stack</strong></p><p>The first thing a request encounters is the middleware stack: a series of functions it must pass through before reaching any route handler. Middleware performs work that needs to happen for most or all requests, without duplicating that logic in every handler.</p><p><em>Think of it as the security and boarding process at an airport. Before reaching your gate, you pass through ticket verification, ID check, and bag screening. Each checkpoint either clears you to continue or stops you entirely. Your gate only handles passengers who have cleared every checkpoint.</em></p><p>A typical middleware chain might include:</p><p><strong>Authentication middleware</strong>: verifies that the request carries a valid credential. <em>If a request to GET /orders/55 carries no authentication token, this middleware returns 401 Unauthorized and the chain terminates. The route handler never runs.</em></p><p><strong>Body parser middleware</strong>: reads the raw bytes of the request body and converts them into a usable data structure. <em>A POST request carrying JSON is just bytes until the parser turns it into an object your code can work with.</em></p><p><strong>Rate limiting middleware</strong>: checks whether this client has exceeded its allowed request frequency. <em>If a single IP has sent five hundred requests in the last second, this middleware returns 429 Too Many Requests.</em></p><p><strong>Logging middleware</strong>: records that the request arrived, what it was, and when. This runs for every request regardless of outcome.</p><p>The order of the chain matters. Authentication must run before authorization, because you cannot check permissions for a user whose identity you have not yet verified. Logging should run early so it captures requests that fail at later stages. Getting middleware order wrong is a common source of subtle bugs that only surface at edge cases.</p><p><strong>10.2 The Router</strong></p><p>After middleware, the router takes over. Its job is lookup: given the HTTP method and the URL, find the function registered to handle this specific combination.</p><p><em>GET /users/42 maps to the fetchUser handler. DELETE /users/42 maps to the deleteUser handler. POST /users maps to the createUser handler.</em> The router is essentially a pattern-matching table. Matching happens in milliseconds.</p><p><strong>10.3 The Handler and Response</strong></p><p>Inside the handler, your actual application logic runs. This is the code you write: query a database, call another service, run validation, compute a result. When you have what you need, you construct a response with a status code, headers, and a body.</p><p>That response then travels back through the middleware stack on the way out. Some middleware adds security headers to every outgoing response. Some logs the final status code. After clearing the stack, the response exits the application, passes back through the OS network layer, and travels across the internet to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*afYNRBAFwefRYCtXLiTzSQ.png" /><figcaption>Entire Request Journey.</figcaption></figure><p><strong>11. Summary</strong></p><p>The different API styles we covered are not in competition. They solve different problems.</p><p>Style Communication Pattern Transport Data Format Best For REST Request-Response, stateless HTTP/1.1 JSON Public APIs, web and mobile apps SOAP Remote Procedure Call HTTP, SMTP XML Enterprise, contractual integrations GraphQL Query against schema HTTP JSON Multi-client products with varied data needs gRPC Remote Procedure Call HTTP/2 Binary Protobuf High-performance internal service communication WebSockets Persistent bidirectional TCP Any Real-time: chat, live data, collaboration WebRTC Peer-to-peer direct UDP Binary media Video, audio, low-latency peer communication</p><p>The server architecture behind all of them follows the same fundamental structure: a concurrency model that determines how simultaneous connections are handled, a middleware chain that processes every request through shared logic, a router that directs requests to handlers, and handlers that produce responses.</p><p>None of this is arbitrary. REST is stateless because statelessness enables horizontal scaling. gRPC uses binary encoding because binary is smaller and faster. The event loop avoids threads because threads waste memory waiting. Middleware runs in sequence because shared logic should execute once in a predictable order.</p><p>Understanding why each choice was made is more durable knowledge than knowing the syntax of any particular framework. Frameworks change. The problems they solve do not.</p><p>Part 3 will go into databases. We have covered how requests travel across a network and how servers process them when they arrive. The remaining question is: when the handler runs and asks for data, what is happening on the other side of that database call? That is where the next layer of foundational thinking lives.</p><p><strong>References</strong></p><p>[1] Roy Thomas Fielding. “Architectural Styles and the Design of Network-based Software Architectures.” Doctoral Dissertation, University of California, Irvine, 2000.</p><p>[2] Don Box, David Ehnebuske, Gopal Kakivaya, et al. “Simple Object Access Protocol (SOAP) 1.1.” W3C Note, World Wide Web Consortium, May 2000.</p><p>[3] Lee Byron, Nick Schrock, Dan Schafer. “GraphQL: A Data Query Language.” Engineering at Meta, Meta Open Source, September 2015.</p><p>[4] Google. “Introduction to gRPC.” gRPC Official Documentation, grpc.io, 2016.</p><p>[5] Ian Fette, Alexey Melnikov. “The WebSocket Protocol.” RFC 6455, Internet Engineering Task Force, December 2011.</p><p>[6] W3C Working Group. “WebRTC 1.0: Real-Time Communication Between Browsers.” W3C Recommendation, World Wide Web Consortium, January 2021.</p><p>[7] Node.js Documentation Team. “The Node.js Event Loop, Timers, and process.nextTick.” Node.js Official Documentation, nodejs.org, 2024.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5e2669b298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend from First Principles: Part 1]]></title>
            <link>https://medium.com/@ani05/backend-from-first-principles-part-1-af487626aa9a?source=rss-127ea839ba82------2</link>
            <guid isPermaLink="false">https://medium.com/p/af487626aa9a</guid>
            <category><![CDATA[first-principles]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Animesh Mishra]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 04:44:56 GMT</pubDate>
            <atom:updated>2026-01-03T04:55:00.411Z</atom:updated>
            <content:encoded><![CDATA[<p>To truly master backend engineering, we have to look beyond frameworks. We have to look at the wire. The code we write is just a small part of a massive, orchestrated system of data exchange. If we don’t understand the rules of that exchange, we are just guessing.</p><p>This is the first part of my roadmap to understanding the backend, starting with the bedrock: <strong>The HTTP Protocol and Networking.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHS7hlqfuhvqMi5S15thhg.png" /><figcaption>jargon</figcaption></figure><h3>1. The Core Principles of Backend Communication</h3><p>Everything in backend development relies on a client and a server agreeing on a specific language. That language is the <strong>HTTP Protocol</strong>. But before we look at the syntax, we need to understand the behavior.</p><h3>The Anatomy of HTTP</h3><p>At its heart, HTTP is a text-based request-response protocol. It isn’t magic; it’s raw text sent over a wire.</p><ul><li><strong>Raw Messages:</strong> If you look at a raw HTTP message, it’s just a formatted block of text. It consists of a start line, headers, an empty line, and an optional body.</li><li><strong>Methods (The “Verbs”):</strong> We use different methods to indicate intent.</li><li><strong>GET:</strong> Retrieve data. Should be idempotent (safe to repeat).</li><li><strong>POST:</strong> Submit new data.</li><li><strong>PUT/PATCH:</strong> Update existing data.</li><li><strong>DELETE:</strong> Remove data.</li><li><em>My Perspective:</em> Knowing <em>when</em> to use these distinguishes a scraped together API from a RESTful one.</li><li><strong>Status Codes (The “Grades”):</strong> The server tells the client how the request went using specific codes.</li><li><strong>2xx:</strong> Success (e.g., 200 OK).</li><li><strong>3xx:</strong> Redirection (e.g., 301 Moved Permanently).</li><li><strong>4xx:</strong> Client Error (e.g., 400 Bad Request, 404 Not Found).</li><li><strong>5xx:</strong> Server Error (e.g., 500 Internal Server Error).</li></ul><h3>The Evolution: HTTP 1.1 vs 2.0 vs 3.0</h3><p>Not all HTTP is created equal. We must understand how the protocol has evolved to solve performance bottlenecks</p><p><strong>HTTP 1.1:</strong> The standard for years. It introduced <strong>persistent connections</strong> (keep-alive), allowing us to reuse a TCP connection for multiple requests rather than opening a new handshake for every single file.</p><p><strong>HTTP 2.0:</strong> A massive leap. It introduced <strong>multiplexing</strong>, allowing multiple requests to be sent in parallel over a single TCP connection, fixing the “head-of-line blocking” issue.</p><p><strong>HTTP 3.0:</strong> The future. It runs over <strong>QUIC</strong> (UDP) instead of TCP, further reducing latency in unreliable networks</p><h3>2. High-Level Understanding: The Life of a Request</h3><p>When a user types a URL and hits enter, what <em>actually</em> happens? This “High Level Understanding” is critical for debugging latency and connection issues.</p><h3>The Journey</h3><ol><li><strong>Browser to Network:</strong> The request leaves the browser and traverses the <strong>local network</strong>, passing through <strong>firewalls</strong> and routers.</li><li><strong>DNS Resolution:</strong> The browser finds the IP address of the server.</li><li><strong>The Internet (Routing):</strong> The packet travels through various <strong>hops</strong> across the internet. It doesn’t fly straight to the server; it is routed dynamically.</li><li><strong>The Server:</strong> Finally, it hits our backend infrastructure (e.g., an AWS server).</li></ol><h3>Optimization on the Wire</h3><p>To make this journey faster, we use <strong>Compression</strong>. We don’t send raw, bloated text. We compress it using algorithms like:</p><p><strong>Gzip</strong></p><p><strong>Deflate</strong></p><p>Brotli (BR)</p><h3>3. Headers: The Metadata of the Web</h3><p>Headers are the “context” of the conversation. They tell the server who the client is, what format they want, and how to handle the data.</p><p><strong>Types of Headers:</strong></p><ul><li><strong>Request Headers:</strong> “ JSON”.</li><li><strong>Representation Headers:</strong> Describe the body (e.g., Content-Type)</li><li><strong>Security Headers:</strong> Strict-Transport-Security, X-Frame-Options.</li></ul><blockquote>MAKE SURE TO REFER TO GOOGLE FOR WHATEVER YOU DO NOT GET AS NOTHING IS BETTER THAN STUDYING ABOUT A NICHE FROM GOOGLE..</blockquote><ul><li><strong>Content Negotiation:</strong> This is a cool concept where the client and server negotiate the format. The client sends Accept: application/json, and the server decides if it can fulfill that</li><li><strong>Caching Headers:</strong> We use headers like ETag and Cache-Control to tell the browser, &quot;You already have this file, don&#39;t ask for it again&quot;. This is crucial for performance.</li></ul><h3>4. Security &amp; The Handshake (SSL/TLS)</h3><p>We cannot send data in plain text. We use <strong>SSL/TLS</strong> to turn HTTP into <strong>HTTPS</strong>.</p><p><strong>The Concept:</strong> It ensures privacy and data integrity.</p><p><strong>The Mechanism:</strong> It involves a “Handshake” where keys are exchanged. The server proves its identity with a certificate, and an encrypted tunnel is established.</p><h3>5. CORS (Cross-Origin Resource Sharing)</h3><p>This is the bane of every frontend developer’s existence, but it’s a vital security feature.</p><p><strong>The Flaw &amp; The Fix:</strong> By default, browsers block requests from one domain (e.g., localhost:3000) to another (e.g., <a href="https://www.google.com/search?q=api.myserver.com)">https://www.google.com/search?q=api.myserver.com)</a> to prevent malicious scripts from hijacking sessions.</p><p><strong>Pre-flight Requests:</strong> For complex requests (like those with custom headers), the browser first sends an OPTIONS request (the &quot;pre-flight&quot;). It asks, &quot;Hey server, are you okay with me sending this?&quot;.</p><p><strong>The Flow:</strong> Browser → Server (Pre-flight) → Browser (Approval) → Server (Actual Request).</p><p><strong>That was a big read.</strong></p><p>I know diving into the nitty-gritty of HTTP headers, handshakes, and compression algorithms isn’t as flashy as building a new feature. But this is the “invisible” layer that makes everything else possible. Understanding these concepts is what separates a developer who just writes code from an engineer who understands the system.</p><p>This was just the beginning. I’ve broken down my entire backend roadmap into a <strong>5-Part Series</strong> to ensure we give every topic the depth it deserves without getting overwhelmed.</p><p>It is definitely gonna take some time as I first also need to understand and then write about it , but we’ll make sure these blog contain everything about backend Practices.</p><p>I’m building this roadmap to solidify my own understanding, and I hope it helps you do the same.</p><p><strong>Stay tuned for Part 2.</strong> We’re just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af487626aa9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[django internal in easy words]]></title>
            <link>https://medium.com/@ani05/django-internal-in-easy-words-7be21ad4d360?source=rss-127ea839ba82------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be21ad4d360</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-develop]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Animesh Mishra]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 13:48:33 GMT</pubDate>
            <atom:updated>2025-08-24T13:48:33.435Z</atom:updated>
            <content:encoded><![CDATA[<p><strong># The Django RESTaurant: From HTTP Order to a JSON Meal</strong></p><p>_Django REST Framework feels like magic. You write a few lines of code, and a powerful, browsable API appears. But what’s really happening under the hood? Let’s find out._</p><p>If you’ve ever used Django REST Framework (DRF), you’ve felt it. You define a `Model`, a `Serializer`, and a `ViewSet`, wire them up with a `Router`, and suddenly you have a full CRUD API. It feels too easy, almost like you’re cheating.</p><p>To demystify the process, let’s think of your web application as a high-end restaurant. Django is the building, the kitchen, and the staff. An API request is a customer’s order. Let’s follow a single `GET` request from the moment it arrives at the front door to the moment a JSON meal is served.</p><p>1. The URL Resolver</p><p>A customer (an HTTP request) arrives at the restaurant’s address. The first person they meet is the **Maître d’** (`urls.py`). Their job is to look at the customer’s reservation (the URL path, like `/api/articles/`) and direct them to the correct section of the restaurant.</p><p>In Django, this process starts in your project’s root `core/urls.py`. This file is the main reservation book. For our API, it sees the `/api/` prefix and hands the customer off to a specialized manager: the DRF `Router`. The router knows exactly which chef is responsible for the `/articles/` table.</p><p><strong>## 2. The Head Chef — The `ViewSet` (The Brains of the Operation)</strong></p><p>The **Head Chef** (`ViewSet`) is the central decision-maker in the kitchen. They don’t chop every vegetable, but they hold the master plan. When the order for “all articles” arrives, the Head Chef knows to execute the `list()` recipe.</p><p>This is where the “viewpoint determines the logic of the project.” The `ViewSet` is the brain, orchestrating the entire workflow by defining three critical things:</p><p><em>1. **What data to work with?** (`queryset = Article.objects.all()`): The chef decides which section of the pantry (which database model) the ingredients will come from.</em></p><p><em>2. **How should the data be formatted?** (`serializer_class = ArticleSerializer`): The chef points to the specific station responsible for plating and quality control.</em></p><p><em>3. **Who is allowed to place this order?** (`permission_classes = […]`): The chef checks the customer’s credentials before starting any work.</em></p><p>The `ViewSet` contains no data itself; it is pure **logic and orchestration**. It directs the flow of work.</p><p><strong>## 3. The Recipe Book &amp; The Pantry — The Model &amp; The Database</strong></p><p>Following the Head Chef’s instructions, a cook is sent to the **pantry** (the database) with a shopping list. This list is ased on the official **recipe book** (the `Article` model in `articles/models.py`), which defines exactly what an “article” ingredient is made of-a title, some content, an author, etc.</p><p>This is the Django ORM (Object-Relational Mapper) in action. It translates the chef’s command (`Article.objects.all()`) into a raw SQL query, retrieves the data from the database, and brings it back to the kitchen as a collection of Python objects.</p><p><strong>## 4. The Universal Translator &amp; Quality Control — The `Serializer`</strong></p><p>This is the most critical station in our RESTaurant. The `Serializer` acts as both a **Universal Translator** and a **Quality Control Inspector**.</p><blockquote>**As a Translator (for outgoing orders):**</blockquote><p><em>When the Head Chef sends the raw ingredients (Python `Article` objects), the translator’s job is to prepare them for the outside world. It follows a strict blueprint (the `fields` in its `Meta` class) to arrange the data into a standardized JSON “dish.” It can nest data, like putting author details inside the article dish, to create the rich, complex JSON that allows different projects to communicate seamlessly. The final JSON meal is a universal language that any client-a web frontend, a mobile app, or another server-can understand.</em></p><p>**As a Quality Control Inspector (for incoming orders):**</p><p>When a new delivery of ingredients arrives (`POST` data), this station inspects it first. Does the data match the recipe’s requirements? Is the `title` a string? Is the `content` included? If anything is wrong, the delivery is rejected immediately with a `400 Bad Request` validation error. This prevents bad data from ever entering your database.</p><p>The `Serializer` doesn’t contain application logic; it is a strict and powerful **data transformation and validation tool**.</p><p><strong>## 5. The Waiter — The Renderer and The Final Dish</strong></p><p>The finished dish is ready. A **waiter** (`Renderer`) picks it up. But how do they serve it? They look at the customer.</p><p><em>* Is it a person in the dining room using a web browser? The waiter serves the beautiful plate on a fancy platter. This is the **`BrowsableAPIRenderer`**, which wraps the JSON in the helpful HTML interface we all know and love.</em></p><p><em>* Is it a takeout order from a script or mobile app? The waiter puts it in a simple, efficient to-go box. This is the **`JSONRenderer`**, which serves the raw, unadulterated JSON data.</em></p><p>This process, called Content Negotiation, allows the same endpoint to serve both humans and machines effectively.</p><p><strong>## The Meal is Served</strong></p><p>So, the next time you write a `ViewSet` and a `Serializer` and see your API spring to life, you’ll know it’s not magic. It’s the result of a highly efficient, well-structured kitchen staff working in perfect harmony.</p><p>Understanding this flow from request to response demystifies the framework and empowers you to step in and customize any part of the recipe.</p><p>Happy cooking!</p><p><em>Originally published at </em><a href="https://gist.github.com/aniismess/3602e38a93f3e199b83097ab5bda1101"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be21ad4d360" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>