<?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 Vijay Khot on Medium]]></title>
        <description><![CDATA[Stories by Vijay Khot on Medium]]></description>
        <link>https://medium.com/@vijay-khot?source=rss-3244100d2325------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O4RdqVLidPauAjUXTOzJBw.jpeg</url>
            <title>Stories by Vijay Khot on Medium</title>
            <link>https://medium.com/@vijay-khot?source=rss-3244100d2325------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:40:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijay-khot/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[Building Production-Grade Idempotency with Node.js, Fastify, and Redis]]></title>
            <link>https://javascript.plainenglish.io/building-production-grade-idempotency-with-node-js-fastify-and-redis-4876de266222?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/4876de266222</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 23:02:59 GMT</pubDate>
            <atom:updated>2025-12-29T14:57:30.462Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A definitive guide to handling duplicate requests, race conditions, and distributed locks in your API.</strong></p><p>In distributed systems, the network is not reliable. A client might send a POST request to create a resource (like a payment or a document submission), but the response gets lost due to a timeout or a shaky Wi-Fi connection.</p><p>The client, not knowing if the server received the request, naturally retries.</p><p>Without <strong>Idempotency</strong>, this retry creates a duplicate record. Your user gets charged twice, or two identical documents appear in your database.</p><p>In this guide, we will implement a robust, thread-safe idempotency layer using <strong>Node.js (Fastify)</strong> and <strong>Redis</strong>. We won’t just cover the happy path; we will dive into the specific race conditions and framework lifecycles that trip up even senior engineers.</p><h3>Understanding the Fastify Lifecycle</h3><p>Before we write code, it is critical to understand <em>when</em> our logic executes. Fastify processes requests in a specific order. We are injecting our logic at two specific points:</p><ol><li><strong>Incoming Request</strong> ⬇️</li><li><strong>preHandler Hook (Phase 1: The Check)</strong></li></ol><ul><li><em>When it runs:</em> After validation/parsing and authentication, but <strong>immediately before</strong> your Controller (business logic).</li><li><em>What we do:</em> We check the cache. If the data exists, we reply immediately and <strong>skip</strong> the Controller entirely. If not, we lock the key and enter the controller execution.</li></ul><p><strong>3. Controller / Handler</strong></p><ul><li><em>When it runs:</em> This is your standard API route logic (e.g., writing to Database).</li></ul><p>4. <strong>onSend Hook (Phase 2: The Save)</strong></p><ul><li><em>When it runs:</em> <strong>After</strong> the Controller finishes and calls reply.send(), but <strong>before</strong> the response is actually flushed to the client.</li><li><em>What we do:</em> We intercept the payload, save it to Redis for future retries, and release the lock.</li></ul><p>5. <strong>Outgoing Response</strong> ⬆️</p><h3>The Architecture: Two-Phase Locking</h3><p>A naive approach is to simply check the database: <em>“Does this ID exist? If yes, skip.”</em> This fails under concurrency. If two requests arrive at the exact same millisecond (a “double-click”), both pass the check, and both create records.</p><p>To prevent this, we use a <strong>Two-Phase Locking Strategy</strong> utilizing Redis.</p><h3>Step 1: The Setup</h3><p>We need ioredis for robust Redis communication.</p><pre>import { FastifyRequest, FastifyReply } from &quot;fastify&quot;;<br>import Redis from &quot;ioredis&quot;;<br><br>const redis = new Redis(process.env.REDIS_URL);<br>const IDEMPOTENCY_HEADER = &quot;idempotency-key&quot;;<br>const LOCK_TTL = 10; // Seconds to hold lock during processing<br>const CACHE_TTL = 86400; // 24 hours to keep the response</pre><h3>Step 2: Phase One — The Check &amp; The Lock (preHandler)</h3><p>In the preHandler hook, we handle the race condition. We use the Redis SET ... NX command. NX stands for &quot;Not Exists&quot;—it only sets the key if it does <em>not</em> already exist. This is an atomic operation.</p><pre>async function checkHook(req: FastifyRequest, reply: FastifyReply) {<br>    // 1. Only apply to mutating methods<br>    if (req.method !== &quot;POST&quot; &amp;&amp; req.method !== &quot;PATCH&quot;) return;<br><br>    // 2. Extract Header<br>    const key = req.headers[IDEMPOTENCY_HEADER] as string;<br>    if (!key) return; <br><br>    const redisKey = `idempotency:${key}`;<br>    const lockKey = `lock:${key}`;<br><br>    // 3. Cache Hit?<br>    const cached = await redis.get(redisKey);<br>    if (cached) {<br>      const { statusCode, body, headers } = JSON.parse(cached);<br>      // STOP EXECUTION: Send cached response immediately<br>      reply.status(statusCode).headers(headers).send(body);<br>      return reply; <br>    }<br><br>    // 4. Cache Miss? Acquire Atomic Lock<br>    // Syntax: SET key value EX ttl NX<br>    const acquired = await redis.set(lockKey, &quot;LOCKED&quot;, &quot;EX&quot;, LOCK_TTL, &quot;NX&quot;);<br>    <br>    if (acquired !== &quot;OK&quot;) {<br>      // Lock failed: Another request is processing this key RIGHT NOW.<br>      reply.code(409).send({ error: &quot;Request in progress&quot; });<br>      return reply;<br>    }<br>    <br>    // 5. Attach lock key to request for the next phase<br>    (req as any).idempotencyLockKey = lockKey;<br>}</pre><h3>Step 3: Phase Two — The Save &amp; Release (onSend)</h3><p>Once the controller has done its work, we need to cache that result and release the lock. Fastify’s onSend hook allows us to inspect the payload right before it leaves the server.</p><pre>async function saveHook(req: FastifyRequest, reply: FastifyReply, payload: any) {<br>    const key = req.headers[IDEMPOTENCY_HEADER];<br>    const lockKey = (req as any).idempotencyLockKey;<br><br>    // Only proceed if we hold the lock<br>    if (key &amp;&amp; lockKey) {<br>      if (reply.statusCode &gt;= 200 &amp;&amp; reply.statusCode &lt; 300) {<br>        // Success: Cache the response AND release lock<br>        const cacheData = JSON.stringify({<br>          statusCode: reply.statusCode,<br>          headers: reply.getHeaders(),<br>          body: payload<br>        });<br>        <br>        await Promise.all([<br>          redis.setex(`idempotency:${key}`, CACHE_TTL, cacheData),<br>          redis.del(lockKey)<br>        ]);<br>      } else {<br>        // Failure: Just release the lock so the client can retry<br>        await redis.del(lockKey);<br>      }<br>    }<br>    return payload;<br>}</pre><figure><img alt="The Dataflow for the Check and Save Phases in Idempotency" src="https://cdn-images-1.medium.com/max/1024/1*GlOcGZtKJvFFqg8lmnvFbQ.png" /><figcaption>The Dataflow for Check and Save Phase in the Idempotency Architecture</figcaption></figure><h3>The “Gotchas”: 3 Issues That Will Break Your API</h3><p>Implementing the logic above is straightforward. However, integrating it into a real-world asynchronous framework introduces subtle bugs.</p><h3>1. The Double Execution Bug</h3><p><strong>The Problem:</strong> Fastify’s onSend hook is not guaranteed to run only once. It can be triggered multiple times for a single request (e.g., during stream serialization). <strong>The Result:</strong> Your code tries to release the Redis lock twice. The first time works; the second time causes logging noise or race conditions. <strong>The Fix:</strong> Implement an execution guard on the reply object to debounce the hook.</p><pre>async function saveHook(req: FastifyRequest, reply: FastifyReply, payload: any) {<br>    // Guard: Has this hook run already?<br>    if ((reply as any)._idempotencyProcessed) return payload;<br>    <br>    // Mark as processed<br>    (reply as any)._idempotencyProcessed = true;<br><br>    // ... execute Redis logic ...<br>}</pre><h3>2. The “Reply Already Sent” Crash</h3><p><strong>The Problem:</strong> In Node.js frameworks, reply.send() does not automatically stop the execution of your function. It simply starts the response stream. If your code continues running (e.g., into a catch block) and tries to send a <em>second</em> response (like a 500 Error), the application will crash with ERR_HTTP_HEADERS_SENT.</p><p><strong>The Fix:</strong> You must explicitly return the result of reply.send().</p><pre>// Controller Logic<br>try {<br>  const result = await createResource(req.body);<br>  <br>  // INCORRECT WAY: Not returning the reply<br>  // reply.code(201).send(result); <br>  // Code continues running here and you get errors...<br>  <br>  // CORRECT WAY:<br>  return reply.code(201).send(result);<br>  // Function exits immediately.<br>  <br>} catch (error) {<br>  // Even with the return above, defensive programming is wise:<br>  if (reply.sent) {<br>    req.log.error(&quot;Error occurred after response sent&quot;);<br>    return; <br>  }<br>  return reply.code(500).send({ error: &quot;Internal Error&quot; });<br>}</pre><h3>3. Redis Library Syntax</h3><p><strong>The Problem:</strong> Libraries like ioredis are strict about argument ordering. Using redis.set(key, val, &quot;NX&quot;, &quot;EX&quot;, 10) might fail silently or throw errors depending on the version. <strong>The Fix:</strong> Always verify the canonical syntax for your client. For ioredis, the correct order for atomic locking is: redis.set(key, value, &quot;EX&quot;, ttl_seconds, &quot;NX&quot;)</p><h3>Testing Your Implementation</h3><p>You cannot rely on manual testing for race conditions. You must write integration tests that simulate concurrency.</p><ul><li><strong>Test Cache Hits:</strong> Send the same request twice sequentially. Assert that the second request returns the exact same ID as the first, and that the database row count is 1.</li><li><strong>Test Race Conditions:</strong> Manually set a lock key in Redis (SET lock:123 ...), then fire a request with that key. Assert that the API returns 409 Conflict.</li></ul><h3>Conclusion</h3><p>Idempotency is one of those features that separates “bootcamp projects” from production systems. By combining Fastify’s lifecycle hooks with Redis’s atomic locking, and being careful with your return statements, you ensure your API is reliable, consistent, and resilient to the chaos of the internet.</p><h3>Resources &amp; Connect</h3><p><strong>Source Code</strong>: The code for this article is part of Permit Workflow Service, a full-stack construction permit workflow platform I’m building. You can explore the full codebase and architecture in my <a href="https://github.com/vijaybkhot/permit-workflow-service">GitHub</a> repository, specifically in the src/hooks/idempotency.ts file.</p><p><strong>Let’s Connect</strong>: I write regularly about backend engineering, system design, and TypeScript. Connect with me on <a href="https://www.linkedin.com/in/vijay-khot/">LinkedIn</a> so you don’t miss the next guide. View my full portfolio and project history <a href="https://www.vijaykhot.com/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4876de266222" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-production-grade-idempotency-with-node-js-fastify-and-redis-4876de266222">Building Production-Grade Idempotency with Node.js, Fastify, and Redis</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling ML Artifacts: A Pattern for S3-Based Model Storage in Production]]></title>
            <link>https://awstip.com/decoupling-ml-artifacts-a-pattern-for-s3-based-model-storage-in-production-cbe89d042ee1?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbe89d042ee1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 23:17:04 GMT</pubDate>
            <atom:updated>2025-12-19T11:44:25.815Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started building the Material Forecasting Engine — a full-stack ML system that predicts volatile construction material prices (Steel, Lumber, Concrete) using FRED economic data — my deployment strategy was straightforward:</p><ol><li>Train models locally (SARIMAX per material)</li><li>Save .pkl artifacts</li><li>Commit artifacts (or otherwise bundle them) with the app</li><li>Deploy everything together</li></ol><p>It worked… until the project grew.</p><p>As model artifacts accumulated, my Docker image size ballooned, deploys slowed down dramatically, and I hit the classic “large artifact” trap: model files behave like data, but I was treating them like source code. I needed an architecture where code deploys are fast and safe, while model artifacts can be updated independently.</p><p>This article walks through the refactor that fixed it: a Hybrid S3 Architecture that decouples application code from model artifacts using a small, environment-aware abstraction layer.</p><p><em>(Scope note: This post focuses on artifact storage architecture and code structure (S3 + adapter pattern), not CI/CD.)</em></p><h3>The Problem: “Baked-In” Models Don’t Scale</h3><p>My initial architecture was effectively a monolith: the API and the ML artifacts lived in the same deployable unit.</p><p><strong>Workflow (old):</strong> Train → package models with the app → deploy a large build artifact</p><p><strong>What broke as the project grew:</strong></p><ul><li><strong>Slow deploys:</strong> A one-line code change forced re-uploading large model layers.</li><li><strong>Tight coupling:</strong> Retraining meant “redeploy the entire app,” even when no code changed.</li><li><strong>Repo friction:</strong> Large artifacts don’t belong in Git, and GitHub’s file-size limits make it painful fast.</li><li><strong>Poor iteration loop:</strong> Model improvements were gated by release mechanics.</li></ul><p>The fix wasn’t “use a different hosting platform.” The fix was making storage and serving artifact-aware.</p><h3>The Target State: A Hybrid Architecture</h3><p>The goal was simple:</p><ul><li>Keep the API container small and easy to build.</li><li>Store heavy .pkl artifacts in object storage.</li><li>Let the API load the right artifact at runtime.</li><li>Avoid hardcoding AWS logic across the codebase.</li><li>Preserve reproducibility (versioning, metadata) instead of creating an “S3 dumping ground.”</li></ul><p>At a high level:</p><ul><li><strong>Code</strong> stays in the deployment artifact (container/build).</li><li><strong>Models + metadata</strong> live in <strong>S3</strong>.</li><li>The app loads models through an abstraction: ArtifactManager.</li></ul><p>This pattern works anywhere you run Python: Heroku, ECS, Kubernetes, Cloud Run, on-prem — S3 is just an endpoint.</p><h3>The Core Idea: The “Artifact Manager” Adapter Pattern</h3><p>I didn’t want S3 logic scattered across training scripts, FastAPI endpoints, service layer code, and tests. Instead, I introduced a single gateway: ArtifactManager.</p><p>It chooses its storage backend based on an environment variable:</p><ul><li><strong>ARTIFACT_STORAGE_MODE=LOCAL</strong> Reads/writes to ml/models/ (fast dev loop, offline-friendly).</li><li><strong>ARTIFACT_STORAGE_MODE=S3</strong> Reads/writes to s3://&lt;bucket&gt;/models/... (production).</li></ul><p><strong>Why this matters</strong></p><p>This tiny abstraction gives you:</p><ul><li><strong>One place</strong> to manage artifact naming, paths, metadata, and error handling.</li><li><strong>One mental model</strong> for code running locally vs in production.</li><li>A clean seam to add features later (versioning, rollback, caching, signing, encryption).</li></ul><h3>Implementation: ArtifactManager.load_model() (Read Path)</h3><p>Below is a simplified version of the S3 streaming approach. The key point: no temp files are required — S3 bytes can be streamed into memory.</p><pre># backend/app/core/artifact_manager.py (simplified)<br>import os<br>from io import BytesIO<br>import boto3<br>import joblib<br>class ArtifactManager:<br>    def __init__(self):<br>        self.mode = os.getenv(&quot;ARTIFACT_STORAGE_MODE&quot;, &quot;LOCAL&quot;).upper()<br>        self.bucket = os.getenv(&quot;S3_BUCKET_NAME&quot;)<br>        if self.mode == &quot;S3&quot;:<br>            # In production, consider IAM roles over static keys.<br>            self.s3_client = boto3.client(&quot;s3&quot;)<br>    def load_model(self, series_id: str):<br>        if self.mode == &quot;LOCAL&quot;:<br>            return joblib.load(f&quot;ml/models/{series_id}.pkl&quot;)<br>        buffer = BytesIO()<br>        key = f&quot;models/{series_id}.pkl&quot;<br>        self.s3_client.download_fileobj(self.bucket, key, buffer)<br>        buffer.seek(0)<br>        return joblib.load(buffer)</pre><p><strong>Two production notes (worth calling out):</strong></p><ul><li><strong>Caching:</strong> In real systems, you typically cache loaded models in memory (or Redis) to avoid repeated S3 reads on every request.</li><li><strong>Versioning &amp; atomic cutover:</strong> You generally do not overwrite models/PPI_STEEL.pkl in-place. You upload versioned artifacts and flip a pointer (more on this below).</li></ul><h3>Implementation: Training Pipeline (Write Path)</h3><p>On the training side, the “win” is that the training job no longer cares where the model ends up.</p><pre># ml/scripts/train_all_models.py (conceptual)<br><br>manager = ArtifactManager()<br><br>model = SARIMAX(df[&quot;value&quot;], ...).fit()<br><br>manifest = {<br>    &quot;series_id&quot;: &quot;PPI_STEEL&quot;,<br>    &quot;trained_at&quot;: &quot;2025-12-14T00:00:00Z&quot;,<br>    &quot;model_type&quot;: &quot;SARIMAX&quot;,<br>    &quot;metrics&quot;: {&quot;mape&quot;: 0.08},<br>    &quot;data_range&quot;: {&quot;start&quot;: &quot;2010-01-01&quot;, &quot;end&quot;: &quot;2025-11-01&quot;},<br>}<br><br>manager.save_model(&quot;PPI_STEEL&quot;, model, manifest)</pre><p><strong>Why metadata matters</strong></p><p>The .pkl is not enough. The manifest lets you answer critical questions later:</p><ul><li>What data range trained this model?</li><li>What metrics did it achieve?</li><li>What hyperparameters were used?</li><li>Which model is currently “production”?</li><li>Can I roll back?</li></ul><p>The difference between “artifact storage” and “MLOps” is governance — metadata is the beginning of governance.</p><h3>Implementation: Serving Predictions (Inference)</h3><p>Once the abstraction exists, your FastAPI code stays clean. The endpoint doesn’t need to know local vs S3.</p><pre># backend/app/api/endpoints/forecast.py (conceptual)<br>@router.get(&quot;/forecast&quot;)<br>def forecast(material_id: str):<br>    manager = ArtifactManager()<br>    model = manager.load_model(material_id)<br>    return generate_forecast(model, ...)</pre><p><strong>Practical caching strategy (recommended):</strong></p><p>A simple approach: load once on first request, store in an in-memory dict keyed by material_id, and optionally refresh after a TTL or via an admin endpoint. This avoids S3 download latency for hot paths while still allowing controlled refresh.</p><h3>The Missing Piece: Versioning + Rollback (Don’t Skip This)</h3><p>If you only take one “senior” lesson from this post, take this: Do not overwrite production artifacts in-place. Version them.</p><p>A robust pattern looks like:</p><ol><li>Upload versioned artifacts:</li></ol><ul><li>models/PPI_STEEL/2025-12-14/model.pkl</li><li>models/PPI_STEEL/2025-12-14/manifest.json</li></ul><p>2. Maintain a small pointer:</p><ul><li>models/PPI_STEEL/prod.json → { &quot;version&quot;: &quot;2025-12-14&quot; }</li></ul><p>Your API loads prod.json, reads the version, then loads the corresponding model.</p><p><strong>Why it matters:</strong></p><ul><li><strong>Atomic cutover:</strong> Switch “prod” pointer only after model + manifest upload completes.</li><li><strong>Rollback:</strong> Point back to the previous version if something goes wrong.</li><li><strong>Auditability:</strong> You can prove which model served predictions on a given day.</li></ul><p>This is the difference between “it worked on my machine” and “I can operate this.”</p><h3>Results: What Improved (and What Actually Changed)</h3><p>After moving artifacts out of the deployable unit:</p><ul><li><strong>Deploys got faster</strong> because the build artifact became much smaller.</li><li><strong>Retraining decoupled from redeploys:</strong> Upload new model artifacts, flip the “production pointer,” and you’re done.</li><li><strong>Iteration speed improved:</strong> Model improvements no longer required a full release cycle.</li></ul><p>This is the main mental shift: <em>Your app becomes a stable serving layer. Your models become versioned data products.</em></p><h3>Security and Cost (Quick, Practical Notes)</h3><p><strong>Credentials</strong> For production, prefer IAM roles (ECS task roles, IRSA on Kubernetes, etc.) over static AWS keys. Apply least privilege: the service generally needs only s3:GetObject for reads (and s3:PutObject if it also trains).</p><p><strong>Cost</strong> S3 is typically cheap for small projects, and AWS offers a free tier for many accounts — but free tier rules can change, so I recommend: checking the current AWS Free Tier page, setting a budget alert, and monitoring bucket size.</p><h3>Conclusion</h3><p>Building the Material Forecasting Engine taught me that ML engineering isn’t only about selecting a better model — it’s about building the plumbing to reliably deliver models into production.</p><p>Baking .pkl files into deployable artifacts works for prototypes. But if you want fast releases, tractable iteration, independent model updates, and an upgrade path toward real MLOps, you need to decouple artifacts from code.</p><p>A small abstraction like ArtifactManager, plus S3-backed storage and versioned manifests, turned a slow, coupled deployment loop into a clean and scalable serving architecture.</p><p><strong>Quick Notes:</strong></p><ul><li>I deployed this project on Heroku + Vercel, but this pattern works the same on ECS/Kubernetes/Cloud Run.</li><li>You can explore the project here: <a href="https://github.com/vijaybkhot/material-forecasting-engine">[Material Forecasting Engine]</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe89d042ee1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/decoupling-ml-artifacts-a-pattern-for-s3-based-model-storage-in-production-cbe89d042ee1">Decoupling ML Artifacts: A Pattern for S3-Based Model Storage in Production</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Engine Factory” Problem: Why Your MLOps Pipeline Needs a Registry]]></title>
            <link>https://medium.com/@vijay-khot/the-engine-factory-problem-why-your-mlops-pipeline-needs-a-registry-04a32eb9b2ef?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a32eb9b2ef</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cloud-infrastructure]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 00:06:00 GMT</pubDate>
            <atom:updated>2025-12-07T00:06:00.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A split-panel infographic illustration titled “THE ‘ENGINE FACTORY’ PROBLEM” contrasting two approaches to managing machine learning models." src="https://cdn-images-1.medium.com/max/1024/1*sInO0N4v5oxjeJDBIAVIuQ.png" /></figure><p>Let me be honest with you. When I started my journey into Machine Learning, I treated my trained models like temporary files.</p><p>I would write a script, train a model, and save it as model.pkl. It felt great. But then, a week later, I would tweak the code, retrain it, and overwrite that same file with a new model.pkl.</p><p>I thought this was fine. I thought I was just “updating” my software. But actually, I was making a massive mistake. I was suffering from “Model Amnesia.”</p><p>Recently, while building my <strong>Material Forecasting Engine</strong> (a system that predicts construction prices), I hit a wall. I realized that if my new model suddenly started giving bad predictions in production, I had no way to go back. I had deleted the old one. I didn’t even know which version of the code produced the old one.</p><p>That is when I learned about <strong>Model Versioning</strong>, and I want to explain it to you using a simple analogy that made it click for me.</p><h3>The Analogy: The Engine Factory</h3><p>Imagine you are running a factory that builds car engines. Every week, your brilliant engineering team designs a new, faster, more efficient engine.</p><p><strong>The Amateur Way (What I was doing):</strong> Your team builds the new “Engine V2.” They are so confident it is better that they immediately take the old “Engine V1,” crush it into scrap metal, and throw it in the trash. Then they install V2 into the customer’s car.</p><p>But what happens if V2 overheats after 100 miles? You panic. You look for V1 to put it back, but it is gone. You crushed it. You have to tell the customer, “Sorry, we have to build a new one from scratch.”</p><p><strong>The Professional Way (MLOps):</strong> Now, imagine a “Logbook” and a “Storage Shelf.”</p><p>When the team builds “Engine V2,” they don’t touch V1. Instead:</p><ol><li>They put V2 on the shelf next to V1.</li><li>They open the Logbook (Registry) and write: <em>“Built Engine V2 on Tuesday. Top speed: 150mph. Built using Blueprint #55.”</em></li><li>Only <em>then</em> do they put V2 in the car.</li></ol><p>If V2 overheats? No problem. You check the Logbook, see that V1 was stable, take V1 off the shelf, and put it back in the car. Service restored.</p><h3>Turning this into Code</h3><p>In my project, I decided to move from the Amateur Way to the Professional Way. I needed a Logbook.</p><p>I didn’t need a complex, expensive tool for this. I just needed a database table. I call this the <strong>Model Registry</strong>.</p><p>I used <strong>PostgreSQL</strong> and <strong>Alembic</strong> (a migration tool) to create a simple table called models. It looks something like this:</p><ul><li><strong>id:</strong> The unique ID of the model.</li><li><strong>name:</strong> What are we predicting? (e.g., PPI_STEEL_SARIMAX).</li><li><strong>version:</strong> A unique tag (e.g., v1.0.2).</li><li><strong>git_sha:</strong> This is crucial. This is the exact commit hash of the code that trained this model.</li><li><strong>metrics:</strong> How accurate was it? (e.g., 92%).</li><li><strong>is_production:</strong> A simple flag. Is this the one currently running?</li></ul><h3>Why does this matter to you?</h3><p>If you are building ML projects to get hired, stop overwriting your models.</p><p>When you implement a Model Registry, you are telling a hiring manager: <strong>“I don’t just build models. I build systems that are safe, reproducible, and reliable.”</strong></p><p>Now, if my forecast for Steel prices looks weird tomorrow, I don’t panic. I just check my Logbook, see exactly what changed, and if needed, I pull the old engine off the shelf.</p><p>That is peace of mind. That is MLOps.</p><p><em>If you found this helpful, feel free to check out the code for my Material Forecasting Engine on </em><a href="https://github.com/vijaybkhot/material-forecasting-engine"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a32eb9b2ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Eval is Evil”: Why You Should Never Store Code in a Database]]></title>
            <link>https://medium.com/@vijay-khot/eval-is-evil-why-you-should-never-store-code-in-a-database-955fb3cfa4cf?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/955fb3cfa4cf</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 20:56:06 GMT</pubDate>
            <atom:updated>2025-12-06T20:56:06.298Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been there: the spec changes at 3pm on a Friday and suddenly your neat validation code looks like a house of cards.</p><p>On my recent project, <strong>Permit Workflow Service</strong>, I sat through that exact spiral. We had dozens of jurisdictions (cities), each with slightly different building codes, and a product team asking for instant flexibility. “Austin needs a 35ft height limit, but NYC needs 75ft. Oh, and can we add a rule about heritage trees next week without a deployment?”</p><p>My first instinct was the lazy one: <em>Why not just store the rule logic as a string in the database, </em><em>eval() it at runtime, and go home?</em></p><p>Fortunately, I stopped myself. Here is the story of why that path is a trap, and the boring, reliable pattern I used to fix it.</p><h3>The Siren Song of eval()</h3><p>If you haven’t tangled with dynamic code execution before, it is practically irresistible in the moment. Imagine storing this string in your Postgres database:</p><pre>&quot;return context.buildingHeight &lt;= 35;&quot;</pre><p>When a request comes in, you fetch the string, run it, and boom — instant validation. No code changes, no deployments. Infinite flexibility.</p><p>But here is the reality of that decision:</p><ul><li><strong>Security Nightmares (RCE):</strong> If a hacker (or a disgruntled employee) gains write access to your database, they don’t just change data. They change <em>logic</em>. They can update that string to require(&#39;fs&#39;).rmdirSync(&#39;/&#39;) or send your environment variables to a remote server. Your database just became a root shell.</li><li><strong>Stack Traces That Lie:</strong> When dynamic code crashes, your logs point to &lt;anonymous&gt; at line 1. Good luck debugging that at 2am.</li><li><strong>Type Safety? Gone:</strong> I use TypeScript for a reason. I want the compiler to yell at me if I type ctx.hieght instead of ctx.height. If my logic is just a string in a database column, the compiler can&#39;t help me.</li></ul><h3>The Realization: Separate the “What” from the “How”</h3><p>The breakthrough came when I realized I was conflating two things. I didn’t need to store <em>how</em> to calculate a rule in the database. I only needed to store <em>which</em> rule to apply.</p><p><strong>Data belongs in the database. Logic belongs in the code.</strong></p><p>This is essentially the <strong>Strategy Pattern</strong></p><p>The database tells the application <em>what</em> to do (e.g., “Apply the Austin Impervious Cover Rule”), and the code knows <em>how</em> to execute that math.</p><h3>The Setup</h3><p>I modeled the data to handle the relationships:</p><ul><li><strong>Jurisdiction:</strong> The city (e.g., “Austin, TX”).</li><li><strong>RuleSet:</strong> A versioned collection of rules active for a specific time.</li><li><strong>Rule:</strong> The metadata. It has an ID, a severity (Required/Warning), and crucially, a <strong>Key</strong> (e.g., ATX_IMPERVIOUS_COVER).</li></ul><p>That key is the magic link. It’s the contract between my database and my code.</p><h3>The Implementation Map</h3><p>Instead of eval, I created a &quot;Implementation Map&quot; in my TypeScript code. This acts as a dictionary of strategies.</p><pre>// src/core/rules/ruleImplementations.ts<br>type RuleLogicFn = (context: RuleContext) =&gt; RuleResult;<br>export const ruleImplementations: Record&lt;string, RuleLogicFn&gt; = {<br>  // Strategy 1: The Austin Logic<br>  &#39;ATX_IMPERVIOUS_COVER&#39;: (context) =&gt; {<br>    // We calculate logic safely in compiled code<br>    const ratio = context.imperviousArea / context.lotArea;<br>    <br>    return {<br>      passed: ratio &lt;= 0.45,<br>      // Logic determines the message, safe and typed<br>      message: ratio &lt;= 0.45 <br>        ? &quot;Compliance met&quot; <br>        : `Impervious cover (${(ratio * 100).toFixed(1)}%) exceeds 45% limit`<br>    };<br>  },</pre><pre>// Strategy 2: The NYC Logic<br>  &#39;NYC_FIRE_STANDPIPE&#39;: (context) =&gt; {<br>    return {<br>      passed: context.buildingHeight &lt;= 75,<br>      message: context.buildingHeight &lt;= 75 <br>        ? &quot;No standpipe required&quot; <br>        : &quot;Standpipes required for buildings over 75ft.&quot;<br>    };<br>  }<br>};</pre><h3>The Engine: The Orchestrator</h3><p>My rule engine (evaluateRules.ts) became a simple orchestrator. It doesn&#39;t know how to check for impervious cover. It just knows how to look things up.</p><ul><li><strong>Fetch:</strong> It queries the database for the active RuleSet for the given jurisdiction.</li><li><strong>Iterate:</strong> It loops through the rule records found in the DB.</li><li><strong>Lookup:</strong> It uses the rule.key to grab the corresponding function from the ruleImplementations map.</li><li><strong>Execute:</strong> It runs that safe, pre-compiled TypeScript function.</li></ul><pre>// Inside evaluateRules.ts (Simplified)<br>for (const dbRule of ruleSet.rules) {<br>  const logicFn = ruleImplementations[dbRule.key];<br><br>// Graceful Fallback: Don&#39;t crash if code is missing!<br>  if (!logicFn) {<br>    console.warn(`No implementation found for rule key: ${dbRule.key}`);<br>    results.push({ <br>      ruleKey: dbRule.key, <br>      passed: false, <br>      message: &quot;System Error: Rule logic missing&quot;, <br>      severity: dbRule.severity <br>    });<br>    continue;<br>  }<br><br><br>// Safe Execution<br>  const result = logicFn(context);<br>  results.push({ ...result, severity: dbRule.severity });<br>}</pre><h3>A Real Midnight Saved</h3><p>Here is why this matters. We actually had a scenario where a requirement changed — a city decided to change a warning rule to a blocker (Required) overnight.</p><p>If the logic and configuration were hardcoded together, I would have had to push a hotfix deployment at an ungodly hour. Because we used this pattern, I just ran a SQL query to update the severity column in the database from WARNING to REQUIRED. The next request picked up the change instantly. No deployment, no downtime, and I stayed in bed.</p><h3>Why This Works (and a few Gotchas)</h3><p>This hybrid approach gives you the best of both worlds:</p><ul><li><strong>Declarative:</strong> You declare the <em>desired state</em> in the DB.</li><li><strong>Safe:</strong> The code is immutable at runtime. You cannot inject malicious JavaScript.</li><li><strong>Fast:</strong> The functions are compiled by the engine at startup. There is no runtime parsing overhead.</li><li><strong>Versioned:</strong> Since the logic is in Git, I can see exactly <em>who</em> changed the math and <em>when</em> via git blame.</li></ul><p><strong>The Gotchas:</strong></p><ul><li><strong>Missing Implementations:</strong> You must handle the case where the DB has a key like NEW_RULE but your code hasn&#39;t been deployed with that function yet. My engine logs a warning and fails gracefully rather than crashing the request.</li><li><strong>Key Management:</strong> You need a naming convention (like CITY_FEATURE_NAME) so you don&#39;t accidentally reuse keys.</li></ul><h3>The Takeaway</h3><p>Building this into my project taught me that “flexibility” doesn’t have to mean “chaos.”</p><p>By using the Strategy Pattern, I built a system where the business rules are dynamic (I can turn them on/off or change severity in the DB), but the execution is rock-solid and type-safe.</p><p>So, next time you feel the urge to store code in your database… don’t. Build a map instead. Your future self (and your security audit team) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955fb3cfa4cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrape Smarter: The Browser Trick That Cracked 2,000 Records in 45 Minutes]]></title>
            <link>https://blog.stackademic.com/stop-scraping-the-ui-how-i-saved-days-of-work-by-listening-to-the-browser-fffeaf65c886?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffeaf65c886</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 03:11:30 GMT</pubDate>
            <atom:updated>2025-12-28T06:21:26.980Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detective story about hidden APIs, hard limits, and the “Pincer Maneuver” that beat them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRaAwb5mumXG80dNM0_0Dg.png" /><figcaption>Peering into the digital shadows: A developer uncovers hidden JSON APIs in the browser, then deploys the ‘pincer maneuver’ — sorting data ascending and descending — to bypass offset limits and unlock the full dataset for a Python-powered scrape.</figcaption></figure><p>My teammate looked exhausted.</p><p>He was staring at a table on a membership portal containing about 2,000 records. We needed to extract all of them, specifically the phone numbers. The problem? The phone numbers were hidden. You had to click “View Details” on every single row to see them.</p><p>He was building a Selenium script to automate it: <em>Open browser -&gt; Click Row -&gt; Scrape Number -&gt; Go Back -&gt; Next Page -&gt; Repeat.</em></p><p>It was slow, fragile, and kept crashing after a few pages. He asked for help fixing the script. But looking at the 100+ pages of data, I realized the problem wasn’t the script. The problem was that we were trying to mimic a human, instead of thinking like a computer.</p><p>I decided to look under the hood.</p><h4>The Discovery</h4><p>Modern websites are essentially just pretty masks over raw data. When you load a table, the website isn’t painting those rows from scratch; it’s usually asking a server for a list of clean data (JSON) and then drawing it for you.</p><p>I opened the <strong>Chrome Developer Tools</strong> (F12), went to the <strong>Network Tab</strong>, and hit refresh.</p><p>I watched the traffic scroll by …images, CSS, scripts … until I saw it. A request returning a massive JSON object. I clicked on it, expanded the preview, and there it was: the “hidden” phone number.</p><p>The website <em>had</em> the data all along; it just wasn’t showing it to us. We didn’t need to click “View Details” 2,000 times. We just needed to ask the server for this JSON file.</p><h4>The Wall</h4><p>I copied the request into <strong>Postman</strong> so I could play with the parameters.</p><p>My first thought was greedy: <em>“Just give me everything.”</em> I changed the limit parameter to 5,000. The Server replied immediately: <strong>&quot;Error. Limit Exceeded.&quot;</strong></p><p>Fair enough. I lowered the number until it worked. It turned out the magic number was <strong>789 records</strong>. Anything higher crashed the request.</p><ul><li>Attempt 1: Get records 0–789. <strong>Success.</strong></li><li>Attempt 2: Get records 790–1578. <strong>Success.</strong></li><li>Attempt 3: Get records 1579+. <strong>CRASH.</strong></li></ul><p>I hit a wall. The server returned a specific, nasty error: <strong>“SOQL Offset Limit.”</strong></p><p>Basically, the database was saying: <em>“For performance reasons, I am not allowed to look past the 2,000th record. You cannot scroll this far.”</em></p><p>We had 2,000 records. I had 80% of the data, but the last 20% was locked behind this invisible wall. I couldn’t page forward any further.</p><h4>The “Pincer Maneuver”</h4><p>I stared at the error. I couldn’t ask the server to skip to record 2,001. But then I realized I didn’t need to change the <em>position</em>; I could change the <em>direction</em>.</p><p>If I couldn’t reach the end of the line from the front, why not start from the back?</p><ol><li>I pulled the first 1,500 records sorted <strong>A-Z (Ascending)</strong>.</li><li>I went into the API payload and changed one tiny parameter: sortOrder: &quot;DESC&quot;.</li><li>I pulled the list again, this time sorted <strong>Z-A (Descending)</strong>.</li></ol><p>It worked. The server happily handed over the records starting from “Z,” “Y,” and “X.”</p><p>I had the top of the list, and I had the bottom of the list. The middle overlapped, but that didn’t matter.</p><h4>The Result</h4><p>I took my three JSON files, threw them into a simple Python script to merge them and remove duplicates, and exported a clean CSV.</p><ul><li><strong>Total time:</strong> 45 minutes.</li><li><strong>Total clicks:</strong> 0.</li><li><strong>Total records:</strong> 100% complete.</li></ul><h4>The Takeaway</h4><p>As developers, we often reach for the tools we know — like Selenium — to brute force a problem. But sometimes, the UI is a trap.</p><p>Next time you’re faced with a scraping task, don’t look at the screen. Look at the network. The API is usually whispering the answers you need; you just have to listen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffeaf65c886" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/stop-scraping-the-ui-how-i-saved-days-of-work-by-listening-to-the-browser-fffeaf65c886">Scrape Smarter: The Browser Trick That Cracked 2,000 Records in 45 Minutes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS gave me a bill, but DevOps gave me a lesson!  (From $$-Costly to $0-Free Deployment)]]></title>
            <link>https://medium.com/@vijay-khot/aws-gave-me-a-bill-but-devops-gave-me-a-lesson-from-costly-to-0-free-deployment-9fb0bcb2ddea?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fb0bcb2ddea</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 11:31:04 GMT</pubDate>
            <atom:updated>2025-12-25T15:04:44.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdNoAEE4L7elab98YMrq6A.png" /><figcaption>Construction Materials Forecasting Dashboard</figcaption></figure><h4><strong>The Context:</strong></h4><p>So, I built this full-stack <strong>Material Forecasting Engine</strong> — Next.JS frontend, FastAPI backend, Machine Learning models (SARIMAX), Postgres, Redis… the full works. A proper “Industry Grade” project.</p><p>Naturally, I thought, <em>“Okay, let’s deploy this on AWS ECS Fargate. That’s what the big companies use, right?”</em></p><p>I set up everything. VPCs, Subnets, Load Balancers, the whole heavy infrastructure. And then… <strong>The Bill arrived.</strong></p><p>It turns out, the AWS “Free Tier” is a bit like a buffet where the plates are free, but you pay for the spoons. I was getting charged for <strong>VPC Endpoints</strong> and <strong>Public IPs</strong> just to let my private services talk to each other securely.</p><p>I realized: For a portfolio project, I don’t need enterprise-level billing. I need smart engineering. So, I pivoted. I moved the whole stack to a <strong>Vercel + Heroku</strong> architecture using the Herouku Student Pack, and brought the cost down to <strong>exactly $0.00</strong>.</p><p>Here is the knowledge I gained from battling Docker, Heroku, and Database migrations for 48 hours straight.</p><h4>The Explanation :</h4><p>Frow AWS, we shifted to a decoupled architecture.</p><ol><li><strong>Frontend:</strong> Deployed on <strong>Vercel</strong> (Best-in-class for Next.js).</li><li><strong>Backend:</strong> Deployed on <strong>Heroku</strong> using their Container Registry.</li><li><strong>Database/Cache:</strong> Heroku Postgres &amp; Redis (Managed Add-ons).</li></ol><p>But the real learning was not the platform; it was the <strong>Process</strong>.</p><p><strong>1. The “Architect vs. Movers” Analogy</strong> I faced a crash loop where my app kept saying Table not found. Why? Because my data ingestion script (The Mover) was trying to insert data before the database table was even created.</p><ul><li><strong>Lesson:</strong> Always respect the order of operations.</li><li><strong>The Architect (Alembic):</strong> Run migrations first. Build the house.</li><li><strong>The Mover (Script):</strong> Move the furniture (data) in second.</li><li>I fixed this by chaining commands in heroku.yml: release: alembic upgrade head &amp;&amp; python ingest.py. Sorted!</li></ul><p><strong>2. The Docker “Context” Trap</strong> I have a monorepo. My Dockerfile was in backend/, but it needed to copy ML models from the root/ folder. Docker kept screaming &quot;File Not Found.&quot;</p><ul><li><strong>Lesson:</strong> Docker is strict, boss. If you tell it the build context is ./backend, it puts blinders on and cannot see the folder above it.</li><li><strong>Fix:</strong> We moved the Dockerfile to the <strong>Root</strong> and updated the build context to .. Now Docker can see everything.</li></ul><h4>Q &amp; A (The “Viva” Round):</h4><p><strong>Q: Why not just push the code to Heroku directly via GitHub? Why use Container Registry?</strong></p><p><strong>A:</strong> Ah, good question. GitHub has a strict <strong>100MB file limit</strong>. My trained Machine Learning models (.pkl files) were huge. I couldn&#39;t push them to Git without paying for LFS. <strong>The Solution:</strong> I built the Docker image <strong>locally</strong> on my laptop (where the models exist), &quot;baked&quot; the models into the image, and pushed the <em>whole image</em> directly to Heroku. GitHub holds the code; Heroku holds the heavy artifacts. Best of both worlds.</p><p><strong>Q: What was the most annoying error?</strong> <strong>A:</strong> 504 Gateway Timeout mixed with CORS Error. Trust me, it’s rarely actually CORS. It was my API container crashing silently because of a missing Python dependency (psycopg2-binary). The Load Balancer timed out, and the browser assumed it was a CORS issue. <strong>Lesson:</strong> Always check the server logs (heroku logs --tail) before you blame the frontend code!</p><p><strong>Conclusion:</strong> Deployment is not just “uploading code.” It is about managing state, networking, and dependencies. I went from burning cash on AWS to a stable, robust, free deployment on Heroku/Vercel, and I learned more about DevOps in these 2 days than in months of coding.</p><p>Now, the <strong>Material Forecasting Engine</strong> is live, always-on, and predicting steel prices like a champ! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fb0bcb2ddea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Prometheus Metrics Work: The 5 Questions I Wish I’d Asked Sooner]]></title>
            <link>https://medium.com/@vijay-khot/your-application-is-talking-are-you-listening-a-beginners-guide-to-metrics-with-prometheus-3780f5ae7d2a?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/3780f5ae7d2a</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 21:45:00 GMT</pubDate>
            <atom:updated>2025-12-27T00:39:28.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An abstract digital landscape where multiple, distinct application nodes are emitting faint streams of glowing data particles (metrics). From a central, powerful Prometheus logo beacon, beams of light extend out to “scrape” or collect these particles. The beacon then organizes the incoming light trails into a structured, stored history. The image should convey a sense of massive scale, automated collection, and the power of a central monitoring system." src="https://cdn-images-1.medium.com/max/1011/1*13riZb0kLcwEcgj8rUc2Zw.jpeg" /><figcaption>The “Prometheus Beacon”</figcaption></figure><h3><em>A beginner’s guide to counters, scraping, rate(), and the architecture behind modern observability.</em></h3><p>Your application is live. Suddenly, users report it’s slow. Is it the database? A spike in traffic? An error in a new feature? Without data, you’re just guessing.</p><p>This is where metrics come in. Metrics are the vital signs of your application — like a heart rate monitor, a thermometer, or a speedometer. They give you the <em>observability</em> to move from guessing to knowing.</p><p>As I’ve been building out a backend service, I’ve implemented a modern metrics stack using prom-client and making it compatible with Prometheus. Here’s a simple guide to what these tools are, why you need them, and how they work, followed by answers to the tricky questions that came up along the way.</p><h3>What, Why, and How in 60 Seconds</h3><ul><li><strong>What are we doing?</strong> We’re adding “gauges” to our application using a library like prom-client. These gauges, called metrics (like Counters), track events such as &quot;submissions created&quot; or &quot;jobs failed.&quot;</li><li><strong>Why are we doing it?</strong> To get a real-time pulse of our application’s health and performance. 🩺</li><li><strong>How does it work?</strong> Our application exposes these metrics on a special webpage (an API endpoint like /metrics). A separate system called Prometheus then reads (or &quot;scrapes&quot;) this page every few seconds to collect and store the data for analysis and alerting.</li></ul><h3>Common Questions &amp; “Aha!” Moments</h3><p>Here are the questions that helped me truly understand how this system works.</p><p><strong>Q1: Okay, but where are the metric counts actually stored?</strong></p><p><strong>A1:</strong> The counts are stored directly in your application’s memory. When you create a counter with prom-client and call .inc(), you&#39;re just increasing a number held in a variable. This makes it incredibly fast. But it also means that if your application restarts, the counter resets to zero.</p><p><strong>Q2: Wait, if the counter resets when my app restarts, isn’t that a huge problem?</strong></p><p><strong>A2:</strong> This was my biggest “aha!” moment. It’s not a problem at all; <strong>it’s by design.</strong></p><p>You almost never care about the total, raw value of a counter (like an odometer). You care about the <em>rate of change</em> (like a speedometer). Prometheus has a powerful function called rate() that automatically calculates this for you.</p><p>rate() is smart enough to detect when a counter resets to zero and handles it correctly. So, even if one of your app instances restarts, Prometheus can still accurately tell you the rate of submissions per minute.</p><p><strong>Q3: Does my app need to tell Prometheus when it started for the </strong><strong>rate() to work?</strong></p><p><strong>A3:</strong> No. <strong>Prometheus is the timekeeper.</strong> When Prometheus scrapes your /metrics endpoint, it records the value and the exact timestamp of the scrape. It calculates the rate by comparing the change in value and the change in time between its own scrapes, completely independent of your application&#39;s uptime.</p><p><strong>Q4: So my app isn’t running Prometheus, it’s just <em>compatible</em> with it?</strong></p><p><strong>A4:</strong> Exactly! This is the key architectural concept.</p><ul><li>Your application is a <strong>Prometheus target</strong>. Its only job is to expose the current metrics on the /metrics endpoint.</li><li><strong>Prometheus</strong> is a completely separate system that you run. Its job is to collect, store, query, and alert on the data from your application (and many others).</li></ul><p><strong>Q5: How does this look in a real-world deployment?</strong></p><p><strong>A5:</strong> You would typically deploy multiple copies (containers) of your application for reliability. You would then run one central Prometheus server. Using “service discovery,” Prometheus would automatically find all your running app containers and start scraping the /metrics endpoint from each one, aggregating all the data in its own database.</p><h3>Final Thoughts</h3><p>The beauty of this system is the <strong>separation of concerns</strong>. Your app’s job is simple: keep track of what’s happening <em>right now</em>. Prometheus’s job is complex: remember the past, spot trends, and alert you about the future.</p><p>This approach is the foundation of modern monitoring and observability.</p><h3>Resources &amp; Connect</h3><p><strong>Source Code</strong>: The code for this article is part of Permit Workflow Service, a full-stack construction permit workflow platform I’m building. You can explore the full codebase and architecture in my <a href="https://github.com/vijaybkhot/permit-workflow-service">GitHub</a> repository.</p><p><strong>Let’s Connect</strong>: I write regularly about backend engineering, system design, and TypeScript. Connect with me on <a href="https://www.linkedin.com/in/vijay-khot/">LinkedIn</a> so you don’t miss the next guide.</p><p><strong>Work With Me</strong>: I’m a Backend Engineer specializing in resilient distributed systems and currently open to new opportunities. View my full portfolio and project history <a href="https://www.vijaykhot.com/">here</a>.</p><p>#Metrics #Observability #Prometheus #DevOps #Backend #NodeJS #SystemDesign #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3780f5ae7d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Making Users Wait: A Simple Guide to Job Queues (and Restaurant Kitchens)]]></title>
            <link>https://medium.com/@vijay-khot/stop-making-users-wait-a-simple-guide-to-job-queues-and-restaurant-kitchens-9d18f06015ee?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d18f06015ee</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[bullmq]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 18:49:39 GMT</pubDate>
            <atom:updated>2025-10-12T18:49:39.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IC9LXXEaWNAB3_mZ" /></figure><p>We’ve all been there. You click a button on a website-like “Generate Report”-stare at a loading spinner for an eternity, and then… timeout. It’s a terrible user experience, and it’s a sign that the application’s “kitchen” is completely overwhelmed.</p><p>What if the waiter could take your order, confirm it’s been received, and let you relax while the chefs handle the complex cooking in the background? That’s exactly what a job queue does for your app.</p><p>This isn’t just theory. I ran straight into this problem while building my own permit workflow service. Learning about job queues was a game-changer, so I wanted to share what I learned through the lens of a simple restaurant analogy.</p><h4><strong>The Analogy: A Busy Restaurant Kitchen</strong></h4><ul><li><strong>The Waiter (Your API Endpoint) :</strong> On the front lines. Fast, responsive, and talks directly to the customer. Their job is to take the order and get back to the customer-not to cook the meal.</li><li><strong>The Ticket Spike (The Job Queue — e.g., Redis) :</strong> The simple, reliable “to-do list” for the kitchen. Orders are handled first-in, first-out.</li><li><strong>The Chef (The Worker):</strong> The background process that pulls a ticket from the spike and does the actual, time-consuming work (the cooking).</li></ul><p>With that in mind, let’s tackle the questions that usually come up.</p><h4><strong>Q1. So, what is a job queue, really?</strong></h4><p><strong>A1:</strong> It’s a system that lets you hand off slow or heavy tasks to be processed in the background. Instead of forcing a user to wait, your app just adds a “job” to a to-do list (the queue) and immediately tells the user, “Got it! We’re on it.” A library like BullMQ gives you the tools to manage this whole process.</p><h4><strong>Q2. Why can’t I just do the task in the API request?</strong></h4><p><strong>A2:</strong> This is the big one. Why not just have the waiter cook the meal? There are two huge reasons:</p><ol><li><strong>User Experience:</strong> An API request has a very short lifespan (maybe 30 seconds). A task like crunching numbers for a report can take minutes. Doing it in the request means a long, frustrating wait and a high chance of the request timing out.</li><li><strong>Reliability:</strong> If your server crashes while “cooking,” the work is lost forever. But if the job is on a persistent ticket spike (like Redis), a restarted worker can just pick the ticket right back up and try again. It guarantees the work eventually gets done.</li></ol><h4><strong>Q3. What’s the difference between a Job Name and a Job ID?</strong></h4><p><strong>A3: </strong>Okay, this one really tripped me up at first.</p><ul><li>The Job Name is the category of work. Think of it as a dish on the menu, like ‘Steak Frites’.</li><li>The Job ID is the unique ticket number for a single order of that dish, like ‘Order #101’.</li></ul><p>Every time a user requests a PDF, you add a job with the name ‘generate-pdf’, and BullMQ gives it a new, unique ID.</p><p><strong>The Waiter (Your API):</strong></p><pre> // Add a job named &#39;generate-pdf&#39; to the queue <br>await packetQueue.add(&#39;generate-pdf&#39;, { submissionId: &#39;abc-123&#39; });</pre><h4><strong>Q4:Why give a job a name if it’s not the unique ID?</strong></h4><p><strong>A4: </strong>The name is for routing. It tells the chef what “recipe” to follow. A single worker process can be trained to handle several different jobs, and it uses the job’s name to decide which block of code to run.</p><p><strong>The Chef (Your Worker):</strong></p><pre>new Worker(&#39;dinner-orders&#39;, async (job) =&gt; { <br>    if (job.name === &#39;Cook Steak&#39;) { <br>       // ... follow the steak recipe <br>    } else if (job.name === &#39;Prep Salad&#39;) { <br>       // ... follow the salad recipe <br>    } <br> });</pre><h4><strong>Q5: Is a Worker like a webhook?</strong></h4><p><strong>A5: </strong>Not quite. A webhook is a “push” system-an external service pushes data to you when it’s ready. A worker is a “pull” system-it’s constantly checking the queue and pulling the next job when it’s free.</p><h4>Q6: Can one worker handle multiple queues?</h4><p><strong>A6: </strong>Nope. A worker is a specialist. It listens to one queue only. If you have a queue for “Dinner Orders” and another for “Dessert Orders,” you need two separate workers: a line cook and a pastry chef.</p><h4>Key Takeaways:</h4><p>Putting a real queue system in place is a massive leap toward building professional, scalable apps. It’s the difference between a food truck and a full-service restaurant. You get:</p><p>✅ Better User Experience: No more angry customers staring at loading spinners.</p><p>✅ Increased Reliability: Dropped orders can be retried automatically.</p><p>✅ Scalability: If the restaurant gets busy, you can just hire more “chefs” (workers) without slowing down your “waiters” (API).</p><p>I’m using this exact setup in my permit workflow project, and it has completely changed how I think about building apps.</p><p>How have you used job queues in your projects? Share your favorite analogies in the comments!</p><p>#SoftwareDevelopment #WebDevelopment #Backend #NodeJS #TypeScript #Redis #BullMQ #SystemDesign #TechExplained</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/stop-making-users-wait-simple-guide-job-queues-restaurant-vijay-khot-scake/?trackingId=0ESSjtD4Tt%2BDxXxNe5dUpg%3D%3D"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d18f06015ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Forecasting Model Got Worse When I Gave It More Data. Here’s Why.]]></title>
            <link>https://medium.com/@vijay-khot/my-forecasting-model-got-worse-when-i-gave-it-more-data-heres-why-4ce443e5681e?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce443e5681e</guid>
            <category><![CDATA[contech]]></category>
            <category><![CDATA[ai-in-construction]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 16:52:26 GMT</pubDate>
            <atom:updated>2025-10-12T16:52:26.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>An honest look at the pitfalls of using external regressors with Prophet for time-series forecasting.</h4><figure><img alt="A photorealistic, high-detail image of a sleek, modern robot (representing the Prophet model) standing in front of a complex holographic dashboard." src="https://cdn-images-1.medium.com/max/1014/1*KsZhQT9Pj8YHyEmv-G8-Pg.png" /></figure><p>In my journey to build a forecasting engine for construction prices, I had a clear winner from my last round of tests: a classic statistical model called Exponential Smoothing. But I had a nagging hypothesis. My other model, the more modern Prophet, had lost the race. What if it lost because it didn’t have enough information?</p><p>This led me to my next experiment: enhancing the Prophet model with <strong>external regressors</strong>. I thought that by giving the model more context, I could build an even more accurate forecast.</p><p>The results were not what I expected.</p><h4>What Are External Regressors, Anyway?</h4><p>An external regressor is simply another time-series variable that you believe influences the variable you’re trying to predict.</p><p><strong>A simple analogy:</strong> If you want to forecast ice cream sales (your target), it would be incredibly helpful to also know the weather forecast (your regressor). A model can learn the relationship: “when the temperature is high, sales are also high.”</p><p>In my case, my target was steel prices. I hypothesized that HOUSING_STARTS, CPI_ALL (inflation), and the FED_FUNDS_RATE (interest rates) could act as my &quot;weather forecast.&quot;</p><h4>The Experiment and the Surprising Result</h4><p>Using Prophet’s .add_regressor() method, I trained a new model that included all three of these economic indicators. My initial hypothesis was that this new, more knowledgeable model would easily beat my previous champion.</p><p><strong>I was wrong.</strong> The result was dramatically worse. The forecast error jumped from <strong>~11%</strong> (for the simple Prophet) to a staggering <strong>~35%</strong>.</p><p>After some more digging, I ran a second experiment using <em>only</em> HOUSING_STARTS as a regressor. The result was much better at <strong>~12% error</strong>, but still couldn&#39;t beat the original champion, Exponential Smoothing.</p><p>Here’s the final ranking of all the models I’ve tested:</p><pre>Model                                        sMAPE (Error %)<br>Exponential Smoothing                          4.72%<br>Prophet (Simple)                               11.30%<br>Prophet with Regressors (Housing Starts only)  12.43%<br>Naive                                          14.73%<br>... ...<br>Prophet with Regressors (All three)            34.79%</pre><h4>A Q&amp;A From My Learning Journey</h4><p>The most valuable part of this experiment wasn’t the final score, but the problems I had to solve along the way. Here are some of the questions that came up.</p><p><strong>Q1: My first attempt to add regressors produced NaN (Not a Number) errors. Why?</strong></p><p>A1: I discovered this was a data problem. The different time series (steel vs. housing starts) didn’t all cover the exact same date range. When I merged them, this created blank spots (NaNs) in the data. The fix was to use Forward Fill (.ffill()), a technique that fills any blanks by carrying forward the last known value.</p><p><strong>Q2: I saw the .pivot() function in pandas. What does that do?</strong></p><p>A2: This was a cool discovery. The .pivot() function is a powerful tool for reshaping data. My raw data was in a “long” format, like a list of transactions. Pivot transforms it into a “wide” format, like a spreadsheet, where each time series gets its own column. This was essential for aligning all my data by date.</p><p><strong>Q3: Even after fixing the data, my final metrics were still NaN. What happened?</strong></p><p>A3: This was the trickiest problem. The NaNs were caused by an index misalignment. My “actual values” DataFrame had a time-series index (e.g., rows numbered 500–523), but the “forecast” DataFrame had a default index (rows 0–23). When I tried to compare them, pandas couldn’t find any matching index labels and returned NaN. The solution was to explicitly align both tables on the date column before calculating the metrics, ensuring a perfect one-to-one comparison.</p><h3>Conclusion: The Biggest Lesson</h3><p>This “failed” experiment was one of my most valuable successes so far. It proved a critical lesson in machine learning: <strong>more data is not always better data</strong>.</p><p>The features you add must have a true, meaningful relationship with what you’re trying to predict. This experiment showed that HOUSING_STARTS had a real signal, but the other variables were just adding &quot;noise&quot; that confused the model. With a clear champion model now fully tested, I&#39;m ready to move on to the final validation and deployment stages.</p><p>#DataScience #MachineLearning #TimeSeries #Forecasting #Prophet #FeatureEngineering #Python #DataAnalysis #PredictiveAnalytics</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce443e5681e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Cars and Smart Students: A Beginner’s Guide to Advanced Forecasting Models]]></title>
            <link>https://medium.com/@vijay-khot/automatic-cars-and-smart-students-a-beginners-guide-to-advanced-forecasting-models-208691e4aecf?source=rss-3244100d2325------2</link>
            <guid isPermaLink="false">https://medium.com/p/208691e4aecf</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[contech]]></category>
            <dc:creator><![CDATA[Vijay Khot]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 14:19:28 GMT</pubDate>
            <atom:updated>2025-10-11T14:19:28.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A photorealistic image of a data scientist’s futuristic control room" src="https://cdn-images-1.medium.com/max/1024/1*fvw1uuYWjHVztcGS-Y0eNg.png" /></figure><p>In my last sprint, I set a benchmark for my project on forecasting construction material prices. Before you can prove a sophisticated model is any good, you need to know the “score to beat.” This is where simple, <strong>“common sense” models</strong> come in.</p><p>These aren’t fancy AI; they’re basic rules of thumb that answer questions like:</p><ul><li>What if we just guess next month’s price will be the same as <strong>this month’s price</strong>? (This is the <strong>‘Naive’</strong> model).</li><li>What if we guess it will be the same as the price from <strong>this month last year</strong>? (The <strong>‘Seasonal Naive’</strong> model).</li><li>What if we just average the <strong>last few months</strong>? (The <strong>‘Moving Average’</strong> model).</li></ul><p>Running these simple checks showed that a basic guess would have an error rate of about <strong>15%</strong>. The big question was: can a more sophisticated approach do better?</p><p>This week, I dove into the world of advanced forecasting to find out. I learned that these complex models aren’t magic; they’re just different tools for different jobs. I like to think of them as a “Smart Student” and an “Automatic Car.”</p><h4>The “Smart Student”: Exponential Smoothing</h4><p>First, I tried a classic statistical method called <strong>Exponential Smoothing</strong> (specifically, the Holt-Winters variant).</p><p><strong>What it is:</strong> This model is like a very smart student. It doesn’t just look at the last value. It systematically learns three things from the historical data:</p><ol><li>The baseline <strong>level</strong> of the prices.</li><li>The overall <strong>trend</strong> (are prices generally going up or down?).</li><li>The <strong>seasonality</strong> (is there a repeating yearly pattern?).</li></ol><p><strong>How it works:</strong> I fed it my raw training data and gave it simple instructions: assume the trend and seasonality are additive and that the seasonal pattern repeats every 12 months. The model then &quot;fit&quot; itself to the data, learning the optimal parameters for these components.</p><h4>The “Automatic Car”: Facebook’s Prophet</h4><p>Next, I used <strong>Prophet</strong>, a popular forecasting library developed by Meta (Facebook).</p><p><strong>What it is:</strong> If Exponential Smoothing is a smart student you have to give instructions to, Prophet is like a self-driving, <strong>automatic car</strong>. It’s designed to handle most of the hard work for you.</p><p><strong>How it works:</strong> You just give it the data in a simple format (with a ds column for dates and a y column for values), and its powerful internal engine automatically figures out the trend, seasonality, and even holidays. It also provides built-in &quot;uncertainty intervals&quot;—a best-case/worst-case range for the forecast.</p><h4>The Moment of Truth: The Results</h4><p>After training both models, I compared their performance against my simple baselines. The results were dramatic.</p><pre>Models                   MAPE          MASE<br><br>Exponential Smoothing    4.72%         5.98<br>Prophet                  11.30%        15.02<br>Naive                    14.73%        20.16<br>Seasonal Naive           15.30%        21.05<br>Moving Average           15.32%        21.05</pre><p>The key takeaway was clear: <strong>Exponential Smoothing was the winner</strong>, reducing my forecast error from ~15% down to ~5%! This was a huge validation that a proper modeling approach adds real value.</p><h3>A Q&amp;A From My Learning Journey</h3><p><strong>Q: I spent a whole sprint on “Feature Engineering” (making the data stationary, creating lags). Why didn’t we use that for Prophet?</strong></p><p><strong>A:</strong> This was the biggest “question!” I had. I learned that models like Prophet are the “automatic cars” of forecasting. They are designed to handle raw, trending data internally. Giving them pre-processed (differenced and lagged) data would be like trying to manually shift gears in an automatic car — it’s unnecessary and just confuses the system. That engineered feature set is still incredibly valuable, but it’s meant for “manual transmission” models like XGBoost or LSTMs, which I plan to explore later.</p><h3>Conclusion</h3><p>This sprint was a fantastic learning experience. It proved that advanced models can significantly outperform simple methods, but also that the “best” model isn’t always the most famous one. Now that I have a high-performing model, the next step is to rigorously validate its performance using cross-validation before I build the API to serve its predictions.</p><p>#Python #Prophet #FeatureEngineering #DataScience #MachineLearning #ArtificialIntelligence #DataAnalysis #TimeSeries #Forecasting #PredictiveAnalytics #StatisticalModeling</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=208691e4aecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>