<?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 Rohit Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rohit Kumar on Medium]]></description>
        <link>https://medium.com/@stenzr?source=rss-75b52dbfae85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RGQqc2mwK1PLYXjC.jpg</url>
            <title>Stories by Rohit Kumar on Medium</title>
            <link>https://medium.com/@stenzr?source=rss-75b52dbfae85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:29:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stenzr/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[Context Engineering vs Memory Engineering: Building Agents That Don’t Forget What Matters]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://stenzr.medium.com/context-engineering-vs-memory-engineering-building-agents-that-dont-forget-what-matters-0c339a36842e?source=rss-75b52dbfae85------2"><img src="https://cdn-images-1.medium.com/max/1536/1*Vi16z-9_zZ8tBg9VeKK4OA.png" width="1536"></a></p><p class="medium-feed-snippet">Read this blog for free here&#x2026;</p><p class="medium-feed-link"><a href="https://stenzr.medium.com/context-engineering-vs-memory-engineering-building-agents-that-dont-forget-what-matters-0c339a36842e?source=rss-75b52dbfae85------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://stenzr.medium.com/context-engineering-vs-memory-engineering-building-agents-that-dont-forget-what-matters-0c339a36842e?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c339a36842e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 05:41:43 GMT</pubDate>
            <atom:updated>2026-08-22T05:42:20.639Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[We’ve Been Building AI Loops for Years. We Just Didn’t Call Them That.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://stenzr.medium.com/weve-been-building-ai-loops-for-years-we-just-didn-t-call-them-that-97e61bed2b6f?source=rss-75b52dbfae85------2"><img src="https://cdn-images-1.medium.com/max/1536/1*SufGkY-hLIiNqc88OXsdpg.png" width="1536"></a></p><p class="medium-feed-snippet">Read the blog for free&#x2026;</p><p class="medium-feed-link"><a href="https://stenzr.medium.com/weve-been-building-ai-loops-for-years-we-just-didn-t-call-them-that-97e61bed2b6f?source=rss-75b52dbfae85------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://stenzr.medium.com/weve-been-building-ai-loops-for-years-we-just-didn-t-call-them-that-97e61bed2b6f?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e61bed2b6f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[loop-engineering]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 09:22:50 GMT</pubDate>
            <atom:updated>2026-07-26T09:24:58.900Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Markdown: The Unexpected Backbone of the AI Era]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://stenzr.medium.com/markdown-the-unexpected-backbone-of-the-ai-era-cde97e297c05?source=rss-75b52dbfae85------2"><img src="https://cdn-images-1.medium.com/max/1536/1*l1DxHKcbntl4aM6u_ESziw.png" width="1536"></a></p><p class="medium-feed-snippet">A few days ago, I was doing what most of us do between meetings, coffee breaks, or moments of procrastination. I was scrolling through X&#x2026;</p><p class="medium-feed-link"><a href="https://stenzr.medium.com/markdown-the-unexpected-backbone-of-the-ai-era-cde97e297c05?source=rss-75b52dbfae85------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://stenzr.medium.com/markdown-the-unexpected-backbone-of-the-ai-era-cde97e297c05?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde97e297c05</guid>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 06:45:58 GMT</pubDate>
            <atom:updated>2026-06-13T06:45:58.293Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Claude Code: Production-Ready Workflow & Usage Guide]]></title>
            <link>https://stenzr.medium.com/claude-code-production-ready-workflow-usage-guide-917d6eac55f6?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/917d6eac55f6</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 15:49:35 GMT</pubDate>
            <atom:updated>2026-04-15T15:49:35.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’re using Claude Code in a serious engineering environment, the difference between average and high-leverage usage comes down to structure.</p><p>This guide combines a production-grade workflow template with a complete command and thinking model reference so you can use Claude as a repeatable engineering system.</p><h3>1. Thinking Modes: Controlling Reasoning Depth</h3><h3>Thinking Keywords</h3><pre>+--------------------------+-------------------+------------------------------+<br>| Keyword                  | Thinking Budget   | Use Case                     |<br>+--------------------------+-------------------+------------------------------+<br>| (none)                   | Medium            | Standard development         |<br>| think                    | ~4K tokens        | Small fixes, refactoring     |<br>| think hard / megathink   | ~10K tokens       | Multi-step logic             |<br>| ultrathink               | ~32K tokens       | Architecture, deep debugging |<br>+--------------------------+-------------------+------------------------------+</pre><h3>Practical Usage</h3><ul><li>Default → CRUD, basic APIs</li><li>think → Small bugs, improvements</li><li>think hard → System design, integrations</li><li>ultrathink → Large unfamiliar systems</li></ul><p><strong><em>Important: ultrathink works only in CLI.</em></strong></p><h3>2. Project Initialization (One-Time Setup)</h3><h3>Initialize Context</h3><pre>/init</pre><h3>Define CLAUDE.md</h3><pre># Project Context</pre><pre>## Overview<br>- Project Name:<br>- Description:<br>- Tech Stack:<br>- Environment:</pre><pre>## Code Standards<br>- Language conventions:<br>- Naming conventions:<br>- Folder structure:<br>- Error handling patterns:</pre><pre>## Architecture Guidelines<br>- API design rules:<br>- Data flow:<br>- Logging &amp; monitoring:</pre><pre>## Constraints<br>- Performance requirements:<br>- Security constraints:<br>- External dependencies:</pre><pre>## Output Expectations<br>- Always return production-ready code<br>- Include error handling<br>- Follow DRY principles<br>- Add minimal necessary comments</pre><h3>3. Context Injection Strategy</h3><h3>Add Codebase</h3><pre>/add-dir src/<br>/add-dir configs/<br>/add-dir services/</pre><h3>Add Supporting Artifacts</h3><pre>@api-docs.md<br>@schema.json<br>@requirements.md</pre><h3>4. Core Workflow: Plan → Think → Generate → Review</h3><h3>Phase 1: Understanding</h3><pre>/plan</pre><pre>Analyze the requirement:<br>[INPUT]</pre><pre>Break into:<br>- Inputs<br>- Outputs<br>- Edge cases<br>- Dependencies<br>- Risks</pre><pre>Do not write code.</pre><h3>Phase 2: Design with Controlled Reasoning</h3><pre>/effort high</pre><pre>think hard</pre><pre>Design:<br>- Architecture<br>- Modules<br>- Data flow<br>- Failure handling</pre><h3>Phase 3: Code Generation</h3><pre>Generate production-ready code:</pre><pre>Requirements:<br>- Modular structure<br>- Error handling<br>- Logging<br>- Config-driven<br>- Scalable</pre><pre>Output:<br>1. File structure<br>2. Code<br>3. Setup instructions</pre><h3>Phase 4: Iteration Loop</h3><pre>/loop</pre><pre>Refine:<br>- Performance<br>- Duplication<br>- Readability<br>- Edge cases</pre><h3>Phase 5: Debugging</h3><pre>/debug</pre><pre>Issue:<br>[ERROR]</pre><pre>Provide:<br>- Root cause<br>- Fix<br>- Prevention</pre><h3>Phase 6: Code Review</h3><pre>/review</pre><pre>Review for:<br>- Bugs<br>- Performance<br>- Security<br>- Maintainability</pre><pre>Give improvements with reasoning.</pre><h3>5. Slash Commands Reference</h3><h3>Core Commands</h3><pre>+----------+------------------------------+<br>| Command  | Function                     |<br>+----------+------------------------------+<br>| /help    | List commands                |<br>| /init    | Create CLAUDE.md             |<br>| /clear   | Reset conversation           |<br>| /compact | Compress context             |<br>| /status  | View context usage           |<br>+----------+------------------------------+</pre><h3>Development Commands</h3><pre>+------------+------------------------------+<br>| Command    | Function                     |<br>+------------+------------------------------+<br>| /plan      | Analysis mode                |<br>| /review    | Code review                 |<br>| /debug     | Debug workflow              |<br>| /simplify  | Detect architecture issues  |<br>| /loop      | Iterative improvement       |<br>+------------+------------------------------+</pre><h3>Configuration Commands</h3><pre>+--------------+-----------------------------+<br>| Command      | Function                    |<br>+--------------+-----------------------------+<br>| /model       | Switch model                |<br>| /effort      | Set reasoning level         |<br>| /fast        | Speed optimization          |<br>| /memory      | Edit CLAUDE.md              |<br>| /config      | Settings                    |<br>| /permissions | Access control              |<br>| /mcp         | Integration management      |<br>+--------------+-----------------------------+</pre><h3>Context Commands</h3><pre>+-------------------+------------------------------+<br>| Command           | Function                     |<br>+-------------------+------------------------------+<br>| /add-dir          | Add directories              |<br>| /resume           | Load session                 |<br>| /batch            | Parallel changes             |<br>+-------------------+------------------------------+</pre><h3>6. CLI Usage</h3><pre>+------------------------------------------+-----------------------------+<br>| Command                                  | Description                 |<br>+------------------------------------------+-----------------------------+<br>| claude                                   | Start session               |<br>| claude -c                                | Continue last session       |<br>| claude --resume                          | Select session              |<br>| claude --worktree &lt;branch&gt;               | Isolated environment        |<br>| claude --print                           | Non-interactive             |<br>| claude --system-prompt                   | Replace system prompt       |<br>| claude --append-system-prompt            | Extend prompt               |<br>| claude --dangerously-skip-permissions    | Skip checks                 |<br>+------------------------------------------+-----------------------------+</pre><h3>7. Keyboard Shortcuts</h3><pre>+----------------------+------------------+<br>| Shortcut             | Action           |<br>+----------------------+------------------+<br>| Esc                  | Interrupt        |<br>| Esc Esc              | Go back          |<br>| Tab                  | Toggle thinking  |<br>| Shift + Tab          | Switch modes     |<br>| Shift + Tab x2       | Plan mode        |<br>| Ctrl + C x2          | Exit             |<br>+----------------------+------------------+</pre><h3>8. Context Management Strategy</h3><h3>Rules</h3><ul><li>Use /compact when context exceeds 80 percent</li><li>Use /clear when switching tasks</li><li>Use /add-dir instead of manual input</li></ul><h3>9. Advanced Workflow Patterns</h3><h3>Feature Development</h3><pre>/init → /add-dir → /plan → /effort high → generate → /review → /compact</pre><h3>Debugging</h3><pre>/add-dir → /debug → /effort high → fix → /review</pre><h3>Large Refactor</h3><pre>/plan → /simplify → /batch → /review</pre><h3>Integration Pipeline</h3><pre>think hard</pre><pre>Input:<br>- API docs: @api-docs.md<br>- Field config: @field-config.json</pre><pre>Generate:<br>- Mapping layer<br>- Transformation logic<br>- Error handling<br>- Retry mechanism<br>- Logging</pre><h3>10. Power Usage Patterns</h3><pre>+--------+------------------------------+<br>| Symbol | Function                     |<br>+--------+------------------------------+<br>| !      | Execute shell command        |<br>| #      | Save to memory               |<br>| @      | Inject file context          |<br>| &amp;      | Background tasks             |<br>+--------+------------------------------+</pre><h3>11. Performance Optimization</h3><pre>+------------------+------------------------------+<br>| Scenario         | Action                       |<br>+------------------+------------------------------+<br>| Large codebase   | Use /add-dir                |<br>| Long session     | Use /compact                |<br>| New task         | Use /clear                  |<br>| Complex problem  | Use /effort high            |<br>+------------------+------------------------------+</pre><h3>12. Team-Level Standardization</h3><ul><li>Share a common CLAUDE.md</li><li>Define reusable prompt templates</li><li>Enforce workflow: Plan → Think → Generate → Review</li></ul><h3>13. Starter Execution Template</h3><pre>/init<br>/add-dir src/</pre><pre>/plan<br>Analyze requirement: [INPUT]</pre><pre>/effort high<br>think hard</pre><pre>Design solution</pre><pre>Generate production-ready code:<br>- Modular<br>- Scalable<br>- Error-handled</pre><pre>/review<br>/compact Focus on current module</pre><h3>Final Perspective</h3><p>Used casually, Claude is a coding assistant.<br>Used systematically, it becomes a structured engineering workflow that can plan, design, implement, and review like a senior developer.</p><p>The leverage comes from:</p><ul><li>Explicit reasoning control</li><li>Structured workflows</li><li>Context discipline</li><li>Command-driven interaction</li></ul><p>Claude becomes part of your engineering system rather than just a tool.</p><p><em>Thanks For Reading!</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917d6eac55f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Thread, Thousands of Requests: How a Production Incident Taught Me the Real Node.js Event Loop]]></title>
            <link>https://stenzr.medium.com/one-thread-thousands-of-requests-how-a-production-incident-taught-me-the-real-node-js-event-loop-294678d6b4c8?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/294678d6b4c8</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 18:13:23 GMT</pubDate>
            <atom:updated>2026-01-06T18:13:23.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3jXeVcbrWdcZvZcy_DsEQ.png" /></figure><p>It was supposed to be a quite weekoff.</p><p>No meetings. No dashboards. Just coffee, brain firmly switched to <strong><em>“low-power mode”</em></strong>, and the luxury of ignoring notifications and emails for a few hours.</p><p>I was mid-sip and scrolling aimlessly in instagram reels when my phone vibrated. The name Mr. X on the screen meant not a good time.</p><p><strong><em>“API latency climbing. No CPU spike. No memory spike. Node service looks stuck on the request.”</em></strong></p><p>The service in question? A Node.js API handling thousands of concurrent requests — auth, database reads, real-time updates. And the immediate reaction from someone new on the team came exactly as expected:</p><p>That last line is what caught my attention.</p><p><strong><em>“Looks stuck”</em></strong> and <strong><em>“Node.js”</em></strong> usually trigger the same reaction in a room full of engineers:</p><p><strong><em>“Isn’t Node single-threaded?”</em></strong></p><p>That question asked casually in production has caused more confusion, bad fixes, and unnecessary rewrites than almost any other Node.js concept. This incident turned into a reminder of why understanding the Event Loop is not optional at scale.</p><p>This is the story of how one thread handled thousands of requests… until we asked it to wait.</p><h3>The Myth That Never Dies: “Node.js Is Single-Threaded”</h3><p>Yes Node.js executes JavaScript on a single main thread.</p><p>No this does not mean it can only handle one request at a time.</p><p>If Node behaved the way many people imagine it does waiting synchronously for every database call or file read most Node services would collapse under moderate traffic. Ours had been serving thousands of concurrent users for months.</p><p>So what changed?</p><h4>The Symptom Pattern That Matters</h4><p>The metrics told a quiet story:</p><ul><li>CPU: stable</li><li>Memory: flat</li><li>Error rate: low</li><li>Latency: climbing slowly, consistently</li></ul><p>This combination almost always points to waiting, not computation.</p><p>And in Node.js,<strong> waiting means I/O.</strong></p><h4>The Core Idea That Makes Node.js Scale: Delegation</h4><p>Node.js doesn’t win by doing everything itself. It wins by knowing what not to wait for.</p><p>When JavaScript execution encounters an I/O operation database query, file read, network call Node doesn’t pause execution. It delegates the work and moves on.</p><p>Think of the Node.js main thread as a coordinator, not a worker.</p><h4>What Actually Happens</h4><blockquote>1. Request arrives</blockquote><blockquote>2. JavaScript starts executing</blockquote><blockquote>3. An I/O operation is encountered</blockquote><blockquote>4. Node delegates it elsewhere</blockquote><blockquote>5. JavaScript continues handling other requests</blockquote><blockquote>6. When the I/O completes, a callback is queued</blockquote><blockquote>7. The Event Loop eventually executes that callback</blockquote><p>Concurrency without parallel JavaScript execution. That’s the entire trick.</p><h4>I/O Is the Real Bottleneck (Always Has Been)</h4><p>Almost every Node performance issue I’ve debugged in production had the same root cause:</p><ul><li>Something external was slow and we waited poorly.</li></ul><p><strong>I/O includes:</strong></p><ul><li>Database calls</li><li>File system operations</li><li>Network requests</li><li>DNS lookups</li></ul><p>These don’t consume CPU. They consume time. And this is where <strong>libuv</strong> quietly does the heavy lifting.</p><h4>Libuv: The Part Everyone Uses but Few Understand</h4><p>Node.js relies on libuv, a C++ library that provides cross-platform asynchronous I/O.</p><p><strong>libuv handles I/O in two ways:</strong></p><p><strong>1. OS-Level Asynchronous I/O</strong></p><p>For most networking operations:</p><ul><li>The OS handles waiting</li><li>Node registers interest</li><li>No threads are blocked</li></ul><p>This path is extremely efficient.</p><p><strong>2. The Thread Pool (Where Things Get Interesting)</strong></p><p>Some operations cannot be made async at the OS level:</p><ul><li>File system operations (`fs.readFile`)</li><li>DNS lookups</li><li>Certain crypto operations</li></ul><p>For these, libuv uses a thread pool:</p><ul><li>4 threads by default</li><li>Shared across the process</li><li>Finite and easy to saturate</li></ul><p>In our incident, this pool quietly became the choke point.</p><h4>The Event Loop: Not Magic, Just Order</h4><p>The Event Loop is not a black box. It’s a <strong>deterministic scheduler</strong> that cycles through phases, executing queued callbacks.</p><p>The important distinction is priority.</p><p><strong>Microtasks (Highest Priority)</strong></p><ul><li>process.nextTick</li><li>Promise callbacks</li></ul><p>These run:</p><ul><li>Immediately after current execution</li><li>Before the Event Loop proceeds</li></ul><p>Misuse them, and you can starve the loop entirely.</p><p><strong>Macrotasks (Phase-Based)</strong></p><ul><li>Timers (`setTimeout`)</li><li>I/O callbacks</li><li>`setImmediate`</li></ul><p>Each runs in a specific phase of the loop.</p><p>Understanding <strong>when code runs</strong> often matters more than <strong>what code runs</strong>.</p><h4><strong>The Production Bug (In One Sentence)</strong></h4><p>We had introduced a code path that:</p><ul><li>Triggered excessive file system reads</li><li>Saturated libuv’s thread pool</li><li>Delayed I/O callbacks</li><li>Caused the Event Loop to spin with nothing ready to execute</li></ul><p>The system wasn’t blocked.</p><p>It was waiting efficiently but for too many things.</p><h4>The Fix Was Small. The Lesson Was Not.</h4><p>We:</p><ul><li>Reduced unnecessary filesystem access</li><li>Batched I/O operations</li><li>Removed an accidental `process.nextTick` loop</li><li>Tuned thread pool usage carefully</li></ul><h3>Impact (ahh moment)</h3><ul><li>Latency dropped.</li><li>Alerts stopped.</li><li>Weekend partially recovered.</li><li>But the real value was reinforcing the mental model.</li></ul><h4>Lifecycle of a request in node:</h4><pre>Time ─────────────────────────────────────────────────────────▶<br><br>Request A arrives<br>│<br>├─ JS executes handler<br>│<br>├─ fs.readFile() called<br>│   │<br>│   ├─ Delegated to libuv thread pool<br>│   │   └─ Thread #2 busy reading file<br>│   │<br>│   └─ JS continues (non-blocking)<br>│<br>├─ Request B arrives<br>│   │<br>│   └─ JS executes immediately<br>│<br>├─ Promise resolved<br>│   └─ Microtask queue executed<br>│<br>├─ Event Loop: Poll Phase<br>│   │<br>│   ├─ Thread pool still busy<br>│   └─ No I/O callbacks ready<br>│<br>├─ Event Loop: Check Phase<br>│   └─ setImmediate callbacks run<br>│<br>├─ libuv thread finishes fs.readFile<br>│   └─ Callback queued<br>│<br>├─ Event Loop: Poll Phase<br>│   └─ fs.readFile callback executed<br>│<br>└─ Response A sent</pre><h3>Final Takeaways (From Production, Not Slides)</h3><ul><li>Node.js is single-threaded by design, not limitation</li><li>The Event Loop does not block your code does</li><li>I/O is almost always the bottleneck</li><li>libuv’s thread pool is finite and shared</li><li>Microtasks can starve your application</li><li>Execution order matters more than syntax</li><li>Understanding the Event Loop isn’t academic.</li><li>It’s the difference between guessing and debugging.</li></ul><p><em>Thanks For Reading!</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294678d6b4c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Outage That Didn’t Fail: Debugging a Silent Performance Collapse]]></title>
            <link>https://stenzr.medium.com/the-outage-that-didnt-fail-debugging-a-silent-performance-collapse-da7b358fae19?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7b358fae19</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 17:49:11 GMT</pubDate>
            <atom:updated>2026-01-06T00:59:58.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zea_y0ZCOV9sYiwZKkDLSQ.png" /></figure><p>I’ve been on enough on-calls to know the difference between a real outage and noise.</p><p>This one was real.</p><p>On a quiet Saturday, I was enjoying my coffee while watching Interstellar. Time moved differently in the movie, stretching and compressing in ways that didn’t look dangerous, until it was.</p><p>Production latency has a similar habit. Production outages rarely arrive with explosions. More often, they show up as “everything is technically working,” while throughput quietly collapses underneath you.</p><h4>The System I Thought I Understood</h4><p>We run a Node.js based SaaS that processes structured documents at scale. Think invoices, contracts, and forms, each document broken down into rows, processed asynchronously, and enriched with metadata.</p><p>At a high level:</p><ul><li><strong>Node.js</strong> API handles ingestion and orchestration</li><li><strong>MongoDB s</strong>tores documents, rows, and configuration</li><li><strong>RabbitMQ </strong>drives row-level async processing</li><li><strong>Redis </strong>exists, but mostly for key metadata strorage</li></ul><p>On paper, the architecture was sound. In production, scale exposed a blind spot.</p><p>Our document-processing pipeline slowed to a crawl. Not down. Not failing. Just… taking forever. The worst kind of incident.</p><h4>First Signal: Throughput Collapse Without Errors</h4><p>The first thing I noticed wasn’t CPU or memory. It was throughput.</p><p>Our dashboards showed:</p><ul><li>Row processing rate dropped from ~4,200 rows/min → ~700 rows/min</li><li>RabbitMQ queue depth steadily increasing</li><li>No spike in error rate</li><li>No increase in retry counts</li></ul><p>That told me immediately:</p><ul><li><em>This is not a failure problem.</em></li><li><em>This is a latency amplification problem.</em></li></ul><h4><strong>Establish Ground Truth</strong></h4><p>Before touching code, I confirmed facts.</p><p><strong>MongoDB</strong></p><pre>mongotop 5</pre><p><strong>Collections under pressure:</strong></p><pre>`document_rows`<br>`users`<br>`workspaces`<br>`feature_flags`</pre><p><strong>Reads were disproportionately high compared to writes.</strong></p><p>Then:</p><pre>db.currentOp({ “secs_running”: { $gt: 5 } })</pre><p><strong>Result:</strong></p><ul><li>Dozens of long-running read operations</li><li>Same query shapes</li><li>Same filters</li><li>Same documents</li><li>That’s when the smell hit.</li></ul><h4><strong>RabbitMQ Wasn’t the Problem — It Was the Amplifier</strong></h4><p>I checked RabbitMQ next.</p><pre>rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers</pre><p><strong>What I saw:</strong></p><ul><li>Consumers were alive</li><li>Messages were acknowledged — slowly</li><li>No poison messages</li><li>No redelivery storms</li><li>So the queue wasn’t stuck.</li><li>The workers were slow.</li></ul><h4><strong>Workers Were Doing Too Much Work Per Row</strong></h4><p>I attached logs and sampling to one worker instance.</p><p>Each row-processing job did this:</p><p>1. Fetch document metadata</p><p>2. Fetch user preferences</p><p>3. Fetch workspace configuration</p><p>4. Fetch feature flags</p><p>5. Process the row</p><p>That means every single row caused:</p><ul><li>4–6 MongoDB reads</li><li>Mostly identical data across rows of the same document</li></ul><p>For a 5,000-row document?</p><ul><li><em>30,000 identical reads.</em></li></ul><p>Multiply that by concurrent documents. Now MongoDB wasn’t just storing data, it was being used as shared memory.</p><h4><strong>Metrics That Confirmed the Root Cause</strong></h4><p>Once I knew what to look for, the metrics lined up perfectly.</p><h4><strong>Observed during peak:</strong></h4><ul><li>MongoDB read ops/sec: +4.5x baseline</li><li>Node.js event loop lag: 180–250ms</li><li>Worker execution time: 3.8x slower</li><li>Redis CPU: &lt;10% (doing almost nothing)</li></ul><h4>Our Conclusion:</h4><ul><li>Redis was idle.</li><li>MongoDB was drowning.</li><li>Business SLAs were suffering</li></ul><h3><strong>Short-Term Fix: Stop Repeating Known Answers</strong></h3><p>I didn’t redesign anything that weekend but did three surgical things.</p><h4><strong>1. Cache Document-Scoped Data in Redis</strong></h4><p>Instead of fetching metadata per row:</p><pre>doc:{docId}:meta<br>workspace:{workspaceId}:config<br>user:{userId}:prefs</pre><p><strong>Workers:</strong></p><ul><li>Read once from MongoDB</li><li>Cache with TTL</li><li>Reuse across thousands of rows</li></ul><p>TTL was intentionally boring:</p><ul><li>10–30 minutes</li><li>Acceptable staleness</li><li>Predictable behavior</li></ul><h4><strong>2. Kill the Cache on Writes — Explicitly</strong></h4><p>Any update path ended with:</p><pre>redis.del(`doc:${docId}:meta`);<br>redis.del(`workspace:${workspaceId}:config`);</pre><p>No magic. No listeners. No guessing.</p><h4><strong>3. Protect MongoDB Immediately</strong></h4><p>I temporarily:</p><ul><li>Reduced worker concurrency</li><li>Limited max rows per document batch</li><li>Added rate limits at the API layer</li></ul><p>This bought MongoDB breathing room while caches warmed.</p><h4><strong>Result Within Hours</strong></h4><p>By the evening:</p><ul><li>Row throughput recovered to ~95%</li><li>MongoDB read ops dropped ~88%</li><li>RabbitMQ queues drained naturally</li><li>No code rollback needed</li><li>Most importantly, <em>The system became predictable again.</em></li></ul><h3><strong>Long-Term Fixes (What We Did After the Incident)</strong></h3><p>Short-term fixes stabilize systems. Long-term fixes prevent repeat incidents.</p><p><strong>1. Row-Processing Context Caching</strong></p><p>We introduced a processing context per document:</p><ul><li>Loaded once</li><li>Passed implicitly</li><li>Reused across rows</li></ul><p>No worker should <em>“rediscover”</em> the same metadata.</p><p><strong>2. Cache Metrics Became First-Class</strong></p><p>We started tracking:</p><ul><li>Cache hit/miss ratio</li><li>Redis latency</li><li>DB reads per job</li></ul><p>Caching without visibility is just delayed failure.</p><p><strong>3. Backpressure at the Queue Level</strong></p><p>We moved from, <em>“Consume as fast as possible” </em>to <em>“Consume as fast as the database can tolerate”</em></p><p>RabbitMQ prefetch limits now adapt based on system health.</p><p><strong>4. Design Rule We Now Enforce</strong></p><p><em>If a worker processes N rows, it should not perform N identical reads.</em></p><h3><strong>Final Reflection</strong></h3><p>This incident didn’t teach me that Redis is powerful.</p><p>I already knew that. It taught me something more important, <strong><em>Distributed systems fail quietly before they fail loudly.</em></strong></p><p>When document processing slows, it’s rarely <strong><em>“just slow code.”</em></strong></p><p>It’s almost always repeated work, multiplied by scale.</p><ul><li>Databases remember things.</li><li>Caches remember things faster.</li><li>Good systems know who should remember what.</li></ul><p>That afternoon reminded me of that, the hard way.</p><p>Thanks for reading ;)</p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7b358fae19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP 3-Way Handshake Explained]]></title>
            <link>https://stenzr.medium.com/tcp-3-way-handshake-explained-cddfd13a8c7b?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/cddfd13a8c7b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 17:34:03 GMT</pubDate>
            <atom:updated>2025-09-09T17:34:03.950Z</atom:updated>
            <content:encoded><![CDATA[<p>🖧</p><p>One of the first things you learn about networking is the <strong>TCP 3-way handshake</strong>. It sounds simple: <em>SYN → SYN-ACK → ACK</em>. But until you’ve debugged a flaky production system at 3 AM with tcpdump scrolling on your terminal, you don’t really <em>appreciate</em> the elegance of these three tiny packets.</p><p>Let’s walk through what the handshake looks like at the <strong>packet level</strong>, with some Linux commands and real-world anecdotes sprinkled in.</p><h3>Why Should You Care?</h3><p>If you’re building distributed systems, you will — at some point — face:</p><ul><li>Clients failing to connect to servers intermittently.</li><li>Firewalls dropping SYN packets silently.</li><li>Services stuck in SYN_SENT or TIME_WAIT.</li><li>Latency spikes because of slow handshakes.</li></ul><p>Understanding the handshake helps you debug faster. Think of it as knowing the first words of a conversation before worrying about the whole discussion.</p><h3>The 3 Steps of the TCP Handshake</h3><h3>Step 1: SYN — Client Initiates</h3><p>The client kicks things off with a <strong>SYN</strong> packet. It also sends a <strong>random Initial Sequence Number (ISN)</strong>, say 1000.</p><p>Packet view:</p><pre>Client → Server<br>Flags: SYN<br>Seq = 1000</pre><p>On Linux, you can spot these in real time:</p><pre>sudo tcpdump -n -i eth0 &#39;tcp[tcpflags] &amp; (tcp-syn) != 0&#39;</pre><p>I’ve used this countless times when a service team said, <em>“Our API isn’t responding”</em> — only to find out the SYN packets weren’t even leaving the client box.</p><h3>Step 2: SYN-ACK — Server Responds</h3><p>The server replies with:</p><ul><li>Its own <strong>SYN</strong> (say sequence number 5000).</li><li>An <strong>ACK</strong> for the client’s SYN (1001).</li></ul><p>Packet view:</p><pre>Server → Client<br>Flags: SYN, ACK<br>Seq = 5000<br>Ack = 1001</pre><p>Linux check:</p><pre>ss -t state syn-recv</pre><p>This shows sockets where the server received a SYN but hasn’t seen the client’s ACK yet. Very handy when debugging <strong>half-open connections</strong> during a traffic spike.</p><h3>Step 3: ACK — Client Confirms</h3><p>Finally, the client acknowledges the server’s SYN.</p><p>Packet view:</p><pre>Client → Server<br>Flags: ACK<br>Seq = 1001<br>Ack = 5001</pre><p>At this point, netstat -ant or ss -t will show the connection in <strong>ESTABLISHED</strong> state.</p><h3>Visual Recap</h3><pre>Client                                Server<br>  | ---- SYN (Seq=1000) ------------&gt;   |<br>  | &lt;--- SYN,ACK (Seq=5000, Ack=1001)   |<br>  | ---- ACK (Seq=1001, Ack=5001) ----&gt; |<br>Connection established ✅</pre><h3>Real-World Example with Wireshark</h3><p>Here’s what an actual capture looks like when you run tcpdump -i eth0 port 80 while curling a site:</p><p><strong>Packet 1 (Client SYN):</strong></p><pre>Flags: SYN<br>Seq = 0<br>Win = 64240</pre><p><strong>Packet 2 (Server SYN-ACK):</strong></p><pre>Flags: SYN, ACK<br>Seq = 0<br>Ack = 1<br>Win = 65535</pre><p><strong>Packet 3 (Client ACK):</strong></p><pre>Flags: ACK<br>Seq = 1<br>Ack = 1<br>Win = 64240</pre><p>Notice how the <strong>acknowledgment number always equals the other side’s sequence number + 1</strong>. That’s TCP’s way of saying, <em>“Yes, I got your message.”</em></p><h3>Anecdote: The Case of the Missing SYN-ACK</h3><p>Back when I was debugging a load balancer issue, connections from one region kept getting stuck in SYN_SENT. The client sent SYNs, but the server never replied with SYN-ACK. Turned out, a firewall in between was dropping SYN packets because of a misconfigured security rule.</p><p>Lesson learned: whenever you see connections stuck in SYN_SENT, don’t immediately blame the server. Sometimes the SYN never even reaches it.</p><p><strong>Pro tip:</strong></p><pre>sudo tcpdump -n host &lt;server-ip&gt; and tcp port 443</pre><p>will quickly show you whether the SYN leaves your machine and whether the SYN-ACK comes back.</p><h3>Why Exactly Three Steps?</h3><p>Why not 2? Why not 4?</p><ul><li>The first SYN says: <em>“I want to talk.”</em></li><li>The SYN-ACK says: <em>“I heard you, and I want to talk too.”</em></li><li>The final ACK confirms: <em>“Cool, we’re both ready.”</em></li></ul><p>Three steps ensure both sides agree on <strong>initial sequence numbers</strong> and prevent old duplicate packets from resurrecting dead connections.</p><h3>Closing Thoughts</h3><p>The TCP handshake is one of those things you think you understand… until you’re staring at packet captures in production. It’s elegant, minimal, and battle-tested.</p><p>Next time you type:</p><pre>telnet google.com 80</pre><p>and it says <em>Connected</em>, remember that three tiny packets just did their dance across the internet in a few milliseconds to make that possible.</p><p><em>Thanks for reading …</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cddfd13a8c7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Let Failures Take Down Your System: A Deep Dive into the Circuit Breaker Pattern]]></title>
            <link>https://stenzr.medium.com/dont-let-failures-take-down-your-system-a-deep-dive-into-the-circuit-breaker-pattern-dc12d85f8418?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc12d85f8418</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 17:32:16 GMT</pubDate>
            <atom:updated>2025-07-31T17:32:16.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Deep Dive into the Circuit Breaker Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*5We6Tx9nEw3cSkxRWYwMWQ.png" /></figure><p>In today’s world of cloud-native, microservice-based architectures, <strong>system resilience</strong> is everything.</p><p>One slow or failing service can create a domino effect that spirals into <strong>cascading failures</strong>, <strong>downtime</strong>, and <strong>frustrated users</strong>. Ever seen your entire app hang because one API didn’t respond on time? That’s where the <strong>Circuit Breaker Pattern</strong> steps in — <strong>your first line of defense</strong> against unreliable dependencies and runaway failures.</p><p>In this blog, we’ll explore:</p><ul><li>What the circuit breaker pattern is and why it matters</li><li>How it works (with examples and states)</li><li>Common libraries and real-world use cases</li><li>Best practices, gotchas, and when <em>not</em> to use it</li></ul><h3>The Problem: One Bad Service Can Break Everything</h3><p><strong>Imagine this scenario:</strong><br> Your microservice (Service A) makes a call to an external payments API (Service B). One day, Service B becomes slow or goes down completely. What happens?</p><ul><li>Requests from Service A <strong>hang or timeout</strong></li><li>Threads pile up, resources get exhausted</li><li>Service A itself slows down or crashes</li><li>Other services calling A get impacted</li><li>The failure spreads — welcome to <strong>cascading failure</strong></li></ul><p>Retrying the call blindly only makes things worse.<br> That’s not fault tolerance — it’s <strong>failure amplification</strong>.</p><h3>The Solution: Circuit Breaker to the Rescue</h3><p>The <strong>Circuit Breaker Pattern</strong> is a defensive programming strategy. It acts as a <strong>trip switch</strong>, <strong>monitoring calls to external systems</strong>, and <strong>blocking them</strong> if the failure threshold is breached.</p><p>In other words, <strong>fail fast, recover smart</strong>.</p><h3>What Is the Circuit Breaker Pattern?</h3><p>It’s a software pattern that wraps a function call and:</p><ul><li><strong>Detects failures</strong></li><li><strong>Blocks calls</strong> after too many failures</li><li><strong>Allows retries</strong> after a cool-off period</li></ul><p>This prevents your app from wasting resources or getting stuck waiting for doomed operations.</p><h3>How It Works: States of a Circuit Breaker</h3><p>Circuit breakers cycle through <strong>three core states</strong>:</p><h3>1. Closed</h3><ul><li>All calls go through.</li><li>Failure count is monitored.</li><li>If failures cross the threshold, it moves to <strong>Open</strong>.</li></ul><h3>2. Open</h3><ul><li>All calls are blocked immediately.</li><li>After a set timeout, it transitions to <strong>Half-Open</strong>.</li></ul><h3>3. Half-Open</h3><ul><li>A few trial requests are allowed.</li><li>If they succeed → back to <strong>Closed</strong>.</li><li>If they fail → back to <strong>Open</strong>.</li></ul><p>This state machine prevents overloading failing systems and gives them time to recover.</p><h4>Visual Summary:</h4><pre>Success                 Failure Threshold<br>Closed ---------&gt; Open ------------------&gt; Half-Open<br>   ^                                               |<br>   |------------------- Success -------------------|</pre><h3>A Real-World Analogy</h3><p>You love a particular restaurant and go there regularly (<strong>Closed</strong> state).<br> One day, the food is terrible. You stop going for a few weeks (<strong>Open</strong> state).</p><p>Later, you give it one more chance (<strong>Half-Open</strong>).<br> If it’s good again, you become a regular again (<strong>Closed</strong>).<br> If not, back to avoidance mode (<strong>Open</strong>).</p><h3>Circuit Breaker in Action (Python Example)</h3><p>Using pybreaker, a simple circuit breaker library for Python:</p><pre>import pybreaker<br>import requests<br><br>breaker = pybreaker.CircuitBreaker(fail_max=3, reset_timeout=10)<br>@breaker<br>def call_external_api():<br>    return requests.get(&quot;https://some-api.com/data&quot;)<br><br># Now, this function will trip after 3 failures and pause for 10 seconds</pre><p><strong>Benefits</strong>:</p><ul><li>No more thread pile-ups</li><li>Fast fallback responses</li><li>Self-healing behavior</li></ul><h3>Circuit Breaker Libraries by Language</h3><pre>+------------+-----------------------------+<br>| Language   | Library                     |<br>+------------+-----------------------------+<br>| Java       | Resilience4j, Hystrix       |<br>| Python     | pybreaker                   |<br>| Node.js    | opossum                     |<br>| .NET       | Polly                       |<br>+------------+-----------------------------+</pre><p>Most of these libraries also support <strong>fallbacks</strong>, <strong>timeouts</strong>, <strong>bulkheads</strong>, and more — great for robust service-to-service communication.</p><h3>Where Should You Use Circuit Breakers?</h3><p>You should wrap calls to:</p><ul><li><strong>Third-party APIs</strong> (SMS, payments, weather, etc.)</li><li><strong>Microservice-to-microservice communication</strong></li><li><strong>Databases or caches</strong> (if external)</li><li><strong>File systems or message brokers</strong></li></ul><p>Anywhere you don’t fully control the latency or availability.</p><h3>When Not to Use It</h3><p>Like any pattern, it’s not a silver bullet.</p><p>Avoid using circuit breakers:</p><ul><li>For <strong>in-process</strong> method calls (they don’t fail the same way)</li><li>If failures are <strong>non-recoverable</strong> or indicate a bug</li><li>When there’s <strong>no fallback</strong> and fast failure isn’t better</li></ul><h3>Best Practices</h3><ol><li><strong>Start conservative</strong>: Low thresholds and short timeouts help catch issues early.</li><li><strong>Log everything</strong>: State transitions help during debugging.</li><li><strong>Provide fallbacks</strong>: Return cached data, default responses, or graceful errors.</li><li><strong>Monitor</strong>: Expose circuit state metrics to Prometheus/Grafana.</li><li><strong>Combine patterns</strong>: Use with <strong>retries</strong>, <strong>timeouts</strong>, and <strong>rate limiting</strong>.</li></ol><h3>Advanced Tips</h3><ul><li>Use <strong>different breakers per dependency</strong>, not one global breaker.</li><li>Implement <strong>exponential backoff</strong> with retries.</li><li>For <strong>critical paths</strong>, consider queueing + bulkhead patterns alongside breakers.</li><li>In cloud-native environments, tools like Istio/Envoy can enforce circuit breaking at the <strong>infrastructure level</strong> too.</li></ul><h3>Wrapping Up: Break Before You Break</h3><p>The <strong>Circuit Breaker Pattern</strong> is essential for building <strong>resilient, fault-tolerant distributed systems</strong>. It helps you:</p><ul><li>Detect failures early</li><li>Reduce cascading outages</li><li>Recover from errors gracefully</li></ul><p>In an architecture where services are increasingly dependent on each other, <strong>a single failing component shouldn’t sink your ship</strong>. The circuit breaker lets you protect your system from external chaos.</p><h3>What’s Your Take?</h3><p>Have you used circuit breakers in your projects? What’s your favorite tool or implementation trick?<br> <strong>Drop your thoughts in the comments — let’s learn from each other.</strong></p><p><em>Thanks For Reading!</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc12d85f8418" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Role-Based Access Control (RBAC) in a Large Application]]></title>
            <link>https://stenzr.medium.com/implementing-role-based-access-control-rbac-in-a-large-application-5f5cc055cf19?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5cc055cf19</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[role-based-access-control]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 12:01:39 GMT</pubDate>
            <atom:updated>2025-07-20T12:01:39.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-hkwMh_QIF4E6hQaYJfYjA.png" /></figure><p>In large-scale applications — especially enterprise SaaS platforms, CRMs, or B2B portals — <strong>Role-Based Access Control (RBAC)</strong> is a foundational building block. As your product grows from a single-user setup to supporting thousands of organizations, each with their own admins, editors, and viewers, hardcoding access checks or using ad-hoc flags simply doesn’t scale.</p><p>RBAC helps answer questions like:</p><ul><li>Can <strong>user X</strong> delete <strong>document Y</strong> in <strong>organization Z</strong>?</li><li>Should <strong>button A</strong> be visible to a user with <strong>only view permissions</strong>?</li><li>Can <strong>support agents</strong> impersonate customers?</li><li>Should <strong>audit logs</strong> be accessible to someone from another team?</li></ul><p>This post walks you through implementing a scalable, flexible RBAC system using <strong>Node.js</strong>, Express, and a Data Base, while keeping it extensible enough for multi-tenancy and context-based permissions.</p><h3>🔍 What is Role-Based Access Control?</h3><p><strong>RBAC</strong> is a strategy where:</p><ol><li><strong>Users are assigned Roles</strong> (e.g., Admin, Viewer)</li><li><strong>Roles are granted Permissions</strong> (e.g., project:read, user:invite)</li><li>Permissions can be <strong>evaluated in context</strong> (e.g., only inside a specific organization or workspace)</li></ol><h3>Illustration:</h3><pre>{<br>  &quot;roles&quot;: [&quot;editor&quot;],<br>  &quot;permissions&quot;: [<br>    { &quot;action&quot;: &quot;edit&quot;, &quot;resource&quot;: &quot;document&quot; },<br>    { &quot;action&quot;: &quot;view&quot;, &quot;resource&quot;: &quot;document&quot; }<br>  ]<br>}</pre><h3>Database Schema Design</h3><p>A normalized schema ensures reusability and flexibility.</p><h3>Core Tables</h3><pre>1. users (id, name, email)<br>2. roles (id, name) -- admin, viewer, editor, etc.<br>3. permissions (id, action, resource) -- action=view/edit/delete, resource=document/user/project<br>4. user_roles (user_id, role_id, org_id)<br>5. role_permissions (role_id, permission_id)<br></pre><ul><li>org_id enables multi-tenancy or organization-specific roles.</li></ul><p>We can extend it with:</p><ul><li>resource_id for per-resource permissions</li><li>granted_by for audit trails</li></ul><pre>| User  | Role   | Org  |<br>| ----- | ------ | ---- |<br>| Rohit | Admin  | OrgA |<br>| Aman  | Viewer | OrgA |<br>| Bitan | Editor | OrgB |</pre><pre>| Role   | Permission                   |<br>| ------ | ---------------------------- |<br>| Admin  | project\:create, delete      |<br>| Viewer | project\:view                |<br>| Editor | project\:view, project\:edit |</pre><h3>Authorization Service in Node.js (Express)</h3><h3>Step 1: Define Permissions</h3><pre>// permission.constants.js<br>export const PERMISSIONS = {<br>  PROJECT_CREATE: &#39;project:create&#39;,<br>  PROJECT_VIEW: &#39;project:view&#39;,<br>  PROJECT_EDIT: &#39;project:edit&#39;,<br>  PROJECT_DELETE: &#39;project:delete&#39;,<br>};</pre><h3>Step 2: Role to Permission Mapping (Seeded or from DB)</h3><pre>const rolePermissionsMap = {<br>  admin: [<br>    PERMISSIONS.PROJECT_CREATE,<br>    PERMISSIONS.PROJECT_EDIT,<br>    PERMISSIONS.PROJECT_DELETE,<br>    PERMISSIONS.PROJECT_VIEW,<br>  ],<br>  editor: [<br>    PERMISSIONS.PROJECT_EDIT,<br>    PERMISSIONS.PROJECT_VIEW,<br>  ],<br>  viewer: [PERMISSIONS.PROJECT_VIEW],<br>};</pre><h3>Step 3: Middleware — authorize(role | permission)</h3><pre>// middleware/authorize.js<br>export const authorize = (requiredPermission) =&gt; {<br>  return (req, res, next) =&gt; {<br>    const user = req.user; // assume user is already decoded from JWT<br>    const permissions = getUserPermissions(user); // returns array of permission strings<br><br>     if (permissions.includes(requiredPermission)) {<br>          return next();<br>        }<br>        return res.status(403).json({ error: &#39;Forbidden&#39; });<br>      };<br>};<br>// Simulated permission resolver<br>const getUserPermissions = (user) =&gt; {<br>  const allPermissions = new Set();<br>  user.roles.forEach(role =&gt; {<br>    const perms = rolePermissionsMap[role] || [];<br>    perms.forEach(p =&gt; allPermissions.add(p));<br>  });<br>  return Array.from(allPermissions);<br>};<br><br></pre><h3>Step 4: Use in Express Routes</h3><pre>import express from &#39;express&#39;;<br>import { authorize } from &#39;./middleware/authorize.js&#39;;<br>import { PERMISSIONS } from &#39;./permission.constants.js&#39;;<br><br>const router = express.Router();<br>router.post(<br>  &#39;/projects&#39;,<br>  authorize(PERMISSIONS.PROJECT_CREATE),<br>  (req, res) =&gt; {<br>    // Create project logic<br>    res.send(&#39;Project created!&#39;);<br>  }<br>);</pre><h3>Dynamic Permissions from DB</h3><p>If your permissions are stored in the DB:</p><pre>async function getPermissionsFromDB(userId, orgId) {<br>  const roles = await db.query(`<br>    SELECT r.name FROM roles r<br>    JOIN user_roles ur ON ur.role_id = r.id<br>    WHERE ur.user_id = $1 AND ur.org_id = $2<br>  `, [userId, orgId]);<br><br>const permissions = await db.query(`<br>    SELECT p.action || &#39;:&#39; || p.resource as permission<br>    FROM permissions p<br>    JOIN role_permissions rp ON rp.permission_id = p.id<br>    WHERE rp.role_id = ANY($1)<br>  `, [roles.rows.map(r =&gt; r.name)]);<br>  return permissions.rows.map(r =&gt; r.permission);<br>}</pre><h3>Context-Aware Permissions</h3><p>Some permissions only make sense <strong>within an organization/project context</strong>.</p><pre>// Check if user has delete permission *in Org A*<br>const canDelete = await checkPermission(userId, &#39;project:delete&#39;, orgId);</pre><p>Design APIs to always pass context (orgId, projectId) so your AuthorizationService can evaluate accordingly.</p><h3>Performance Tips</h3><ol><li><strong>Cache permissions</strong> using Redis or in-memory LRU per session.</li><li><strong>Batch permission checks</strong> if evaluating multiple permissions.</li><li><strong>Use JSON Web Tokens (JWT)</strong> to encode roles/permissions for low-latency validation.</li><li>Periodically <strong>refresh user roles</strong> if your roles change frequently.</li></ol><h3>UI Integration</h3><p>RBAC should also drive frontend visibility:</p><p>Maintain a lightweight permission snapshot in the frontend, but always enforce real checks on the backend.</p><pre>if (userPermissions.includes(&#39;project:edit&#39;)) {<br>  showEditButton();<br>}</pre><h3>Best Practices</h3><ul><li>Model roles, permissions, and resources as separate entities.</li><li>✅ Ensure permission checks happen <strong>at all entry points</strong>: APIs, background jobs, UI.</li><li>✅ Include audit logs for permission/role changes.</li><li>✅ Handle default roles for onboarding (e.g., viewer role on signup).</li><li>❌ Avoid hardcoding permissions or roles in business logic.</li><li>❌ Don’t trust client-side role checks.</li></ul><h3>Real-World Examples</h3><h3>Example 1: Organization Scoped Access</h3><pre>GET /orgs/:orgId/projects/:projectId<br><br>Check if user has `project:view` permission in `orgId`</pre><h3>Example 2: Multi-Role Users</h3><p>A user might be:</p><ul><li>Admin in Org A</li><li>Editor in Org B</li></ul><p>Ensure your access checks are <strong>context-aware</strong> (OrgId, WorkspaceId, etc.)</p><h3>Summary</h3><p>RBAC is more than just a security requirement — it’s a <strong>design principle</strong> for scalable access management. Whether you’re building SaaS platforms, internal admin tools, or multi-tenant apps, investing in a clean RBAC foundation will:</p><ul><li>Make your access logic transparent</li><li>Reduce bugs</li><li>Enable dynamic configuration</li><li>Scale effortlessly across teams and orgs</li></ul><p><em>Thanks For Reading!</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5cc055cf19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session Management — being enterprise-ready]]></title>
            <link>https://stenzr.medium.com/session-management-being-enterprise-ready-74cfc614b315?source=rss-75b52dbfae85------2</link>
            <guid isPermaLink="false">https://medium.com/p/74cfc614b315</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rohit Kumar]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 14:28:47 GMT</pubDate>
            <atom:updated>2025-07-16T14:31:47.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Session Management — being enterprise-ready</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jHv5EtPmrm5jlv4W1FvWjQ.jpeg" /></figure><p>Web sessions are the glue that holds the user experience together on the modern internet. From keeping you logged into your favourite sites to personalising dashboards, sessions enable stateful interactions in a stateless protocol like HTTP.</p><p>But have you ever wondered how sessions actually work behind the scenes? Or how large-scale applications handle complex session requirements like multi-device logins, tab-level control, or auto-logout?</p><p>In this post, we’ll break down the <strong>lifecycle of a session</strong>, explore common implementation patterns in <strong>Express.js</strong>, and dive into <strong>enterprise-grade features</strong> like <strong>device/tab limits</strong>, <strong>inactivity detection</strong>, and <strong>OAuth/JWT integration</strong>.</p><h3>What Is a Web Session?</h3><p>A session is a temporary state maintained between the client (browser) and the server across multiple HTTP requests. Since HTTP is stateless by default, sessions allow servers to recognize the same user across requests without re-authentication each time.</p><h3>Lifecycle of a Session</h3><p>Understanding the session lifecycle is crucial for building secure and scalable apps.</p><h4>1. Session Creation</h4><p>When a user visits your site, your backend checks if a session ID exists in the cookies. If not, it creates a new session, generates a session ID, and stores it (usually in memory, Redis, or a database).</p><h4>2. Session Storage</h4><p>This session ID maps to user-specific data (cart items, login status, preferences) stored server-side.</p><h4>3. Session Retrieval</h4><p>With every request, the browser sends the session ID cookie. The backend uses this to retrieve the correct session and attach the data to the request.</p><h4>4. Session Update</h4><p>If the server modifies the session (e.g., user adds an item to cart), it updates the session store.</p><h4>5. Session Expiry</h4><p>Sessions can expire after a certain time (inactivity or absolute timeout). Upon expiration, the session is removed from the store, and the session ID is no longer valid.</p><h4>6. Session Destruction</h4><p>Manual termination (like logout) destroys the session and removes the session ID cookie from the client.</p><h3>How to Handle Sessions in Express.js</h3><p>Let’s look at a practical session setup in Express using express-session.</p><pre>const express = require(&#39;express&#39;);<br>const session = require(&#39;express-session&#39;);</pre><pre>const app = express();</pre><pre>app.use(session({<br>  secret: &#39;your-secret&#39;,<br>  resave: false,<br>  saveUninitialized: false,<br>  cookie: {<br>    maxAge: 30 * 60 * 1000, // 30 mins<br>    httpOnly: true,<br>    secure: process.env.NODE_ENV === &#39;production&#39;,<br>    sameSite: &#39;lax&#39;<br>  }<br>}));</pre><h3>Example: Store Login Info</h3><pre>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  req.session.user = { id: 123, name: &#39;Rohit&#39; };<br>  res.send(&#39;Logged in&#39;);<br>});</pre><h3>Middleware to Protect Routes</h3><pre>function isAuthenticated(req, res, next) {<br>  if (req.session.user) return next();<br>  res.status(401).send(&#39;Unauthorized&#39;);<br>}</pre><h3>Enterprise Session Management Features</h3><p>Big systems need more than just cookie-based sessions. Let’s look at features real businesses demand and how to implement them.</p><h4>Limit Sessions per Device (n Devices)</h4><p>Store a list of active session IDs per user in your DB or Redis. On login, check if they exceeded the allowed count.</p><pre>// pseudocode: on login<br>if (activeSessions[userId].length &gt;= MAX_SESSIONS) {<br>  rejectLogin();<br>} else {<br>  activeSessions[userId].push(newSessionId);<br>}</pre><h4>Limit Sessions per Browser Tab</h4><p>Browsers share cookies across tabs, but you can simulate tab-specific sessions using localStorage and window.name.</p><ul><li>Store a unique tab ID in sessionStorage.</li><li>Send it as a custom header or append to query params.</li><li>On server, maintain separate sub-sessions for each tab.</li></ul><p>This is often used in banking or dashboards where simultaneous tab use needs tracking.</p><h4>Auto Logout on Inactivity</h4><p>Use a front-end timer + server update strategy:</p><h4><strong>The frontend way:</strong></h4><ol><li>Frontend tracks user activity and resets a timer.</li><li>After inactivity, it calls /logout or clears tokens.</li><li>Optionally, ping the server every X minutes to keep session alive.</li></ol><pre>let timer = setTimeout(logout, 15 * 60 * 1000); // 15 mins</pre><pre>window.onmousemove = window.onkeydown = () =&gt; {<br>  clearTimeout(timer);<br>  timer = setTimeout(logout, 15 * 60 * 1000);<br>};</pre><h4>The backend way:</h4><ol><li>Tracks last user activity</li><li>Auto-destroys the session after a period of inactivity</li><li>Also enforces a hard expiration (absolute timeout)</li></ol><pre>// session handling middleware<br><br>const session = require(&#39;express-session&#39;);<br>const MAX_IDLE_TIME = 15 * 60 * 1000;       // 15 mins of inactivity<br>const MAX_SESSION_LIFETIME = 60 * 60 * 1000; // 1 hour absolute limit<br><br>app.use(session({<br>  secret: &#39;my-secret&#39;,<br>  resave: false,<br>  saveUninitialized: false,<br>  cookie: {<br>    maxAge: MAX_SESSION_LIFETIME,<br>    httpOnly: true<br>  }<br>}));<br><br>// Middleware to track inactivity and session age<br>app.use((req, res, next) =&gt; {<br>  const now = Date.now();<br><br>  // First request, initialize times<br>  if (!req.session.createdAt) {<br>    req.session.createdAt = now;<br>    req.session.lastActivity = now;<br>  }<br><br>  // Auto-logout if session is too old (absolute timeout)<br>  if (now - req.session.createdAt &gt; MAX_SESSION_LIFETIME) {<br>    return req.session.destroy(() =&gt; {<br>      res.clearCookie(&#39;connect.sid&#39;);<br>      res.status(440).send(&#39;Session expired (absolute timeout)&#39;);<br>    });<br>  }<br><br>  // Auto-logout if idle for too long<br>  if (now - req.session.lastActivity &gt; MAX_IDLE_TIME) {<br>    return req.session.destroy(() =&gt; {<br>      res.clearCookie(&#39;connect.sid&#39;);<br>      res.status(441).send(&#39;Logged out due to inactivity&#39;);<br>    });<br>  }<br><br>  // Update last activity time<br>  req.session.lastActivity = now;<br>  next();<br>});</pre><h3>OAuth + JWT Sessions</h3><p>Modern apps increasingly rely on OAuth (Google, GitHub) and JWTs for authentication and stateless sessions.</p><h3>Why Use OAuth + JWT?</h3><ul><li>Scales well in microservices</li><li>No server-side session store required</li><li>Ideal for APIs and SPAs</li></ul><h3>JWT Auth Flow</h3><ol><li>User logs in via Google</li><li>Your backend gets an access token and ID token (JWT)</li><li>Verify JWT signature and extract user info</li><li>Optionally, store session in Redis for logout/tracking</li></ol><pre>const jwt = require(&#39;jsonwebtoken&#39;);</pre><pre>function jwtMiddleware(req, res, next) {<br>  const token = req.cookies.jwt;<br>  try {<br>    req.user = jwt.verify(token, &#39;jwt-secret&#39;);<br>    next();<br>  } catch (e) {<br>    res.status(401).send(&#39;Invalid token&#39;);<br>  }<br>}</pre><h3>Best Practices (Dos &amp; Don’ts)</h3><h4>Do:</h4><ul><li>Use HttpOnly, Secure, and SameSite cookies</li><li>Rotate session ID on login to prevent fixation</li><li>Auto-expire old sessions (absolute + idle timeout)</li><li>Store session data securely (preferably not in memory for production)</li><li>Clean up expired sessions to save memory</li></ul><h4>Don’t:</h4><ul><li>Store passwords or sensitive data in session</li><li>Trust cookie data blindly — always validate</li><li>Allow unlimited concurrent sessions for one user</li><li>Forget to handle logout and device/session cleanup</li></ul><h3>Conclusion</h3><p>Sessions are fundamental to secure and personalized user experiences. Whether you’re building a small web app or a large-scale enterprise system, understanding and properly managing the session lifecycle is key.</p><p>Robust session management is essential for both security and user experience. Understanding the session lifecycle and applying enterprise-level controls ensures your application scales securely.</p><p>From basic cookie-based storage to advanced multi-device management and OAuth+JWT flows, the approach depends on your app’s complexity and security needs.</p><p><em>Thanks For Reading!</em></p><blockquote><a href="https://medium.com/@stenzr"><strong><em>Rohit Kumar</em></strong></a><strong><em> </em></strong><em>is a passionate software evangelist. Who loves implementing, breaking and engineering software products. </em><a href="https://stenzr.github.io/"><em>He actively engages</em></a><em> on platforms such as </em><a href="https://www.linkedin.com/in/rkrohitkr01/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/stenzr"><em>GitHub</em></a><em>, &amp; </em><a href="https://stenzr.medium.com/subscribe"><em>Medium through email</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74cfc614b315" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>