<?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 Surya Pratap Singh on Medium]]></title>
        <description><![CDATA[Stories by Surya Pratap Singh on Medium]]></description>
        <link>https://medium.com/@suryapratap04?source=rss-84719f441bf3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*08z66pL-n-OY_4OqTzCMTQ.jpeg</url>
            <title>Stories by Surya Pratap Singh on Medium</title>
            <link>https://medium.com/@suryapratap04?source=rss-84719f441bf3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:41:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suryapratap04/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[Background Tasks and Task Queues]]></title>
            <link>https://suryapratap04.medium.com/background-tasks-and-task-queues-0b8c303c2e64?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b8c303c2e64</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 09:31:01 GMT</pubDate>
            <atom:updated>2026-08-06T09:31:01.448Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Overview</strong></h4><p>A <strong>background task</strong> (or background job) is any unit of work executed <em>outside</em> the request–response cycle of a web application. Instead of completing all logic while the client waits for an HTTP response, the server hands slow or non-critical work off to a separate process that finishes it independently.</p><p>Background processing is a foundational pattern in modern backend systems. You’ll find it in nearly every production SaaS product — payment gateways, e-commerce platforms, healthcare systems, and messaging apps all rely on it. For backend engineers, understanding this pattern is essential to building services that stay <strong>responsive under load</strong> and <strong>resilient to external failures</strong>.</p><h3>Example</h3><p>Consider an e-commerce checkout service. When a customer places an order, the backend must:</p><ol><li>Validate the cart and payment,</li><li>Persist the order,</li><li>Send a confirmation email,</li><li>Notify the warehouse system.</li></ol><p>Steps 3 and 4 depend on <strong>external services</strong> you don’t control — an email provider and a third-party inventory API. If either is slow or temporarily down, and the work runs <strong>synchronously</strong>, two bad outcomes follow:</p><ul><li><strong>Without robust error handling</strong>, a failure in the email call bubbles up and fails the <em>entire</em> checkout request, even though the payment succeeded.</li><li><strong>With error handling</strong>, the request succeeds but the confirmation is silently lost — yet the UI already told the customer “Confirmation sent.” The user is left retrying manually.</li></ul><p>The root problem: <strong>tightly coupling non-critical work to the request lifecycle makes your API only as reliable and fast as its slowest dependency.</strong> Background tasks decouple this work so the API can respond immediately.</p><h3>Core Concepts</h3><h4>Task Queue</h4><p><strong>Definition.</strong> A task queue is a system for storing and distributing background jobs between the code that creates them and the code that runs them.</p><p><strong>Working principle.</strong> It has three parts:</p><ul><li><strong>Producer</strong> — your application code. It gathers everything a job needs (e.g., recipient address, order ID, template data), <strong>serializes</strong> it (typically to JSON), and pushes it onto the queue. This push is called <strong>enqueuing</strong>.</li><li><strong>Broker</strong> — the queue itself. It durably holds tasks until a worker is free. Common brokers include <strong>Redis (Pub/Sub)</strong>, <strong>RabbitMQ</strong>, and <strong>Amazon SQS</strong> (a managed, multi-region option for large-scale systems).</li><li><strong>Consumer (Worker)</strong> — a program running in a <em>separate process</em>. It monitors the broker, <strong>dequeues</strong> a task, deserializes it into a native object (a Python dict, a JS object, a Go struct), and runs the registered <strong>handler</strong>.</li></ul><p>Think of it as a <strong>to-do list for your backend</strong>: producers add items, workers cross them off one at a time.</p><p><strong>Benefit.</strong> Slow work no longer blocks the API. <strong>Trade-off.</strong> You introduce operational complexity (a broker to run, workers to monitor).</p><h3>Acknowledgements and Visibility Timeout</h3><p>When a worker finishes a task successfully, it sends an <strong>acknowledgement (ack)</strong> to the broker, which then removes the task. If no ack arrives within a configured <strong>visibility timeout</strong> — perhaps the worker crashed or an external call hung — the broker makes the task visible again so another worker can retry it. This guarantees tasks aren’t silently lost mid-processing.</p><h3>Retries and Exponential Backoff</h3><p>When a handler fails, mature frameworks re-enqueue the task automatically. A common strategy is <strong>exponential backoff</strong>: wait 1 minute, then 2, then 4, then 8, up to a configured maximum number of attempts. Since most external outages last only seconds, a task usually succeeds on an early retry. This built-in resilience is one of the biggest reasons to use a task queue.</p><p><strong>Popular frameworks:</strong> Celery (Python), BullMQ (Node.js), and Asynq (Go).</p><h3>Architecture / Workflow</h3><p>The full lifecycle for the order-confirmation email:</p><ol><li>The client submits the checkout request.</li><li>The backend validates the payment and persists the order.</li><li>Instead of calling the email provider directly, it <strong>serializes</strong> the email payload and <strong>enqueues</strong> a task.</li><li>The API <strong>returns immediately</strong> with 201 Created; the UI confirms the order.</li><li>An email worker <strong>dequeues</strong> the task and <strong>deserializes</strong> the payload.</li><li>The worker calls the email provider’s API.</li><li>On success, it <strong>acks</strong> the broker, which removes the task.</li><li>On failure, the task is re-queued and retried with backoff until it succeeds or exhausts its attempts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*WmiRzM96Rckq3Pjlxx_Bdw.png" /></figure><h3>Common Task Types</h3><ul><li><strong>One-off tasks</strong> — triggered by a single event. <em>Example:</em> sending a password-reset link when a user requests it.</li><li><strong>Recurring tasks</strong> — run on a schedule (via cron or the framework’s scheduler). <em>Examples:</em> emailing weekly account statements; nightly cleanup of expired login sessions.</li><li><strong>Chained tasks</strong> — jobs with parent–child dependencies. <em>Example:</em> a media pipeline where a video must be <strong>encoded</strong> first, after which <strong>thumbnail generation</strong> and <strong>subtitle transcription</strong> run in parallel, followed by thumbnail resizing.</li><li><strong>Batch tasks</strong> — one trigger fans out into many jobs. <em>Examples:</em> an account-deletion request that spawns sub-tasks to remove a user’s assets, records, and memberships across shards; or dispatching thousands of monthly reports at once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*UKTwnhElC0MmHVZDpE26nA.png" /></figure><h3>Design Considerations</h3><ul><li><strong>Idempotency</strong> — design tasks so re-running them causes no duplicate side effects. Wrap multi-step database work in a transaction so a mid-way failure rolls back cleanly and the retry starts fresh.</li><li><strong>Robust error handling</strong> — because work runs in a separate process, catch, log, and surface failures explicitly so retries and debugging are possible.</li><li><strong>Monitoring</strong> — track queue length, success/failure counts, and failure causes using tools like Prometheus and Grafana.</li><li><strong>Scalability</strong> — scale workers <strong>horizontally</strong> by adding consumer nodes as load grows.</li><li><strong>Ordering &amp; rate limiting</strong> — verify your framework supports ordered delivery when sequence matters, and throttle calls to external services to respect their limits and control cost.</li></ul><h3>Best Practices</h3><ul><li><strong>Keep tasks small and focused</strong> — one task, one responsibility. Smaller tasks are easier to retry, monitor, and reason about.</li><li><strong>Avoid long-running tasks</strong> — split heavy work into concurrent or chained sub-tasks so a late failure doesn’t force reprocessing everything.</li><li><strong>Invest in logging and error handling</strong> — it’s what makes retries effective and debugging tractable.</li><li><strong>Alert on queue length and worker health</strong> — get notified when the backlog grows or workers die, so you can scale out or investigate before users notice.</li></ul><h3>Summary</h3><p>Background tasks let you offload time-consuming and non-critical work from the request path, keeping APIs fast and preventing timeouts caused by external dependencies. Backed by a task queue — producer, broker, and worker — they add acknowledgements, retries with backoff, and horizontal scalability. Applied with idempotency, sound error handling, and monitoring, they are a core building block of scalable, reliable backend systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b8c303c2e64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching]]></title>
            <link>https://suryapratap04.medium.com/caching-717fe74769e6?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/717fe74769e6</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 06:41:01 GMT</pubDate>
            <atom:updated>2026-08-04T06:41:01.614Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Overview</strong></p><p><strong>Caching</strong> is the practice of keeping a copy of frequently used data in a location that is faster and cheaper to access than the original source. Instead of repeating expensive work — recomputing a result or fetching data from slow storage — an application serves a pre-stored answer.</p><p>Caching appears at nearly every layer of modern computing: inside CPUs, across networks, in operating systems, in browsers, and in backend services. It is one of the highest-leverage techniques available for building <strong>high-performance systems</strong>, particularly those where latency is measured in single- or double-digit milliseconds. Any engineer working on systems that must scale to many users needs a working mental model of how and where caching applies.</p><h3>why Caching</h3><p>Two recurring situations make naive systems slow and expensive:</p><ol><li><strong>Repeated heavy computation</strong> — The same expensive calculation is performed again and again for identical inputs.</li><li><strong>Repeated transfer of large or slow-to-fetch data</strong> — The same data is fetched from a distant or disk-based source on every request.</li></ol><p>Consider an <strong>inventory dashboard</strong> for a warehouse-management platform. Suppose rendering it requires a SQL query that joins several million rows across products, suppliers, and stock movements. If thousands of employees load this dashboard every minute, and each load re-runs the full query, the database is quickly overwhelmed, latency climbs, and the service degrades or crashes.</p><p>Caching breaks this cycle: compute or fetch the result <strong>once</strong>, store it somewhere fast, and serve subsequent requests from that store until the data needs refreshing.</p><h3>Core Concepts</h3><h4>Cache Hit and Cache Miss</h4><p>When a request finds the data it needs already in the cache, that is a <strong>cache hit</strong>, and the response is returned immediately. When the data is absent, that is a <strong>cache miss</strong>: the system falls back to the original source, retrieves the data, stores it in the cache, and then returns it — so the next identical request becomes a hit.</p><h4>Why In-Memory Caches Are Fast</h4><p>Caching technologies such as <strong>Redis</strong>, <strong>Valkey</strong>, <strong>Memcached</strong>, or managed services like <strong>Amazon ElastiCache</strong> are called <em>in-memory</em> stores because they hold data in <strong>RAM (main memory)</strong> rather than on disk.</p><ul><li><strong>RAM</strong> provides near-constant access time to any address via electrical signaling. It is fast but <strong>volatile</strong> (data is lost on power loss) and <strong>limited</strong> in capacity.</li><li><strong>Disk storage (HDD/SSD)</strong> is slower to access but <strong>persistent</strong> and far larger and cheaper.</li></ul><p>This trade-off is why a cache holds only a <strong>subset</strong> of the primary data — storing everything in memory would be prohibitively expensive and would defeat the purpose. In-memory stores achieve durability behind the scenes by periodically persisting to disk and reloading on startup, but all reads and writes still occur in fast primary memory.</p><h4>Key-Value NoSQL Model</h4><p>Most caches are <strong>key–value stores</strong>. Unlike relational databases with strict schemas, tables, and rows, they map a simple key to a value (a string, number, list, or JSON object). This simplicity — SET key value / GET key—is what makes them fast and easy to integrate.</p><h3>Caching Strategies</h3><p>StrategyHow It WorksTrade-off<br> <strong>Lazy loading (cache-aside)</strong>Data is cached only when first requested and missed.Cache stays lean; first request per key is slow.<br><strong>Write-through</strong>Every write updates the database <em>and</em> the cache in the same operation.Cache is always fresh; writes carry extra overhead.</p><h3>Eviction Policies</h3><p>Because memory is finite, a full cache must remove existing entries to admit new ones. The chosen <strong>eviction policy</strong> governs this:</p><ul><li><strong>No eviction</strong> — Rejects new writes with an error when full.</li><li><strong>LRU (Least Recently Used)</strong> — Evicts the entry accessed longest ago.</li><li><strong>LFU (Least Frequently Used)</strong> — Evicts the entry accessed the fewest times.</li><li><strong>TTL-based</strong> — Evicts the entry closest to expiring, based on a per-key <strong>Time To Live (TTL)</strong>.</li></ul><h3>Where Caching Lives: Three Layers</h3><h4>1. Network-Level Caching</h4><p><strong>Content Delivery Networks (CDNs)</strong> cache content — images, videos, static HTML/CSS/JS — on <strong>edge servers</strong> placed geographically close to users.<br>A cluster of edge servers in one region is called a <strong>Point of Presence (PoP)</strong>. Requests are routed by DNS to the nearest PoP; a cache hit is served locally, while a miss is fetched from the <strong>origin server</strong> and then cached under a TTL. This minimizes latency and offloads the origin.<br><strong>DNS resolution</strong> is itself heavily cached. Resolving a domain to an IP can require walking from root servers to top-level-domain servers to authoritative servers — expensive work to repeat per request. Caches at the OS, browser, and recursive-resolver levels short-circuit this lookup.</p><h4>2. Hardware-Level Caching</h4><p>CPUs maintain <strong>L1, L2, and L3 caches</strong> between the processor and RAM. Predictive prefetching loads likely-needed memory (for example, contiguous array elements) into these caches, which is why sequential array traversal is fast.</p><h3>3. Software-Level Caching</h3><p>This is the layer backend engineers control directly via libraries and services like Redis or ElastiCache. It builds on the hardware memory beneath it but is driven by application code.</p><h3>Architecture / Workflow</h3><h4>Cache-Aside Request Lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*3FImvixTBV02jlPVGkV8Rw.png" /></figure><h4>CDN Delivery Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*yQsaBwzeLLbEpwCgJEX6Pw.png" /></figure><h3>Different Use Cases</h3><ol><li><strong>Database query caching</strong> — Cache the results of expensive, read-heavy queries (for example, a <strong>blogging platform’s</strong> popular-posts list) with a TTL, invalidating on write. Ideal when reads vastly outnumber writes and the underlying data changes infrequently.</li><li><strong>Session storage</strong> — After authentication, store session tokens in an in-memory store so every subsequent API call validates the session in memory rather than hitting the primary database.</li><li><strong>External API caching</strong> — When a <strong>payment gateway</strong> integrates a third-party currency-rate API with rate limits and per-call pricing, caching responses for a fixed TTL avoids redundant calls, controls cost, and prevents throttling.</li><li><strong>Rate limiting</strong> — A middleware extracts the client IP (typically from the X-Forwarded-For header) and maintains a per-IP request counter in Redis. If the count exceeds the allowed threshold within a window, the request is rejected with <strong>HTTP 429 (Too Many Requests)</strong>. Using an in-memory store keeps this check fast and keeps the load off the relational database.</li></ol><h3>Summary</h3><p>Caching trades a small amount of extra memory and complexity for large gains in <strong>latency</strong> and <strong>throughput</strong>. Whenever a system repeatedly performs heavy computation or repeatedly moves the same data, caching — whether at the CDN, DNS, hardware, or application layer — is the standard remedy. For backend work, in-memory key-value stores like Redis and Valkey, combined with sound caching strategies and eviction policies, are the practical tools of choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717fe74769e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful APIs]]></title>
            <link>https://suryapratap04.medium.com/restful-apis-8d9f0836baee?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d9f0836baee</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 09:42:19 GMT</pubDate>
            <atom:updated>2026-08-02T09:42:19.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>A <strong>REST API</strong> (Representational State Transfer Application Programming Interface) is a convention for exposing server-side resources over HTTP so that clients — browsers, mobile apps, or other services — can read and modify them in a predictable way.</p><p>REST is not a framework or a library; it is an <strong>architectural style</strong>. It defines a set of constraints that, when followed, produce systems that are scalable, loosely coupled, and easy to evolve. It coexists with other API paradigms such as <strong>RPC</strong> and <strong>GraphQL</strong>, but remains the most widely adopted standard for public and internal web APIs.</p><p>Backend engineers spend a large portion of their time designing APIs. A well-designed API reduces integration effort, eliminates guesswork for consumers, and lets teams focus on business logic rather than debating conventions. This document consolidates the rules and patterns that make an API feel consistent and intuitive.</p><h3>Problem Statement</h3><p>The web was originally built around <strong>multi-page applications (MPAs)</strong>, where the server rendered complete HTML documents for every navigation. Modern applications are dominated by <strong>single-page applications (SPAs)</strong> and service-to-service communication, where clients request structured data (usually JSON) and handle rendering or orchestration themselves.</p><p>Because REST conventions predate this shift, engineers repeatedly face the same ambiguous questions:</p><ul><li>Should a path segment be singular or plural?</li><li>When updating a resource, should I use PUT or PATCH?</li><li>What HTTP status code fits each scenario?</li><li>How do I model an operation that is neither create, read, update, nor delete?</li></ul><p>The goal is not to invent new standards but to <strong>extract a consistent, defensible set of guidelines</strong> from the existing REST specification. Adopting them removes recurring decisions from day-to-day development.</p><h3>Core Concepts</h3><h3>What “REST” Actually Means</h3><p>The name decomposes into three ideas:</p><ul><li><strong>Representational</strong> — A resource (a piece of data, such as a customer order) has no single fixed form. It can be <em>represented</em> as JSON for a service consumer, or as HTML for a browser. The same underlying entity yields different representations depending on the client’s needs.</li><li><strong>State</strong> — Each resource has a current condition (its fields and values). For example, a shopping cart’s state includes its line items, quantities, and total.</li><li><strong>Transfer</strong> — Representations of that state move between client and server over HTTP using standard methods.</li></ul><p>Combined, REST describes a system in which resources have multiple representations, their state can be transferred between client and server, and the whole exchange obeys a fixed set of constraints.</p><h3>The Six Architectural Constraints</h3><p><strong>Constraint</strong> <strong>Purpose</strong> <strong>Client–Server</strong> Separates the user interface (client) from data storage and business logic (server) so each can evolve independently. <strong>Uniform Interface</strong> Standardizes how components communicate (resource identification, manipulation through representations, self-descriptive messages, hypermedia). <strong>Layered System</strong> Allows intermediaries — load balancers, proxies, caches — to sit between client and server without either side knowing. <strong>Cacheable</strong> Responses must declare whether they can be cached, reducing load and latency. <strong>Stateless</strong> Every request carries all information needed to process it; the server stores no client context between requests. <strong>Code on Demand</strong> <em>(optional)</em> The server may extend client behavior by sending executable code (e.g., JavaScript).</p><p><strong>Statelessness</strong> is what makes horizontal scaling practical: because no request depends on server-side session memory, a load balancer can route successive requests from the same client to different servers.</p><h3>Idempotency</h3><p>An operation is <strong>idempotent</strong> if performing it multiple times produces the same server-side effect as performing it once. Idempotency is measured strictly by the <em>side effect on the server</em>, not by whether the response body changes over time.</p><p><strong>Method</strong> <strong>Typical Use</strong> <strong>Idempotent?</strong> GET Retrieve a resource Yes — reading never mutates state PUT Replace a resource entirely Yes — the same payload yields the same final state PATCH Update part of a resource Yes — reapplying the same partial update is a no-op DELETE Remove a resource Yes — after the first call the resource is gone; repeats change nothing POST Create a resource / custom action <strong>No</strong> — each call typically creates a new resource</p><p><strong>PUT vs. </strong><strong>PATCH:</strong> Use PATCH to modify a subset of fields; use PUT to replace the entire representation. Although developers often treat them interchangeably, sticking to the correct semantics matters for public APIs, where consumers rely on standard behavior.</p><p><strong>POST as an escape hatch:</strong> POST is intentionally open-ended. Any operation that does not map to create/read/update/delete—a <strong>custom action</strong>—is expressed as a POST.</p><h3>Designing a URL</h3><p>A typical URL decomposes into distinct parts:</p><pre>&lt;https://api.example.com/v1/products?status=active#reviews&gt;<br>└─┬─┘   └──────┬──────┘ └┬┘ └──┬───┘ └─────┬─────┘ └──┬──┘<br>scheme      authority   ver  path      query params  fragment</pre><p>Recommended API conventions:</p><ul><li><strong>Dedicated subdomain</strong> — expose the API under api.example.com.</li><li><strong>Versioning</strong> — prefix paths with /v1, /v2, etc., so breaking changes don&#39;t disrupt existing consumers.</li><li><strong>Plural resource names</strong> — always use the plural form in path segments, even when addressing a single item:</li><li>List: GET /v1/products</li><li>Single: GET /v1/products/8fa3c1</li><li><strong>Hierarchy through </strong><strong>/</strong> — a forward slash expresses a parent–child relationship (/products/8fa3c1 = &quot;this product within the collection of products&quot;).</li><li><strong>Slugs</strong> — when placing human-readable text in a URL, lowercase it and replace spaces with hyphens (e.g., Wireless Keyboard → wireless-keyboard). Avoid spaces and underscores.</li></ul><h3>Architecture / Workflow</h3><p>API interface design should precede any coding. The recommended sequence:</p><ol><li><strong>Study the UI/wireframes</strong> to understand how end users interact with data.</li><li><strong>Identify resources</strong> — extract the nouns from the requirements. For an e-commerce catalog these might be warehouses, products, and reviews.</li><li><strong>Design the database schema</strong> for those resources (covered separately).</li><li><strong>Enumerate the actions</strong> clients must perform (CRUD plus any custom actions).</li><li><strong>Design the interface</strong> in a tool such as Insomnia, Postman, or an OpenAPI/Swagger editor before writing business logic.</li></ol><h3>Standard CRUD Endpoints</h3><p>Using products as the example resource:</p><p><strong>Action</strong> <strong>Method &amp; Route</strong> <strong>Success Status</strong> List products GET /v1/products 200 OK Create product POST /v1/products 201 Created Get one product GET /v1/products/{id} 200 OK Update product PATCH /v1/products/{id} 200 OK Delete product DELETE /v1/products/{id} 204 No Content</p><p>The server distinguishes GET /v1/products from POST /v1/products by the <strong>HTTP method</strong>, even though the paths are identical. Server-managed fields (id, createdAt, updatedAt) are never accepted in the request body—they are generated server-side.</p><h3>List Endpoints: Pagination, Sorting, Filtering</h3><p>Returning an entire table in one response is expensive to serialize and slow for users. <strong>Pagination</strong> returns a bounded slice of data plus metadata:</p><pre>{<br>  &quot;data&quot;: [ /* subset of products */ ],<br>  &quot;total&quot;: 137,<br>  &quot;page&quot;: 1,<br>  &quot;totalPages&quot;: 14<br>}</pre><ul><li><strong>limit</strong> — number of items per page (server applies a sensible default, e.g., 10 or 20).</li><li><strong>page</strong> — which slice to return (defaults to 1).</li><li><strong>sortBy</strong> / <strong>sortOrder</strong> — field and direction; default to createdAt descending so results are stable across calls.</li><li><strong>Filtering</strong> — allow query parameters such as ?status=active or ?name=keyboard to narrow the list.</li></ul><p>A list endpoint that matches no records returns an <strong>empty array with </strong><strong>200 OK</strong>, never 404. A 404 Not Found is reserved for requests that target a <em>specific</em> resource that does not exist.</p><h3>Custom Actions</h3><p>When an operation cannot be modeled as CRUD, express it as a POST with an action segment appended to the resource path.</p><p><strong>Example — archiving a warehouse.</strong> Setting status = archived is not a simple field update: archiving may also relocate inventory, notify affected staff, and close open shipments. Because it triggers side effects beyond a single field, it is a custom action:</p><pre>POST /v1/warehouses/{id}/archive     → 200 OK</pre><p>Note that a POST does <strong>not</strong> always return 201. A custom action that mutates but does not create a resource returns 200; one that creates a new resource (e.g., cloning) returns 201.</p><h3>Best Practices</h3><ul><li><strong>Provide interactive documentation.</strong> Maintain an OpenAPI/Swagger definition from the start. It doubles as a live testing playground and as authoritative documentation for consumers.</li><li><strong>Be consistent and intuitive.</strong> Once you choose a routing style, payload shape, or naming convention, apply it uniformly across every resource. Consumers form assumptions from the first endpoint they integrate; inconsistency forces them back into the docs.</li><li><strong>Use JSON conventions.</strong> Keep field names in camelCase for both requests and responses.</li><li><strong>Supply sane defaults.</strong> Don’t force clients to send obvious values — default the page, limit, sort order, and reasonable initial states (e.g., a new order defaults to status = pending).</li><li><strong>Avoid abbreviations.</strong> Prefer description over desc. Consumers lack your context; readable names prevent avoidable errors.</li><li><strong>Design before you code.</strong> The API interface is a design artifact, independent of the implementation language. Dedicate a session to modeling routes, payloads, and responses before writing any server code.</li></ul><h3>Summary</h3><p>REST provides a shared vocabulary for client–server communication built on resources, representations, and a fixed set of constraints. In practice, a clean API means: plural, hierarchical, versioned routes; correct HTTP methods and status codes; idempotent operations where expected; paginated, sortable, and filterable list endpoints; custom actions expressed through POST; and—above all—<strong>consistency</strong>. Following these conventions lets both the authors and the consumers of an API work without guesswork.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d9f0836baee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend Request Lifecycle]]></title>
            <link>https://suryapratap04.medium.com/backend-request-lifecycle-efff731eef66?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/efff731eef66</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 13:42:16 GMT</pubDate>
            <atom:updated>2026-07-27T13:42:16.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>A backend application processes each HTTP request through a series of structured stages before returning a response. In production systems, this flow is commonly organized using:</p><ul><li><strong>Handlers or controllers</strong> for HTTP-specific input and output.</li><li><strong>Services</strong> for business logic.</li><li><strong>Repositories</strong> for database access.</li><li><strong>Middleware</strong> for reusable cross-cutting behavior.</li><li><strong>Request context</strong> for request-scoped metadata.</li></ul><p>This separation helps to build backend systems that are easier to test, maintain, debug, and extend.</p><h3>Problem Statement</h3><p>A backend API could technically place all logic inside a single route handler: parsing input, validating data, checking authentication, querying databases, applying business rules, and sending responses.</p><p>However, this approach quickly becomes difficult to maintain as the application grows. Common issues include:</p><ul><li>Repeated authentication and logging logic across many handlers.</li><li>Business logic tightly coupled to HTTP frameworks.</li><li>Database queries scattered throughout the codebase.</li><li>Inconsistent error responses.</li><li>Difficult unit testing due to mixed responsibilities.</li></ul><p>Layered backend architecture solves this by assigning clear responsibilities to each part of the request lifecycle.</p><h3>Core Concepts</h3><h4>Handler or Controller</h4><p>A <strong>handler</strong> is the function mapped to an API route. It is the HTTP-facing layer of the application.</p><h4>Purpose</h4><p>The handler translates between HTTP and application logic.</p><p>Typical responsibilities include:</p><ul><li>Reading path parameters, query parameters, headers, and request body.</li><li>Deserializing JSON into native data structures.</li><li>Validating and transforming input.</li><li>Calling the service layer.</li><li>Mapping service results to HTTP responses.</li><li>Returning appropriate status codes such as 200, 201, 204, 400, 401, or 500.</li></ul><h3>Working Principle</h3><p>For example, a POST /orders handler may:</p><ol><li>Read the request body.</li><li>Validate required fields.</li><li>Extract the authenticated user ID from request context.</li><li>Call orderService.createOrder(...).</li><li>Return 201 Created with the created order.</li></ol><p>Handlers should not contain complex business rules or direct database queries.</p><h3>Service Layer</h3><p>A <strong>service</strong> contains the application’s business logic. It should not depend on HTTP request or response objects.</p><h3>Purpose</h3><p>Services coordinate application behavior.</p><p>They may:</p><ul><li>Enforce business rules.</li><li>Call one or more repositories.</li><li>Invoke external services.</li><li>Send emails or notifications.</li><li>Combine data from multiple sources.</li><li>Return domain-specific results or errors.</li></ul><h3>Working Principle</h3><p>A service method should look like a regular function. It receives structured input, performs work, and returns a result.</p><p>For example, an order service may check inventory, calculate totals, create an order, and publish an event.</p><h3>Benefits</h3><ul><li>Easier unit testing.</li><li>Reusable outside HTTP APIs, such as jobs or message consumers.</li><li>Keeps business logic independent from transport details.</li></ul><h3>Repository Layer</h3><p>A <strong>repository</strong> is responsible for database operations.</p><h3>Purpose</h3><p>Repositories isolate persistence logic from business logic.</p><p>They typically:</p><ul><li>Build database queries.</li><li>Insert, update, delete, or fetch records.</li><li>Return database results in a predictable shape.</li></ul><h3>Working Principle</h3><p>A repository method should perform one clearly defined operation.</p><p>Good examples:</p><ul><li>findOrderById(orderId)</li><li>listOrdersByCustomer(customerId)</li><li>createOrder(orderData)</li></ul><p>Avoid designing one repository method that returns different data shapes based on optional parameters. Separate methods are usually clearer and safer.</p><h3>Middleware</h3><p><strong>Middleware</strong> is reusable logic executed during the request lifecycle before or after the handler.</p><p>Middleware commonly receives:</p><ul><li>The request object.</li><li>The response object.</li><li>A next function or equivalent mechanism to continue execution.</li></ul><h3>Purpose</h3><p>Middleware is used for cross-cutting concerns that apply to many routes.</p><p>Common examples include:</p><p>Middleware TypeResponsibilityCORSControls which browser origins may access the APISecurity headersAdds headers such as content security policiesAuthenticationVerifies tokens or sessionsRate limitingRejects excessive requestsLoggingRecords request metadataCompressionCompresses large responsesError handlingConverts internal errors into consistent API responses</p><h3>Trade-offs</h3><p>Middleware order is important. Authentication must run before authorization checks. Error handling is usually registered near the end so it can process failures from previous layers.</p><h3>Request Context</h3><p>A <strong>request context</strong> is request-scoped storage available throughout the lifecycle of a single request.</p><h3>Purpose</h3><p>It carries metadata without requiring every function call to pass many parameters manually.</p><p>Common context values include:</p><ul><li>Authenticated user ID.</li><li>User role or permissions.</li><li>Request ID or correlation ID.</li><li>Deadlines and cancellation signals.</li><li>Tenant or organization ID.</li></ul><h3>Benefits</h3><p>Request context is especially useful in distributed systems. A request ID can be passed across services so logs from multiple systems can be correlated during debugging.</p><h3>Architecture / Workflow</h3><p>A typical request lifecycle:</p><ol><li>The client sends an HTTP request.</li><li>The server receives the request on a listening port.</li><li>Global middleware runs, such as CORS, logging, or security headers.</li><li>The router matches the request path and method to a handler.</li><li>Route-specific middleware may authenticate or authorize the request.</li><li>The handler extracts and validates input.</li><li>The handler calls the service layer with clean application data.</li><li>The service executes business logic.</li><li>The repository performs required database operations.</li><li>The service returns the result to the handler.</li><li>The handler serializes the response and sends an HTTP status code and body.</li></ol><h3>Example: Creating an Order</h3><p>Consider an e-commerce API endpoint:</p><p>POST /orders</p><p>The request body contains product IDs and quantities. The authenticated customer ID is not accepted from the client payload. Instead, it is read from the request context after authentication.</p><p>This prevents a malicious client from creating orders on behalf of another user.</p><p>Workflow:</p><ol><li>Authentication middleware validates the access token.</li><li>Middleware stores userId in request context.</li><li>Handler validates the order payload.</li><li>Handler calls the order service.</li><li>Service checks inventory and calculates totals.</li><li>Repository inserts the order and order items.</li><li>Handler returns 201 Created.</li></ol><h3>Code</h3><pre>import express, { Request, Response, NextFunction } from &quot;express&quot;;<br><br>const app = express();<br><br>app.use(express.json());<br><br>type AuthenticatedRequest = Request &amp; {<br>  context?: {<br>    userId: string;<br>    requestId: string;<br>  };<br>};<br><br>function requestContext(<br>  req: AuthenticatedRequest,<br>  _res: Response,<br>  next: NextFunction<br>) {<br>  req.context = {<br>    userId: &quot;&quot;,<br>    requestId: crypto.randomUUID(),<br>  };<br><br>  next();<br>}<br><br>function authenticate(<br>  req: AuthenticatedRequest,<br>  res: Response,<br>  next: NextFunction<br>) {<br>  const token = req.header(&quot;Authorization&quot;);<br><br>  if (!token) {<br>    return res.status(401).json({<br>      code: &quot;UNAUTHORIZED&quot;,<br>      message: &quot;Missing authorization token.&quot;,<br>    });<br>  }<br><br>  // Token verification omitted for brevity.<br>  req.context!.userId = &quot;customer_123&quot;;<br><br>  next();<br>}<br><br>class OrderRepository {<br>  async createOrder(<br>    customerId: string,<br>    items: Array&lt;{ productId: string; quantity: number }&gt;<br>  ) {<br>    return {<br>      id: &quot;order_789&quot;,<br>      customerId,<br>      items,<br>      status: &quot;CREATED&quot;,<br>    };<br>  }<br>}<br><br>class OrderService {<br>  constructor(private readonly orderRepository: OrderRepository) {}<br><br>  async createOrder(<br>    customerId: string,<br>    items: Array&lt;{ productId: string; quantity: number }&gt;<br>  ) {<br>    if (items.length === 0) {<br>      throw new Error(&quot;Order must contain at least one item.&quot;);<br>    }<br><br>    return this.orderRepository.createOrder(customerId, items);<br>  }<br>}<br><br>const orderService = new OrderService(new OrderRepository());<br><br>app.post(<br>  &quot;/orders&quot;,<br>  requestContext,<br>  authenticate,<br>  async (<br>    req: AuthenticatedRequest,<br>    res: Response,<br>    next: NextFunction<br>  ) =&gt; {<br>    try {<br>      const items = req.body.items;<br><br>      if (!Array.isArray(items)) {<br>        return res.status(400).json({<br>          code: &quot;INVALID_BODY&quot;,<br>          message: &quot;Items must be an array.&quot;,<br>        });<br>      }<br><br>      const order = await orderService.createOrder(<br>        req.context!.userId,<br>        items<br>      );<br><br>      return res.status(201).json(order);<br>    } catch (error) {<br>      next(error);<br>    }<br>  }<br>);<br><br>app.use(<br>  (<br>    error: Error,<br>    _req: Request,<br>    res: Response,<br>    _next: NextFunction<br>  ) =&gt; {<br>    res.status(500).json({<br>      code: &quot;INTERNAL_SERVER_ERROR&quot;,<br>      message: error.message,<br>    });<br>  }<br>);</pre><h3>Best Practices</h3><ul><li>Keep handlers thin and focused on HTTP concerns.</li><li>Place business rules in services, not controllers.</li><li>Keep repositories dedicated to persistence operations.</li><li>Validate all external input before passing it downstream.</li><li>Do not trust user identity values from request bodies.</li><li>Use middleware for repeated cross-cutting logic.</li><li>Register middleware in a deliberate order.</li><li>Use request IDs for tracing and debugging.</li><li>Return consistent error response formats.</li><li>Write unit tests for services independently from HTTP routes.</li></ul><h3>Common Mistakes</h3><ul><li><strong>Putting all logic in handlers</strong>: Move business rules to services and database logic to repositories.</li><li><strong>Passing HTTP objects into services</strong>: Services should receive plain data, not framework-specific objects.</li><li><strong>Trusting client-provided user IDs</strong>: Use authenticated context instead.</li><li><strong>Creating overly generic repository methods</strong>: Prefer explicit methods with predictable return types.</li><li><strong>Incorrect middleware order</strong>: Ensure security, authentication, and error-handling middleware are placed correctly.</li><li><strong>Skipping validation</strong>: Validate path parameters, query parameters, headers, and body payloads.</li></ul><h3>Key Takeaways</h3><ul><li>Backend request processing is easier to maintain when responsibilities are separated.</li><li>Handlers manage HTTP concerns.</li><li>Services contain business logic.</li><li>Repositories handle database operations.</li><li>Middleware centralizes reusable lifecycle behavior.</li><li>Request context stores metadata for one request.</li><li>Middleware order affects correctness and security.</li><li>Validation and transformation should happen before business logic.</li><li>Consistent error handling improves API reliability.</li><li>Clean layering improves scalability, testing, and maintainability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efff731eef66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorization]]></title>
            <link>https://suryapratap04.medium.com/authentication-and-authorization-b4588b4f0591?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4588b4f0591</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 19:27:46 GMT</pubDate>
            <atom:updated>2026-07-24T19:27:46.073Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Authentication</strong> and <strong>authorization</strong> are the two pillars of access control in any software system. Every login screen, sign-up form, and “Continue with Google” button is an expression of these concepts working behind the scenes.</p><p>The distinction is best captured in two questions:</p><ul><li><strong>Authentication</strong> answers <em>“Who are you?”</em> — it assigns a verified identity to a subject (a user, service, or device) within a given context.</li><li><strong>Authorization</strong> answers <em>“What are you allowed to do?”</em> — it determines the permissions and capabilities that identity holds.</li></ul><h3>Why Things Look the Way They Do</h3><p>Understanding the evolution helps explain today’s design decisions.</p><p>Era Mechanism Underlying Principle Pre-industrial Personal recognition, handshakes Human contextual trust Medieval Wax seals on documents Something you <strong>have</strong> (possession) Industrial Telegraph passphrases / shared secrets Something you <strong>know </strong>Mainframe (1960s)First digital passwords (MIT CTSS)Stored credentials1970s Diffie–Hellman key exchange, Kerberos ticketsAsymmetric cryptography1990sMulti-Factor Authentication (MFA), biometricsCombining multiple factors2000s–todayOAuth, JWT, OpenID Connect, zero-trust, passwordlessToken-based, delegated trust</p><p>An early lesson still shapes practice today: on the MIT CTSS system, passwords were stored in <strong>plaintext</strong>, and a printout accidentally exposed the entire password file. That incident helped establish the principle that credentials must be stored using irreversible <strong>hashing</strong> — an algorithm that converts any input into a fixed-length, deterministic, one-way string.</p><p>The three classic authentication factors remain foundational:</p><ul><li><strong>Something you know</strong> — password, PIN.</li><li><strong>Something you have</strong> — hardware token, OTP generator, smart card.</li><li><strong>Something you are</strong> — biometrics (fingerprint, retina).</li></ul><h3>Three Core Building Blocks</h3><h3>1. Sessions</h3><p>HTTP is <strong>stateless</strong> by design — each request is treated as an isolated interaction with no memory of previous ones. This was fine for early static websites but broke down once applications needed continuity (staying logged in, remembering a shopping cart).</p><p>A <strong>session</strong> introduces temporary server-side state for each user:</p><ol><li>On login, the server generates a unique <strong>session ID</strong> and stores it alongside user data in a persistent store.</li><li>The session ID is returned to the client (usually via a cookie).</li><li>Each subsequent request carries the session ID, letting the server look up the associated state.</li><li>Sessions are short-lived and expire after a set interval.</li></ol><p>Session storage has evolved from <strong>file-based → database-backed → distributed in-memory stores</strong> (like Redis or Memcached) for speed and scalability.</p><h3>2. JSON Web Tokens (JWT)</h3><p>As applications became globally distributed, keeping session state on the server became expensive (memory overhead) and hard to synchronize across regions (replication latency). JWTs solve this by being <strong>stateless and self-contained</strong>.</p><p>A JWT is a Base64-encoded string with three parts:</p><p>PartContents<strong>Header</strong>Metadata, e.g. the signing algorithm<strong>Payload</strong>Claims such as sub (subject/user ID), iat (issued-at), role, name<strong>Signature</strong>Cryptographic signature verifying integrity, created with a secret key</p><p>Because the signature validates that the token hasn’t been tampered with, the server can trust its contents <strong>without a database lookup</strong>.</p><p><strong>Advantages:</strong> statelessness (no server storage), scalability (any server holding the shared secret can validate the token), and portability (compact and URL-safe).</p><p><strong>Limitations:</strong> a stolen JWT can be used to impersonate a user, and there’s <strong>no easy revocation</strong> before expiry — invalidating one token by rotating the secret logs out <em>everyone</em>.</p><h3>3. Cookies</h3><p>A <strong>cookie</strong> is a piece of data a server stores in the user’s browser. Browsers automatically attach the relevant cookie to every subsequent request to the issuing server, and cookies are scoped so one site cannot read another’s. Marking a cookie HttpOnly prevents JavaScript from reading it — important protection against token theft.</p><h3>Authentication Strategies Compared</h3><h4>Stateful Authentication</h4><h4>Stateless Authentication</h4><p>Criteria <br>StatefulStateless (JWT)<strong>Control</strong>Centralized<br>easy revocation &amp; real-time session viewRevocation is hard until expiry<strong>Scalability</strong>Limited<br>sync overhead across regionsExcellent for distributed systems<strong>Best for</strong>Web apps, SaaS dashboardsAPIs, mobile clients,microservices<strong>Security</strong>Generally stronger (revocable)Depends on token handling</p><p><strong>Hybrid approach:</strong> Use stateful auth for browser-based web apps (where revocability matters) and stateless JWTs for mobile apps or third-party integrations. A JWT <strong>blacklist</strong> in Redis can add revocation, though it partially reintroduces state — a common trade-off discussion.</p><blockquote><strong><em>Practical advice:</em></strong><em> For medium-to-large production systems, use a managed identity provider (Auth0, Clerk, Cognito, etc.) rather than building auth from scratch. Implementing your own is valuable for </em>learning<em> the trade-offs, but production auth is a specialized, security-critical discipline.</em></blockquote><h3>API Key Authentication</h3><p>API keys serve <strong>machine-to-machine (M2M)</strong> communication rather than human logins. A user generates a cryptographically random key from a dashboard and attaches it to programmatic requests.</p><p><em>Example:</em> A translation platform exposes an API. Your inventory system calls it directly — server to server, no human clicking a login form — authenticating with a scoped, expiring API key. Keys are ideal because M2M flows have no visual/interactive login step.</p><h3>OAuth 2.0 and OpenID Connect</h3><p>OAuth solves the <strong>delegation problem</strong>: letting one application access a user’s resources on another platform <em>without sharing passwords</em>. Password sharing was disastrous — it granted total access and could only be revoked by changing the password everywhere.</p><p>OAuth 2.0 replaces passwords with <strong>scoped tokens</strong>. Four roles are involved:</p><ul><li><strong>Resource Owner</strong> — the user who owns the data.</li><li><strong>Client</strong> — the app requesting access.</li><li><strong>Resource Server</strong> — where the protected data lives.</li><li><strong>Authorization Server</strong> — issues tokens after user consent.</li></ul><p>OAuth 2.0 introduced simpler <strong>bearer tokens</strong> and multiple flows for different app types:</p><ul><li><strong>Authorization Code</strong> — server-side apps.</li><li><strong>Client Credentials</strong> — machine-to-machine.</li><li><strong>Device Code</strong> — input-constrained devices (smart TVs).</li><li><strong>Implicit</strong> — legacy browser apps (now discouraged).</li></ul><p>Crucially, OAuth handles <em>authorization</em>, not <em>authentication</em> — it doesn’t verify <strong>who</strong> the user is. <strong>OpenID Connect (OIDC)</strong> fills that gap by adding an <strong>ID token</strong> (a JWT containing user ID, name, email, issuer, and issue time). This powers “Sign in with Google/Facebook/Discord” — the client authenticates the user via a trusted provider without managing its own credentials.</p><h3>Authorization: Role-Based Access Control (RBAC)</h3><p>Once a user is authenticated, authorization decides <strong>what they can do</strong>. Not every user should have the same power — an admin can purge archived records; a regular user cannot.</p><p>Hard-coding a secret “god-mode” string into requests is insecure and unscalable. <strong>RBAC</strong> is the standard solution:</p><ul><li>Define <strong>roles</strong> (user, editor, moderator, admin).</li><li>Attach <strong>permissions</strong> to roles (read, write, delete) per resource.</li><li>Assign roles to users.</li></ul><p>Typically the role is resolved early in the request cycle (in middleware) and passed downstream so later logic can enforce fine-grained checks.</p><h3>Example</h3><p>An original, production-style Express.js example combining stateless JWT authentication with RBAC:</p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>const SECRET = process.env.JWT_SECRET;<br>// - - Authentication middleware - -<br>function authenticate(req, res, next) {<br> const header = req.headers.authorization || &quot;&quot;;<br> const token = header.startsWith(&quot;Bearer &quot;) ? header.slice(7) : null;<br> if (!token) {<br>   // Generic message - never reveal what specifically failed<br>   return res.status(401).json({ error: &quot;Authentication failed&quot; });<br> }<br> try {<br>   // Verifying the signature also decodes the payload (sub, role, iat)<br>   req.user = jwt.verify(token, SECRET);<br>   next();<br> } catch {<br>   return res.status(401).json({ error: &quot;Authentication failed&quot; });<br> }<br>}<br>// - - Authorization middleware (RBAC) - -<br>function authorize(…allowedRoles) {<br>  return (req, res, next) =&gt; {<br>    if (!allowedRoles.includes(req.user.role)) {<br>       return res.status(403).json({ error: &quot;Forbidden&quot; });<br>    }<br>    next();<br>   };<br>}<br>// Only admins may access archived (&quot;dead zone&quot;) records<br>app.delete(<br>    &quot;/api/archive/:id&quot;,<br>     authenticate,<br>     authorize(&quot;admin&quot;),<br>      (req, res) =&gt; res.json({ <br>          status: &quot;permanently deleted&quot; <br>      })<br>);</pre><h3>Security Best Practices</h3><ul><li><strong>Hash passwords</strong> with a strong, salted algorithm (bcrypt, scrypt, Argon2) — never store plaintext or use fast hashes like plain MD5/SHA-1.</li><li><strong>Use generic error messages</strong> during authentication (see Common Mistakes).</li><li><strong>Set </strong><strong>HttpOnly, </strong><strong>Secure, and </strong><strong>SameSite</strong> flags on session/token cookies.</li><li><strong>Keep tokens short-lived</strong> and use refresh tokens for renewal.</li><li><strong>Store secret keys</strong> in environment variables or a secrets manager — never in source code.</li><li><strong>Prefer managed identity providers</strong> for production systems.</li><li><strong>Apply least privilege</strong> — grant the minimum scopes and permissions necessary.</li></ul><h3>Common Mistakes and How to Avoid Them</h3><h4>1. Leaking information through error messages</h4><p>Messages like &quot;User not found&quot; or &quot;Incorrect password&quot; tell an attacker exactly where to focus — confirming valid usernames or shifting effort to password brute-forcing. <strong>Always return a single generic message</strong> (&quot;Authentication failed&quot;) for every credential failure.</p><h4>2. Timing attacks</h4><p>Consider this login flow:</p><p>If a missing username fails <strong>instantly</strong> but a valid username with a wrong password takes longer (because the expensive password hash is computed), the measurable time difference leaks whether the username exists. <strong>Mitigations:</strong></p><ul><li>Use <strong>constant-time comparison</strong> functions for hashes.</li><li><strong>Normalize response time</strong> — perform a dummy hash even when the user doesn’t exist, or introduce a small artificial delay so all outcomes take the same time.</li></ul><h4>3. Storing JWTs in localStorage</h4><p>This exposes tokens to XSS attacks. Prefer HttpOnly cookies.</p><h3>Key Takeaways</h3><ul><li><strong>Authentication = identity (“who”);</strong></li><li><strong>Authorization = permissions (“what”).</strong></li><li><strong>Sessions, JWTs, and cookies</strong> are the core building blocks of nearly every auth flow.</li><li><strong>Stateful auth</strong> offers control and easy revocation; <strong>stateless JWT auth</strong> offers scalability — a <strong>hybrid</strong> approach often wins.</li><li><strong>API keys</strong> are built for machine-to-machine communication.</li><li><strong>OAuth 2.0</strong> enables password-free delegated access; <strong>OpenID Connect</strong> adds identity on top.</li><li><strong>RBAC</strong> is the standard model for fine-grained authorization.</li><li><strong>Never store plaintext passwords</strong> — always hash with a strong, salted algorithm.</li><li><strong>Return generic auth errors</strong> and <strong>normalize response times</strong> to resist enumeration and timing attacks.</li><li>For production systems, <strong>lean on managed identity providers</strong> rather than rolling your own.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4588b4f0591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serialization and Deserialization]]></title>
            <link>https://suryapratap04.medium.com/serialization-and-deserialization-in-backend-d571ef933a52?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d571ef933a52</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 04:59:29 GMT</pubDate>
            <atom:updated>2026-07-22T05:01:00.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Modern backend applications rarely operate in isolation. A web browser communicates with a backend server, microservices exchange data with one another, and applications integrate with external APIs. These systems are often written in different programming languages and run on different operating systems.</p><p>For example:</p><ul><li>Frontend → JavaScript (React, Angular, Vue)</li><li>Backend → Java, Node.js, Go, Rust, Python</li><li>Mobile App → Kotlin, Swift</li></ul><p>Since every language represents objects differently, they cannot directly exchange their in-memory data structures. Before data can be transmitted over a network or stored, it must be converted into a <strong>common, language-independent format</strong>.</p><p>This conversion process is known as <strong>serialization</strong>, while the reverse process is called <strong>deserialization</strong>.</p><h3>Why Serialization is Needed</h3><p>Consider a frontend application written in JavaScript communicating with a backend written in Rust.</p><p>JavaScript object:</p><pre>{<br>    name: &quot;Alice&quot;,<br>    age: 25<br>}</pre><p>Rust cannot directly understand JavaScript objects because both languages have different memory layouts, data types, and runtime environments.</p><p>Instead of exchanging language-specific objects, both applications agree on a <strong>common serialization format</strong>, such as JSON.</p><pre>JavaScript Object<br>        │<br>Serialization<br>        │<br>        ▼<br>JSON<br>        │<br>Network<br>        │<br>        ▼<br>JSON<br>        │<br>Deserialization<br>        │<br>        ▼<br>Rust Struct</pre><p>By converting data into a shared format, applications developed using different technologies can communicate reliably.</p><h3>Client–Server Communication</h3><p>A typical web application consists of two main components:</p><ul><li>Client (Browser or Mobile App)</li><li>Server (Backend Application)</li></ul><p>Communication occurs over protocols such as:</p><ul><li>HTTP (REST APIs)</li><li>WebSocket</li><li>gRPC</li></ul><p>In this, our focus is on <strong>HTTP-based communication</strong>, where serialized data is exchanged in request and response bodies.</p><h3>What is Serialization?</h3><p>Serialization is the process of converting an application’s internal data structure into a standardized format suitable for transmission or storage.</p><p>In backend systems, serialization typically occurs before sending data over the network.</p><p>Example:</p><p>JavaScript Object</p><pre>const user = {<br>    id: 1,<br>    name: &quot;Alice&quot;<br>};</pre><p>Serialized JSON</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Alice&quot;<br>}</pre><p>The serialized data is then included in the HTTP request body and transmitted to the server.</p><h3>What is Deserialization?</h3><p>Deserialization is the reverse process.</p><p>The receiving application converts serialized data back into its native data structures.</p><p>Example:</p><p>Received JSON</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Alice&quot;<br>}</pre><p>After deserialization:</p><ul><li>Java → Object</li><li>Rust → Struct</li><li>Python → Dictionary</li><li>JavaScript → Object</li></ul><p>The backend can now validate the data, execute business logic, interact with databases, and generate responses.</p><h3>Serialization Workflow</h3><p>The complete communication process is illustrated below.</p><pre>Client Application<br>        │<br>Application Object<br>        │<br>Serialization<br>        ▼<br>JSON<br>        │<br>HTTP Request<br>        │<br>Internet<br>        │<br>HTTP Response<br>        ▼<br>JSON<br>        │<br>Deserialization<br>        ▼<br>Application Object<br>Server Application</pre><p>From an developer’s perspective, the important stages are serialization before transmission and deserialization after reception. Lower-level networking details (such as packets, frames, or electrical signals) are handled by the networking stack and operating system.</p><h3>Serialization Standards</h3><p>A serialization standard defines the rules for representing data in a format that different systems can understand.</p><p>two broad categories of Serialization.</p><h3>Text-Based Formats</h3><p>These formats are human-readable.</p><p>Examples:</p><ul><li>JSON</li><li>XML</li><li>YAML</li></ul><p>Advantages:</p><ul><li>Easy to read</li><li>Easy to debug</li><li>Language-independent</li><li>Widely supported</li></ul><p>Disadvantages:</p><ul><li>Larger payload size</li><li>Slower parsing than binary formats</li></ul><h3>Binary Formats</h3><p>Binary serialization stores data in a compact binary representation.</p><p>Example:</p><ul><li>Protocol Buffers (ProtoBuf)</li></ul><p>Advantages:</p><ul><li>Smaller messages</li><li>Faster serialization</li><li>Faster deserialization</li><li>Better network efficiency</li></ul><p>Disadvantages:</p><ul><li>Not human-readable</li><li>Requires predefined schemas</li></ul><p>Binary formats are commonly used in high-performance distributed systems and RPC frameworks.</p><h3>Why JSON is Popular</h3><p><strong>JSON (JavaScript Object Notation)</strong> as the most widely used serialization format for HTTP-based communication.</p><p>JSON became the preferred format because it is:</p><ul><li>Human-readable</li><li>Lightweight</li><li>Language-independent</li><li>Easy to parse</li><li>Supported by virtually every programming language</li></ul><p>It is commonly used in:</p><ul><li>REST APIs</li><li>Configuration files</li><li>Log files</li><li>Web applications</li></ul><h3>JSON Structure</h3><p>A JSON document consists of key-value pairs enclosed within curly braces.</p><p>Example:</p><pre>{<br>    &quot;id&quot;: 101,<br>    &quot;name&quot;: &quot;Laptop&quot;,<br>    &quot;price&quot;: 850<br>}</pre><p>General rules:</p><ul><li>Objects begin with { and end with }.</li><li>Keys must be strings enclosed in double quotes.</li><li>Keys are separated from values using a colon (:).</li><li>Key-value pairs are separated using commas.</li></ul><h3>JSON Data Types</h3><p>the following JSON value types:</p><p>String &quot;Alice&quot; <br>Number 25<br>Booleantrue<br>Array[&quot;Java&quot;,&quot;Go&quot;]<br>Object{ &quot;city&quot;: &quot;Delhi&quot; }</p><p>Example:</p><pre>{<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 24,<br>    &quot;isStudent&quot;: false,<br>    &quot;skills&quot;: [<br>        &quot;Java&quot;,<br>        &quot;Python&quot;<br>    ]<br>}</pre><h3>Nested Objects</h3><p>JSON objects can contain objects.</p><p>Example:</p><pre>{<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;address&quot;: {<br>        &quot;country&quot;: &quot;India&quot;,<br>        &quot;city&quot;: &quot;Delhi&quot;<br>    }<br>}</pre><p>Nested structures allow complex relationships to be represented while maintaining readability.</p><h3>JSON Arrays</h3><p>Arrays contain ordered collections of values.</p><p>Example:</p><pre>{<br>    &quot;books&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;Clean Code&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;Design Patterns&quot;<br>        }<br>    ]<br>}</pre><p>Arrays frequently appear in API responses that return multiple resources.</p><h3>Serialization in HTTP</h3><p>During an HTTP request, the client serializes its data into JSON before sending it to the server.</p><p>Example request:</p><pre>POST /books HTTP/1.1<br>Content-Type: application/json</pre><p>Request Body</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;title&quot;: &quot;Clean Code&quot;,<br>    &quot;author&quot;: &quot;Robert C. Martin&quot;<br>}</pre><p>The server:</p><ol><li>Receives the HTTP request.</li><li>Deserializes the JSON body.</li><li>Executes business logic.</li><li>Creates a response.</li><li>Serializes the response into JSON.</li><li>Sends the response back to the client.</li></ol><p>Example response:</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;message&quot;: &quot;Book created&quot;<br>}</pre><p>This request-response cycle represents the practical application of serialization and deserialization in REST APIs.</p><h3>Relationship with the Network Stack</h3><p>the OSI model explain that applications do not directly transmit programming language objects over the network. Instead, applications work with serialized data (such as JSON), while the underlying networking layers handle packetization, transmission, and reconstruction before delivering the data back to the receiving application. The intermediate network representations are abstracted away from backend developers.</p><h3>Best Practices</h3><ul><li>Use a standardized serialization format across your APIs.</li><li>Prefer JSON for HTTP-based REST APIs unless performance requirements dictate otherwise.</li><li>Maintain a consistent JSON structure across endpoints.</li><li>Keep property names meaningful and consistent.</li><li>Validate incoming data after deserialization.</li><li>Return well-structured JSON responses with predictable schemas.</li><li>Use binary serialization formats only when performance or bandwidth requirements justify their complexity.</li></ul><h3>Common Mistakes</h3><ul><li>Assuming language-specific objects can be transmitted directly over the network.</li><li>Confusing JavaScript objects with serialized JSON.</li><li>Using inconsistent JSON structures across endpoints.</li><li>Sending malformed JSON with missing braces or quotation marks.</li><li>Returning different response formats for similar API endpoints.</li><li>Ignoring validation after deserialization.</li></ul><h3>Key Takeaways</h3><ul><li>Serialization converts application data into a common format suitable for transmission or storage.</li><li>Deserialization reconstructs serialized data into native application objects.</li><li>A common serialization format enables communication between applications written in different programming languages.</li><li>JSON is the most widely used serialization format for HTTP-based APIs because it is lightweight, human-readable, and language-independent.</li><li>JSON supports objects, arrays, strings, numbers, and Boolean values, allowing complex data structures to be represented clearly.</li><li>Text-based formats such as JSON, XML, and YAML prioritize readability, while binary formats such as Protocol Buffers prioritize efficiency.</li><li>During HTTP communication, clients serialize request data before transmission, and servers deserialize it before processing, then perform the reverse process for responses.</li><li>Backend developers primarily interact with serialized application data; lower-level network transmission is handled by the networking stack.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d571ef933a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination]]></title>
            <link>https://suryapratap04.medium.com/pagination-aa652095cdd8?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa652095cdd8</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 11:11:01 GMT</pubDate>
            <atom:updated>2026-07-20T11:11:01.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Pagination?</h3><p>Pagination is the technique of dividing a large dataset into smaller, manageable chunks (pages) instead of returning all records in a single response.</p><p>For example, suppose a database contains <strong>1,000,000 products</strong>.</p><p>Without pagination:</p><pre>GET /products</pre><p>The server would attempt to return all one million products in a single response, leading to:</p><ul><li>Very large response sizes</li><li>High memory consumption</li><li>Increased database load</li><li>Slow network transfer</li><li>Poor user experience</li></ul><p>Instead, the server returns only a small subset of records.</p><h3>How Pagination Works</h3><p>The client tells the server which page it wants by using <strong>query parameters</strong>.</p><p>Example:</p><pre>GET /products?page=1&amp;limit=20</pre><p>This means:</p><ul><li><strong>page = 1</strong> → First page</li><li><strong>limit = 20</strong> → Return only 20 products</li></ul><p>The server queries the database and returns:</p><pre>{<br>    &quot;data&quot;: [<br>        { &quot;id&quot;: 1, &quot;name&quot;: &quot;Laptop&quot; },<br>        { &quot;id&quot;: 2, &quot;name&quot;: &quot;Mouse&quot; }<br>    ],<br>    &quot;pagination&quot;: {<br>        &quot;page&quot;: 1,<br>        &quot;limit&quot;: 20,<br>        &quot;totalItems&quot;: 1000,<br>        &quot;totalPages&quot;: 50<br>    }<br>}</pre><h3>Client–Server Flow</h3><pre>Client<br>   │<br>GET /products?page=2&amp;limit=20<br>   │<br>   ▼<br>Server<br>   │<br>Reads page = 2<br>Reads limit = 20<br>   │<br>Calculates records to fetch<br>   │<br>Queries Database<br>   │<br>Returns only 20 products<br>   ▼<br>Client</pre><h3>Database Calculation</h3><p>Most SQL databases use <strong>OFFSET</strong> and <strong>LIMIT</strong>.</p><p>Formula:</p><pre>OFFSET = (page - 1) × limit</pre><p>Example:</p><p>Suppose:</p><pre>page = 3<br>limit = 20</pre><p>Then</p><pre>OFFSET = (3 - 1) × 20<br>OFFSET = 40</pre><p>Database query:</p><pre>SELECT *<br>FROM products<br>LIMIT 20<br>OFFSET 40;</pre><p>Meaning:</p><ul><li>Skip first 40 rows</li><li>Return next 20 rows</li></ul><p>So:</p><p>PageRecords11–20221–40341–60461–80</p><h3>Why Query Parameters?</h3><p>Notice that:</p><pre>/products</pre><p>still refers to the <strong>Products</strong> resource.</p><p>Pagination doesn’t change <em>which</em> resource is being requested — it changes <em>how</em> the results are returned.</p><p>That’s why pagination belongs in <strong>query parameters</strong>, not path parameters.</p><p>Correct:</p><pre>GET /products?page=3</pre><p>Not recommended:</p><pre>GET /products/page/3</pre><p>The first expresses that you’re requesting the <strong>products collection</strong>, with an instruction to return the third page.</p><h3>Typical Pagination Parameters</h3><p>ParameterPurposepageCurrent page numberlimitNumber of records per pageoffsetNumber of records to skipsortSort fieldorderasc or descsearchSearch keywordfilterFilter condition</p><p>Example:</p><pre>GET /products?page=2&amp;limit=20&amp;sort=price&amp;order=asc&amp;category=laptops</pre><h3>Typical Response</h3><p>A paginated API usually returns both the requested data and pagination metadata.</p><pre>{<br>    &quot;data&quot;: [<br>        ...<br>    ],<br>    &quot;pagination&quot;: {<br>        &quot;page&quot;: 2,<br>        &quot;limit&quot;: 20,<br>        &quot;totalItems&quot;: 186,<br>        &quot;totalPages&quot;: 10,<br>        &quot;hasNextPage&quot;: true,<br>        &quot;hasPreviousPage&quot;: true<br>    }<br>}</pre><p>The metadata helps the frontend determine:</p><ul><li>Which page is currently displayed</li><li>Whether a “Next” button should be enabled</li><li>Whether a “Previous” button should be enabled</li><li>How many total pages exist</li></ul><h3>Types of Pagination</h3><h3>1. Offset Pagination (Most Common)</h3><p>Uses LIMIT and OFFSET.</p><p>Example:</p><pre>GET /products?page=4&amp;limit=25</pre><p><strong>Advantages:</strong></p><ul><li>Simple to implement</li><li>Easy to understand</li><li>Ideal for admin dashboards and small to medium datasets</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Performance degrades with very large offsets because the database must skip many rows.</li></ul><h3>2. Cursor Pagination</h3><p>Instead of a page number, the client provides a cursor (often the ID or timestamp of the last item received).</p><p>Example:</p><pre>GET /products?cursor=105&amp;limit=20</pre><p>The server returns:</p><pre>{<br>    &quot;data&quot;: [...],<br>    &quot;nextCursor&quot;: 125<br>}</pre><p><strong>Advantages:</strong></p><ul><li>Faster on large datasets</li><li>Stable even when new records are inserted or deleted</li><li>Commonly used in social media feeds, messaging apps, and infinite scrolling</li></ul><h3>Best Practices</h3><ul><li>Always specify a reasonable default limit (e.g., 20 or 50).</li><li>Set a maximum limit (e.g., 100) to prevent clients from requesting excessively large datasets.</li><li>Include pagination metadata (totalItems, totalPages, etc.) in the response.</li><li>Use offset pagination for simple applications and dashboards.</li><li>Use cursor pagination for large-scale or real-time systems where performance and consistency are critical.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa652095cdd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing]]></title>
            <link>https://suryapratap04.medium.com/routing-96344bbfeee2?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/96344bbfeee2</guid>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 13:07:58 GMT</pubDate>
            <atom:updated>2026-07-19T13:07:58.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Routing is one of the core responsibilities of every backend application. Whenever a client sends an HTTP request, the server must determine <strong>which piece of application code should process that request</strong>. Routing provides this mapping between incoming HTTP requests and server-side logic.</p><p>A route is identified by the combination of:</p><ul><li>HTTP Method</li><li>URL Path</li></ul><p>The server examines both components and forwards the request to the appropriate handler, where business logic, database operations, validation, and response generation are performed.</p><p>Modern backend frameworks such as Express, Fastify, Spring Boot, Django, ASP.NET Core, Laravel, and FastAPI all implement routing using this same principle.</p><h3>What is Routing?</h3><p>Routing is the process of mapping an incoming HTTP request to a specific handler or controller in the backend application.</p><p>A route is uniquely identified by:</p><ul><li>HTTP Method</li><li>URL Path</li></ul><p>For example:</p><pre>GET /users</pre><p>The HTTP method defines <strong>what</strong> the client wants to do, while the URL path specifies <strong>where</strong> the action should be performed.</p><ul><li><strong>HTTP Method</strong> → Action or intent</li><li><strong>Route (URL Path)</strong> → Target resource</li></ul><p>Together, they uniquely identify the server-side operation.</p><h3>How Routing Works</h3><p>When a request reaches the server, the routing engine follows a sequence of steps:</p><pre>Client<br>   │<br>HTTP Request<br>(Method + URL)<br>   │<br>   ▼<br>Router<br>   │<br>Match Route<br>   │<br>   ▼<br>Controller / Handler<br>   │<br>Business Logic<br>   │<br>Database / Services<br>   │<br>Generate Response<br>   │<br>   ▼<br>Client</pre><p>For example:</p><pre>GET /users</pre><p>The router performs the following operations:</p><ol><li>Checks the HTTP method.</li><li>Matches the requested URL against registered routes.</li><li>Selects the appropriate handler.</li><li>Executes business logic.</li><li>Returns an HTTP response.</li></ol><p>If no matching route exists, the server returns <strong>404 Not Found</strong>.</p><h3>Route Matching</h3><p>Routing is based on the combination of <strong>HTTP Method</strong> and <strong>URL Path</strong>.</p><p>For example:</p><pre>GET /books</pre><pre>POST /books</pre><p>Although both requests use the same URL, they represent different operations.</p><p>MethodRouteOperationGET/booksRetrieve booksPOST/booksCreate a new book</p><p>The router treats these as two completely different routes because the HTTP methods differ.</p><p>This separation allows REST APIs to expose multiple operations on the same resource while maintaining clear semantics.</p><h3>Static Routes</h3><p>A static route contains a fixed URL path that never changes.</p><p>Example:</p><pre>GET /books</pre><pre>POST /users</pre><p>Characteristics:</p><ul><li>No variable components</li><li>Predictable URL structure</li><li>Represents a collection or fixed endpoint</li><li>Simple to match and maintain</li></ul><p>Static routes are commonly used for:</p><ul><li>Listing resources</li><li>Creating resources</li><li>Authentication endpoints</li><li>Health checks</li></ul><p>Examples:</p><pre>GET /products</pre><pre>POST /orders</pre><pre>GET /health</pre><h3>Dynamic Routes</h3><p>Static routes are insufficient when accessing individual resources.</p><p>Suppose an application needs details for a specific user.</p><p>Instead of creating routes such as:</p><pre>/users1</pre><pre>/users2</pre><pre>/users3</pre><p>some frameworks use <strong>path parameters</strong>.</p><p>Example:</p><pre>GET /users/:id</pre><p>When a request arrives:</p><pre>GET /users/123</pre><p>the router extracts:</p><pre>id = 123</pre><p>and passes it to the handler.</p><p>The handler can then retrieve the corresponding user from the database.</p><h3>Path Parameters</h3><p>Path parameters:</p><ul><li>Form part of the URL path</li><li>Identify specific resources</li><li>Are dynamic values extracted during route matching</li></ul><p>Examples:</p><pre>/users/123</pre><pre>/orders/500</pre><pre>/products/98</pre><p>Common use cases include:</p><ul><li>User ID</li><li>Product ID</li><li>Order ID</li><li>Blog Post ID</li></ul><p>Since path parameters represent resource identifiers, they should not be used for optional filters or search criteria.</p><h3>Query Parameters</h3><p>Sometimes the client needs to send additional information without changing the identity of the resource.</p><p>This is achieved using <strong>query parameters</strong>.</p><p>Example:</p><pre>GET /search?query=laptop</pre><p>Query parameters begin after the ? character and are expressed as key-value pairs.</p><pre>key=value</pre><p>Multiple parameters can be supplied:</p><pre>GET /products?page=2&amp;limit=20&amp;sort=price</pre><p>The resource remains:</p><pre>/ products</pre><p>while the query parameters modify how the server returns the data.</p><h3>Common Uses</h3><p>Query parameters are commonly used for:</p><ul><li>Searching</li><li>Filtering</li><li>Sorting</li><li>Pagination</li><li>Optional configuration</li></ul><p>Examples:</p><pre>GET /products?page=3</pre><pre>GET /users?role=admin</pre><pre>GET /books?author=Martin</pre><p>Unlike path parameters, query parameters do not identify a resource — they refine or customize the response.</p><h3>Path Parameters vs Query Parameters</h3><p>Path ParametersQuery ParametersIdentify a specific resourceModify or filter the responseMandatoryUsually optionalPart of the URL pathFollow the ? characterUsed for resource identificationUsed for searching, filtering, sorting, pagination</p><p>Examples:</p><pre>/users/15</pre><p>Specific user.</p><pre>/users?page=2</pre><p>Second page of users.</p><h3>Nested Routes</h3><p>Resources often have hierarchical relationships.</p><p>Consider the following entities:</p><ul><li>Users</li><li>Posts</li></ul><p>A user can have multiple posts.</p><p>Instead of exposing unrelated routes, REST APIs express this relationship through nested routes.</p><p>Example:</p><pre>GET /users/123/posts</pre><p>This indicates:</p><ul><li>Retrieve posts</li><li>Belonging to user 123</li></ul><p>Further nesting can identify an individual resource.</p><pre>GET /users/123/posts/456</pre><p>Meaning:</p><p>Retrieve post <strong>456</strong> belonging to user <strong>123</strong>.</p><p>Nested routes improve readability and clearly express relationships between resources.</p><p>Typical examples include:</p><pre>/users/15/orders</pre><pre>/products/20/reviews</pre><pre>/projects/4/tasks</pre><pre>/companies/7/employees</pre><p>Overusing nesting should be avoided. Deeply nested URLs become difficult to understand and maintain.</p><h3>API Versioning</h3><p>APIs evolve over time.</p><p>Response structures, validation rules, and resource representations often change as applications grow.</p><p>Instead of modifying existing endpoints directly, APIs introduce versioning.</p><p>Example:</p><pre>/api/v1/products</pre><pre>/api/v2/products</pre><p>Each version represents a different contract with API consumers.</p><p>For example:</p><p>Version 1:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Laptop&quot;<br>}</pre><p>Version 2:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;title&quot;: &quot;Laptop&quot;<br>}</pre><p>Existing clients continue using Version 1 while new applications migrate to Version 2.</p><p>Versioning prevents breaking changes and allows gradual adoption of new API designs.</p><h3>Route Deprecation</h3><p>Once a newer API version becomes stable, the older version can be deprecated.</p><p>The typical lifecycle is:</p><pre>Release v2</pre><pre>↓</pre><pre>Notify Clients</pre><pre>↓</pre><pre>Migration Period</pre><pre>↓</pre><pre>Deprecate v1</pre><pre>↓</pre><pre>Remove v1</pre><p>Deprecation provides consumers sufficient time to update their applications without causing service disruptions.</p><h3>Catch-All Routes</h3><p>Not every incoming request matches a registered route.</p><p>For example:</p><pre>GET /unknown/path</pre><p>Instead of returning an unexpected response, applications define a <strong>catch-all route</strong>.</p><pre>Any Unmatched Request<br>        │<br>        ▼<br>404 Handler<br>        │<br>        ▼<br>404 Not Found</pre><p>The catch-all route executes only when no other route matches.</p><p>Typical response:</p><pre>{<br>    &quot;message&quot;: &quot;Route not found&quot;<br>}</pre><p>Catch-all routes improve error handling and provide consistent responses for invalid endpoints.</p><h3>RESTful Routing Best Practices</h3><p>A well-designed REST API follows predictable routing conventions.</p><h3>Use nouns instead of verbs</h3><p>Prefer:</p><pre>GET /users</pre><p>Instead of:</p><pre>GET /getUsers</pre><h3>Use HTTP methods to express actions</h3><p>Examples:</p><pre>GET /users</pre><pre>POST /users</pre><pre>PATCH /users/15</pre><pre>DELETE /users/15</pre><h3>Keep URLs hierarchical</h3><p>Use nested routes only when resources have a genuine parent-child relationship.</p><h3>Use path parameters for resource identification</h3><p>Good:</p><pre>/users/15</pre><p>Avoid:</p><pre>/users?id=15</pre><p>when retrieving a single resource.</p><h3>Use query parameters for optional operations</h3><p>Examples include:</p><ul><li>Pagination</li><li>Filtering</li><li>Sorting</li><li>Searching</li></ul><h3>Version public APIs</h3><p>Expose breaking changes through versioned endpoints rather than modifying existing APIs.</p><h3>Provide meaningful 404 responses</h3><p>Always include a clear response body when a route does not exist.</p><h3>Common Mistakes</h3><ul><li>Using verbs in REST endpoints (/getUsers, /deleteUser).</li><li>Using query parameters to identify unique resources.</li><li>Creating deeply nested URLs that are difficult to maintain.</li><li>Ignoring API versioning when introducing breaking changes.</li><li>Returning inconsistent route structures across the application.</li><li>Failing to define a catch-all route for unmatched requests.</li><li>Using different naming conventions for similar resources.</li></ul><h3>Key Takeaways</h3><ul><li>Routing maps incoming HTTP requests to server-side handlers.</li><li>A route is uniquely identified by the combination of <strong>HTTP method</strong> and <strong>URL path</strong>.</li><li>Static routes represent fixed endpoints, while dynamic routes use path parameters to identify specific resources.</li><li>Query parameters provide optional information such as filtering, sorting, searching, and pagination.</li><li>Nested routes represent hierarchical relationships between resources.</li><li>API versioning enables applications to introduce breaking changes without disrupting existing clients.</li><li>Route deprecation provides a controlled migration strategy before removing older API versions.</li><li>Catch-all routes handle unmatched requests by returning a consistent <strong>404 Not Found</strong> response.</li><li>Following RESTful routing conventions improves API readability, maintainability, and scalability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96344bbfeee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Fundamentals]]></title>
            <link>https://suryapratap04.medium.com/http-fundamentals-000963dd4923?source=rss-84719f441bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/000963dd4923</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[http-status-code]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Surya Pratap Singh]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 11:06:14 GMT</pubDate>
            <atom:updated>2026-07-19T11:17:15.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Hypertext Transfer Protocol (HTTP) is the foundation of communication on the World Wide Web. It defines a standardized mechanism through which clients, such as web browsers, mobile applications, and API consumers, communicate with servers to exchange resources and data.</p><p>Although originally designed to transfer hypertext documents, HTTP has evolved into the primary protocol for modern web applications, REST APIs, microservices, and cloud-native systems. Nearly every interaction on the internet — including loading a webpage, authenticating a user, uploading a file, or fetching API data — is performed through HTTP.</p><p>Understanding HTTP is fundamental for backend because every request processed by an application server follows the HTTP protocol before reaching business logic.</p><h3>Why HTTP Exists</h3><p>Before HTTP, there was no standardized method for exchanging information across interconnected systems. Different applications would require custom communication protocols, making interoperability difficult.</p><p>HTTP solves this problem by defining:</p><ul><li>A common request–response model</li><li>A standardized message format</li><li>Well-defined methods for interacting with resources</li><li>Standard status codes</li><li>Extensible metadata through headers</li></ul><p>Because every client and server understands these standards, applications developed using different programming languages and frameworks can communicate seamlessly.</p><h3>HTTP Architecture</h3><p>HTTP follows a <strong>client–server architecture</strong>.</p><p>The client initiates communication by sending a request, while the server processes that request and returns an appropriate response.</p><pre>Client<br>   │<br>   │ HTTP Request<br>   ▼<br>Server<br>   │<br>   │ HTTP Response<br>   ▼<br>Client</pre><h3>Client</h3><p>A client is any application capable of sending HTTP requests.</p><p>Examples include:</p><ul><li>Web browsers</li><li>Mobile applications</li><li>Desktop applications</li><li>REST API clients (Postman, Insomnia)</li><li>Backend services communicating with other services</li></ul><h3>Server</h3><p>The server receives HTTP requests, processes them, interacts with databases or other services if necessary, and generates HTTP responses.</p><p>Examples include:</p><ul><li>Node.js</li><li>Spring Boot</li><li>Django</li><li>ASP.NET Core</li><li>FastAPI</li></ul><h3>Stateless Communication</h3><p>One of HTTP’s defining characteristics is that it is <strong>stateless</strong>.</p><p>A stateless protocol means each request is processed independently. The server does not automatically remember previous requests from the same client.</p><p>For example:</p><pre>Request 1<br>Login<br>↓<br>Response<br>-------------------<br>Request 2<br>View Profile<br>↓<br>Response</pre><p>The second request contains no built-in knowledge of the first request. If user identity needs to persist across requests, additional mechanisms such as sessions, cookies, or tokens (e.g., JWT) must be used.</p><p>Statelessness offers several advantages:</p><ul><li>Simpler server design</li><li>Easier horizontal scaling</li><li>Better fault tolerance</li><li>Independent request processing</li></ul><h3>HTTP Request–Response Lifecycle</h3><p>Every HTTP interaction follows a predictable sequence.</p><pre>Client<br>    │<br>    ▼<br>Create HTTP Request<br>    │<br>    ▼<br>Internet<br>    │<br>    ▼<br>Web Server<br>    │<br>    ▼<br>Application<br>    │<br>    ▼<br>Database / Services<br>    │<br>    ▼<br>Generate Response<br>    │<br>    ▼<br>Return HTTP Response<br>    │<br>    ▼<br>Client</pre><p>Internally, the server typically performs the following operations:</p><ol><li>Receive the request.</li><li>Parse the HTTP message.</li><li>Validate authentication and authorization.</li><li>Execute business logic.</li><li>Access databases or external services if required.</li><li>Generate an HTTP response.</li><li>Send the response back to the client.</li></ol><p>Modern frameworks perform much of the HTTP parsing automatically, allowing developers to focus primarily on application logic.</p><h3>HTTP Messages</h3><p>Communication in HTTP occurs through <strong>HTTP messages</strong>.</p><p>There are only two message types:</p><ul><li>HTTP Request</li><li>HTTP Response</li></ul><p>Both follow a standardized structure that allows any compliant client and server to communicate reliably.</p><h3>HTTP Request Structure</h3><p>An HTTP request contains four primary components:</p><pre>Request Line<br>Headers<br>Blank Line<br>Request Body (Optional)</pre><h3>Request Line</h3><p>The request line specifies:</p><ul><li>HTTP Method</li><li>Resource URL</li><li>HTTP Version</li></ul><p>Example:</p><pre>GET /users HTTP/1.1</pre><p>This tells the server:</p><ul><li>perform a <strong>GET</strong> operation</li><li>on the <strong>/users</strong> resource</li><li>using <strong>HTTP/1.1</strong></li></ul><h3>Headers</h3><p>Headers contain metadata describing the request.</p><p>Example:</p><pre>Host: api.example.com<br>Authorization: Bearer &lt;token&gt;<br>Content-Type: application/json<br>Accept: application/json</pre><p>Headers do not contain application data. Instead, they describe how the request should be processed.</p><h3>Blank Line</h3><p>A blank line separates the headers from the body.</p><p>Although often overlooked, this separator is part of the HTTP specification and enables parsers to determine where metadata ends and payload begins.</p><h3>Request Body</h3><p>The body contains the application’s actual data.</p><p>Example:</p><pre>{<br>  &quot;name&quot;: &quot;UserName&quot;,<br>  &quot;email&quot;: &quot;user@example.com&quot;<br>}</pre><p>Bodies are commonly used with:</p><ul><li>POST</li><li>PUT</li><li>PATCH</li></ul><p>GET requests generally do not include a request body.</p><h3>HTTP Response Structure</h3><p>After processing a request, the server returns an HTTP response.</p><p>A response consists of:</p><pre>Status Line<br>Headers<br>Blank Line<br>Response Body</pre><h3>Status Line</h3><p>Example:</p><pre>HTTP/1.1 200 OK</pre><p>The status line includes:</p><ul><li>HTTP Version</li><li>Status Code</li><li>Status Message</li></ul><p>It immediately informs the client whether the request succeeded.</p><h3>Response Headers</h3><p>Response headers describe the returned resource.</p><p>Examples:</p><pre>Content-Type: application/json<br>Cache-Control: max-age=60<br>Content-Encoding: gzip</pre><p>These headers help clients correctly interpret, cache, and process responses.</p><h3>Response Body</h3><p>The response body contains the requested resource.</p><p>Depending on the endpoint, this could be:</p><ul><li>JSON</li><li>HTML</li><li>Images</li><li>PDFs</li><li>Videos</li><li>XML</li><li>Plain text</li></ul><p>Example:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;john&quot;<br>}</pre><h3>HTTP Methods</h3><p>HTTP methods describe the <strong>intent</strong> of a request. Rather than specifying how the server should implement an operation, methods communicate what the client wants to accomplish.</p><h3>GET</h3><p>Retrieves data without modifying server state.</p><p>Example:</p><pre>GET /products</pre><p>Used for:</p><ul><li>Product listings</li><li>User profiles</li><li>Search results</li><li>Reports</li></ul><p>GET requests should never modify application data.</p><h3>POST</h3><p>Creates a new resource.</p><p>Example:</p><pre>POST /orders</pre><p>POST typically includes a request body containing the data required to create the resource.</p><h3>PUT</h3><p>Replaces an existing resource completely.</p><p>Example:</p><pre>PUT /users/12</pre><p>The entire resource representation is replaced with the new one supplied by the client.</p><h3>PATCH</h3><p>Updates only selected fields.</p><p>Instead of replacing the entire object, PATCH modifies only specified properties.</p><p>Example:</p><pre>{<br>    &quot;city&quot;: &quot;Bangalore&quot;<br>}</pre><p>PATCH is generally preferred for partial updates because it reduces unnecessary data transfer.</p><h3>DELETE</h3><p>Removes an existing resource.</p><p>Example:</p><pre>DELETE /orders/105</pre><p>Successful deletion commonly returns <strong>204 No Content</strong>.</p><h3>OPTIONS</h3><p>Returns information about supported methods and capabilities for a resource.</p><p>It is primarily used by browsers during <strong>CORS preflight requests</strong> before sending certain cross-origin requests.</p><h3>Idempotency</h3><p>Idempotency describes whether repeating the same request produces the same final server state.</p><p>For example:</p><ul><li>Calling <strong>GET /users</strong> ten times does not change stored data.</li><li>Calling <strong>POST /orders</strong> ten times may create ten different orders.</li></ul><p>Designing idempotent APIs where appropriate improves reliability, especially when clients retry requests after network failures.</p><h3>HTTP Headers</h3><p>Headers provide metadata that accompanies HTTP requests and responses. They describe how communication should occur without becoming part of the application data.</p><p>Headers follow a simple key–value format:</p><pre>Header-Name: Value</pre><h3>Request Headers</h3><p>Request headers provide information about the client and its preferences.</p><p>Common examples include:</p><p>HeaderPurposeAuthorizationAuthentication credentialsAcceptPreferred response formatUser-AgentClient software informationAccept-LanguagePreferred languageAccept-EncodingSupported compression</p><h3>Response Headers</h3><p>Response headers describe the returned resource and how clients should process it.</p><p>Examples include:</p><p>HeaderPurposeContent-TypeFormat of response bodyCache-ControlCaching policyContent-EncodingCompression appliedSet-CookieSession informationETagResource version identifier</p><h3>Security Headers</h3><p>Security headers instruct browsers to enforce additional security protections.</p><p>Common examples include:</p><ul><li>Strict-Transport-Security (HSTS)</li><li>Content-Security-Policy (CSP)</li><li>X-Frame-Options</li><li>X-Content-Type-Options</li></ul><p>These headers help mitigate attacks such as clickjacking, MIME sniffing, and cross-site scripting (XSS).</p><h3>HTTP Status Codes</h3><p>Status codes communicate the result of an HTTP request before the client examines the response body.</p><p>HTTP status codes are grouped into five categories.</p><p>CategoryMeaning1xxInformational2xxSuccess3xxRedirection4xxClient Error5xxServer Error</p><h3>Successful Responses (2xx)</h3><p>CodeMeaningTypical Usage200OKSuccessful request201CreatedResource created202AcceptedAsynchronous processing204No ContentSuccess without response body</p><h3>Redirection (3xx)</h3><p>CodeMeaning301Permanent Redirect302Temporary Redirect304Not Modified (cache validation)</p><h3>Client Errors (4xx)</h3><p>CodeMeaning400Bad Request401Unauthorized (authentication required)403Forbidden (authenticated but not permitted)404Resource Not Found405Method Not Allowed409Conflict422Unprocessable Entity429Too Many Requests</p><h3>Server Errors (5xx)</h3><p>CodeMeaning500Internal Server Error502Bad Gateway503Service Unavailable504Gateway Timeout</p><p>Using appropriate status codes makes APIs more predictable, improves debugging, and enables clients to respond intelligently to different situations.</p><h3>HTTPS: Secure HTTP</h3><p>HTTP transmits data in plain text, making it vulnerable to interception and modification during transmission. To address these security concerns, <strong>HTTPS (Hypertext Transfer Protocol Secure)</strong> combines HTTP with <strong>Transport Layer Security (TLS)</strong>, ensuring secure communication between clients and servers.</p><p>HTTPS provides three essential security guarantees:</p><ul><li><strong>Encryption</strong> — Protects transmitted data from being read by unauthorized parties.</li><li><strong>Authentication</strong> — Verifies the identity of the server through digital certificates issued by trusted Certificate Authorities (CAs).</li><li><strong>Integrity</strong> — Ensures that data is not modified while in transit.</li></ul><p>A typical HTTPS connection begins with a <strong>TLS handshake</strong>, during which the client and server negotiate encryption algorithms, verify certificates, and establish shared encryption keys before any HTTP data is exchanged.</p><pre>Client<br>   │<br>   │ TLS Handshake<br>   ▼<br>Server<br>   │<br>Secure Connection Established<br>   │<br>   ▼<br>Encrypted HTTP Communication</pre><p>Today, HTTPS is the standard for virtually all websites and APIs because it protects sensitive information such as login credentials, payment details, and authentication tokens.</p><h3>Evolution of HTTP</h3><p>As web applications became more complex, HTTP evolved to improve performance, efficiency, and scalability.</p><p>VersionKey ImprovementsHTTP/1.0One request per TCP connectionHTTP/1.1Persistent connections (Keep-Alive), host headersHTTP/2Multiplexing, header compression, binary framingHTTP/3QUIC protocol over UDP, reduced latency, faster connection recovery</p><h3>HTTP/1.0</h3><p>Each request required a separate TCP connection, resulting in significant overhead when loading pages containing multiple resources.</p><h3>HTTP/1.1</h3><p>Introduced persistent connections, allowing multiple requests to reuse the same TCP connection, reducing latency and improving performance.</p><h3>HTTP/2</h3><p>HTTP/2 introduced several major improvements:</p><ul><li>Binary protocol instead of plain text</li><li>Multiplexing multiple requests over a single connection</li><li>Header compression (HPACK)</li><li>Reduced network latency</li></ul><p>These improvements significantly accelerated page loading without changing the application programming model.</p><h3>HTTP/3</h3><p>HTTP/3 replaces TCP with <strong>QUIC</strong>, a transport protocol built on UDP.</p><p>Benefits include:</p><ul><li>Faster connection establishment</li><li>Improved performance on unreliable networks</li><li>Better handling of packet loss</li><li>Reduced head-of-line blocking</li></ul><p>Applications continue using the same HTTP semantics while benefiting from improved transport performance.</p><h3>Cross-Origin Resource Sharing (CORS)</h3><p>Modern browsers implement the <strong>Same-Origin Policy (SOP)</strong>, a security mechanism that restricts JavaScript running on one origin from accessing resources hosted on another origin.</p><p>An <strong>origin</strong> is defined by three components:</p><ul><li>Protocol</li><li>Host</li><li>Port</li></ul><p>For example:</p><pre>https://api.example.com:443</pre><p>Changing any one of these components results in a different origin.</p><h3>Why CORS Exists</h3><p>Suppose a frontend application runs on:</p><pre>http://localhost:3000</pre><p>while its backend API runs on:</p><pre>http://localhost:5000</pre><p>Although both are on the same machine, they have different ports and therefore different origins.</p><p>Browsers block such requests unless the server explicitly grants permission through CORS.</p><pre>Browser<br>    │<br>Cross-Origin Request<br>    │<br>    ▼<br>Backend<br>    │<br>Access-Control-Allow-Origin<br>    │<br>    ▼<br>Browser Allows or Blocks Response</pre><h3>Simple and Preflight Requests</h3><p>Simple requests are sent directly by the browser.</p><p>Certain requests, however, require a <strong>preflight</strong> check before the actual request is transmitted. This typically occurs when using:</p><ul><li>PUT</li><li>PATCH</li><li>DELETE</li><li>Custom request headers</li><li>Credentialed requests</li></ul><p>The browser first sends an <strong>OPTIONS</strong> request to determine whether the server permits the intended operation.</p><h3>Important CORS Headers</h3><p>HeaderPurposeAccess-Control-Allow-OriginSpecifies permitted originsAccess-Control-Allow-MethodsLists allowed HTTP methodsAccess-Control-Allow-HeadersLists permitted request headersAccess-Control-Allow-CredentialsAllows cookies and credentials</p><p>It is important to note that <strong>CORS is enforced by browsers</strong>, not by backend servers. Backend-to-backend communication, Postman, and curl are not affected by CORS restrictions.</p><h3>Performance Features in HTTP</h3><p>HTTP includes several built-in mechanisms that improve performance and reduce network overhead.</p><h3>HTTP Caching</h3><p>Caching stores HTTP responses temporarily so that future requests can reuse previously downloaded resources rather than requesting them again.</p><p>Benefits include:</p><ul><li>Faster response times</li><li>Reduced bandwidth usage</li><li>Lower server load</li><li>Improved user experience</li></ul><p>Caching may occur at multiple layers:</p><ul><li>Browser Cache</li><li>CDN</li><li>Reverse Proxy</li><li>Application Cache</li></ul><h3>Cache-Control</h3><p>The Cache-Control header specifies how responses should be cached.</p><p>Examples:</p><pre>Cache-Control: max-age=3600</pre><pre>Cache-Control: no-store</pre><p>Common directives include:</p><ul><li>max-age</li><li>no-cache</li><li>no-store</li><li>public</li><li>private</li></ul><p>Sensitive data such as banking or medical information should generally use no-store.</p><h3>ETag and Last-Modified</h3><p>Rather than downloading unchanged resources repeatedly, browsers validate cached resources before requesting them again.</p><h3>ETag</h3><p>An <strong>ETag</strong> uniquely identifies a specific version of a resource.</p><pre>ETag: &quot;abc123&quot;</pre><p>When requesting the resource again, the browser sends:</p><pre>If-None-Match: &quot;abc123&quot;</pre><p>If the resource has not changed, the server returns:</p><pre>304 Not Modified</pre><p>allowing the browser to reuse its cached copy.</p><h3>Last-Modified</h3><p>Instead of version identifiers, Last-Modified uses timestamps.</p><pre>Last-Modified: Tue, 22 Jul</pre><p>The browser later sends:</p><pre>If-Modified-Since</pre><p>If the resource remains unchanged, the server again responds with <strong>304 Not Modified</strong>.</p><h3>Content Negotiation</h3><p>Content negotiation allows clients and servers to agree on the most appropriate representation of a resource.</p><p>Negotiation commonly occurs for:</p><ul><li>Response format</li><li>Language</li><li>Compression</li></ul><p>Examples include:</p><p>HeaderPurposeAcceptPreferred response formatAccept-LanguagePreferred languageAccept-EncodingSupported compression algorithms</p><p>A client requesting:</p><pre>Accept: application/json</pre><p>expects a JSON response, while another client may request XML for the same resource.</p><h3>HTTP Compression</h3><p>Large HTTP responses increase network latency and bandwidth consumption.</p><p>Compression reduces response size before transmission.</p><p>Common compression algorithms include:</p><ul><li>gzip</li><li>Brotli</li></ul><p>Example:</p><pre>Content-Encoding: gzip</pre><p>The browser automatically decompresses the response before processing it.</p><p>Compression significantly improves application performance, particularly for large JSON responses, HTML pages, CSS, and JavaScript files.</p><h3>Persistent Connections (Keep-Alive)</h3><p>HTTP/1.1 introduced persistent TCP connections, commonly referred to as <strong>Keep-Alive</strong>.</p><p>Instead of opening and closing a TCP connection for every request, multiple requests reuse the same connection.</p><pre>Client<br>    │<br>TCP Connection<br>    │<br>GET<br>    │<br>Response<br>    │<br>GET<br>    │<br>Response<br>    │<br>Connection Reused</pre><p>Benefits include:</p><ul><li>Reduced latency</li><li>Fewer TCP handshakes</li><li>Better throughput</li><li>Improved server efficiency</li></ul><h3>Multipart Requests</h3><p>HTTP bodies often contain structured data such as JSON, but file uploads require a different format.</p><p>Multipart requests use:</p><pre>Content-Type: multipart/form-data</pre><p>This format allows files and text fields to be transmitted together within a single request.</p><p>Typical use cases include:</p><ul><li>Profile picture uploads</li><li>Document uploads</li><li>Image galleries</li><li>Video uploads</li></ul><p>Frameworks generally provide built-in multipart parsers to simplify processing uploaded files.</p><h3>Streaming Responses</h3><p>Traditional HTTP responses are transmitted only after the entire response has been generated.</p><p>Streaming allows servers to send data incrementally as it becomes available.</p><p>Examples include:</p><ul><li>Video streaming</li><li>Large file downloads</li><li>Live logs</li><li>AI-generated responses</li><li>Server-Sent Events (SSE)</li></ul><p>Streaming improves perceived performance and reduces memory consumption because large responses do not need to be buffered completely before transmission.</p><h3>Example</h3><p>Consider an e-commerce application where a user views products and places an order.</p><ol><li>The browser sends a GET /products request.</li><li>The server checks its cache before querying the database.</li><li>The response is compressed using gzip and returned with caching headers.</li><li>The browser stores static resources locally.</li><li>The user submits a POST /orders request containing order details.</li><li>The server validates the request, processes payment, stores the order, and returns 201 Created.</li><li>Future requests reuse cached resources and persistent connections, improving overall performance.</li><li>This example illustrates how HTTP methods, headers, status codes, caching, compression, and persistent connections work together in a typical backend application.</li></ol><h3>Best Practices</h3><ul><li>Always use HTTPS in production.</li><li>Select HTTP methods according to their intended semantics.</li><li>Return appropriate HTTP status codes for every response.</li><li>Configure CORS only for trusted origins.</li><li>Enable gzip or Brotli compression for text-based responses.</li><li>Use caching for static resources and frequently accessed content.</li><li>Validate cached resources using ETag or Last-Modified.</li><li>Reuse persistent connections whenever possible.</li><li>Use multipart/form-data for file uploads.</li><li>Stream large responses instead of buffering them entirely in memory.</li><li>Keep HTTP headers concise and meaningful.</li><li>Follow REST conventions consistently across APIs.</li></ul><h3>Key Takeaways</h3><ul><li>HTTPS secures HTTP communication using TLS by providing encryption, authentication, and integrity.</li><li>HTTP has evolved significantly from HTTP/1.0 to HTTP/3, improving efficiency and reducing latency.</li><li>CORS enables controlled cross-origin communication while preserving browser security.</li><li>HTTP caching reduces redundant network requests and improves performance.</li><li>Cache-Control, ETag, and Last-Modified work together to optimize resource caching.</li><li>Content negotiation allows clients and servers to exchange data in the most appropriate format.</li><li>Compression minimizes response size and improves transmission speed.</li><li>Persistent connections reduce connection overhead and improve throughput.</li><li>Multipart requests are the standard mechanism for file uploads.</li><li>Streaming enables efficient delivery of large or continuously generated content.</li><li>Following HTTP standards and best practices results in secure, scalable, and maintainable backend APIs.</li></ul><h3>Summary</h3><p>HTTP provides a standardized communication protocol that enables clients and servers to exchange information consistently and efficiently. Understanding its request–response architecture, stateless nature, message structure, methods, headers, and status codes forms the foundation for designing reliable backend systems and RESTful APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=000963dd4923" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>