<?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 Aman on Medium]]></title>
        <description><![CDATA[Stories by Aman on Medium]]></description>
        <link>https://medium.com/@cappiing?source=rss-d91de3d40fd7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GvXn4iv2NpvfGFLMw8-SJQ.jpeg</url>
            <title>Stories by Aman on Medium</title>
            <link>https://medium.com/@cappiing?source=rss-d91de3d40fd7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:21:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cappiing/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[What Nginx Actually Does Between the Internet and Your Code]]></title>
            <link>https://medium.com/@cappiing/what-nginx-actually-does-between-the-internet-and-your-code-197964f5e719?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/197964f5e719</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 18:36:26 GMT</pubDate>
            <atom:updated>2026-10-18T18:36:26.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M62BmjsmxV5o8Bb4sG6qng.png" /><figcaption>In production, almost nobody exposes a raw Node.js, Python, or Java process to the internet. A fast web server called Nginx stands at the front door, and your application hides behind it.</figcaption></figure><p>This post explains what Nginx does, why it is called a reverse proxy, how it chooses where to send each request, and how the response finds its way back.</p><p>The Big Picture</p><p>Here is the path a request takes from the user down to your data layer:</p><ul><li><strong>Browser</strong> <em>(Sends HTTPS on port 443)</em> ➔ <strong>Nginx</strong> <em>(Public IP)</em> ➔ <strong>App Server</strong> <em>(Plain HTTP on a private port like Express, FastAPI, or Spring Boot)</em> ➔ <strong>Database</strong></li></ul><p>Nginx acts as the public front door, while your app stays secure in the private back room.</p><blockquote><strong><em>Analogy:</em></strong><em> Think of it like a hotel reception desk that checks every guest and forwards requests to back-office staff who never meet the public.</em></blockquote><p>Public Face, Private Backroom</p><p>When you deploy to a cloud provider such as AWS, DigitalOcean, or Google Cloud, the setup looks like this:</p><ol><li><strong>The public face.</strong> You get a machine with a public IP (for example, 203.0.113.50) and install Nginx on it.</li><li><strong>The DNS link.</strong> In your authoritative DNS dashboard, you create an A record mapping yourdomain.com to that public IP.</li><li><strong>The private backroom.</strong> Your app runs either on the same machine, bound to a local port like 127.0.0.1:5000, or on separate servers that only have private IPs like 10.0.0.5.</li></ol><p><strong>Infrastructure Mapping</strong></p><ul><li><strong>DNS Entry:</strong> Maps yourdomain.com ➔ Public IP 203.0.113.50</li><li><strong>Public Gateway:</strong> Nginx running on 203.0.113.50</li><li><strong>Isolated Private Network:</strong></li><li>App instance running on localhost:5000</li><li>App server running on 10.0.0.5:5000</li></ul><p>The only IP the internet, your ISP, and the user’s browser ever see is the Nginx public IP. The real application addresses stay completely hidden.</p><p>What Nginx Does</p><p>Nginx listens on ports 80 (HTTP) and 443 (HTTPS). When a packet arrives for one of those ports, the operating system kernel hands it to Nginx because Nginx is bound to those ports.</p><p>It then acts as a traffic cop with three main jobs:</p><p>JobWhat happens<strong>TLS termination</strong>Nginx does the heavy work of decrypting HTTPS. Inside the machine, traffic continues as plain HTTP.<strong>Static files</strong>Images and HTML files are served straight from disk, so your app is never woken up.<strong>Reverse proxying</strong>API paths like /users/profile are forwarded directly to the app&#39;s internal port.</p><p>A minimal configuration looks like this:</p><p><strong>nginx</strong></p><pre>server {<br>    listen 443 ssl;<br>    server_name myapp.com;</pre><pre>    # 1. TLS termination happens here<br>    ssl_certificate     /etc/letsencrypt/live/myapp.com/fullchain.pem;<br>    ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;</pre><pre>    # 2. Forward traffic to the backend application<br>    location / {<br>        proxy_pass <a href="http://localhost:5000;">http://localhost:5000;</a><br>        proxy_set_header Host $host;<br>    }<br>}</pre><p>Use code with caution.</p><blockquote><strong><em>Analogy:</em></strong><em> The front desk checks ID at the door (TLS), hands out brochures itself (static files), and forwards real requests to the back office (proxy).</em></blockquote><p><strong>Why “Reverse” Proxy?</strong></p><p>To understand a reverse proxy, start with the ordinary kind.</p><p>A <strong>forward proxy</strong> sits in front of the user. A school that blocks social media, or a VPN that hides your location, is a forward proxy. The website only sees the proxy’s IP, so the <strong>client</strong> is protected.</p><p>A <strong>reverse proxy</strong> sits in front of the servers. Users only ever talk to Nginx and have no idea what your internal network looks like. The <strong>servers</strong> are protected.</p><p>The Network Layout Comparison</p><ul><li><strong>Forward Proxy (Hides the Client):</strong> Client ➔ Forward Proxy ➔ Website</li><li><strong>Reverse Proxy (Hides the Servers):</strong> Client ➔ Nginx ➔ <em>[Server A (Node.js) / Server B (Python) / Server C (Static Files)]</em></li></ul><p>FeatureForward proxyReverse proxy<strong>Sits in front of</strong>The clientThe servers<strong>Protects</strong>The client’s identityThe servers’ identity and layout<strong>Examples</strong>Office web filter, VPNNginx</p><p>This matters at scale. If your Node.js app crashes or needs an update, Nginx can switch traffic to a backup server or show a maintenance page. Users never see a raw server error.</p><blockquote><strong><em>Analogy:</em></strong><em> A forward proxy is a personal assistant who makes calls for you. A reverse proxy is a company receptionist who decides which person inside takes your call.</em></blockquote><p>How Nginx Picks the Right Server and Port</p><p>Nginx reads its configuration file and decides where to route traffic using a 4-step hierarchy:</p><ul><li><strong>Step 1:</strong> Packets arrive at the VM ➔ <strong>Listen Directive</strong> <em>(Filters by destination port)</em></li><li><strong>Step 2:</strong> <strong>Host Header</strong> <em>(Matches domain to specific server block)</em></li><li><strong>Step 3:</strong> <strong>URL Path</strong> <em>(Evaluates matching location block)</em></li><li><strong>Step 4:</strong> <strong>proxy_pass</strong> <em>(Routes to internal IP and port)</em></li></ul><p><strong>Step 1: The Port</strong></p><p>A VM has 65,535 ports. Nginx guards the ones you list with listen. Packets for port 80 or 443 go straight to Nginx.</p><p><strong>Step 2: The Host Header</strong></p><p>Many domains can point to the same Nginx IP. Every HTTP/1.1 request carries a Host header, and Nginx uses it to find the server block whose server_name matches.</p><p><strong>http</strong></p><pre>GET /users/profile HTTP/1.1<br>Host: myapp.com</pre><p>Use code with caution.</p><p><strong>Step 3: The Path</strong></p><p>Inside the matching server block, location blocks match on the URL path:</p><h4>nginx snap</h4><pre>location /static/ {<br>    root /var/www/myapp;               # served directly from disk<br>}</pre><pre>location /users/ {<br>    proxy_pass <a href="http://127.0.0.1:5000;">http://127.0.0.1:5000;</a>  # forwarded to the app<br>}</pre><p>Use code with caution.</p><p>Step 4: The Internal Hop</p><p>proxy_pass http://127.0.0.1:5000; is where the forwarding happens.</p><ul><li>127.0.0.1 (or localhost) means the same machine Nginx runs on.</li><li>If the app lives on another VM in your private network, use its private IP, such as <a href="http://10.0.0.5:5000.">http://10.0.0.5:5000.</a></li><li>:5000 is the port where your Node.js, Python, or Java app is listening.</li></ul><blockquote><strong><em>Analogy:</em></strong><em> Floor (port), department (Host header), desk (path), phone extension (</em><em>proxy_pass).</em></blockquote><p>What Your Backend Framework Does</p><p>Your app is bound to the internal port 5000. It reads the HTTP method and path forwarded by Nginx and processes it through three distinct layers:</p><ul><li><strong>Inbound Hop from Nginx</strong> ➔ <strong>1. Router</strong> <em>(Matches verb/path)</em> ➔ <strong>2. Middleware</strong> <em>(Auth, logging, rate limits)</em> ➔ <strong>3. Controller</strong> <em>(DB operations &amp; JSON construction)</em> ➔ <strong>Response Back to Nginx</strong></li></ul><p>If a request hits the router but does not match the allowed verbs, it breaks away early:</p><ul><li><strong>Router Error:</strong> Verb mismatch ➔ <strong>405 Method Not Allowed</strong></li></ul><pre>// Example in Express (Node.js); Python frameworks work the same way<br>app.get(&#39;/users/profile&#39;, (req, res) =&gt; {<br>    // 1. Authenticate the user (read JWT)<br>    // 2. Fetch data from the database (SQL or NoSQL)<br>    // 3. Return a JSON response<br>    res.json({ name: &quot;Alex&quot;, role: &quot;Developer&quot; });<br>});</pre><p>Use code with caution.</p><ol><li><strong>Router:</strong> It looks for a route matching both the verb (GET) and the path (/users/profile). If you send a POST to a path that only defines GET, you get a 405 Method Not Allowed error.</li><li><strong>Middleware:</strong> A chain of functions that runs before your core execution logic. Typical jobs include verifying JWTs, logging requests, and checking rate limits.</li><li><strong>Controller:</strong> Your core function code talks to the database, builds the final JSON payload, and hands it back up to Nginx.</li></ol><blockquote><strong><em>Analogy:</em></strong><em> The router is the front desk finding your department, middleware is the security checkpoint, and the controller is the clerk who does the work.</em></blockquote><p>The Return Journey</p><p>Because Nginx sits in the middle, the connection is split into two separate conversations:</p><p><strong>1. Request Flow</strong></p><ul><li><strong>Browser</strong> (192.0.2.75) sends an Encrypted HTTPS request ➔ <strong>Nginx</strong> (203.0.113.50)</li><li><strong>Nginx</strong> decrypts the payload and sends a Plain HTTP request ➔ <strong>App</strong> (127.0.0.1:5000)</li></ul><p><strong>2. Response Flow</strong></p><ul><li><strong>App</strong> (127.0.0.1:5000) delivers raw JSON response back ➔ <strong>Nginx</strong> (203.0.113.50)</li><li><em>Nginx wraps the payload in an HTTP response header and encrypts it with the host’s TLS keys.</em></li><li><strong>Nginx</strong> dispatches the Encrypted response ➔ <strong>Browser</strong> (192.0.2.75)</li></ul><p>The outgoing packets carry two addresses: source 203.0.113.50 (Nginx) and destination 192.0.2.75 (the user). The ISP and internet routers only read those outer headers, so they deliver the packet safely without ever learning your internal private application addresses.</p><p><strong>SSL vs TLS</strong></p><p>FeatureSSLTLS<strong>Full name</strong>Secure Sockets LayerTransport Layer Security<strong>Introduced</strong>1995, by Netscape1999, as SSL’s successor<strong>Status</strong>Deprecated due to serious flawsCurrent industry standard<strong>Latest version</strong>NoneTLS 1.3</p><p>TLS is the modern, secure version of SSL. People still say “SSL certificate” out of habit, and Nginx directives like ssl_certificate keep the old phrasing, but the underlying engine running your server traffic is TLS.</p><p>Nginx is the front door that handles encryption, static files, and routing, so your application code can focus entirely on business logic. Everything the outside world sees is concentrated on a single public IP, keeping your internal infrastructure private and secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=197964f5e719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Hit an HTTP Endpoint]]></title>
            <link>https://medium.com/@cappiing/what-really-happens-when-you-hit-an-http-endpoint-e507a779b3a9?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e507a779b3a9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[application-layer]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 18:30:37 GMT</pubDate>
            <atom:updated>2026-10-18T18:30:37.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJ7EVwgDD4TsAE6jmy2Q7A.png" /></figure><p>You type <a href="http://example.com:8080/users/profile">http://example.com:8080/users/profile</a> and press Enter. A few milliseconds later, JSON appears. In between, your request goes through DNS, caches, a global lookup hierarchy, a TCP handshake, and the operating system of a server on the other side of the planet.</p><p>This post walks that journey step by step, with one diagram and one analogy per stage.</p><p>The Journey at a Glance</p><p>DNS answers “where is the server?”. TCP answers “can we talk reliably?”. HTTP answers “what do I want?”. The server answers “here it is”.</p><p><strong>Analogy:</strong> find the address (DNS), ring the doorbell and wait for an answer (TCP), state your request (HTTP), and the shopkeeper hands it over (server).</p><p><strong>Step 1: Finding the IP Address on Your Machine</strong></p><p>A browser cannot connect to example.com. It needs an IP address. Before asking the internet, it checks four places in order and stops at the first hit.</p><ul><li><strong>Browser cache.</strong> The browser checks its own short-term memory for a recent lookup of example.com.</li><li><strong>OS call.</strong> If that misses, the browser asks the operating system through a low-level function, typically getaddrinfo().</li><li><strong>OS DNS cache.</strong> The OS checks its own cache, run by mDNSResponder on Mac or Dnscache on Windows.</li><li><strong>Hosts file.</strong> The OS reads a plain text file on disk. It lives at /etc/hosts on Mac and Linux, and at C:\Windows\System32\drivers\etc\hosts on Windows. If you mapped the domain to an IP here, the lookup ends instantly.</li><li><strong>Network.</strong> Only now does the OS wrap a DNS request in a UDP packet and send it through your router to your ISP’s resolver.</li></ul><p>When an answer comes back, it is stored in the OS cache and handed up to the browser.</p><p><strong>Analogy:</strong> you check your memory, then your phone contacts, then your address book, and only then call directory enquiries.</p><p><strong>Step 2: The Global Lookup</strong></p><p>Your ISP’s resolver now has to find the answer. Four roles work together.</p><p>RoleJobAnalogy<strong>Recursive resolver</strong>Keeps asking until it finds the final answer. Run by your ISP, Cloudflare (1.1.1.1) or Google (8.8.8.8)The librarian<strong>Root nameservers</strong>Sit at the top of the hierarchy and point to the right TLD serverSignposts<strong>TLD nameservers</strong>Handle one extension each, such as .com, .org or .inRegistry managers<strong>Authoritative nameservers</strong>Hold the real IP, set by the developer in Route 53, Cloudflare or GoDaddyThe actual owner</p><p>Your browser asks one question. The resolver does all the follow-up work on its behalf.</p><p><strong>Step 3: DNS Records You Will Actually Use</strong></p><p>A and AAAA</p><p>RecordMaps a name toExampleSize<strong>A</strong>An IPv4 address192.0.2.132 bits<strong>AAAA</strong>An IPv6 address2001:db8:85a3:0000:0000:8a2e:0370:7334128 bits</p><p>IPv6 is four times larger than IPv4, which is an easy way to remember why it is called quad-A.</p><p>CNAME: the alias</p><p>A CNAME maps one domain name to another domain name. It never maps to an IP.</p><p>Say you host an API on AWS. AWS gives your load balancer a long generated hostname. You want clients to call api.yourdomain.com instead, so you create this record:</p><ul><li><strong>Type:</strong> CNAME</li><li><strong>Name:</strong> api.yourdomain.com</li><li><strong>Value:</strong> my-load-balancer-12345.us-east-1.elb.amazonaws.com</li></ul><p>The resolver now does double the work. It follows the alias, then resolves the target.</p><p>The golden rule: a CNAME must always point to another domain name, never directly to an IP address.</p><p><strong>Analogy:</strong> a forwarding note on a shop door saying “we moved, see the other address”.</p><p>Why the root domain cannot be a CNAME</p><p>The bare domain, yourdomain.com, is called the zone apex. It cannot be a CNAME. Subdomains such as api.yourdomain.com can.</p><p>The reason is that a CNAME cannot share a name with other records, and the apex must hold essential records like NS and SOA.</p><p>Modern DNS providers (Cloudflare, Route 53, Namecheap) work around this with ANAME or ALIAS records. They look like a CNAME to you. Behind the scenes, the provider resolves the target to a raw IP and answers the public query like a normal A record.</p><p>The zone file</p><p>All of these records live in a plain text zone file on the authoritative server. A simple example:</p><p>text</p><pre>$TTL 300<br>@     IN  NS     ns1.dnshost.example.<br>@     IN  A      192.0.2.1<br>@     IN  AAAA   2001:db8::1<br>www   IN  CNAME  yourdomain.com.<br>api   IN  CNAME  my-load-balancer-12345.us-east-1.elb.amazonaws.com.</pre><p>Use code with caution.</p><p>The @ symbol means the apex, and $TTL is the default cache lifetime in seconds.</p><p><strong>Step 4: DNS in Production</strong></p><p>Changing records safely with TTL</p><p>When you edit a record, the world does not see it instantly. Millions of resolvers have cached your old IP and will keep it until their TTL (Time to Live) timer reaches zero.</p><p>If you plan a server migration next Tuesday, lower the TTL today from 86400 seconds (24 hours) to 300 seconds (5 minutes).</p><p>Geolocation: ECS and GeoDNS</p><p>The authoritative server sees only the resolver’s IP, not yours. If you are in Mumbai but your ISP’s resolver is in Bangalore, plain DNS thinks you are in Bangalore.</p><p>EDNS Client Subnet (ECS) fixes this. The resolver attaches a truncated prefix of your IP, such as 192.0.2.x, to the query. The authoritative server can then place you more accurately.</p><p>GeoDNS builds on that. Imagine two identical servers, one in Mumbai and one in Virginia, behind one domain name. The authoritative DNS returns a different IP depending on where the query comes from.</p><p>DNSSEC: trusting the answer</p><p>Plain DNS is unencrypted and unsigned. An attacker could intercept the UDP packet and return a fake IP, sending a user to a fake banking site.</p><p>DNSSEC adds cryptographic signatures to DNS records. The resolver verifies them through a chain of trust that begins at the root servers. If the signature matches, the IP has not been tampered with.</p><p><strong>Step 5: The TCP Handshake</strong></p><p>DNS is done. The OS now opens a socket and runs the three-way handshake with 192.0.2.1:8080.</p><p>SYN stands for Synchronise and ACK stands for Acknowledge. No HTTP data moves until all three steps finish.</p><p><strong>Analogy:</strong> “Hello?”, “Yes, I can hear you.”, “Great, I will start talking.”</p><p><strong>Step 6: The HTTP Request</strong></p><p>With the pipe open, the browser writes plain text straight into the socket:</p><pre>GET /users/profile HTTP/1.1<br>Host: example.com:8080<br>User-Agent: Mozilla/5.0<br>Accept: application/json</pre><p>The path /users/profile sits in the very first line. The routers between you and the server never read it. They only care about moving TCP packets to the destination IP.</p><p><strong>Analogy:</strong> routers read the address on the envelope. The letter inside is for the receiver only.</p><p><strong>Step 7: Inside the Backend Server</strong></p><p>The kernel routes by port. The application routes by path.</p><p><strong>Analogy:</strong> the receptionist sends you to the right floor (port), and the staff on that floor find the right desk (path).</p><p>Would you like me to add a <strong>bulleted summary</strong> of the server steps to replace the diagram flow, or does this layout match the rest of your post?</p><p>By the time your server’s code runs, the browser has found the right regional IP, TCP has opened a reliable connection, and the HTTP request has arrived. The next layer is where Nginx and your backend framework take over, and that is the topic of the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e507a779b3a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OS Basics Every Backend Engineer Should Know]]></title>
            <link>https://medium.com/@cappiing/os-basics-every-backend-engineer-should-know-3c63a21ec008?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c63a21ec008</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 18:04:10 GMT</pubDate>
            <atom:updated>2026-10-18T18:04:10.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*HZjUuEkF_TsHzYmP_qu55w.png" /></figure><p>Most backend bugs that feel mysterious are often operating-system behavior in disguise.</p><p>Why does a Node.js server freeze when processing one heavy request? Why does a Java service consume 5 GB of RAM? Why does a container get killed even though everything appears normal?</p><p>The answers become easier to understand when we start from the bottom:</p><p><strong>Hardware → Kernel → Processes and Threads → Frameworks → Containers</strong></p><p>Each layer builds on the one below it. A limitation at a lower layer eventually affects everything above it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POujvNjePNBqVdUuHDENMg.png" /></figure><p><strong>Analogy:</strong> Think of a restaurant. Hardware is the kitchen equipment. The kernel is the head chef deciding who cooks what and when. Processes and threads are the cooks. Docker creates separate kitchen stations, each with its own walls and ingredient quota.</p><h3>1. Hardware: CPU Cores and Hyper-Threads</h3><p>A <strong>CPU core</strong> is a physical execution unit that runs instructions. A four-core CPU can execute work on four physical cores at the same time.</p><p><strong>Hyper-threading</strong>, also called simultaneous multithreading, allows one physical core to appear as two logical CPUs to the operating system. As a result, a four-core CPU may appear as eight vCPUs.</p><p>However, hyper-threading does not make the CPU twice as fast. It helps when one thread is waiting — for example, for data from memory or storage because the core can use that time to work on another thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQgI5AzQfniO8oKZErAluw.png" /></figure><p><strong>Analogy:</strong> Imagine one chef with two cutting boards. While one dish is waiting in the oven, the chef can prepare another dish on the second board.</p><h3>2. Memory: A Speed Ladder</h3><p>The CPU performs calculations, but the data it needs is stored across several levels of memory.</p><p>The closer the memory is to the CPU, the faster it is and the smaller its capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx01i7HqV77u-3yIWTwHQg.png" /></figure><p>Memory layerApproximate access timePurposeRegisters~0.5 nsTiny storage locations inside the CPU coreL1, L2, and L3 cache1–15 nsSmall, fast memory located on or near the CPURAM60–100 nsMain memory used by running programsSSD or NVMe storage50,000+ nsPersistent storage for files and databases</p><p>When the CPU looks for data in the cache and cannot find it, a <strong>cache miss</strong> occurs. The CPU must wait for the data to arrive from RAM or another slower layer.</p><p>These small delays matter. A program that repeatedly accesses data scattered across memory can become much slower than one that accesses nearby data efficiently.</p><p><strong>Analogy:</strong> Registers are your hands, the cache is your desk, RAM is the bookshelf in the room, and the SSD is a library across town.</p><h3>3. The Scheduler and Context Switching</h3><p>A computer may run hundreds of programs even though it has only a few CPU cores.</p><p>The operating system makes this possible through <strong>time-slicing</strong>. The kernel scheduler gives each thread a short turn on the CPU often a few milliseconds then pauses it and runs another thread.</p><p>The act of pausing one thread and starting another is called a <strong>context switch</strong>.</p><p>During a context switch, the operating system must:</p><ol><li>Save the current thread’s state.</li><li>Load the next thread’s state.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGU4zOFVxYeH_bTdvRlx2Q.png" /></figure><ol><li>Resume execution from the correct point.</li></ol><p>A context switch is not free. The CPU cache may contain data belonging to the previous thread, so the next thread can experience additional cache misses.</p><p>With too many active threads, the CPU may spend more time switching between threads than performing useful work. This is sometimes called <strong>CPU thrashing</strong>.</p><p><strong>Analogy:</strong> Picture a chef managing 100 orders who spends more time swapping pans and reading tickets than actually cooking.</p><h3>4. Processes vs. Threads</h3><p>A <strong>process</strong> is a running instance of a program. The operating system gives each process its own virtual address space and protects it from other processes.</p><p>If a process attempts to access memory that does not belong to it, the operating system may terminate it with an error such as a segmentation fault.</p><p>A <strong>thread</strong> is an execution path inside a process. Threads belonging to the same process share resources such as:</p><ul><li>The heap</li><li>Objects</li><li>Database connection pools</li><li>Open network connections</li><li>Loaded application code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Db12Z-rSqZvS4EY7qyntVw.png" /></figure><p>Each thread also has its own private stack, which stores local variables and function-call information.</p><p>ProcessThreadMemoryHas its own virtual address spaceShares the process heapStackHas one or more thread stacksOwns its individual stackCostRelatively expensive to createRelatively lightweightFailure impactUsually isolated from other processesCan crash the entire process</p><p><strong>Analogy:</strong> A process is an apartment with a locked door. Threads are roommates sharing one refrigerator the heap while each has their own bedroom the stack.</p><h3>The Catch: Race Conditions</h3><p>Because threads share the heap, two threads can read and modify the same value at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYXIfhbnrEtEf4Uz9n4eZg.png" /></figure><p>For example, imagine two threads incrementing a shared counter:</p><p>Both threads read the value 5. Each calculates 5 + 1, and both write back 6. One update is lost.</p><p>This is a <strong>race condition</strong>.</p><p>A common solution is a <strong>mutex</strong>, or mutual-exclusion lock. The lock allows only one thread at a time to enter the critical section of code.</p><p><strong>Analogy:</strong> It is the “one person at the refrigerator” rule. Only one roommate can open it and change the shared inventory at a time.</p><h3>5. How Backend Frameworks Use These Concepts</h3><p>Backend frameworks commonly use one of two execution models:</p><ol><li><strong>Thread-per-request</strong></li><li><strong>Event loop</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNJli1c1p34CRGdg_9sIoQ.png" /></figure><p>Both models are built on the operating-system concepts we have already covered.</p><h3>Thread-per-request</h3><p>In a thread-per-request model, each incoming request is assigned to a worker thread.</p><p>If one request makes a slow database call, only its worker thread is blocked. Other requests can continue on other threads, assuming the process has enough available workers and CPU capacity.</p><p>The trade-off is memory usage. Each thread requires stack memory.</p><p><strong>Analogy:</strong> One waiter is assigned to each table. If one table takes a long time to decide what to order, the other waiters can continue serving their tables.</p><h3>Event loop</h3><p>An event-loop model uses one primary thread to handle many requests.</p><p>When a request needs to wait for a database or network operation, the event loop registers a callback and moves on to another request. When the operation finishes, the callback runs.</p><p>This approach can use less memory and support a large number of concurrent connections.</p><p>However, CPU-heavy work blocks the event-loop thread. While that work is running, every other request waiting on the same event loop may be delayed.</p><p><strong>Analogy:</strong> One waiter takes orders from every table. When one table’s food is being prepared, the waiter serves another table instead of standing idle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VE5N3MKuH3qzsQu6vQESg.png" /></figure><h3>A Simple Formula for Thread Memory</h3><p>A rough estimate for stack memory is:</p><pre>stack memory≈N(threads) × S(stack)</pre><p>For example, if an application has 5,000 threads and each thread reserves 1 MB of stack space:</p><pre>5000×1MB=5000MB≈5GB</pre><p>That is approximately 5 GB of memory used only for thread stacks — before the application stores objects, buffers, caches, or database results.</p><p>The actual memory usage depends on the language runtime, operating system, stack configuration, and whether all reserved stack memory is physically committed. Still, the formula illustrates why creating thousands of threads can be expensive.</p><h3>6. Containers: Processes with Walls</h3><p>A Docker container is not a small virtual machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKvQDOEfqA0DJxTM6nL9Gw.png" /></figure><p>A container is a normal process or group of processes running on the host machine’s kernel. Linux features such as <strong>namespaces</strong> and <strong>cgroups</strong> make the process appear isolated and allow resource limits to be enforced.</p><h3>Namespaces: What the Process Can See</h3><p>Namespaces control the system resources visible to a process.</p><p>NamespaceWhat the container seesWhat exists on the hostPIDIts main process may appear as process 1The process has a different host PIDNetworkIts own interfaces and portsThe host has the underlying network stackMountIts own root filesystemThe host has the complete filesystem</p><p>Namespaces provide isolation, but they do not create a separate kernel. Containers still use the host operating system’s kernel.</p><h3>cgroups: What the Process Can Use</h3><p>A process with an infinite loop could consume all available CPU or memory and affect other applications.</p><p><strong>Control groups</strong>, commonly called <strong>cgroups</strong>, allow the kernel to enforce resource limits.</p><p>For example, Kubernetes resource limits may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWAwSb-U-tP-pSZzcrTo4A.png" /></figure><p>The container runtime converts these settings into Linux cgroup configuration.</p><p>Exceeding a memory limit can cause a process to be terminated. Exceeding a CPU limit usually causes throttling rather than an immediate kill.</p><p><strong>Analogy:</strong> Namespaces are the walls of the room. cgroups are the electricity and water meters that limit how many resources the room can consume.</p><h3>7. Environment Variables</h3><p>When the operating system starts a process, it provides a collection of NAME=value pairs called <strong>environment variables</strong>.</p><p>Common examples include:</p><ul><li>DATABASE_URL</li><li>PORT</li><li>LOG_LEVEL</li><li>API_KEY</li></ul><p>Environment variables allow the same application code and container image to run in different environments. Only the configuration values change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8ucWGF0C-IuXheGs-Zq5A.png" /></figure><p>This helps keep environment-specific settings and secrets out of the source code, although secrets still need to be managed carefully because environment variables may be visible to processes, debugging tools, or logs if handled incorrectly.</p><p><strong>Analogy:</strong> It is the same actor performing in different theatres, with a different instruction card provided at each location.</p><h3>8. Filesystems and Volumes</h3><p>A container’s writable filesystem is usually temporary.</p><p>When a container is removed or recreated, files written only inside that container may disappear. For a database, this could mean losing important data.</p><p>A <strong>volume</strong> or <strong>bind mount</strong> stores data outside the container’s temporary writable layer.</p><p>For example, a database directory such as /var/lib/mysql can be connected to persistent storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCsfuZWF53Cod10MvxmRRg.png" /></figure><p>A volume is managed by Docker or the container platform. A bind mount connects a container path directly to a specific directory on the host.</p><p><strong>Analogy:</strong> A volume is like a hotel safe-deposit box. Your belongings survive when the hotel room is cleaned. The container’s temporary filesystem is like leaving those belongings in the room.</p><p>Every layer of backend infrastructure follows from the layer below it.</p><p>CPU cores are limited, so the kernel schedules and time-slices threads. Context switching has a cost, so frameworks choose carefully between threads and event loops. Containers add isolation and resource limits on top of ordinary operating-system processes.</p><p>The next time a service freezes, consumes too much memory, gets killed, or loses data after a restart, ask yourself:</p><p><strong>Which operating-system layer is responsible for this behavior?</strong></p><p>Once you learn to trace backend problems from the application down to the kernel and hardware, many <strong>mysterious</strong> failures become predictable and much easier to debug.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c63a21ec008" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Scale and Organize Your Codebase Using the MVC Pattern]]></title>
            <link>https://medium.com/@cappiing/how-to-scale-and-organize-your-codebase-using-the-mvc-pattern-babad5c49a4d?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/babad5c49a4d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 12:42:36 GMT</pubDate>
            <atom:updated>2026-09-06T12:42:36.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Fmr9HINj--h11uevv8u_8A.png" /><figcaption>Stock-Image(Scaler)</figcaption></figure><p>Well, there are lots of blogs and videos already explaining how to manage your codebase using the MVC pattern. So instead of just repeating the same thing, I tried to explain it in my own way and based on how I implemented it in one of my projects.</p><p>It was actually a pretty good-sized codebase, with a lot of code in it. Because of that, I wanted the structure to be clean and well organized. When you share your source code with teammates, it feels much better if they don’t complain about missing structure or too much noise in the code. So I thought I’d write about how I approached it.</p><p>Recently, I created a repository from scratch, and while setting it up, I read a lot about how to organize the code in the best possible way. The idea was to make sure that if someone looks at it later, they don’t get confused or complain about the structure. That’s what led me to follow the MVC pattern.</p><p>I’m not going to show you my actual production code, because obviously that’s part of the company’s codebase. But I have replicated something similar in my local setup, so I’ll explain it using that example.</p><p>Let’s keep this simple and not too long, so it doesn’t feel boring.</p><h3>What is MVC?</h3><p>Most people already know that MVC stands for <strong>Model, View, and Controller</strong>.</p><h3>Model</h3><p>The model is the part of the codebase that handles the data layer. It doesn’t care about the UI or the overall flow of the application. It mainly deals with the schema, database logic, and queries.</p><p>For example, if you are using PostgreSQL, the model is where you would keep the code for your schema and the database queries. In my case, I used an ORM to communicate with the database, so that code lives inside the model.</p><h3>View</h3><p>The view is what the client sees on the screen. In frontend applications, this could be React, HTML, or JavaScript.</p><p>In my case, the project was backend-only, so the <strong>view</strong> was basically the JSON response returned to the client.</p><h3>Controller</h3><p>The controller is the most important part of the MVC pattern. You can think of it as the brain layer or the traffic cop.</p><p>It receives the request from the route, checks whether the input is valid, applies business logic, verifies user permissions, and decides whether the request should move forward. If everything looks good, it passes the request to the model. The model then talks to the database and returns the result back through the controller.</p><p>If you like football, the controller is kind of like a creative midfielder or a number 8 it connects defense, midfield, and attack.</p><h3>How the flow works</h3><p>A simple backend flow looks like this:</p><blockquote>Route receives the request</blockquote><blockquote>Controller validates the request</blockquote><blockquote>Controller calls the model</blockquote><blockquote>Model interacts with the database</blockquote><blockquote>Response goes back to the client</blockquote><h3>Example structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*JEFq-zuyfzSr-I8c9R-ZhQ.png" /></figure><p>Let’s say you have a user table.</p><p>In the model, you could have something like user.model.js, where you define methods such as:</p><ul><li>createUser</li><li>getUser</li></ul><p>If you are using an ORM like Prisma, this is where you would write your database operations. If you are using plain SQL, then this is where your queries would live.</p><p>Then in the controller, you handle the request and response objects.</p><p>For example:</p><blockquote>If the input is valid, you can create a user or fetch user data</blockquote><blockquote>If the input is invalid, you return an error right away</blockquote><blockquote>The database is never touched unless the request passes validation</blockquote><p>That is the benefit of keeping logic inside the controller first.</p><h3>Why keep routes separate?</h3><p>One thing I strongly followed was keeping the route layer separate from the controller and model.</p><p>So instead of putting everything inside one big index.js file, it’s better to keep the router in its own folder. That way, even if your project grows to 2000 or 3000 lines of code, it is still much easier to manage.</p><p>For example:</p><ul><li>routes/user.route.js</li><li>controllers/user.controller.js</li><li>models/user.model.js</li></ul><p>This makes the codebase cleaner and easier to maintain.</p><h3>Database connection</h3><p>After that, you usually have your main index.js or server entry file, where you establish the database connection and bring everything together.</p><p>So the basic flow is:</p><blockquote>Routes handle the endpoint</blockquote><blockquote>Controller handles logic</blockquote><blockquote>Model handles database communication</blockquote><blockquote>Response goes back as JSON or view data</blockquote><p>If you are using React on the frontend, then the response can be consumed there. If it is backend-only, JSON itself becomes the response layer.</p><h3>Why this structure helps</h3><p>This setup helps you keep backend and frontend concerns organized without mixing everything into one place. You do not need to split everything into completely separate repositories just to keep things clean. MVC helps you maintain structure inside the same codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*CoZ4yDMMAY0rypYfQKnK-w.png" /></figure><h3>Final thought</h3><p>That’s how I usually think about organizing a backend codebase using the MVC pattern. It keeps things clean, readable, and easy to scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=babad5c49a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle a Prisma Migration Conflict in Your Database Gracefully]]></title>
            <link>https://medium.com/@cappiing/how-to-handle-a-prisma-migration-conflict-in-your-database-gracefully-c27341e257bf?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27341e257bf</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 12:15:13 GMT</pubDate>
            <atom:updated>2026-09-06T12:15:13.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*5qjoNUsm7ftxDEm5WpVqOQ.png" /><figcaption>copyright: <a href="https://www.prisma.io/docs/guides/database/schema-changes">https://www.prisma.io/docs/guides/database/schema-changes</a></figcaption></figure><p>A lot of the time, when you try to migrate your schema into an existing database, you run into a migration issue. Prisma may detect a conflict because it finds differences or changes in the database that are not reflected in your local migration history or schema.</p><p>By default, Prisma assumes that if it cannot find a migration history locally, it should rewrite the schema and migrate the database from scratch. But that is not always the right approach. In many cases, especially when you are working with an existing database, you need to resolve the issue more gracefully so you do not run into problems later.</p><p>In this post, I’ll explain how I handle this situation based on my own experience. I looked at a few articles, but I could not find a clear explanation that was simple enough for someone who is new to ORMs. So I decided to explain it in my own way.</p><p>I’ll use Node.js and npm in the examples, but the same idea can apply to other setups as well. The package manager does not really matter here the concept is what matters.</p><h3>Why You Should Not Use migrate reset</h3><p>When you run into an issue while using a command like npx prisma migrate dev, Prisma may suggest that you reset the migration state. You should be careful with that option, because it can wipe out all your database data.</p><p>That is a dangerous step, especially when your database already contains important data. Instead of rewriting everything, you should first understand what Prisma is trying to do and then resolve the conflict safely.</p><h3>A Better Approach</h3><p>Here is the approach I recommend:</p><h3>Step 1: Inspect the existing database</h3><p>Run:</p><p>npx prisma db pull</p><p>This command introspects your existing database and writes the current structure into your schema.prisma file. It brings your Prisma schema in sync with the database you already have.</p><h3>Step 2: Create a baseline migration</h3><p>Next, create a baseline migration. This is an important step.</p><p>Run:</p><p>npx prisma migrate dev --name baseline</p><p>This creates the SQL migration file inside your Prisma migrations folder, but it does not necessarily mean you should apply it blindly to a live database.</p><h3>Step 3: Mark the migration as applied</h3><p>Then run:</p><p>npx prisma migrate resolve --applied baseline</p><p>This tells Prisma that the baseline migration has already been applied. In other words, you are manually updating Prisma’s migration metadata so it understands that the current database state is intentional and valid.</p><h3>How This Works</h3><p>If you have ever dealt with a merge conflict, this idea will feel familiar.</p><p>Imagine your local branch is missing some changes that already exist in the main branch. You would pull the latest changes, resolve the conflict, and then continue working. Prisma migration conflicts are similar.</p><p>Here, you are not changing the database directly. Instead, you are creating a baseline and telling Prisma to trust that the current database structure is the correct starting point. After that, when you run npx prisma migrate dev again, Prisma understands that the existing tables are already accounted for.</p><h3>Why This Is Useful for Large Databases</h3><p>This approach is especially helpful when your database already contains a lot of data.</p><p>Prisma checks the migration history in _prisma_migrations, sees that the baseline has been recorded, and then compares the schema against the current database. Since the database structure matches what Prisma expects, it leaves your existing data untouched and applies only the new changes.</p><p>That means your users table, existing records, and other important data remain safe while Prisma continues managing future schema changes normally.</p><h3>Final Thoughts</h3><p>That is a simple way to handle Prisma migration conflicts gracefully without losing data. Instead of resetting everything, you can establish a baseline, sync Prisma’s history with your existing database, and move forward safely.</p><p>I hope this was helpful. Stay tuned for more posts like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27341e257bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Outbox Pattern, Explained by a Real Problem (Without Breaking the App)]]></title>
            <link>https://medium.com/@cappiing/the-outbox-pattern-explained-by-a-real-problem-without-breaking-the-app-909921908731?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/909921908731</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[transactional-outbox]]></category>
            <category><![CDATA[database-transaction]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 21:56:11 GMT</pubDate>
            <atom:updated>2026-07-25T06:52:46.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGNo2GfLJ55ndPQYAY9FGQ.png" /></figure><p><em>The obvious solution is a database transaction. Here’s why that breaks across two databases, and what I did instead.</em></p><p>I want to start recording the problems I solve day to day. This is the first one, building a reusable audit-logging feature, and I’m writing it partly to document it and partly because the reasoning behind it turned out to be more interesting than the final code. So bear with me while I walk through how I actually got there, dead ends included.</p><h3>The problem</h3><p>The task sounded simple on paper: build audit logging.</p><p>If you haven’t worked on it before, auditing is just this. You record every meaningful interaction that happens in the application. Which user did what, when, and what changed. Someone updates a record, inserts something new, performs some action, and all of it has to be captured. That’s the audit trail.</p><p>And the ask wasn’t to <strong>add auditing to one screen</strong>. It was to build <strong>one generic audit capability</strong> that any tool in our ecosystem can plug into. Abstract it enough that any team can use it without reinventing it.</p><p>So the real problem became: how do you build audit logging that’s generic, reliable, and doesn’t get in the way of the actual application?</p><h3>A bit of background on the setup</h3><p>Our stack is Next.js on the front and back, with MySQL as the primary database. But the important detail, the one that shaped every decision, is that this isn’t a simple monolithic repo with one team. It’s a shared codebase where multiple teams onboard and maintain their own set of tools. We also run several different environments.</p><p>That last part matters. Writing all the audit logs into the <em>same</em> primary database was never really an option. Different teams, different environments, all funneling into one MySQL table would’ve been a mess to isolate and scale. So I started looking at <strong>DynamoDB</strong> for the audit store instead. The plan was that per environment, we get its own Dynamo table holding that environment’s audit logs. Clean separation, and Dynamo is a great fit for append-only, write-heavy data like audit trails anyway.</p><p>But the moment you decide to write audit logs to a <em>different</em> database than your application data, you inherit a much harder problem.</p><h3>The two things that must never happen</h3><p>Once I started sketching the schema, I realized the design hinges on two guarantees:</p><p><strong>One, auditing must never break the real functionality.</strong> My audit code is now sitting in the path of every mutation. If my logging logic throws, the user’s actual action must not fail because of it. The feature comes first; the audit is a passenger.</p><p><strong>Two, but audit failures can’t be silent either.</strong> The lazy version is to wrap the audit write in a try/catch, swallow the error, log a message, and move on. That’s tempting, but it’s wrong. Because now you have a user action that succeeded in the app while its audit log quietly failed, and your audit trail is out of sync with reality. For something whose entire job is to be a reliable record, silently dropping entries defeats the point.</p><p>So I needed both. The app must survive an audit failure, <em>and</em> I can’t just lose the audit entry when it fails. Those two pull in opposite directions, and reconciling them is the whole problem.</p><h3>The obvious idea that doesn’t work here</h3><p>The first instinct anyone has is to wrap it in a transaction. If the audit write and the app write are in one transaction, then either both succeed or both roll back. Problem solved.</p><p>And that’s genuinely correct, <em>if everything lives in one database.</em></p><p>But remember my setup. I’m writing application data to MySQL and audit logs to DynamoDB. Two completely different databases. A standard database transaction can’t span both. There’s no BEGIN ... COMMIT that wraps a MySQL write and a Dynamo write together. So the transaction approach falls apart the moment you cross a database boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTTGOrLz1Ug3Et2hiyjzAw.png" /></figure><p>This is a classic distributed-systems problem, and once I framed it that way, I knew there’d be known patterns for it.</p><h3>The patterns I considered, and why event sourcing wasn’t it</h3><p>The two common answers are <strong>event sourcing</strong> and the <strong>outbox pattern</strong>.</p><p>I looked at event sourcing first, and honestly it was a bit much for what I needed. Event sourcing means modeling everything as a stream of events (start, update, stop, and so on) and you reconstruct state by replaying them, with a status at the end. It’s powerful, but it fits <em>analytical</em> problems better. Like if you wanted to know which section of the app gets used most, or how much time a user spends where, replaying an event stream is perfect for that.</p><p>But my need was simpler and more direct. Reliably record <strong>this actor did this thing</strong> without losing entries and without breaking the app. Going full event-ID-per-stage felt like solving a bigger problem than I had. So I went with the outbox pattern instead.</p><h3>The outbox pattern, and how I actually solved it</h3><p>Here’s the idea, and it’s satisfyingly simple once it clicks.</p><p>At the moment of a mutation, instead of writing to Dynamo directly (across the risky database boundary), I write the audit entry to a <strong>temporary outbox table in MySQL</strong>, the same database as the application data. The payload is small and plain: start time, end time, who the actor was, what they did. Just the normal change record.</p><p>The key move is that because this outbox table lives in the <em>same</em> MySQL database as the app data, I <em>can</em> wrap it in a transaction with the actual application write. So now either the user’s change and its audit entry both commit, or neither does. The <strong>two databases can’t share a transaction</strong> problem disappears, because at write time I’m only touching one database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sebsKrmECydLt-WHj1u8fA.png" /></figure><p>Then a separate <strong>relay</strong> takes over. Its job is to read the outbox table and push those entries into the right DynamoDB table for that environment. When it successfully writes an entry to Dynamo, it marks that row’s status as done, and only <em>then</em> is the outbox row deleted. The outbox table isn’t permanent storage; it’s just a staging area between the write and the relay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEiT2LUZErhrnbpb9RPxRA.png" /></figure><h3>What happens when things fail (the part I care about most)</h3><p>This is where the design earns its keep.</p><p><strong>What if Dynamo is down when the relay runs?</strong> No problem. The relay only marks a row complete (and deletes it) <em>after</em> a confirmed successful Dynamo write. If Dynamo is unavailable, the row just stays in the outbox and gets retried on the next run. Nothing is lost. The status flag is what makes this safe. Done means done, and anything not-done is still pending.</p><p><strong>What if two relay jobs run in parallel and grab the same row?</strong> Handle it the normal way. A row gets claimed and marked before processing, so a second job won’t pick up one that’s already in flight.</p><p>So both of my original guarantees hold. The app never breaks (the risky cross-database write moved out of the request path), and audit entries are never silently lost (they sit safely in the outbox until confirmed delivered).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwzkY0mBDh-RuRnriuG8Vw.png" /></figure><p>Here’s the full picture end to end:</p><p>For the relay itself, I used a scheduled job. But there’s a nicer option worth mentioning, and whether it’s worth it depends entirely on your situation.</p><p>A cron job means polling. You can’t run it nightly, because audit logs need to be near-real-time, so you end up polling the outbox every 10 or 20 seconds. That’s constant pressure on the server, even when there’s nothing to relay.</p><p>The more elegant approach is <strong>Debezium</strong>, a change-data-capture tool commonly used with Kafka. Instead of you polling, it watches MySQL’s own <strong>binlog</strong>, the internal log MySQL keeps of every change. When something lands in your table, Debezium picks it up and pushes it downstream automatically. No polling, no wasted cycles.</p><p>For my case, though, the polling job was fine, and this is a deliberate tradeoff, not laziness. Our users are all <em>internal</em>. This isn’t a consumer-facing app with a huge user base hammering it, so the load from a polling relay is negligible. Debezium is genuinely great if you want to explore it or if your scale demands it, but I didn’t need to reach for it here. Right-sizing the solution to the actual problem matters.</p><h3>A note on the Dynamo side</h3><p>Getting the data <em>into</em> Dynamo reliably is one problem; querying it well is a separate one. With Dynamo, performance lives and dies by how you model your keys: the partition key, sort key, and any global secondary indexes. And that depends entirely on how you intend to read the data back. So before finalizing the Dynamo layer, it’s worth being clear about your access patterns. What questions will you ask of these audit logs? Design the keys around those, not the other way round. That’s a whole topic on its own, so I’ll leave it there for now.</p><h3>Making it truly reusable</h3><p>The last piece was the original goal: a <em>generic</em> system, usable anywhere.</p><p>There are two layers of reuse.</p><p>For anything inside our repo, I wrapped all of this in a <strong>library-style abstraction</strong>. A team just passes in their real data (the actor, the action, the payload) and the wrapper handles everything else: the outbox write, the transaction, the relay, the Dynamo delivery. It’s a black box to them, which is exactly the point.</p><p>For anything <em>outside</em> the repo, I exposed the same logic through an <strong>API</strong>, with endpoints to write and read audit logs. So another repository that wants auditing doesn’t need our internal code at all. They hit the API to store their entries in our DB and to read them back. Same engine, two front doors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8UeRembPTA6Z_JbuC4csg.png" /></figure><h3>Wrapping up</h3><p>So that’s how one audit feature ended up being usable everywhere: an outbox table to make cross-database writes transactional, a relay to deliver them safely with retries, a status flag so nothing is ever silently lost, and a wrapper plus an API so any team can plug in.</p><p>The part I enjoyed most was that the naive answer, “just use a transaction,” was <em>right in spirit</em> but broke against a real constraint (two databases), and the fix was to reshape the problem so a single-database transaction became possible again. That’s the kind of thing I want to keep a record of.</p><p>If you read this far, thanks for sticking with me. If you think my approach was solid, or if you’d have done something completely different, I’d genuinely like to hear it. See you in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909921908731" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Internet Actually Works]]></title>
            <link>https://medium.com/@cappiing/how-the-internet-actually-works-330e94b7c9a4?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/330e94b7c9a4</guid>
            <category><![CDATA[netwroking]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 24 May 2026 16:33:25 GMT</pubDate>
            <atom:updated>2026-05-24T16:33:25.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEsQdrKc_psJlEyArrEmag.png" /></figure><h3>The Big Picture</h3><p>When you type https://google.com and press Enter, 7 things happen in order:</p><ol><li><strong>URL parsing</strong> — browser breaks the URL into pieces</li><li><strong>DNS lookup</strong> — finds the server’s IP address</li><li><strong>TCP connection</strong> — opens a reliable pipe to the server</li><li><strong>TLS handshake</strong> — encrypts that pipe (for HTTPS)</li><li><strong>HTTP request</strong> — your browser sends a message</li><li><strong>Server responds</strong> — sends back HTML/JSON/whatever</li><li><strong>Browser renders</strong> — shows it on screen</li></ol><p>This whole chapter explains steps 1–6 in detail.</p><h3>Typing a URL → Getting a Response</h3><h4>URL Parsing</h4><p>Every URL has parts. Example: <a href="https://api.github.com/users/torvalds?tab=repos#bio">https://api.github.com:443/users/torvalds?tab=repos#bio</a></p><p>Part Example What it means Scheme https Which protocol to use Host api.github.com Server&#39;s name Port 443 Which &quot;door&quot; on the server (443 = HTTPS default, 80 = HTTP default) Path /users/torvalds What resource you want Query string ?tab=repos Extra parameters Fragment #bio Section of the page (<strong>stays in browser, server never sees it!</strong>)</p><p><strong>Key insight:</strong> The fragment (#bio) NEVER goes to the server. That&#39;s why old single-page apps used # for routing same server request no matter which &quot;page&quot; the user was on.</p><h3>DNS — The Internet’s Phonebook</h3><h4>The Problem</h4><p>Computers use IP addresses like 142.250.193.78. Humans remember names like google.com. DNS translates between them.</p><h4>How a DNS Lookup Works</h4><p>When your browser needs google.com&#39;s IP, it asks in this order (stops at first answer):</p><ol><li><strong>Browser cache</strong> — “Did I look this up recently?”</li><li><strong>OS cache</strong> — “Did my computer look this up recently?”</li><li><strong>Router cache</strong> — Sometimes.</li><li><strong>ISP’s DNS resolver</strong> — Your ISP’s phonebook server. Most lookups end here.</li><li><strong>Root servers</strong> → <strong>TLD servers</strong> → <strong>Authoritative servers</strong> — Only if nothing else knows.</li></ol><p><strong>In simple words:</strong> It’s like asking “What’s Alice’s phone number?” First you check your own phone. Then you ask your spouse. Then your roommate. Then your phone provider’s directory. Each level has a cache.</p><h3>DNS Record Types</h3><p>Record What it does Example <strong>A</strong> name → IPv4 address google.com → 142.250.193.78 <strong>AAAA</strong> name → IPv6 address google.com → 2607:f8b0:4005:80f::200e <strong>CNAME</strong> name → another name (alias) www.example.com → example.com <strong>MX</strong> mail server records &quot;Send @gmail.com emails to these servers&quot; <strong>TXT</strong> arbitrary text Used for domain verification, anti-spam <strong>NS</strong> which servers handle this domain Points to authoritative DNS servers</p><h3>TTL — Time To Live</h3><p>Every DNS record has a TTL (in seconds) saying how long it can be cached.</p><ul><li>TTL of 3600 = cache for 1 hour</li><li>TTL of 300 = cache for 5 minutes</li><li>TTL of 86400 = cache for 24 hours</li></ul><p><strong>This is why “DNS propagation takes 24 hours.”</strong> It’s not really propagation — it’s old caches around the world expiring. When you’re about to change DNS, lower the TTL first (a day before), so changes spread fast.</p><h3>Try It Yourself</h3><pre>dig google.com              # See A records<br>dig google.com MX           # See mail servers<br>dig +trace google.com       # Watch the full lookup chain</pre><h3>Mental Model</h3><p><strong>DNS is a distributed, cached key-value lookup.</strong> Keys = names. Values = records. That’s it.</p><h3>TCP — Building a Reliable Pipe</h3><h4>The Problem</h4><p>The internet is unreliable:</p><ul><li>Packets get lost</li><li>They arrive out of order</li><li>They get duplicated</li><li>Networks drop traffic</li></ul><p><strong>Analogy:</strong> Imagine mailing a 500-page book by ripping out each page and sending it in a separate envelope. Some get lost, some arrive late, some out of order.</p><h3>What TCP Does</h3><p>TCP makes this look reliable to your application:</p><ul><li>✅ Numbers every packet so receiver can reassemble in order</li><li>✅ Acknowledges received packets (so sender knows what got through)</li><li>✅ Retransmits anything lost</li><li>✅ Controls flow (fast sender won’t overwhelm slow receiver)</li><li>✅ Detects corruption with checksums</li></ul><p>Your app code just says “send these bytes.” TCP handles the chaos.</p><h3>The 3-Way Handshake</h3><p>Before sending data, both sides agree to talk:</p><pre>Client                          Server<br>  |                                |<br>  |---------- SYN ----------------&gt;|   &quot;Hi, I want to talk. My start # is X&quot;<br>  |                                |<br>  |&lt;------- SYN-ACK ---------------|   &quot;Got it. My start # is Y. Acking X.&quot;<br>  |                                |<br>  |---------- ACK ----------------&gt;|   &quot;Acking Y. Let&#39;s go.&quot;<br>  |                                |<br>  |======= Connection open =======&gt;|</pre><p><strong>Why this matters for performance:</strong> The handshake costs one full round-trip. If your server is 100ms away, that’s 100ms before you’ve sent any actual data. This is why HTTP <strong>keep-alive</strong> matters — reusing a connection skips the handshake on the next request.</p><h3>TCP vs UDP</h3><p>Feature TCP UDP Reliability Guaranteed None Ordering Guaranteed None Handshake Yes (slow start) No (instant) Speed Slower Faster Used for HTTP, SSH, email, file transfer Video calls, games, DNS, HTTP/3 (QUIC)</p><p><strong>Simple rule:</strong> Need every byte in order? TCP. Need it fast and can lose some? UDP. A video call would rather skip a glitchy frame than wait — that’s why it uses UDP.</p><h3>TLS and HTTPS</h3><h4>Why TLS Exists</h4><h4>The Postcard Problem</h4><p>Plain HTTP is like sending postcards. Every person who handles them can:</p><ul><li>Read what’s written (no privacy)</li><li>Change it before delivery (no integrity)</li><li>Pretend to be the sender (no authenticity)</li></ul><p>TLS solves all three:</p><p>Problem TLS Solves It By <strong>Confidentiality</strong> Encryption — nobody in the middle can read <strong>Integrity</strong> Signed messages — tampering is detectable <strong>Authenticity</strong> Certificates — you know you’re really talking to google.com</p><h3>Vocabulary</h3><ul><li><strong>SSL</strong> = old name. Versions 1, 2, 3 all dead. Don’t use.</li><li><strong>TLS</strong> = current name. TLS 1.2 and 1.3 are what we use.</li><li><strong>HTTPS</strong> = HTTP + TLS. Just plain HTTP wrapped in an encrypted tunnel.</li></ul><p>People still say “SSL certificate” out of habit. It’s TLS underneath.</p><h3>Two Kinds of Encryption</h3><h3>Symmetric Encryption</h3><p><strong>One key. Same key locks and unlocks.</strong></p><p>Like a regular padlock — same key opens and closes it.</p><ul><li>✅ Very fast (gigabytes per second)</li><li>❌ Problem: How do both parties share the key safely over an insecure network?</li></ul><h3>Asymmetric Encryption (Public Key Crypto)</h3><p><strong>Two keys that work together: public + private.</strong></p><ul><li>Anything encrypted with the public key can ONLY be decrypted by the private key</li><li>Anything signed with the private key can be verified by the public key</li></ul><p><strong>Analogy:</strong> A public key is like an open padlock you hand out to everyone. People put things in a box and click your padlock shut. Only you (with the private key) can open it.</p><ul><li>❌ Slow (orders of magnitude slower than symmetric)</li><li>✅ Solves the key-sharing problem (you can publish your public key openly)</li></ul><h3>The TLS Magic Trick</h3><p>TLS uses both:</p><ol><li><strong>Asymmetric</strong> to securely agree on a shared secret (slow but secure, done once)</li><li><strong>Symmetric</strong> to encrypt all the actual data (fast, used for the whole conversation)</li></ol><p>Best of both worlds.</p><h3>The TLS Handshake (Simplified)</h3><p>After the TCP handshake but before any HTTP, this happens:</p><h3>Step 1: Client Hello</h3><p>Browser says:</p><ul><li>“I support TLS 1.3”</li><li>“Here are the encryption algorithms I know”</li><li>“Here’s a random number”</li><li>“Here’s my temporary public key for this session”</li><li>“I want to connect to google.com&quot; (this is called <strong>SNI</strong> — same IP can host many sites)</li></ul><h3>Step 2: Server Hello + Certificate</h3><p>Server says:</p><ul><li>“Cool, let’s use TLS 1.3 with [chosen algorithm]”</li><li>“Here’s my random number”</li><li>“Here’s my temporary public key”</li><li><strong>“Here’s my certificate”</strong> ← critical part</li><li>“Here’s a signature proving I own the private key for this certificate”</li></ul><h3>Step 3: Client Verifies</h3><p>Browser checks the certificate:</p><ul><li>Was it signed by a trusted CA?</li><li>Does the domain match?</li><li>Is it expired?</li><li>Has it been revoked?</li></ul><h3>Step 4: Encrypted Data Flows</h3><p>Both sides now have a shared symmetric key. They switch to symmetric encryption and the real HTTP request goes through, fully encrypted.</p><p><strong>TLS 1.3 does this in 1 round trip</strong> (1.2 took 2 — that’s why 1.3 was a big speed win).</p><h3>Certificates</h3><h4>What a Certificate Is</h4><p>A digital document that says:</p><blockquote><em>“The public key </em><em>abc123... belongs to </em><em>google.com, and I, a trusted authority, vouch for this.&quot;</em></blockquote><p>It contains:</p><ul><li>The domain(s) it’s valid for (e.g., google.com, *.google.com for wildcards)</li><li>The public key</li><li>Expiration date</li><li>Name of the <strong>Certificate Authority (CA)</strong> that issued it</li><li>The CA’s digital signature</li></ul><h3>Chain of Trust</h3><p>Certificates form a chain:</p><pre>Root CA (e.g., &quot;ISRG Root X1&quot;)<br>    ↓ signs<br>Intermediate CA (e.g., &quot;Let&#39;s Encrypt R3&quot;)<br>    ↓ signs<br>Server certificate (e.g., &quot;google.com&quot;)</pre><p><strong>Why the chain?</strong> Root CAs keep their private keys in offline vaults. They almost never sign certificates directly. They sign intermediates, which sign actual server certs. If an intermediate gets compromised, you can revoke it without nuking the root.</p><p>Your OS comes with ~150 trusted root CAs pre-installed. Browsers trust anything that chains back to one of those.</p><h3>What Your Browser Checks</h3><p>When the server sends its certificate:</p><ol><li>✅ Is it signed by a CA my OS trusts? (Chain leads to a trusted root)</li><li>✅ Does the domain match what I’m visiting?</li><li>✅ Is it not expired?</li><li>✅ Has it not been revoked?</li><li>✅ Does the server actually own the matching private key? (Proven by signature)</li></ol><p>All pass → 🔒 padlock. Any fail → big scary warning.</p><h3>Let’s Encrypt</h3><p>Before 2016: TLS certificates cost $50–$500/year. Process was manual, slow, painful. Most small sites just used HTTP.</p><p><strong>Let’s Encrypt</strong> (2016, nonprofit, backed by Mozilla, EFF, etc.):</p><ul><li>Free certificates</li><li>Automated via <strong>ACME</strong> protocol</li><li>90-day validity, auto-renewed</li><li>Tool certbot makes it a one-command setup</li></ul><p><strong>Result:</strong> HTTPS adoption jumped from ~30% in 2014 to 95%+ today. One of the great infrastructure projects of the modern web.</p><h3>How It Verifies You Own a Domain</h3><p><strong>HTTP-01 challenge:</strong> “Put this random string at http://yourdomain.com/.well-known/acme-challenge/&lt;token&gt;.&quot; If you can, you control the server.</p><p><strong>DNS-01 challenge:</strong> “Add this TXT record to your DNS.” Required for wildcard certificates (*.example.com).</p><h3>Things People Misunderstand About HTTPS</h3><h4>1. Encryption is for data IN TRANSIT only</h4><p>Once data arrives at the server, it’s decrypted. <strong>If the server logs your password to a file, the file is in plain text.</strong> HTTPS doesn’t protect against bad server practices.</p><h4>2. The padlock ≠ trustworthy site</h4><p>A phishing site g00gle-login.com can have a valid Let&#39;s Encrypt cert. The padlock means &quot;encrypted connection to whoever owns this domain.&quot; It does NOT mean &quot;this site is safe&quot; or &quot;this company is legit.&quot;</p><h4>3. What HTTPS hides vs. doesn’t hide</h4><p>Visible to network observer Hidden by HTTPS The domain you’re visiting (via SNI) The URL path The IP address Headers Approximate request sizes/timing Request body Response body</p><p>So HTTPS hides “what you did on Facebook” but not “that you went to Facebook.”</p><h4>4. Self-signed certificates</h4><p>You can make a certificate signed by yourself. Cryptographically valid but no browser trusts it (you’re not a known CA). Useful for local dev, internal services, learning.</p><h4>5. mTLS (Mutual TLS)</h4><p>Normal TLS: server proves identity, client is anonymous. <strong>mTLS:</strong> both sides have certificates. Used in microservices, banking APIs, zero-trust networks.</p><h3>HTTP — The Protocol</h3><h4>Core Idea</h4><p>HTTP is <strong>a text-based protocol where a client sends a request and the server sends back a response.</strong> Stateless — server doesn’t remember you between requests. Every request must carry whatever the server needs.</p><p>This statelessness is what lets the web scale infinitely — any server can handle any request.</p><h4>Anatomy of a Request and Response</h4><h4>A Request Looks Like This</h4><pre>GET /users/torvalds HTTP/1.1<br>Host: api.github.com<br>User-Agent: Mozilla/5.0<br>Accept: application/json</pre><p>Four parts:</p><ol><li><strong>Request line:</strong> METHOD path HTTP/version</li><li><strong>Headers:</strong> key-value pairs</li><li><strong>Blank line</strong> (separates headers from body — critical!)</li><li><strong>Body</strong> (empty for GET, has data for POST/PUT/PATCH)</li></ol><h3>A Response Looks Like This</h3><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Length: 1234</pre><pre>{&quot;login&quot;:&quot;torvalds&quot;,&quot;name&quot;:&quot;Linus Torvalds&quot;}</pre><p>Same four parts:</p><ol><li><strong>Status line:</strong> HTTP/version code message</li><li><strong>Headers</strong></li><li><strong>Blank line</strong></li><li><strong>Body</strong></li></ol><p><strong>That’s it.</strong> All of HTTP is variations on this.</p><p>HTTP Methods (Verbs)</p><h3>The Common Ones</h3><p>Method Purpose Safe? Idempotent? Has body? <strong>GET</strong> Read a resource Yes Yes No <strong>POST</strong> Create / submit / do something No No Yes <strong>PUT</strong> Replace a resource entirely No Yes Yes <strong>PATCH</strong> Update part of a resource No Should be Yes <strong>DELETE</strong> Remove a resource No Yes No <strong>HEAD</strong> Like GET but only headers Yes Yes No <strong>OPTIONS</strong> “What can I do here?” Yes Yes No</p><h4>PUT vs PATCH — The Confusion</h4><p>User currently is: {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}</p><p><strong>PUT</strong> with {&quot;name&quot;: &quot;Alice&quot;}:</p><ul><li>Result: {&quot;name&quot;: &quot;Alice&quot;} (age is gone — full replacement)</li></ul><p><strong>PATCH</strong> with {&quot;name&quot;: &quot;Alice&quot;}:</p><ul><li>Result: {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30} (only name updated)</li></ul><p><strong>Rule of thumb:</strong> PUT replaces, PATCH modifies.</p><p>Most APIs labeled “PUT” actually behave like PATCH. It’s technically wrong but very common.</p><p>Idempotency (Important!)</p><p><strong>Idempotent = doing it once or many times gives the same result.</strong></p><p>Operation Idempotent? Why GET /users/42 ✅ Yes Reading 5 times = same data DELETE /users/42 ✅ Yes Deleting an already-deleted user = still deleted PUT /users/42 {name: &quot;Alice&quot;} ✅ Yes Setting name 5 times = name is still Alice POST /users {name: &quot;Alice&quot;} ❌ No 5 POSTs = 5 new Alice users</p><h3>Why It Matters in Production</h3><p>Networks fail. A request times out — did the server get it or not?</p><ul><li>If idempotent: just retry safely</li><li>If not idempotent: need an <strong>idempotency key</strong> (unique ID the client sends, server deduplicates)</li></ul><p>Stripe famously uses idempotency keys for payment requests so a network hiccup doesn’t charge a customer twice.</p><h3>Status Codes</h3><h4>The Top-Level Grouping</h4><p>Range Meaning <strong>1xx</strong> Informational (rare) <strong>2xx</strong> Success <strong>3xx</strong> Redirection <strong>4xx</strong> Client error (your fault) <strong>5xx</strong> Server error (server’s fault)</p><p>Memorize this. When you see 502 in logs → server problem. When you see 404 → client problem.</p><h4>2xx — Success</h4><p>Code Name When to use <strong>200</strong> OK Generic success <strong>201</strong> Created POST succeeded and made a new resource (include Location header) <strong>204</strong> No Content Success but nothing to return (common for DELETE/PUT) <strong>206</strong> Partial Content Range requests (resumable downloads, video seeking)</p><h4>3xx — Redirects</h4><p>Code Name When to use <strong>301</strong> Moved Permanently This URL is gone forever. <strong>Cached aggressively — be careful!</strong> <strong>302</strong> Found / Temporary Use this other URL for now <strong>303</strong> See Other “POST succeeded, now GET this URL” — prevents form resubmission <strong>304</strong> Not Modified Your cached version is still good (used with ETag/If-None-Match) <strong>307</strong> Temporary Redirect Like 302 but preserves the HTTP method <strong>308</strong> Permanent Redirect Like 301 but preserves the method</p><p>⚠️ <strong>Don’t 301 by mistake</strong> — browsers cache it forever. Use 302/307 if unsure.</p><h4>4xx — Client Errors</h4><p>Code Name What it means <strong>400</strong> Bad Request Your request is malformed (bad JSON, missing field) <strong>401</strong> Unauthorized “Who are you?” — Auth missing/invalid. <strong>Fix: log in.</strong> <strong>403</strong> Forbidden “I know you, but no.” — Auth fine, no permission. <strong>Fix: ask admin.</strong> <strong>404</strong> Not Found Resource doesn’t exist <strong>405</strong> Method Not Allowed You used POST on a GET-only endpoint <strong>409</strong> Conflict Conflicts with current state (e.g., email already exists) <strong>410</strong> Gone Like 404 but explicitly permanent <strong>415</strong> Unsupported Media Type Sent XML when server wanted JSON <strong>422</strong> Unprocessable Entity Valid JSON, but invalid content (e.g., bad email format) <strong>429</strong> Too Many Requests Rate limited (check Retry-After header)</p><h4>401 vs 403 — Asked in Every Interview</h4><ul><li><strong>401 = “Who are you?”</strong> (Identity problem — log in)</li><li><strong>403 = “I know you, but no.”</strong> (Permission problem — ask admin)</li></ul><h4>5xx — Server Errors</h4><p>Code Name What it usually means <strong>500</strong> Internal Server Error Server crashed/threw exception — <strong>GO INVESTIGATE</strong> <strong>502</strong> Bad Gateway Reverse proxy (nginx) couldn’t reach your app — <strong>app is down or not listening</strong> <strong>503</strong> Service Unavailable Server overloaded / in maintenance <strong>504</strong> Gateway Timeout App is alive but too slow — <strong>probably slow DB query or external API</strong></p><h4>502 vs 504 — Senior Debugging Skill</h4><ul><li><strong>502</strong> = Your app is dead or not accepting connections</li><li><strong>504</strong> = Your app is alive but didn’t respond in time</li></ul><p>Different problems, different fixes.</p><h3>Headers — Where Most of HTTP Lives</h3><p>Methods and status codes get attention, but headers do most of the real work.</p><h4>Request Headers (Client → Server)</h4><p>Header Purpose Example Host Which domain you want Host: api.github.com User-Agent What browser/client Mozilla/5.0... Accept What content types you accept application/json Accept-Encoding Compression you support gzip, br Authorization Credentials Bearer eyJhbGc... (JWT) Cookie Stored cookies session=abc123 Content-Type What you&#39;re sending (for POST/PUT) application/json Content-Length Body size in bytes 1234 If-None-Match &quot;I have version with this ETag&quot; &quot;abc123&quot;</p><h4>Response Headers (Server → Client)</h4><p>Header Purpose Example Content-Type What&#39;s in the body application/json; charset=utf-8 Content-Length Body size 1234 Content-Encoding Compression used gzip Cache-Control How to cache public, max-age=3600 ETag Version identifier &quot;abc123&quot; Set-Cookie Tell browser to store a cookie session=xyz; HttpOnly Location Redirect target (with 3xx) /login Retry-After Wait before retrying (429/503) 60 (seconds)</p><h4>Security Headers (Important!)</h4><p>Header What it does Strict-Transport-Security (HSTS) &quot;Always use HTTPS for this domain&quot; Content-Security-Policy (CSP) Restricts what scripts/resources can load X-Frame-Options Prevents your site being put in iframes (anti-clickjacking) X-Content-Type-Options: nosniff Browser shouldn&#39;t guess MIME types</p><h3>Caching — Where Most Web Performance Comes From</h3><h4>Cache-Control Directives</h4><p>Directive Meaning public Anyone can cache (browser, CDN, proxy) private Only the browser, not shared proxies no-cache Cache it, but <strong>revalidate with server every time</strong> (counterintuitive name!) no-store Actually don&#39;t cache. For sensitive data. max-age=3600 Fresh for 3600 seconds s-maxage=3600 Like max-age but only for shared caches (CDNs) immutable This URL&#39;s content will never change. Don&#39;t ever revalidate.</p><h4>Conditional Requests — Saving Bandwidth</h4><p>Server sends a resource with an ETag (hash of content):</p><pre>ETag: &quot;abc123&quot;</pre><p>Next time, browser asks:</p><pre>GET /image.png<br>If-None-Match: &quot;abc123&quot;</pre><p>If unchanged, server replies <strong>304 Not Modified</strong> — empty body, no bandwidth wasted. Browser uses its cached copy.</p><h4>Classic Caching Pattern for JS/CSS</h4><p>Use <strong>content-hashed filenames</strong> like app.a3f2c8.js:</p><ul><li>Cache header: Cache-Control: public, max-age=31536000, immutable (1 year!)</li><li>When code changes, the filename changes (app.b9e1d4.js) → fresh fetch</li><li>No cache invalidation problems</li></ul><p>This is why Webpack/Vite output weird filenames — it’s a cache strategy.</p><p>&lt;a name=”cors”&gt;&lt;/a&gt;</p><h3>CORS — The Frontend Confusion</h3><h4>The Same-Origin Policy</h4><p>Browsers enforce a security rule: <strong>JavaScript on </strong><strong>https://example.com can&#39;t make requests to </strong><strong>https://api.different.com</strong> by default. This prevents a random site from calling your bank API using your cookies.</p><p><strong>Origin</strong> = (scheme, host, port). Different in any of these = different origin = blocked.</p><h4>How CORS Works</h4><p>The cross-origin server says “JS from these origins is allowed to call me.”</p><p>Browser sends:</p><pre>Origin: https://example.com</pre><p>Server replies:</p><pre>Access-Control-Allow-Origin: https://example.com</pre><p>If they match (or server sent * for &quot;anyone&quot;), browser lets your JS see the response. Otherwise, the request <strong>still happened</strong> — the browser just hides the response from your JS.</p><h4>Preflight Requests</h4><p>For “complex” requests (PUT, DELETE, custom headers, etc.), browser does a preflight:</p><ol><li>Browser sends OPTIONS /resource describing what it wants to do</li><li>Server replies with what’s allowed</li><li>If allowed, browser sends the real request</li><li>If not, dreaded CORS error in console</li></ol><h4>Critical Mental Model</h4><p><strong>CORS is enforced by the BROWSER, not the server.</strong></p><ul><li>curl ignores CORS entirely (no error)</li><li>The server just announces what’s allowed</li><li>The browser decides whether to hide the response from your JS</li></ul><p>This is why CORS errors are confusing — your request actually worked, but the browser is hiding the result.</p><h4>REST — What It Actually Means</h4><p>When people say “REST API,” they usually mean “JSON over HTTP with sensible URLs.” Real REST has specific principles.</p><h4>REST Principles</h4><ol><li><strong>Resources</strong> — everything has a URL (/users/42, /orders/123/items)</li><li><strong>Standard methods</strong> — use GET/POST/PUT/PATCH/DELETE properly</li><li><strong>Statelessness</strong> — no session state on server between requests</li><li><strong>Cacheability</strong> — responses indicate cacheability</li><li><strong>Uniform interface</strong> — same patterns across all resources</li></ol><h4>REST Design Conventions</h4><p>Do Don’t /users/42 (nouns) /getUser?id=42 (verbs) /users (plural) /user /users/42/orders (nested) /userOrders?userId=42 DELETE /users/42 POST /deleteUser Return 404 for not found Return 200 with {error: &quot;not found&quot;}</p><h4>When NOT to Use REST</h4><ul><li><strong>GraphQL</strong> — clients need flexible queries, fetching many resources in one call</li><li><strong>gRPC</strong> — service-to-service where performance matters more than human readability</li><li><strong>WebSockets</strong> — real-time bidirectional communication (chat, live updates)</li></ul><h4>Quick Reference Cheat Sheets</h4><h4>Methods Cheat Sheet</h4><pre>GET    → Read           (safe, idempotent, no body)<br>POST   → Create/action  (not idempotent, has body)<br>PUT    → Replace        (idempotent, full resource in body)<br>PATCH  → Partial update (idempotent if done right, partial body)<br>DELETE → Remove         (idempotent, no body)<br>HEAD   → GET but headers only<br>OPTIONS→ &quot;What can I do here?&quot; (CORS preflight)</pre><h4>Status Code Cheat Sheet</h4><pre>2xx Success<br>  200 OK<br>  201 Created<br>  204 No Content</pre><pre>3xx Redirect<br>  301 Permanent (CAREFUL - cached forever)<br>  302 Temporary<br>  304 Not Modified (cache validation)</pre><pre>4xx Client Error<br>  400 Bad Request      — malformed<br>  401 Unauthorized     — who are you?<br>  403 Forbidden        — I know you, but no<br>  404 Not Found        — doesn&#39;t exist<br>  409 Conflict         — already exists / state conflict<br>  422 Unprocessable    — semantically invalid<br>  429 Too Many         — rate limited</pre><pre>5xx Server Error<br>  500 Internal         — server crashed<br>  502 Bad Gateway      — app is down<br>  503 Unavailable      — overloaded<br>  504 Gateway Timeout  — app is slow</pre><h3>The Full Journey of an HTTP Request</h3><pre>1. Parse URL<br>        ↓<br>2. DNS lookup (cached at multiple levels)<br>        ↓<br>3. TCP 3-way handshake (SYN → SYN-ACK → ACK)<br>        ↓<br>4. TLS handshake (if HTTPS)<br>   - Client hello + key share<br>   - Server hello + certificate + key share<br>   - Verify cert (chain, domain, expiry)<br>   - Both sides derive shared symmetric key<br>        ↓<br>5. HTTP request sent (encrypted)<br>        ↓<br>6. Server processes and responds<br>        ↓<br>7. Browser renders</pre><h3>Useful Commands to Remember</h3><h4>DNS</h4><pre>dig google.com                    # Look up A record<br>dig google.com MX                 # Mail servers<br>dig +trace google.com             # Watch the full resolution chain<br>nslookup google.com               # Older alternative to dig</pre><h4>HTTP Inspection</h4><pre>curl -v https://example.com                       # Verbose, see all bytes<br>curl -I https://example.com                       # HEAD request only<br>curl -i https://example.com                       # Show response headers<br>curl -X POST https://api.example.com/users \      # POST with JSON<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;name&quot;: &quot;Alice&quot;}&#39;<br>curl -H &quot;Authorization: Bearer TOKEN&quot; ...         # With auth</pre><h4>Testing Status Codes</h4><pre>curl -i https://httpbin.org/status/404            # Returns 404<br>curl -i https://httpbin.org/status/500            # Returns 500<br>curl https://httpbin.org/headers                  # See what you&#39;re sending<br>curl https://httpbin.org/ip                       # See your public IP</pre><h4>TLS / Certificates</h4><pre>openssl s_client -connect google.com:443 -showcerts &lt; /dev/null<br># See certificate chain</pre><pre>openssl s_client -connect google.com:443 -servername google.com &lt; /dev/null<br># Use SNI explicitly</pre><h4>Network Debugging</h4><pre>sudo tcpdump -i any -n &#39;host google.com and port 443&#39;   # Watch traffic<br>ss -tulpn                                               # See listening ports<br>ss -t state established                                 # See open TCP connections<br>lsof -i :3000                                           # What&#39;s on port 3000</pre><h4>Practice Sites</h4><ul><li><strong>httpbin.org</strong> — returns whatever HTTP responses you ask for</li><li><strong>badssl.com</strong> — test pages with broken/expired/wrong certs</li><li><strong>example.com</strong> — minimal real site for testing</li></ul><h3>Final Mental Models to Carry With You</h3><ol><li><strong>DNS = distributed cached phonebook</strong> mapping names to IPs.</li><li><strong>TCP = reliable pipe</strong> built on top of unreliable internet.</li><li><strong>TLS = encrypted, authenticated tunnel</strong> added on top of TCP. Uses asymmetric crypto to exchange a symmetric key.</li><li><strong>Certificate = “This public key belongs to this domain, signed by a trusted CA.”</strong></li><li><strong>HTTP = text-based stateless request/response</strong> flowing through the pipe.</li><li><strong>Idempotent operations can be safely retried.</strong> Non-idempotent ones need idempotency keys.</li><li><strong>Status codes group by first digit:</strong> 2 good, 3 redirect, 4 your fault, 5 server’s fault.</li><li><strong>CORS is browser-enforced, not server-enforced.</strong> The server just announces what’s allowed.</li><li><strong>Caching saves the web.</strong> Use ETags, Cache-Control, and content-hashed filenames.</li><li><strong>HTTPS hides content, not metadata.</strong> Domain is still visible.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330e94b7c9a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Node.js Event Loop — How Does It Actually Work?]]></title>
            <link>https://medium.com/@cappiing/the-node-js-event-loop-how-does-it-actually-work-5c1b8a30dbb1?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1b8a30dbb1</guid>
            <category><![CDATA[os]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 19:47:38 GMT</pubDate>
            <atom:updated>2026-03-15T19:47:38.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*EFUFs3yE_qHhJyshkIcxRg.png" /></figure><p>So you’ve been writing Node.js code right? Maybe an Express server, some API calls, reading files and all that. But have you ever wondered how Node.js handles so many things at once when JavaScript is literally single threaded? Like one thread, one lane road — how is it managing thousands of requests?</p><p>That’s the event loop. And trust me once you understand this, a LOT of things about Node.js will start making sense.</p><p><strong>What Even is the Event Loop?</strong></p><p>Event loop is the reason that allows Node.js to perform non-blocking I/O operations even though JS is a single thread by default. It does this by offloading operations to the system kernel depending on the need.</p><p>Two words I need to explain first before going further — <strong>Kernel</strong> and <strong>Poll Queue</strong>.</p><p><strong>What is Kernel?</strong></p><p>Kernel is the central and most critical part of the OS — it’s the bridge between your hardware (CPU, RAM, Disk) and software applications.</p><p>Think of it as the <strong>manager in a restaurant</strong>: it takes orders from customers (apps), decides which chef (CPU core) handles which order, makes sure apps don’t crash each other, and reports back with results. Without the kernel, nothing coordinates absolute chaos.</p><p>Nowadays modern kernels are multi-threaded, so they can handle multiple operations in the background. When one completes, the kernel tells Node.js so the appropriate callback can be queued up.</p><p><strong>What is Poll Queue?</strong></p><p>The poll queue is where <strong>completed I/O callbacks</strong> wait to be executed file reads that finished, network responses that arrived, DNS lookups that resolved.</p><p>But here’s the thing that makes this queue special: when the poll queue is <strong>empty</strong>, the event loop doesn’t just move on. It <strong>parks itself and waits</strong> for new I/O events to arrive (unless there’s a `setImmediate` or an expired timer pulling it away). It’s the event loop’s “home base” where it spends most of its idle time.</p><p>Think of it like a restaurant manager who, after serving all orders, stands at the door waiting for the next customer to walk in instead of pointlessly running laps around the kitchen.</p><p>The Big Picture — What Happens When You Run Node?</p><p>When you type `node app.js` in your terminal, here’s the flow:</p><pre>┌─────────────────────────────────────────────┐<br>│              node app.js                     │<br>└──────────────────┬──────────────────────────┘<br>                   ▼<br>┌─────────────────────────────────────────────┐<br>│  1. INITIALIZE                               │<br>│     V8 engine starts, libuv loads            │<br>└──────────────────┬──────────────────────────┘<br>                   ▼<br>┌─────────────────────────────────────────────┐<br>│  2. EXECUTE TOP-LEVEL CODE                   │<br>│     require(), console.log(), variables,     │<br>│     function calls — all sync, line by line  │<br>│                                              │<br>│     Async calls (setTimeout, fs.readFile)    │<br>│     → callbacks GET REGISTERED, not executed │<br>└──────────────────┬──────────────────────────┘<br>                   ▼<br>┌─────────────────────────────────────────────┐<br>│  3. ENTER EVENT LOOP                         │<br>│  ┌─────────────────────────────────────┐    │<br>│  │  Phase 1: Timers (setTimeout)       │    │<br>│  │       ↓  [nextTick + microtasks]    │    │<br>│  │  Phase 2: Pending Callbacks         │    │<br>│  │       ↓  [nextTick + microtasks]    │    │<br>│  │  Phase 3: Idle / Prepare            │    │<br>│  │       ↓  [nextTick + microtasks]    │    │<br>│  │  Phase 4: Poll (I/O callbacks)      │◄───┤<br>│  │       ↓  [nextTick + microtasks]    │    │<br>│  │  Phase 5: Check (setImmediate)      │    │<br>│  │       ↓  [nextTick + microtasks]    │    │<br>│  │  Phase 6: Close Callbacks           │    │<br>│  │       ↓                             │    │<br>│  │  ┌──────────────────────┐           │    │<br>│  │  │ More work to do?     │──── YES ──┘    │<br>│  │  └──────┬───────────────┘                │<br>│  │         NO                               │<br>│  └─────────┼───────────────────────────┘    │<br>└────────────┼────────────────────────────────┘<br>             ▼<br>┌─────────────────────────────────────────────┐<br>│  4. EXIT PROCESS                             │<br>└─────────────────────────────────────────────┘</pre><p>Let me break each part down.</p><p><strong>1. Top Level Code Runs First</strong></p><p>This is the synchronous JS code you’ve written. Plain simple stuff:</p><pre>console.log(&quot;server starting…&quot;);<br>const port = 3000;<br>function add(a, b) {<br>return a + b;<br>}<br>if (port === 3000) {<br>console.log(&quot;running on default port&quot;);<br>}</pre><p>All of this runs first. No event loop involved yet. It’s like when you arrive at the restaurant — you sit down, read the menu, decide what you want. You haven’t ordered yet.</p><p><strong>2. Async Code Gets Registered</strong></p><p>Then Node encounters the async stuff — file reads, setTimeout, API calls, database queries. It doesn’t execute them right away. It registers their callbacks and says “I’ll get back to you.”</p><pre>setTimeout(() =&gt; {<br>console.log(&quot;timer done&quot;);<br>}, 1000);<br>fs.readFile(&quot;data.txt&quot;, (err, data) =&gt; {<br>console.log(&quot;file read complete&quot;);<br>});<br>console.log(&quot;this runs first!&quot;);</pre><p><strong>3. Event Loop Starts</strong></p><p>Now the actual event loop kicks in. And this is where it gets interesting.</p><p><strong>The 6 Phases of the Event Loop</strong></p><p>The event loop is not just one big queue. It has <strong>6 phases</strong> and it goes through them one by one in order, like a circular track.</p><p><strong>But First — The Two Queue Jumpers</strong></p><p>Before I explain the phases, there are two special queues that run <strong>BETWEEN every single phase </strong>(and actually, after each individual callback within a phase too):</p><p>1. <strong>process.nextTick() queue </strong>highest priority, drains completely first</p><p>2. <strong>Microtask queue (Promises) </strong>drains after nextTick queue is empty</p><p>These are like VIP customers at the restaurant. After every single dish is served to any table, the manager checks “any VIP orders? serve them first before moving to next table.” Not just between courses — between every single plate.</p><pre>setTimeout(() =&gt; console.log(&quot;1. setTimeout&quot;), 0);<br>Promise.resolve().then(() =&gt; console.log(&quot;2. promise&quot;));<br>process.nextTick(() =&gt; console.log(&quot;3. nextTick&quot;));<br>console.log(&quot;4. sync code&quot;);</pre><p>See that? Sync runs first. Then nextTick jumps the queue. Then promise jumps the queue. Then finally setTimeout gets its turn. nextTick and promises are basically cutting in line every single time.</p><p>Now the actual phases:</p><p><strong>Phase 1: Timers</strong></p><p>This is where `setTimeout` and `setInterval` callbacks get executed.</p><pre>setTimeout(() =&gt; {<br>console.log(&quot;500ms timer done&quot;);<br>}, 500);<br>setTimeout(() =&gt; {<br>console.log(&quot;1000ms timer done&quot;);<br>}, 1000);</pre><p>Important thing — the timer doesn’t guarantee exact timing. It guarantees <strong>minimum</strong> time. If the event loop is busy doing something else, your 500ms callback might run at 510ms or even later. It’s like saying “pizza will be ready in 30 mins” it could be 30, could be 35, but definitely not before 30.</p><p>One crucial detail: <strong>setTimeout(fn, 0) is internally clamped to setTimeout(fn, 1)</strong>. The minimum delay is 1ms, not 0ms. This tiny detail is exactly why <em>setTimeout(fn, 0) vs setImmediate()</em> is non-deterministic at the top level it’s a race against whether 1ms has elapsed by the time the event loop reaches Phase 1. Sometimes it has (setTimeout wins), sometimes it hasn’t (setImmediate wins via Phase 5). More on this later.</p><p><strong>Phase 2: Pending Callbacks (Deferred Callbacks)</strong></p><p>These are callbacks from system operations that got deferred. Like some TCP errors, certain I/O callbacks that didn’t get handled in the previous loop iteration.</p><pre>const net = require(&quot;net&quot;);<br>const server = net.createServer((socket) =&gt; {<br>// connection callback might end up here<br>// if it was deferred from previous cycle<br>});</pre><p>You won’t interact with this phase directly most of the time. It’s internal plumbing. Think of it as the manager handling complaints from previous shift.</p><p><strong>Phase 3: Idle/Prepare (Internal)</strong></p><p>This is purely internal to Node.js. You can’t hook into this phase. Node does its own housekeeping here. Like the manager doing inventory between serving customers — you don’t see it happening but it needs to happen.</p><p><strong>Phase 4: Poll</strong></p><p>This is the <strong>most important phase</strong>. This is where the magic happens.</p><p>The poll phase does two things:</p><p>1. <strong>Calculates how long it should block and wait for I/O</strong></p><p>2. <strong>Processes events in the poll queue</strong></p><pre>const fs = require(&quot;fs&quot;);<br>fs.readFile(&quot;bigfile.txt&quot;, (err, data) =&gt; {<br>console.log(&quot;file read done!&quot;);<br>// this callback executes in the Poll phase<br>});<br>const https = require(&quot;https&quot;);<br>https.get(&quot;https://api.example.com/data&quot;, (res) =&gt; {<br>console.log(&quot;API response received!&quot;);<br>// this also executes in Poll phase<br>});</pre><p>Most of your I/O callbacks file reading, network requests, database queriesthey all land here.</p><p>Now here’s the interesting part. If there is no timeout callback, no immediate callback, and there are no callbacks waiting the poll phase just <strong>parks itself and waits</strong>. It’s like the manager saying “no orders? cool, I’ll just stand here and wait for someone to walk in.”</p><p>But if a setImmediate() is scheduled, it moves to the next phase. If timers are due, it loops back to phase 1.</p><p><strong>Phase 5: Check</strong></p><p>This is where <strong>setImmediate()</strong> callbacks execute.</p><pre>setImmediate(() =&gt; {<br>console.log(&quot;setImmediate runs here&quot;);<br>});</pre><p>Now you might ask — what’s the difference between `setTimeout(() =&gt; {}, 0)` and `setImmediate()`? Great question. Inside an I/O cycle, `setImmediate` always runs before `setTimeout`:</p><pre>const fs = require(&quot;fs&quot;);<br>fs.readFile(&quot;file.txt&quot;, () =&gt; {<br>setTimeout(() =&gt; {<br>console.log(&quot;timeout&quot;);<br>}, 0);<br>setImmediate(() =&gt; {<br>console.log(&quot;immediate&quot;);<br>});<br>});</pre><p>Because after the poll phase (where the file read callback ran), it moves to the check phase (setImmediate) before looping back to timers (setTimeout).</p><p>But outside an I/O cycle? The order is non-deterministic. Could be either one first. It’s like two people arriving at the restaurant door at the exact same time who goes in first? Depends on the day.</p><p><strong>Phase 6: Close Callbacks</strong></p><p>This is where close event callbacks go. Like socket.on(‘close’, …).</p><pre>const net = require(&quot;net&quot;);<br>const server = net.createServer((socket) =&gt; {<br>socket.on(&quot;close&quot;, () =&gt; {<br>console.log(&quot;socket closed!&quot;);<br>// this runs in Phase 6<br>});<br>});</pre><p>It’s the cleanup phase. Restaurant is closing, make sure all tabs are settled, chairs are up on tables.</p><p>Putting It All Together One Big Example</p><pre>const fs = require(&quot;fs&quot;);<br>console.log(&quot;1. sync - top level&quot;);<br>process.nextTick(() =&gt; console.log(&quot;2. nextTick&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;3. promise&quot;));<br>setTimeout(() =&gt; {<br>console.log(&quot;4. setTimeout&quot;);<br>process.nextTick(() =&gt; console.log(&quot;5. nextTick inside timeout&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;6. promise inside timeout&quot;));<br>}, 0);<br>setImmediate(() =&gt; {<br>console.log(&quot;7. setImmediate&quot;);<br>});<br>fs.readFile(__filename, () =&gt; {<br>console.log(&quot;8. file read done&quot;);<br>setTimeout(() =&gt; {<br>console.log(&quot;9. timeout inside file read&quot;);<br>}, 0);<br>setImmediate(() =&gt; {<br>console.log(&quot;10. immediate inside file read&quot;);<br>});<br>process.nextTick(() =&gt; console.log(&quot;11. nextTick inside file read&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;12. promise inside file read&quot;));<br>});<br>console.log(&quot;13. sync - bottom level&quot;);</pre><p><strong>Why most likely and not guaranteed? </strong>Remember, setTimeout(fn, 0) is clamped to 1ms. At the top level, whether the timer has expired by the time Phase 1 runs depends on system load. So <strong>4 and 7 can swap </strong>that’s the non-deterministic behavior we talked about earlier. Everything else is deterministic.</p><p><strong>The nextTick Trap — Starvation</strong></p><p>Remember how I said nextTick and microtasks drain completely between every phase? That’s powerful, but it’s also dangerous:</p><pre>let count = 0;<br>function run() {<br>count++;<br>console.log(&quot;nextTick count:&quot;, count);<br>process.nextTick(run); // adds itself back to the queue<br>}<br>run();<br>setTimeout(() =&gt; console.log(&quot;will this ever print?&quot;), 0);<br>setImmediate(() =&gt; console.log(&quot;what about this?&quot;));</pre><p>The setTimeout and setImmediate <strong>never fire</strong>. Ever.</p><p>Why? Because process.nextTick(run) adds run back to the nextTick queue every time it completes. The queue never empties. And since queue jumpers drain completely before any phase starts, the event loop is permanently stuck it can never enter Phase 1 or Phase 5. Your CPU goes to 100% and the process is frozen.</p><p>This is called <strong>I/O starvation</strong>. The fix is simple use setImmediate(run) instead. With setImmediate, each call goes through Phase 5 (Check), so the event loop cycles through all phases normally. No starvation.</p><p><strong>Rule of thumb:</strong> Never use recursive process.nextTick(). If you need to repeat something async, use setImmediate().</p><p><strong>Why Does process.nextTick Even Exist?</strong></p><p>If nextTick can cause starvation and is tricky to reason about, why was it created? There’s a very specific engineering problem it solves.</p><p>Look at this code:</p><pre>const net = require(&quot;net&quot;);<br>const server = net.createServer(() =&gt; {});<br>server.listen(8080);<br>server.on(&quot;listening&quot;, () =&gt; {<br>console.log(&quot;Server is ready&quot;);<br>});</pre><p>This works. Server is ready prints. But how? Line 5 (server.listen) binds the port. Line 7 (server.on) registers the handler. If the port binding was instant and the listening event fired synchronously on line 5, line 7 wouldn’t exist yet the event fires before the handler is registered. Lost forever.</p><p>Here’s what Node.js does internally (simplified):</p><pre>Server.prototype.listen = function (port) {<br>bindToPort(port);<br>process.nextTick(() =&gt; {<br>this.emit(&quot;listening&quot;); // fires AFTER all sync code finishes<br>});<br>};</pre><p>emit = <strong>trigger</strong> the event (call all registered handlers).</p><p>on = <strong>subscribe</strong> to the event (register a handler).</p><p>By wrapping `emit` in process.nextTick, Node guarantees the event fires <strong>after</strong> the current synchronous code finishes which means after server.on(‘listening’, cb) on line 7 has run and registered the handler. The handler is ready when the event fires.</p><p><strong>This is the primary reason nextTick exists:</strong> let library/framework authors defer events until the user’s synchronous setup code is complete. You’ll rarely need it in application code.</p><p><strong>ESM vs CJS: It Actually Matters Here-</strong></p><p>All the examples in this blog use CommonJS (`require`). If you switch to ES Modules (`import`), the queue jumper ordering can change:</p><pre>// CJS - process.nextTick always before Promise.then ✓<br>const fs = require(&quot;fs&quot;);<br>// ESM - Promise.then might run BEFORE process.nextTick<br>import fs from &quot;fs&quot;;</pre><p>Why? ES Modules load asynchronously the module evaluation itself runs inside a promise chain. This changes the microtask scheduling context, and Promise.then callbacks can end up running before process.nextTick callbacks.</p><p>If you’re using ESM (which is becoming the standard), keep this in mind:</p><p>- The 6-phase model is the same</p><p>- The timer/I/O/check behavior is the same</p><p>- But the nextTick-vs-Promise priority can flip</p><p>This is actually one of the reasons the Node.js docs recommend `setImmediate()` over `process.nextTick()` — fewer surprises across module systems.</p><p><strong>Why Should You Even Care?</strong></p><p>Because debugging async issues without understanding the event loop is like fixing a car engine without knowing how engines work. You’ll just keep randomly changing things hoping something works.</p><p>Once you get this, you’ll understand why your code runs in a certain order, why some callbacks fire before others, and why sometimes things don’t behave the way you expected.</p><p><em>Now go write some nested setTimeout, setImmediate, nextTick combos and predict the output before running. That’s the best way to learn this. Trust me.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1b8a30dbb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Your Own JavaScript Polyfills: A Deep Dive into Array.prototype.map]]></title>
            <link>https://medium.com/@cappiing/writing-your-own-javascript-polyfills-a-deep-dive-into-array-prototype-map-b7d79dcb0bc0?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d79dcb0bc0</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[polyfill-in-javascript]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 18:47:41 GMT</pubDate>
            <atom:updated>2026-03-12T13:16:27.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K42JidyGRxoOu4nxVcdPFg.png" /></figure><p>So you’ve been using map, filter, reduce and all those fancy array methods right? But have you ever thought about what’s happening behind the scenes? That’s exactly what polyfills are about.</p><p><strong>What Even Are Polyfills?</strong></p><p>It’s basically reimplementing something that already exists natively in JavaScript. Like Map, filter and reduce and other features also.</p><p>Think of it like this, you go to a restaurant, you love their butter chicken, and now you wanna recreate it at home. You know how it tastes, you know the ingredients, you just gotta figure out the recipe.</p><p>That’s polyfills.</p><p>Why would you do this? Because once you cook it yourself, you actually understand what goes into it. Same with JavaScript, once you write your own map, you’ll never forget how it works.</p><p><strong>First Let’s Understand How Map Actually Works</strong></p><p>Starting with the straightforward method which is map. We know right, map works on array:</p><pre>[10, 20, 30, 40].map((value, index, arr) =&gt; {<br>// do something<br>});</pre><p>This way you call a map which returns a new array after operation completes. The callback gets three arguments — value, index, and the array itself. The last two values are optional, most of the time you’ll just use value.</p><p><strong>Alright Now Let’s Build Our Own</strong></p><p>Now to create your own polyfills you need to call the prototype, dot your polyfills name and implement it. Here I would be reimplementing the array methods provided by JS.</p><p>To build it you need to know what to pass:</p><p>• have to pass the callback function</p><p>• and optional thisArgs</p><p><strong>Wait What is thisArgs?</strong></p><p>I will talk about this later in detail but in simple words — it gives your method context/scope to get the correct access. It’s like giving someone your house keys so they can get inside. Without keys (context) they’re just standing outside the door doing nothing.</p><p>thisArgs is optional, it was more practiced before arrow functions. After arrow function we do not have to declare it manually most of the times.</p><p><strong>The Actual Code</strong></p><p>Now to create your own polyfills you have all the required details:</p><pre>Array.prototype.myMap = function (callbackFn, thisArgs) {<br>const result = [];<br>for (let i = 0; i &lt; this.length; i++) {<br><br>  result.push(callbackFn.call(thisArgs, this[i], i, this));<br><br>}<br>return result;<br>};</pre><p>Okay okay I know there’s a lot going on. Let me break it down piece by piece.</p><p><strong>Why We Declared an Empty Array First?</strong></p><p>In map we return new array right? So that’s why we have declared empty array first. Map never touches the original array it’s like photocopying a document and writing on the copy. Original stays safe.</p><p><strong>What is </strong>`this`<strong> Here? Which </strong>`this`<strong> Are We Calling?</strong></p><p>Is it window or undifined?</p><p>Here’s the thing `this` is determined by what’s before the dot when you call it.</p><pre>collectionOfArray.myMap(…).    // this === collectionOfArray<br><br>// Map example written above right?<br><br>arr.myMap(…)</pre><p>so `this` is reference of that array. Whatever is before the dot, that’s your `this`. Simple as that.</p><p><strong>Now The Most Important Part — Why </strong>`.call()`<strong>?</strong></p><p>Now the most important and confusing part. If you don’t know about detached functions give a read to it. Still let me share one example for it.</p><pre>function myFn() {<br>// some logic<br>}<br>const callingFn = myFn;</pre><p>Now `callingFn` has reference not the function itself. It is holding a reference. It’s like writing down someone’s phone number vs actually calling them — just having the number doesn’t mean you’ve talked to them.</p><pre>callingFn // this won&#39;t work, it&#39;s just sitting there<br>callingFn() // this would work!</pre><p>Now coming back to our logic part. We know callbackFn is a function which user will pass but to attach a reference you need to manually bind it. So `.call()` helps you here.</p><p>In plain english it looks like this:</p><p>user_fn(optional thisArgs, value, index, array)</p><p>That’s it. We’re just saying — hey function, here’s your context, and here are the three things you need to know about: the value, where it is, and the whole array.</p><p><strong>Full Working Example Let’s See It In Action</strong></p><pre>Array.prototype.myMap = function (callbackFn, thisArgs) {<br>const result = [];<br><br>for (let index = 0; index &lt; this.length; index++) {<br><br>  result.push(callbackFn.call(thisArgs, this[index], index, this));<br><br>}<br>return result;<br>};<br><br>const collectionOfArray = [10, 20, 30, 40];<br>const newTransformedArray = collectionOfArray.myMap((val) =&gt; val * 2);<br>console.log(newTransformedArray);<br><br>// Output: [20, 40, 60, 80]</pre><p>Boom. Works exactly like the native map. We just built our own.</p><p><strong>What’s Next?</strong></p><p>Now try implementing other Array methods. Go for `filter`, `reduce`, `forEach`, `find` the logic is very similar once you understand the pattern. It’s like learning to drive one car, after that every car feels kinda the same steering, pedals, gears just slightly different flavors.</p><p>Trust me once you start writing polyfills, JavaScript stops being magic and starts making actual sense.</p><p>Now go break some code and rebuild it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d79dcb0bc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises and World Peace (mostly Promises)]]></title>
            <link>https://medium.com/@cappiing/promises-and-world-peace-mostly-promises-ad3722e1a07d?source=rss-d91de3d40fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad3722e1a07d</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aman]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 20:35:34 GMT</pubDate>
            <atom:updated>2026-03-11T07:02:31.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5i4GvfcB8ruFPMsvPjn0g.png" /></figure><p>Look, I was trying to write a blog on Promises and halfway through I realized this whole thing sounds like a UN meeting. So here we are.</p><p><strong>Promise.all — The UN Resolution</strong></p><p>You know how UN passes a resolution? Every permanent member gotta say yes. One country says “nah I don’t feel like it” and the whole thing is dead. That’s Promise.all.</p><pre>Promise.all([usa, russia, china, uk, france]) <br>        .then(peace =&gt; console.log(&quot;wow that actually worked&quot;)) <br>        .catch(veto =&gt; console.log(&quot;see you next year&quot;))</pre><p>It waits for ALL promises to resolve. But if even one rejects, the whole thing fails. Just like that one country who vetoes everything because they had a upset stomach.</p><blockquote>I <em>promise</em> I’ll start going to the gym tomorrow.</blockquote><blockquote>The difference between your promises and JavaScript promises is simple: JavaScript promises either resolve or reject; yours just stay pending forever.</blockquote><p>The thing is, Promise.all is optimistic by design. It assumes everyone gonna cooperate. Which is cute. Almost naive. Like planning a trip to Goa and expecting everyone to show up.</p><p><strong>Promise.race — The Arms Race</strong></p><p>This one is exactly what it sounds like. You shoot multiple promises and whoever reaches first wins. The rest? Nobody cares about the rest. They could still be running, they could have failed, doesn’t matter. First one across the line takes it.</p><pre>Promise.race([applyForJobs, finishProject, ragebaitTweet]) <br>        .then(result =&gt; console.log(result)) // its always the ragebaitweet</pre><blockquote>Imagine the entire <em>Fast &amp; Furious</em> cast sprinting as their lives depend on it. And what’s at the finish line? Not a trophy, not a medal, just one more chance for Dom to say, ‘It’s all about family.’</blockquote><p>This is basically the cold war. Two superpowers doing their thing and the world just sitting there watching who moves first. The scary part is, it doesn’t care if the first result is good or bad. It just returns whatever came first. Which honestly explains a lot about geopolitics.</p><p><strong>Promise.allSettled — The Swiss Approach</strong></p><p>Now this is the mature one. Promise.allSettled doesn’t care if promises resolve or reject. It just waits for everyone to finish and gives you a nice report card. No drama, no short circuits, just facts.</p><pre>Promise.allSettled([trade_deal, climate_pact, border_dispute])   <br>       .then(results =&gt; results.forEach(r =&gt; console.log(r.status))) <br>// &quot;fulfilled&quot;, &quot;rejected&quot;, &quot;fulfilled&quot; — noted, moving on</pre><p>This is Switzerland at every world conflict. They just sitting there with a clipboard like “interesting, interesting, noted.” No judgement, no picking sides. Just collecting data and making chocolate.</p><blockquote><em>Not Funny: </em>Switzerland is the slow‑cooked, scenic version of `Promise.allSettled` everything ends up resolved or rejected, but no one raises their voice.</blockquote><p>You use this when you want to know what happened with everything, even the stuff that went wrong. Like a post-war analysis but without the war part. Very civilized (Sab kuch Shanti Purvak ho Gya h).</p><p><strong>Promise.any — The Oil Strategy</strong></p><p>Promise.any is the opposite energy of Promise.all. You don’t need everyone to succeed. You just need ONE. Any one. Please. Just give me one win.</p><pre>Promise.any([saudi, venezuela, norway, texas]) <br>        .then(oil =&gt; console.log(&quot;we eating tonight&quot;)) <br>        .catch(() =&gt; console.log(&quot;back to bicycles&quot;))</pre><p>It only rejects if ALL of them fail. Which is called an AggregateError and honestly that name alone sounds like something you’d hear in a economics summit that nobody wanted to attend.</p><blockquote>It’s like I proposed to 10 girls in class hoping at least one would say yes 😭. By the way, I told all of them the same thing: <em>“I only love you.”</em></blockquote><p>This is basically every country’s energy strategy. You diversify your suppliers because you know at least someone is gonna come through. And if nobody does? Well that error message is going to be very long and very sad.</p><p><strong>Quick Cheat Sheet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHDMPGsBoBVljnZOAJUhDQ.png" /></figure><p>Notes:</p><ul><li>Pick Promise.all when you need all results.</li><li>use Promise.race when first response is enough but beware of rejecting winners</li><li>for forgiving waits use allSettled</li><li>for first successful result use Promise.any</li></ul><p><strong>The Real Lesson</strong></p><p>Promises in JavaScript are basically international relations but with better error handling. In real geopolitics when something fails you get a 3 hour press conference. In JavaScript you get a .catch() block. Honestly the catch block is more useful.</p><p>Also if you think about it, async/await is just promises wearing a suit pretending to be synchronous. Which is basically every diplomat at the G7. Acting calm on the outside, absolute chaos internally.</p><p>Anyway thats promises. Try it out by yourself. Or don’t. I’m a blog post not your manager.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad3722e1a07d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>