<?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 Smreseedabanu on Medium]]></title>
        <description><![CDATA[Stories by Smreseedabanu on Medium]]></description>
        <link>https://medium.com/@smreseedabanu?source=rss-56bd78d38b50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5LkGUyo1M5eASVVW</url>
            <title>Stories by Smreseedabanu on Medium</title>
            <link>https://medium.com/@smreseedabanu?source=rss-56bd78d38b50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:16:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smreseedabanu/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[Gate, Guide, Govern: Which Layer Is Really Protecting Your AI Agents?]]></title>
            <link>https://medium.com/@smreseedabanu/gate-guide-govern-which-layer-is-really-protecting-your-ai-agents-3bcf1f099760?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bcf1f099760</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 10:14:37 GMT</pubDate>
            <atom:updated>2026-11-27T11:09:42.514Z</atom:updated>
            <content:encoded><![CDATA[<p>The structural difference between API gateways, AI gateways, and AI control planes — and why mixing them up leaves critical security gaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*COH3bJYfpOEPhsU46vmkQA.png" /></figure><p>An API gateway manages API traffic, an AI gateway manages AI model traffic, and an AI control plane governs the AI agents that create that traffic. They build on each other, but they are not three names for the same thing.</p><p>The terms get mixed up because vendors stretch them. Many API gateways now ship AI plugins, and many AI gateways are marketed as a “control plane for AI”. If you are designing an AI platform, the difference matters: buying a gateway and calling it governance leaves real gaps.</p><p>In this post, I’ll walk through what each layer does, what it can’t see, and how the three fit together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjJ4noYfWLmnvjYIZ-4syw.gif" /></figure><h3>API Gateway: The Bouncer Who Never Reads the Message</h3><p>An API gateway sits between callers (web apps, mobile apps, services, partners) and your back-end APIs. Every request passes through one controlled entry point.</p><p>What it does:</p><p>• <strong>Routing and load balancing:</strong> sends each request to the right service.</p><p>• <strong>Authentication:</strong> checks API keys, OAuth tokens or certificates.</p><p>• <strong>Rate limiting:</strong> caps requests per caller, per minute.</p><p>• <strong>TLS and threat protection:</strong> encrypts traffic and blocks bad requests.</p><p>• <strong>Logging:</strong> records who called what, and the response code.</p><p><strong>Its blind spot:</strong> an API gateway sees paths, headers and request counts. It does not understand what is inside an AI call. To it, a prompt is just a JSON body. It cannot tell which model was used, how many tokens were spent, or whether a prompt is trying to leak data.</p><p><strong>The question it answers:</strong> can this caller reach this API?</p><h3>AI Gateway: One Door, Every Model</h3><p>Now your teams start building chatbots and AI features. Each one calls a different model provider, with its own keys, its own SDK and its own bill. Soon nobody knows what is being spent, or where the prompts are going.</p><p>An AI gateway fixes this. It is a gateway that understands AI traffic. Apps and agents call one API, and the gateway handles the rest:</p><p>• <strong>One API for many models:</strong> swap a model without rewriting the app.</p><p>• <strong>Routing and fallback:</strong> if one model is slow or down, try another.</p><p>• <strong>Token limits and cost tracking:</strong> budgets per team, per app or per key.</p><p>• <strong>Prompt and response hooks:</strong> plug in checks for PII, secrets or prompt injection.</p><p>• <strong>Caching:</strong> reuse answers to repeated prompts to save cost.</p><p>• <strong>AI-aware logs:</strong> model, tokens, latency and cost for every call.</p><p><strong>Its blind spot:</strong> an AI gateway sees the request, not the agent behind it. It knows a key or a token made the call. It usually does not know which agent that is, who owns it, whether it was approved, or how to switch it off everywhere at once.</p><p><strong>The question it answers:</strong> which model, at what cost, and is this prompt safe?</p><h3>AI Control Plane: Who’s Actually in Charge of Your Agents?</h3><p>Then come AI agents. They don’t just answer questions. They call tools, read data, trigger workflows and talk to other agents, often with no human in the loop. Now the question is no longer only “is this request OK?” It is “which agent is this, should it be doing this at all, and can we stop it?”</p><p>An AI control plane is the governance layer for that. It is not one product. It is a set of capabilities, usually from several tools, that work together:</p><p>• <strong>Agent identity:</strong> every agent gets its own identity, so each call is tied to a known agent with an owner.</p><p>• <strong>Lifecycle:</strong> agents are registered, approved, run, monitored and retired. Nothing runs unregistered.</p><p>• <strong>Policy and guardrails:</strong> shared rules for prompts, responses, data and models, applied the same way for every agent.</p><p>• <strong>Tool and MCP access:</strong> an allow-list of which tools and actions each agent can use.</p><p>• <strong>Enforcement point:</strong> an AI gateway in the request path, where the policy is actually applied.</p><p>• <strong>No bypass:</strong> cloud and network controls so agents cannot call models or tools directly, around the gateway.</p><p>• <strong>Evidence:</strong> every decision is logged to the security team’s SIEM, so you can prove what happened.</p><p>• <strong>Kill switch:</strong> one action stops a misbehaving agent everywhere, plus a safe way to restore it.</p><p><strong>The question it answers:</strong> which agent is this, is it allowed, can we prove what it did, and can we stop it?</p><p>A simple way to remember it: the API gateway is the door, the AI gateway is the door that understands AI, and the AI control plane decides who gets a key, watches what they do, and can take the key back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fRCl_qMFOLz8UaXq4F8pzA.png" /></figure><h3>“Wait, Isn’t My AI Gateway Already a Control Plane?”</h3><p>No. An AI gateway is usually one component inside an AI control plane. It is where policy gets enforced on each call. The control plane is where that policy is defined, owned and proven, for every agent.</p><p>Three things cause the confusion:</p><p>• <strong>Marketing.</strong> Gateway vendors add governance features every release, and some now call their product a “control plane for AI”. The gateway is moving in that direction, but on its own it rarely covers agent identity, lifecycle, SIEM evidence and organisation-wide containment.</p><p>• <strong>The word “control plane” is overloaded.</strong> Many gateway products have their own control plane (where gateway settings live) and data plane (the nodes that carry traffic). That is the gateway’s internal design. It is not the same as an AI control plane.</p><p>• <strong>“API gateways are for apps, AI gateways are for agents.”</strong> Not quite. The split is by the type of traffic, not by the caller. An agent calling a normal REST API still goes through the API gateway. An app calling a model goes through the AI gateway.</p><p>A good test: if a gateway disappeared tomorrow, would you still know which agents exist, who owns them, what they are allowed to do, and how to stop them? If the answer is no, you have a gateway, not a control plane.</p><h3>Do You Really Need All Three?</h3><p>Most organisations end up with all three, added in this order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*2i2za7_4T5ivD2tnSSaylA.png" /></figure><p>1. <strong>You expose APIs</strong> → an API gateway. Most companies already have one.</p><p>2. <strong>Several teams call AI models</strong> → add an AI gateway, often as AI plugins on the API gateway you already run. Now you control models, cost and prompt safety in one place.</p><p>3. <strong>Agents start acting on their own</strong> → build an AI control plane around the AI gateway. Give every agent an identity and an owner, block direct access to models and tools, send evidence to your SIEM, and make sure you can stop any agent quickly.</p><p>The layers stack. A control plane without a gateway has nowhere to enforce its rules. A gateway without a control plane enforces rules nobody owns.</p><p>The short version: <strong>API gateways manage API traffic. AI gateways manage AI traffic. AI control planes govern the agents behind it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bcf1f099760" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Model is Lying to You in Silence]]></title>
            <link>https://medium.com/@smreseedabanu/your-model-is-lying-to-you-in-silence-397706283ce9?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/397706283ce9</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 12:04:28 GMT</pubDate>
            <atom:updated>2026-11-25T12:04:28.684Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What a predictive maintenance project taught us about the difference between a model that looks right and one that actually is</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*HbRD_5XHZ4hUtZHnq3rRxw.png" /></figure><p>Every machine learning system tells two stories at once.</p><p><em>The checkpoints between a raw reading and a trusted decision — and the exact moment nothing fires.</em></p><p>One is the story everyone sees: dashboards turn green, predictions start flowing, and someone on a call says the launch was a success. The other story is quieter. It happens underneath — a reading drifts out of range, a label turns out to be wrong, a number quietly stops meaning what everyone thinks it means — and none of it trips a single alert. By the time anyone notices, the quiet story has usually been running for a while.</p><p>This is the story of how we went looking for our quiet failure before it found us, while building a model meant to tell technicians, ahead of time, which machine was about to break. The real project turned out to be longer than “build a model and ship it” — it runs from the rawest incoming reading all the way to a technician’s work order, and nearly every step in between hid a quiet failure of its own. If you’re new to data engineering or model training, that’s fine — everything below is really just a handful of ideas, under pressure, in production: turning messy readings into trustworthy data, turning a technician’s handwritten notes into something a model can learn from, turning a raw number into a signal with context, training and testing honestly, deciding what to do when a model disagrees with a simple rule, and keeping the whole thing honest once it’s live. Each term is explained in plain words the first time it shows up, and there’s a glossary at the end.</p><p>Think of what follows as a tasting menu for the whole pipeline: if you’re here to learn, slow down at each course. Every single one hides something that quietly went wrong at least once — and watching how it got caught is the actual meal.</p><h3>It started with messy data, like it always does</h3><p>The first version of anything is the same: read the raw files, join them together, hand the result to a model. It works fine for a demo. It starts to wobble the first time someone asks, “why did this number change since yesterday?”</p><p>Our wobble had a simple cause. Readings arrived on different clocks, at different speeds, with different gaps. One real event sometimes showed up as two or three different rows. And one day we traced a shifted statistic back to a handful of stray test rows, left behind by someone testing a source system months earlier. Nobody put them there on purpose. Nobody noticed until we went looking — a few rows had quietly moved a number the whole model leaned on.</p><h3>Data has to earn its way up</h3><p>We stopped treating that as a one-off bug and built it into the system instead — a pattern sometimes called a <strong>medallion architecture</strong>, though the name matters far less than the idea: each layer promises a little more trust than the one before it. A layer that keeps every raw reading exactly as it arrived, untouched and replayable — often called <strong>bronze</strong>. A layer where it finally gets cleaned, deduplicated, and reconciled onto one clock — often called <strong>silver</strong>. And a last layer — the only one a model is ever allowed to read — that’s safe, aggregated, and ready for a decision, often called <strong>gold</strong>. This is, in plain terms, what “data engineering” means day to day: moving data through these stages until it’s trustworthy enough to make a decision from. The fix for those stray rows didn’t go into a notebook. It went into that cleaning layer as a standing rule, so it keeps applying on its own, forever, instead of quietly disappearing the next time someone copies the notebook.</p><h3>Two kinds of data, and only one of them gets to predict anything</h3><p>Everything a system like this knows comes from two sources that serve completely different purposes. One is continuous <strong>telemetry</strong> — the stream of raw numbers, arriving whether or not anything interesting is happening. The other is a human-written record: notes a technician leaves every time something actually breaks, what they found, and what they did about it.</p><p>Think of it like a hospital patient: telemetry is the continuous pulse-check on the monitor, updating whether or not anything interesting is happening. The maintenance log is the diary entry a nurse writes only once something has already gone wrong. You’d never let the diary predict tomorrow’s pulse — but you’d be foolish not to learn from every entry in it. The written record is only ever created after something has happened, which means it can teach a model what a real failure looked like in hindsight, but it can never legitimately predict something that hasn’t happened yet. So almost all of that text only trains the model ahead of time and is never shown to it live. The one exception is the plainest, least interpretive part of the record — simple timing facts, like how long it’s been since the last stoppage — which stay forward-looking no matter what the notes say, so they’re allowed to run live alongside the raw readings.</p><h3>Getting the label right is a project of its own</h3><p>Before any of that written history can teach a model anything, each note has to clear two separate hurdles. First, is it even relevant? Maintenance logs are noisy, and an early version of our relevance check leaned on a keyword that was supposed to flag real mechanical trouble — only to discover that exact word appeared in the name of every single piece of equipment in the fleet, so a filter meant to catch failures was instead matching everything, failures and non-events alike. Removing that one over-eager word, plus a short list of known false alarms, turned a filter that matched everything into one that actually separated real signal from noise.</p><p>Second, when was something actually fixed? A note might say a part was replaced, or it might just recommend that one be replaced soon — very different facts. Treating a recommendation as if it had already happened would invent a clean slate for the model that never really existed, which is a worse mistake than missing a real one, since it quietly teaches the model something false with total confidence. Each row in this kind of dataset carries a <strong>label</strong> — simply the right answer, here, whether that machine actually failed or not. A failure wrongly labeled “nothing happened” teaches the model the wrong lesson permanently; no amount of tuning afterward undoes a bad label upstream. We’d recommend deciding this on day one, not after the fact.</p><h3>A raw number means nothing without its context</h3><p>A single raw reading, by itself, doesn’t say much. The same number can be completely normal on one machine and a clear warning sign on another — what gives it meaning is the context around it. Turning raw readings into something a model can actually use generally comes down to four lenses, applied to every measurement. The first is simply <strong>distance to limit</strong>: every reading compared directly against its own known safety threshold, as a plain ratio. The second is a <strong>trend vector</strong> — which way the same reading has been moving across several recent windows, since flat-but-high reads completely differently than climbing fast. The third is <strong>peer comparison</strong>: the same measurement on otherwise-identical neighboring equipment, at the same moment, because a number can be unremarkable in isolation and alarming next to its peers. The fourth is <strong>baseline drift</strong> — not the fleet’s normal, but this specific unit’s own established history, over a long trailing window. None of these four views is enough on its own; together, they turn a lone number into something a model can reason about, the same way a reading of “101°” means nothing until you know whether it belongs to a patient or a cup of coffee.</p><h3>The number that fooled us</h3><p>This is the part that changed how we think about every model since, and it’s worth slowing down for if model training is new to you.</p><p>“Training” a model just means showing it a large pile of past examples — readings paired with whether the machine failed afterward — until it finds a pattern connecting the two. To know if it actually found a real pattern (instead of just memorizing the examples), you hold some data back, train on the rest, and test on what you held back. The standard way to do this is called <strong>cross-validation</strong>: you split your data into chunks (“folds”), train on some, test on the rest, then repeat with a different split, so you get several honest tries instead of just one lucky or unlucky one.</p><p>Our first evaluation split the data into folds the common way — shuffled, with no regard for time — and the model came back with a score comfortably in “good enough to ship” territory — a measure of how well it ranked risky machines above safe ones, where a coin flip sits at one end and a perfect ranking at the other. We were ready to feel good about that.</p><p>Then someone on the team asked a quiet question: if we test the model on a reading from March, is it allowed to have trained on data from April?</p><p>In a shuffled split — yes, by accident, it is. In real life, never. Tomorrow’s data doesn’t exist yet when the model has to predict today. So we rebuilt the evaluation the honest way, a method often called <strong>walk-forward validation</strong>: train only on the past, test only on what comes right after, slide forward in time, and repeat.</p><p>The same model, tested that way, dropped hard — down near where a coin flip would land you. Nothing about the model had changed. Only the honesty of the test had. That gap, far more than either number on its own, is the real lesson: a shuffled test can make almost any time-series model look better than it is.</p><p><strong><em>A flattering number is easy to ship. A realistic one is the only kind worth building on.</em></strong></p><p>There was a second trap waiting right behind the first one, and it’s one of the most common mistakes anyone new to this will eventually hit. When real failures are rare, a model that confidently predicts “nothing will happen,” every single time, can clear a deceptively high accuracy score while catching exactly zero real failures. Accuracy alone can’t tell good models from useless ones when the thing you care about is rare. So we stopped leading with it, and started asking two sharper questions instead, often called <strong>precision</strong> and <strong>recall</strong>: when the model raises an alarm, how often is it actually right (precision) — and of every failure that really happened, how many did it catch (recall)?</p><p>That drop wasn’t the end of the story — it was the honest starting line. Three engineering changes, in particular, did most of the work of climbing back out of it. The first was giving the model a sharper target: instead of asking it to predict a vague “failure at some point,” we reframed the goal around a fixed, bounded horizon — will this asset fail within a defined window ahead — which gave the model something concrete to aim at instead of an open-ended guess. The second was giving it a sense of motion, not just a snapshot: trailing velocity features, computed over several rolling windows at different timescales, let the model see a failure curve accelerating rather than just a single number sitting still. The third was correcting for how rare failures actually are — healthy readings vastly outnumber failure events in a system like this, so without correction a model can earn a flattering-looking score by essentially ignoring the rare case entirely, which is why we weighted training examples and resampled folds specifically to keep failures from getting lost in the crowd. Between a sharper target, a sense of momentum, and correcting for how rare the thing we cared about actually was, the walk-forward score climbed from that coin-flip floor into clearly deployment-ready territory.</p><h3>One model, two kinds of truth</h3><p>A risk score, however well-calibrated, is still a probability — a best guess. But some facts aren’t probabilistic at all: a reading has either crossed a known, physical safety limit, or it hasn’t. That’s not something a model should ever get to have an opinion about. Think of a smoke alarm sitting next to a fire-risk model: the model can estimate how likely a fire is today, but the alarm doesn’t care about its estimate — the instant it senses smoke, it screams, full stop.</p><p>So the system runs two independent checks side by side, not one. A probability-based score catches gradual, multi-signal decline — the kind of pattern no single reading would ever flag on its own. But the moment any individual measurement actually crosses its own hard limit, a separate, dead-simple rule overrides everything: that measurement gets flagged by name, immediately, regardless of what the probability model thinks.</p><h3>A single countdown built from several independent guesses</h3><p>Knowing a machine is “at risk” is useful. Knowing roughly how long you have is more useful. So the system estimates a countdown to likely trouble — and rather than trusting one estimate, it takes several independent guesses and goes with whichever one is soonest, the most conservative, the same way a careful doctor weighs several independent tests rather than betting everything on just one.</p><p>One guess comes from how quickly the risk score itself has been climbing. Another comes from how quickly a specific, trusted measurement is approaching its own limit. A third comes from comparing this unit’s age since it was last serviced against how long units like it have typically lasted.</p><h3>A model has to keep learning, or it goes stale in silence</h3><p>A deployed model is a photograph of a world that keeps moving. So every confirmed failure in production has to travel back into the training data, not sit forgotten in an operations log, disconnected from the very model that missed it. We built that as a loop that never stops, not a one-time favor to the model: a failure happens, it gets logged and reviewed, it’s folded back into the training set, and a new candidate gets trained from it. This whole cycle — train, deploy, watch, retrain — is what people mean when they talk about <strong>MLOps</strong>: running a model like an operational system, not a one-time science project.</p><h3>How often is “often enough”?</h3><p>“Retrain it regularly” isn’t an answer anyone can act on. In practice, teams that do this well never rely on a single trigger — they run three independent tripwires side by side, and whichever one fires first starts the retrain.</p><p>The first is the simplest: a fixed calendar, as a floor. Pick a cadence based on how fast the underlying world actually changes — tighter if the thing you’re modeling is tied to fast-shifting behavior, looser for steadier physical or mechanical processes. It’s also the weakest of the three on its own: a calendar guarantees a model is never untouched for too long, but it reacts to nothing in between. The second is a performance floor, watched live — the same metric you’d use to grade the model, recall or precision or whatever actually matters here, tracked over a trailing window of live outcomes. The moment it drops below an agreed line, retrain immediately, calendar be damned. The third, and the earliest warning of the three, is drift in the incoming data itself. Before a wrong answer ever shows up, the shape of the live data quietly stops resembling what the model was trained on — a shift that standard statistical tests catch directly. This is the one that matters most: by the time a performance metric notices something’s wrong, every prediction in between has already been a little bit off.</p><p>No single one of these is sufficient alone — a calendar misses sudden shifts, a performance floor means the damage is already done by the time it trips, and drift alone can false-alarm on ordinary noise. Running all three together is the actual best practice; picking just one is the common mistake.</p><p>That candidate still has to earn its way back into production. It doesn’t get to replace what’s running just because it exists. The earning process became a short, explicit sequence every new model has to clear. First, a data check: the new training data passes the exact same quality gates the live data does, so nothing silently garbage gets in. Then an honest backtest, graded walk-forward the same way as before — never shuffled. Next comes a <strong>shadow deployment</strong>: the candidate runs on live traffic for a trial window, its predictions logged but nothing acted on, purely to see how it behaves on days nobody hand-picked for it. Once shadow looks clean, it earns a <strong>canary release</strong> — a small, random slice of real decisions, commonly in the 5–10% range, while the rest keeps running on the current champion, so a surprise costs little. Only after it beats the champion on both the backtest and the canary window does it reach full promotion.</p><p>Promotion itself is simple: teams often track it through something called a <strong>model registry</strong>, which keeps every version of a model and marks which one is currently “live” (sometimes called the <strong>champion</strong>). Promotion is just that marker moving from the old version to the new one, which means rolling back, if we ever need to, is exactly as fast as rolling forward.</p><p>One more thing paid for itself more than once: being able to trace any number, on any dashboard, all the way back to the exact row that produced it — something called <strong>data lineage</strong>. Whenever a score moved in a way nobody expected, that trail is what let us find the cause in minutes instead of a day spent hunting through logs.</p><p>Two more structural habits made all of this easier for the whole team to trust, not just easier to build. The first is treating time itself as a first-class citizen in the data layer: every feature a model sees has to be joined as of the exact moment it would actually have been known in the real world, never with a five-minute peek into the future, so a backtest literally can’t cheat even by accident — this is the same discipline that caught the shuffled-split trap earlier, just applied one layer down, in the plumbing instead of the evaluation. The second is keeping pipelines decoupled from each other, so a change to how one upstream reading gets collected can never silently reach into a completely different pipeline and corrupt it. Neither habit shows up on a dashboard. Both are the quiet difference between a system a team can actually trust and one that’s one unlucky Tuesday away from breaking itself in a way nobody notices for weeks.</p><h3>If you’re about to design your next ML system</h3><p>Here’s the honest invitation: go looking for your own quiet failure before it finds you. Start with the question we almost didn’t ask — could this model have accidentally learned from the future? Check what a “99% accurate” model is actually catching, not just how often it’s technically correct, and make sure every label describes what already happened rather than what someone merely recommended. Before trusting a raw reading, ask what it means relative to its own history and its peers, not just on its own, and never let a probability dilute an unambiguous physical fact — keep hard rules hard, and name names when one trips. Don’t let a single estimate decide urgency when several independent ones can check each other instead, and build the loop that lets a real failure teach a model something again and again, not just once. Make sure every number can be traced back to where it came from; that trail gets needed sooner than anyone expects.</p><p>Do all of that, and the loud story — the one where the system just works — becomes the only story left to tell.</p><h3>Quick glossary, for reference</h3><p><strong>Data engineering — </strong>moving raw data through cleaning stages (often bronze → silver → gold) until it’s trustworthy enough to build on.</p><p><strong>Telemetry — </strong>the continuous stream of raw readings, as opposed to human-written records.</p><p><strong>Label — </strong>the correct answer attached to a row of training data (here, whether the machine failed).</p><p><strong>Feature engineering — </strong>turning a raw reading into something a model can reason about, by adding context: distance from a limit, trend over time, comparison to peers, drift from normal.</p><p><strong>Training / testing data — </strong>the past examples a model learns from, and the separate examples used to check what it learned.</p><p><strong>Cross-validation — </strong>splitting data into chunks to test a model fairly, instead of relying on one lucky split.</p><p><strong>Walk-forward validation — </strong>cross-validation that respects time, training only on the past and testing on what comes after.</p><p><strong>Precision / recall — </strong>how often an alarm is right, versus how many real events actually get caught.</p><p><strong>Deterministic check — </strong>a simple yes/no rule based on a known fact (like a hard limit), which overrides a model’s probability-based opinion.</p><p><strong>Remaining Useful Life (RUL) — </strong>an estimated countdown to likely trouble, typically taken as the most conservative of several independent guesses.</p><p><strong>MLOps — </strong>the ongoing practice of deploying, monitoring, and retraining a model, rather than training it once and walking away.</p><p><strong>Data drift — </strong>when the live data a model sees quietly stops resembling the data it was trained on — often the earliest sign a retrain is needed.</p><p><strong>Shadow deployment — </strong>running a candidate model on live traffic with its predictions logged but never acted on, purely to observe it.</p><p><strong>Canary release — </strong>trusting a new model with only a small slice of real decisions at first, so a mistake costs little before full promotion.</p><p><strong>Model registry / champion model — </strong>where model versions are tracked, with one marked as the live version currently in use.</p><p><strong>Data lineage — </strong>the ability to trace any number back to the exact data that produced it.</p><p><em>Field notes from a predictive maintenance build on Databricks. If this saved you a detour, it was worth writing — I’d love to hear about your own quiet failure.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397706283ce9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Messy Data to Live Predictions: What Databricks Taught Me the Hard Way]]></title>
            <link>https://medium.com/@smreseedabanu/from-messy-data-to-live-predictions-what-databricks-taught-me-the-hard-way-c62c826c379a?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c62c826c379a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 16:37:22 GMT</pubDate>
            <atom:updated>2026-10-07T16:37:22.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Medallion layers, MLflow, CI/CD and serving on one platform: the hurdles I met and how I got past each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKzC9hAc79rQzFDS3WQPOQ.png" /></figure><h3>It began with a simple question</h3><p>It started the way these projects usually start, with a short question in a meeting: “Can we predict this before it happens?” The event could have been fraud, churn, an outage or a late delivery. It was rare, it was expensive, and everyone had a story about the last time it caught them off guard.</p><p>What followed was a few months of building, measuring, getting surprised, and rebuilding, from the first raw file to a scheduled job that scores fresh data every hour. I did it on Databricks, and the most useful thing I can offer is the sequence of events: how the data engineering started, how the layers appeared, what I had to plan for, how the model was trained and judged, and how it finally reached production and stayed healthy.</p><h3>Why staying in one place mattered</h3><p>Before the story gets going, one thing shaped every chapter of it. I never had to leave the platform.</p><p>In earlier projects, the pipeline lived in one tool, the model code in another, the model catalog somewhere else, and the serving layer, the application database and the app itself in three more. Each came with its own login, its own permissions and its own audit trail. A simple question like “who can see this table, and which model was trained on it?” meant opening five consoles.</p><p>On Databricks, all of it sat side by side. Auto Loader and Lakeflow brought the data in. Lakeflow Spark Declarative Pipelines shaped it, and Lakeflow Jobs scheduled it, all landing in Delta tables. Unity Catalog gave every table, volume and model one three-level name, one set of grants and automatic lineage. Notebooks trained models, MLflow recorded every run, and the Unity Catalog registry versioned them. A Model Serving endpoint could expose the same registered model for real-time answers. Lakebase, a managed Postgres database, was there for applications that need fast reads and writes beside the lakehouse. Databricks Apps hosted dashboards and internal tools under their own service principal. Declarative Automation Bundles, the successor to Asset Bundles, described jobs, pipelines and apps as code so they could be deployed the same way to every environment.</p><p>Data engineering, machine learning, a database and application deployment were one conversation instead of five. Product names move quickly on this platform, so please treat the details as a snapshot of my experience and check the current documentation before you copy anything.</p><p>Here is the whole journey on one page. The rest of the article walks through it in the order it happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KYmZsAO9e1W7HAgpq4qnw.gif" /><figcaption><em>The whole journey: data engineering, model lifecycle, governance and delivery on one platform.</em></figcaption></figure><h3>The first pipeline, and why it did not last</h3><p>The first version was what everyone builds first. I read the raw files, joined them together and fed the result to a model. It worked well enough for a demo, and it started to wobble the first time someone asked, “Why did that number change since yesterday?”</p><p>Three things were behind the wobble. The sources arrived at different speeds, with different clocks and different gaps. People were part of the data, so a single real-world event could show up as several rows with different spellings. And every correction I made was repeated in a handful of notebooks that slowly drifted apart. I needed somewhere for each kind of problem to live. That is how the layers came into the picture.</p><h3>Three layers, one idea</h3><p>The medallion pattern gives each layer a promise about what it may and may not do. Following the data through them is the easiest way to see why they earn their place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ANn4IFl9SBZaGiqB7ztTw.gif" /><figcaption><em>Data engineering on Databricks: sources, bronze, silver, gold, with Unity Catalog governance around every layer.</em></figcaption></figure><p>Everything starts with <strong>sources</strong> that rarely agree with each other. Streams arrive continuously, databases hold the current state of the business, and people drop files into cloud storage. Each has its own speed, clock and shape.</p><p><strong>Bronze</strong> is the layer that refuses to be clever. Auto Loader picks up new files incrementally and remembers which ones it has already seen, while streams and database extracts land in the same way, all as append-only Delta tables stamped with the load time. Nothing is corrected here. That restraint pays off the first time a bug surfaces a month later, because history can be replayed from exactly what arrived.</p><pre>(spark.readStream.format(&quot;cloudFiles&quot;)<br>    .option(&quot;cloudFiles.format&quot;, &quot;json&quot;)<br>    .load(&quot;/Volumes/catalog/landing/events&quot;)<br>  .writeStream.option(&quot;checkpointLocation&quot;, ckpt)<br>    .toTable(&quot;catalog.bronze.events&quot;))</pre><p><strong>Silver</strong> is where the cleaning lives. Everything moves onto one clock and one grain. Duplicates and fragments are merged into real business events. Quality rules sit inside the table definition, so the rule and the table travel together and run on every load.</p><pre>CREATE OR REFRESH STREAMING TABLE silver.events (<br>  CONSTRAINT not_test_row EXPECT (is_test = false) ON VIOLATION DROP ROW<br>) AS SELECT ... FROM STREAM(bronze.events);</pre><p><strong>Gold</strong> is the only layer a model is allowed to read. Feature tables hold one row per entity per time window, together with a label that defines exactly what is being predicted and the reference events that give the data meaning.</p><p>Around all three sits <strong>Unity Catalog</strong>. Grants decide who can read each table, lineage shows where every column came from, and Lakeflow Jobs keep each layer fresh. The model sits at the end of this chain, reading from gold in the same workspace and under the same governance.</p><p>The payoff was simple. Every data issue now had exactly one home. A bad record was dealt with in silver, a new feature was added in gold, and the model never touched raw data.</p><h3>Questions worth asking before writing code</h3><p>By the time the layers settled, I had a short list of questions I wished I had asked on day one. They are worth writing down and agreeing on with the business before any code exists.</p><p><strong>What does one row represent?</strong> The grain decides everything that follows. <strong>What does missing data mean?</strong> A source that goes quiet is often telling you something, and the time since its last record turned out to be a useful feature. <strong>What counts as one event?</strong> An event can span many rows, and if its pieces are split between training and testing, the model quietly sees the answer. <strong>What happens to late and out-of-order data?</strong> Decide how long you wait and how corrections flow downstream. <strong>What do the newest rows mean?</strong> Their outcomes are not confirmed yet, a condition called censoring that I will come back to. <strong>What exactly is the label?</strong> “Happens within the next N days” is a business decision, and it deserves to be written down and signed off. And finally, <strong>can any job be safely re-run, and can any past result be rebuilt?</strong> If the answer is no, trust will erode slowly.</p><h3>The week the numbers stopped agreeing</h3><p>The first real surprise came while I was validating silver. A key reference statistic, one the model relied on, did not match what the business expected. I traced it back through the layers, and the cause was almost comically small. A handful of placeholder rows had been typed into a source system while someone was testing it. They lasted far longer than real records, and one of them carried a status code that slipped past a text filter and counted as a genuine event.</p><p>Removing three such rows moved the statistic by about 9%. A tiny amount of data had been steering a number that the rest of the solution leaned on.</p><p>The fix mattered less than where I put it. I filtered those rows in the silver layer, as an expectation, so that every future load applies the rule automatically. Then I re-ran everything end to end and compared before and after. If that correction had lived inside a model notebook, it would have been waiting to disappear the next time someone copied the notebook. Cleaning belongs in a layer.</p><h3>Letting time keep its order</h3><p>My first evaluation shuffled events into folds, a method called event-grouped k-fold. The results looked encouraging. The classifier reached a ROC-AUC of about 0.73, and I was ready to feel good about it.</p><p>Then a colleague asked a quiet question: when the model is tested on a row from March, is it allowed to have trained on rows from April? In a shuffled split, it is. In production, it never will be, because tomorrow’s data does not exist when you predict today.</p><p>So I rebuilt the evaluation to follow the calendar. <strong>Walk-forward evaluation</strong> trains the model only on the past and tests it on the next block of time, then slides forward and repeats, with an expanding training window. I added one refinement. Cut points are nudged away from active events, so no event straddles the line between training and testing. It is the same idea as purging and embargo in financial machine learning.</p><p>The same model, evaluated this way, landed at around 0.52, close to a coin flip. Nothing about the model had changed. Only the realism of the test had changed, and realism is what a production system is ultimately judged on.</p><h3>Four ways to cut time, and what really separates them</h3><p>It helped to lay the common evaluation methods side by side. The difference is not in the scores they report. ROC-AUC, PR-AUC, precision and recall are measured the same way inside every method. The difference is in how the data is cut into training and testing, and that cut decides whether the score can be believed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuWpv6Q25D8pH3NKpBkVfg.gif" /><figcaption><em>Evaluation methods compared. Rows are folds, columns are time. Red outlines mark training data that comes after the test block.</em></figcaption></figure><p><strong>A single split</strong> trains on the earlier 70% and tests on the rest. It is quick and a fine sanity check. If the split is shuffled, the model can learn from rows that come after the ones it is tested on, and even when it is cut by time, the score rests on one slice and can swing with a different cut.</p><p><strong>Event-grouped k-fold</strong> deals whole events into five folds so that pieces of one event never sit on both sides. That closes one kind of leak. But the folds ignore the calendar, so a fold can train on blocks that happen after its test block. The model has effectively seen the future, which is how it reached 0.73.</p><p><strong>Naive walk-forward</strong> lets the calendar lead. Each fold trains on everything before a cut and tests on the next block, then the cut slides forward. The future is never visible. Its weakness is that a cut can land in the middle of an event and leave part of it on each side.</p><p><strong>Walk-forward with event-safe cuts</strong> keeps the expanding window and adds two refinements. Cut points snap away from active events, and a small gap, called a purge, keeps neighbouring rows apart. It is the closest match to production, and it is the method behind the 0.52 I now plan around.</p><p>From then on I followed a few habits: report every fold separately, choose the decision threshold once and use it everywhere so methods stay comparable, tune and report on different data, and log every fold as its own MLflow run with its parameters, metrics and exact feature list, so any number can be traced back to the run that produced it.</p><h3>The model that scored 96% and did nothing</h3><p>Around the same time I learned why accuracy is a poor guide for rare events. About one row in twenty was positive, so a model that simply said “nothing will happen” scored roughly 96% accuracy while catching nothing at all. My first threshold comfortably cleared a 90% accuracy target and still added no value.</p><p>It helps to picture 200 time windows, nine of which contain a real event. Here is how the metrics read that picture:</p><p>• <strong>Accuracy</strong> is the share labelled correctly. The “nothing” model scores 95.5% and is useless.</p><p>• <strong>Precision</strong> asks: when the model raises an alarm, how often is it real? Low precision breeds a team that stops believing alerts.</p><p>• <strong>Recall</strong> asks: of the nine real events, how many did we catch? Low recall means events slip through.</p><p>• <strong>F1</strong> blends precision and recall into a single number.</p><p>• <strong>ROC-AUC</strong> scores how well the model ranks risky rows above safe ones across every possible threshold. 0.5 is a coin flip.</p><p>• <strong>PR-AUC</strong> does the same but concentrates on the rare events and ignores the sea of easy negatives, which makes it the more informative headline here.</p><p>• <strong>MAE, R-squared and correlation</strong> judge numeric estimates, such as a predicted time remaining.</p><p>The lesson was that no single metric tells the whole story. ROC-AUC and PR-AUC judge the ranking. Precision and recall judge the decision you will actually deploy. I now report both views, with PR-AUC as the headline.</p><h3>The newest results, read with care</h3><p>One result in the walk-forward run made me stop and look twice. The most recent fold had the best ROC-AUC of all five, and it caught zero events.</p><p>The explanation was the censoring I mentioned earlier. The newest rows simply had not had time to confirm their outcomes, so there was almost nothing to find, and a model that ranks quiet rows above quieter rows can look impressive while delivering nothing. Early folds had the opposite problem, with very little training data.</p><p>I started reading every fold, pairing ROC-AUC with PR-AUC and recall, and reporting the spread rather than just the average. At the shared threshold, precision under walk-forward was around 6% and recall around 3%, with wide variation between folds. That is a sobering result, and it is the right place to start improving from. With only a few dozen confirmed events, a pilot cannot promise more. What it can deliver is a reliable way to measure progress as events accumulate.</p><h3>Choosing the right tool for each question</h3><p>With a realistic yardstick in place, the algorithm question became much easier. The metrics did the steering. Accuracy made every candidate look excellent, so it stopped being the headline. PR-AUC and recall at the shared threshold became the tie-breakers, and they supported a gradient-boosted classifier as the core model, with a random forest kept as a sanity-check challenger. When I tried a direct numeric regressor for “how long until it happens,” R-squared hovered near zero, a clear sign it was learning almost nothing from rare events. I switched to ranking rows by risk and mapping that rank to a number with isotonic regression, which held up far better.</p><p>Each family of algorithms answers a different question, and it pays to start from the question and the data you actually have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ce24Vn1LK7P1dntsBIOfIQ.gif" /><figcaption><em>Which algorithm for which situation, and what to watch for with each.</em></figcaption></figure><p>In words:</p><p>• <strong>No labels yet?</strong> Anomaly detection such as an isolation forest or an autoencoder tells you what is unusual. Unusual is not always important, so expect some false alarms.</p><p>• <strong>A few dozen labelled events and a need for advance warning?</strong> A gradient-boosted classifier such as XGBoost, with the rare class weighted and PR-AUC as the judge.</p><p>• <strong>A numeric estimate rather than a flag?</strong> Rank by risk, then calibrate rank to a number with isotonic regression.</p><p>• <strong>Many cases still unresolved, outcomes unknown?</strong> Survival models such as Cox proportional hazards treat ongoing cases properly and make a good challenger.</p><p>• <strong>Large volumes of raw, high-frequency data and many labelled events?</strong> Deep sequence models can learn straight from the raw signal, though they are rarely justified at tens of events.</p><p>• <strong>Something auditable on day one?</strong> Thresholds and rules. They are easy to explain, and their limits often become useful model features later.</p><h3>How the features grew up</h3><p>The feature table did not arrive finished. It started as a wide net and became a narrower, better-understood set as the evaluation work taught me what mattered.</p><p>The first pass produced 168 candidate columns, grouped by the source family they came from, plus a thin layer of cross-cutting features such as the time since a source last reported, how an entity compares with its peers, and how close a reading sits to a known limit. After review, 18 columns were dropped and 150 remained. Columns usually go for familiar reasons: they are constant, they duplicate another column, or they could leak the answer by using information that would not exist at scoring time.</p><p>What made this manageable was that every evaluation run saved its exact feature list as a small file, feature_cols.json, next to its metrics. When a score changed, I could open two runs side by side and see which list produced which result, instead of relying on memory or a notebook comment.</p><h3>How I let features earn their place</h3><p>• <strong>Judge features only with walk-forward evaluation.</strong> A shuffled split rewards features that leak the future, so a feature that looks brilliant there deserves suspicion.</p><p>• <strong>Add and remove by family, not one column at a time.</strong> Compare a run with a whole family of features against a run without it, and keep the family only if the walk-forward PR-AUC improves in more than one fold.</p><p>• <strong>Prefer features that are stable across folds.</strong> A feature that helps in one fold and hurts in another is usually fitting noise.</p><p>• <strong>Use only what exists at scoring time.</strong> Every feature must be computable at the moment the job runs, from data that has actually arrived by then.</p><p>• <strong>Keep the order fixed.</strong> Training and serving read the same list in the same order, which is exactly why the list is stored as a run artifact and loaded by the scoring job.</p><p>• <strong>Keep a changelog.</strong> Each change to the list is a new run with a clear name, so the evolution of the features is as traceable as the evolution of the model.</p><h3>How MLflow remembers every experiment</h3><p>Somewhere in the second month I could no longer answer a simple question from memory: which settings produced the number on that slide? MLflow, which is built into Databricks, answered it for me, as long as I treated logging as part of the design and not an afterthought.</p><p>Each time training or evaluation code runs inside a run, MLflow records it in an experiment in the workspace. A run holds <strong>parameters</strong>, the inputs fixed for that run such as the threshold or the training window. It holds <strong>metrics</strong>, the numbers that came out, optionally recorded step by step. It holds <strong>tags</strong>, labels that make runs searchable. It holds <strong>artifacts</strong>, files such as the feature list, an evaluation summary or a plot. And it can hold the <strong>model</strong> itself and a reference to the exact data it used.</p><p>For evaluation, the pattern that worked best was one parent run per method and one nested run per fold:</p><pre>with mlflow.start_run(run_name=&quot;risk_model_walk_forward&quot;) as parent:<br>    mlflow.set_tags({&quot;stage&quot;: &quot;evaluation&quot;, &quot;git_commit&quot;: git_sha})<br>    mlflow.log_params({&quot;method&quot;: &quot;walk_forward_event_safe&quot;,<br>                       &quot;threshold&quot;: 0.58, &quot;n_folds&quot;: 5})<br>    mlflow.log_input(mlflow.data.load_delta(<br>        table_name=&quot;catalog.gold.features&quot;, version=42), context=&quot;training&quot;)<br>    for k, fold in enumerate(folds, 1):<br>        with mlflow.start_run(run_name=f&quot;fold_{k}&quot;, nested=True):<br>            mlflow.log_param(&quot;train_end&quot;, fold.train_end)<br>            mlflow.log_metrics({&quot;roc_auc&quot;: fold.roc_auc, &quot;pr_auc&quot;: fold.pr_auc,<br>                               &quot;precision&quot;: fold.precision, &quot;recall&quot;: fold.recall})<br>    mlflow.log_metrics({&quot;pr_auc_mean&quot;: mean_pr, &quot;pr_auc_std&quot;: std_pr})<br>    mlflow.log_dict(summary, &quot;evaluation_summary.json&quot;)<br>    mlflow.log_dict(feature_cols, &quot;feature_cols.json&quot;)</pre><p>Once the runs exist, the Experiments page on Databricks becomes the evaluation workbench. I could select the k-fold parent and the walk-forward parent and compare them side by side, chart each fold’s PR-AUC across runs, and open any single fold to see its exact parameters. The same information is available in code, which is how I compared a candidate with the current champion:</p><pre>runs = mlflow.search_runs(<br>    experiment_names=[&quot;/Shared/risk_model&quot;],<br>    filter_string=&quot;tags.stage = &#39;evaluation&#39;&quot;,<br>    order_by=[&quot;metrics.pr_auc_mean DESC&quot;])</pre><h3>What to consider so the logs stay useful</h3><p>• <strong>Use the same metric names and definitions in every run.</strong> If one run calls it recall and another calls it tpr, comparisons quietly break.</p><p>• <strong>Log every fold, not only the average.</strong> The spread between folds is often the most important finding.</p><p>• <strong>Log the threshold and how it was chosen.</strong> Precision and recall mean nothing without it.</p><p>• <strong>Compare like with like.</strong> Only compare runs that used the same folds, the same threshold rule and the same data window.</p><p>• <strong>Record the data version.</strong> Logging the Delta table version with the run means the exact training data can be reconstructed later.</p><p>• <strong>Record the code version.</strong> A git commit tag ties the run to the code that produced it.</p><p>• <strong>Tag deliberately.</strong> Tags such as stage, method and purpose make it possible to filter hundreds of runs in seconds.</p><p>• <strong>Name runs consistently.</strong> A convention such as model_method_fold makes the Experiments page readable.</p><p>• <strong>Log evaluation files as artifacts.</strong> Summaries, confusion matrices and curves belong with the run, as small files.</p><p>• <strong>Keep sensitive data out.</strong> Parameters and artifacts are visible to everyone with access to the experiment, so never log secrets or personal data.</p><p>• <strong>Organise experiments with intent.</strong> One experiment per use case, in a shared path with sensible permissions, keeps the history findable and governed.</p><h3>Knowing where every number came from</h3><p>There is a moment in every project when someone asks a question that sounds simple and is not: “Where does this number come from?” Data lineage is the answer to that question, and on Databricks it comes with Unity Catalog without extra tooling.</p><p>Unity Catalog captures lineage automatically as queries and jobs run, whether they are written in SQL or Python. It records which tables feed which tables, and it goes down to the column level, so you can see that a feature column was built from two specific source columns. Notebooks, jobs, pipelines and dashboards appear in the picture, and models logged with their training data show their upstream tables as well. The Lineage tab in Catalog Explorer displays it, and system lineage tables make the same information queryable.</p><p>It earned its place in several ways:</p><p>• <strong>Debugging.</strong> When a score moved unexpectedly, lineage showed me which upstream table and job changed. The trace from a surprising statistic back through silver to bronze, which I once did by hand, is exactly what lineage automates.</p><p>• <strong>Impact analysis.</strong> Before changing a source column, I could see which features, models and dashboards depended on it, and warn their owners first.</p><p>• <strong>Trust and audit.</strong> When asked which data trained a particular model version, I could answer with evidence: the model version links to its run, the run records the Delta table version, and lineage shows what fed that table.</p><p>• <strong>Governance.</strong> Sensitive columns can be followed downstream, so protection travels with the data and not just with the first table.</p><p>• <strong>Reproducibility.</strong> Lineage together with a logged Delta version makes it possible to rebuild a past result with the same inputs.</p><p>Lineage and the feature evolution described earlier are two views of the same discipline. One tells you where data came from, the other tells you what was done with it, and together they let a team explain any score without guessing.</p><h3>From a run to the registry to a served score</h3><p>Once a model deserved to live, the next question was how it would get from a notebook into a job that people could depend on. The answer is a handshake. Training and scoring are separate jobs, and the registry sits between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rK8WWHmj0AdwrVcJY8hcPQ.gif" /><figcaption><em>Model registry and serving on Databricks: train, track in MLflow, register in Unity Catalog, promote, serve, monitor and retrain.</em></figcaption></figure><p><strong>Training</strong> starts by reading the gold tables in a Databricks job and splits time the realistic way, learning from the past and testing on what came next. Every run is recorded in <strong>MLflow</strong> with the settings used, the scores earned, and artifacts such as the exact feature list. Months later, any number can be traced to the run that produced it.</p><p>A model worth keeping is <strong>registered</strong> in Unity Catalog. It gets a three-level name and a version number, it is controlled with the same grants as any table, and it stays linked to the run that made it. Promotion then happens through gates, which I cover below. When a version passes, an alias called @champion moves to it. Serving always asks for the champion, so promoting a new version and rolling back to an old one are each a single change.</p><p><strong>Serving</strong> was a scheduled Lakeflow Job that loads whatever the registry says is the champion, rebuilds the same features in the same order, and scores the latest data. It never hardcodes a run id. If a use case needs answers on demand, a Model Serving endpoint can load exactly the same version without a separate platform.</p><p>The scores land in a governed <strong>Delta table</strong>, and the model’s job ends there. Dashboards, alerts and Databricks Apps simply read a table, and when an application needs fast reads and writes, Lakebase sits beside the lakehouse for that. The model advises and a person decides.</p><p>The loop closes with <strong>monitoring</strong>. I watch input drift, the score distribution and, as real outcomes are confirmed, live precision and recall. When quality slips or enough new labelled outcomes arrive, a new candidate is trained and the cycle begins again.</p><pre># training side<br>mlflow.set_registry_uri(&quot;databricks-uc&quot;)<br>with mlflow.start_run(run_name=&quot;risk_model_eval&quot;):<br>    mlflow.log_params(params)<br>    mlflow.log_metrics({&quot;pr_auc&quot;: pr_auc, &quot;recall&quot;: recall})<br>    mlflow.log_dict(feature_cols, &quot;feature_cols.json&quot;)<br>    mlflow.sklearn.log_model(model, name=&quot;model&quot;,<br>        registered_model_name=&quot;catalog.schema.risk_model&quot;)<br> <br># promotion: after the release gates pass<br>client = MlflowClient()<br>client.set_registered_model_alias(&quot;catalog.schema.risk_model&quot;, &quot;champion&quot;, version)<br> <br># serving side: ask the registry, never hardcode a run id<br>model = mlflow.pyfunc.load_model(&quot;models:/catalog.schema.risk_model@champion&quot;)<br>scores = model.predict(features_this_hour)<br></pre><p>Resolving the latest registered version works well to start with. Pinning an alias that moves only after the release checks pass is the safer pattern.</p><h3>Getting it to production the same way, every time</h3><p>A model that only runs from one person’s notebook is still a prototype. The next chapter of the journey was building a path from a code change to a running job that is identical every single time. Everything lives in a Git repository: the pipeline code, the model code, the tests, and a small settings file for each environment. Nothing is deployed by hand.</p><p>A change travels like this:</p><p>1. <strong>A pull request is opened</strong> from a short-lived branch, which starts CI.</p><p>2. <strong>CI runs automatically.</strong> Linting, unit tests, data-quality tests and validation of the bundle configuration. If anything is red, the change cannot merge.</p><p>3. <strong>A reviewer approves and the change is merged</strong> to the main branch. The package is built once, and that exact build is what gets promoted, never a rebuild.</p><p>4. <strong>Dev is deployed automatically,</strong> followed by a quick smoke run.</p><p>5. <strong>Staging is deployed automatically</strong> once dev passes, and integration tests run against production-like data.</p><p>6. <strong>A named approver reviews</strong> the test evidence and release notes.</p><p>7. <strong>Production is deployed</strong> after that approval, using the same build with production settings, followed by a smoke test and a ready rollback path.</p><p>For dev and staging this is <strong>continuous delivery</strong>. Every merge flows through without anyone clicking anything. For production it is <strong>approved delivery</strong>. The pipeline pauses at a gate and a person decides, because production touches real users, real decisions and real money. A pull request starts CI, a merge to main starts delivery to dev and then staging, and an approval on the release starts production. Nothing reaches production on its own. A nightly schedule can also run the full test suite and dependency scans, and a manual run exists for emergency fixes.</p><p>The same code serves all three environments. Only a small settings file changes, with one target per environment. It controls the catalog and schema the job reads and writes, the compute size, the schedule, the service principal the job runs as, and where alerts go</p><pre>targets:<br>  dev:<br>    variables: { catalog: dev_catalog, cluster_size: small,  schedule: paused }<br>  stg:<br>    variables: { catalog: stg_catalog, cluster_size: medium, schedule: hourly_test }<br>  prd:<br>    variables: { catalog: prd_catalog, cluster_size: large,  schedule: hourly }<br>    run_as:    { service_principal_name: prd-pipeline-robot }<br> <br>on:<br>  pull_request:                 # CI on every PR<br>  push: { branches: [main] }    # CD to dev, then staging<br>jobs:<br>  ci:         { steps: [lint, unit_tests, data_tests, bundle_validate] }<br>  deploy_dev: { needs: ci,         environment: dev }<br>  deploy_stg: { needs: deploy_dev, environment: stg }<br>  deploy_prd: { needs: deploy_stg, environment: prd }   # needs approval</pre><p>The settings file is a Declarative Automation Bundle, and the pipeline can run on GitHub Actions, Azure DevOps or GitLab CI. In GitHub, the production environment is configured with required reviewers, which is what creates the approval gate. Code is promoted by this pipeline, while a trained model is promoted through the registry. The pipeline deploys the jobs, and the registry alias decides which model those jobs score with.</p><h3>Teaching the model to keep up</h3><p>A deployed model is a snapshot of the world on the day it was trained, and the world keeps moving. Retraining has to become routine, but a retrained model is a candidate, never an automatic replacement.</p><p>I retrain for four reasons. A meaningful batch of <strong>new confirmed outcomes</strong> arrives, which is the biggest lever available. <strong>Drift</strong> moves the inputs or the score distribution away from what the model saw. A <strong>change in process or source</strong> alters what the data means. Or a <strong>fixed cadence</strong>, such as quarterly, keeps retraining ordinary instead of an emergency.</p><p>Before any candidate reaches production, it passes six gates:</p><p>1. <strong>Data checks.</strong> Schema, freshness, label counts, and no placeholder rows.</p><p>2. <strong>Backtest.</strong> Walk-forward folds on the newest data, with event-safe cut points.</p><p>3. <strong>Beat the champion.</strong> Same folds, same metrics, same threshold rule, looking at the worst fold and not only the mean.</p><p>4. <strong>Calibrate.</strong> Refresh the score-to-percentile reference and check the weekly alert volume against what the team can handle.</p><p>5. <strong>Shadow run.</strong> Score live beside the champion for a few weeks while nobody acts on it.</p><p>6. <strong>Promote.</strong> Move the champion alias, and keep the previous version one command away.</p><p>A candidate with a higher average score can still be held. If one fold collapsed, precision fell, or weekly alerts would more than double, it stays out. After release, the monitoring loop keeps watching drift, score distribution, alert volume and, as outcomes are confirmed, live precision and recall.</p><h3>Locking the doors, in plain words</h3><p>Security on Databricks is easiest to understand as an office building. There is a badge at the door, keycards for each floor, rules on the wall and cameras in the hallway.</p><p><strong>The badge is authentication.</strong> People sign in through company single sign-on with multi-factor checks. Jobs and apps run as a service principal, a robot account with short-lived tokens, instead of borrowing a person’s login. Passwords and keys live in a secrets store and never in a notebook.</p><p><strong>The keycards are authorization.</strong> Unity Catalog is the single place where permissions on catalogs, tables and models are granted. I follow least privilege, so the scoring job can read features and run the model and nothing more. Row filters and column masks hide sensitive values from people who do not need them.</p><p><strong>The rules on the wall are guardrails.</strong> Cluster policies cap compute size and runtime versions. Budgets and quotas stop surprise bills. Serving endpoints control who can query them and how fast. Models reach production only through an alias change that follows the release gates.</p><p><strong>The cameras are audit.</strong> Audit logs and system tables record who did what and when, lineage shows which tables fed which model, and every model version links back to the run that created it.</p><p>Around all four, private networking keeps traffic off the public internet, and data is encrypted at rest and in transit. Your cloud administrator switches these on once for the workspace.</p><h3>The qualities nobody puts on the slide</h3><p>Accuracy gets the attention in review meetings. These requirements get the pager at three in the morning, so I now write each one down as a number before building anything. The targets in brackets are examples to adapt:</p><p>• <strong>Reliability:</strong> retries, repeatable jobs, and an alert when a run is late or empty (99% of hourly runs finish on time).</p><p>• <strong>Performance and freshness:</strong> match speed to the decision (scores ready 15 minutes after the hour).</p><p>• <strong>Scalability:</strong> partitioned Delta tables and autoscaling compute, so ten times the volume means more compute and not a rewrite.</p><p>• <strong>Security and privacy:</strong> least privilege, secrets in a vault, encryption, masked sensitive fields.</p><p>• <strong>Observability:</strong> dashboards for data freshness, input drift, score distribution, alert volume and job health (drift alert within 24 hours).</p><p>• <strong>Reproducibility:</strong> versioned data, code, parameters and feature lists, so any past score can be rebuilt.</p><p>• <strong>Explainability and trust:</strong> reason codes beside every alert, and a human in the loop for decisions that cost money.</p><p>• <strong>Cost:</strong> right-sized compute, and scheduled batch over always-on streaming unless minutes matter (budget alert at 80%).</p><p>• <strong>Maintainability:</strong> clear layers, tests on data and code, no hardcoded run ids, and notes a new teammate can follow.</p><p>• <strong>Compliance and audit:</strong> retention rules, lineage, and recorded approvals for every model release.</p><ul><li><strong>Availability and recovery:</strong> backups, a rollback path for the model alias, and a fallback when scoring fails (rollback in under 10 minutes).</li></ul><h3>Where this leaves me</h3><p>Looking back, the most valuable thing I built was not the model. It was a trustworthy way to measure the model, and a platform where data, models, serving and apps share one governance story. A flattering number would have been easy to ship. A realistic number, even a modest one, gives a team something to improve and the credibility to keep going.</p><p>More confirmed outcomes will make the model better, and the same evaluation will show by how much. Until then, the process is the product: clean layers, realistic splits, the right metrics, and release gates that protect the people who rely on the alerts.</p><p><strong>Lessons learned are never too late to be shared.</strong> If this saves you a detour, it was worth writing. I would love to hear how your own Databricks journey is going.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c62c826c379a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lakehouse Playbook: Designing ML Systems That Don’t Fail Quietly]]></title>
            <link>https://medium.com/@smreseedabanu/the-lakehouse-playbook-designing-ml-systems-that-dont-fail-quietly-a0bb1a43949e?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0bb1a43949e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ml-training]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 11:14:03 GMT</pubDate>
            <atom:updated>2026-09-18T11:14:03.077Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(From raw medallion ingestion to Databricks Apps: A blueprint for end-to-end pipeline rigor)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnKJtyngrvyffDxribelAw.png" /></figure><p><strong>Every machine learning system in production tells two stories simultaneously. </strong>The first is the loud one: dashboards are green, predictions are flowing, and the launch was a success. The second is a quieter, more insidious story — one where data subtly drifts, schemas fracture, and the system fails completely without ever throwing an error code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbzZHPQSCyHbyyvMsfphng.png" /></figure><p>This is a playbook for building the first story to last. It is a deep dive into the engineering rigor required between a raw reading hitting a server and a trustworthy, governed decision reaching a human operator.</p><h3>CHAPTER 1 · THE THREE-DISCIPLINE LOOP</h3><h3>Stop Conflating Your Data Teams</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw0E_g2uOsh6IcazSw7wzw.png" /></figure><p>Platform confusion starts when organizations treat data engineering, data science, and ML engineering as competing ideologies. They aren’t. They are sequential stages of a single operational loop.</p><p><strong>Data Engineering </strong>is the plumbing. It moves raw data to a state where it is clean, structured, and trusted. It doesn’t answer questions; it makes questions answerable. Its ultimate output is a table you can actually believe.</p><p><strong>Data Science &amp; Analytics </strong>form the interpretation layer. Analytics looks backward to deduce what happened. Data science looks inward to uncover the statistical patterns driving those events.</p><p><strong>The ML Pipeline </strong>is the automation layer. It takes the patterns discovered by data science, wraps them in production-grade engineering, and forces them to run unattended as new data streams in.</p><h3>CHAPTER 2 · THE DATA MEDALLION</h3><h3>Data Must Earn Its Way to the Top</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxJqegipddtwJguxORieTw.png" /></figure><p>x</p><p>Raw data is toxic by default. Arriving as chaotic telemetry or erratic event logs, it should never be exposed directly to a model or business intelligence tool. Architecture requires checkpoints.</p><p><strong>The Medallion Architecture works because it enforces strict data hygiene:</strong></p><p><strong>Bronze (The Raw Ledger): </strong>An untouched, immutable record of everything that happened. Every timestamp and anomaly is preserved here for replayability.</p><p><strong>Silver (The Cleansing Ground): </strong>Where data earns its structure. We deduplicate, fix units, filter impossible values, and explicitly treat silence as an active data point rather than a blank space.</p><p><strong>Gold (The Business Layer): </strong>Aggregated, enriched, and optimized. Silver rows are joined with reference data and business logic, fully prepped for consumption.</p><p>By anchoring this architecture in Delta Lake under Unity Catalog, every layer inherits ACID guarantees, enforced schemas, and a unified lineage graph. When a downstream prediction breaks, you don’t hunt through disparate server logs; you follow the lineage trail straight back to the corrupted source.</p><h3>CHAPTER 3 · FEATURE ENGINEERING</h3><h3>Where Domain Expertise Destroys Hyperparameter Tuning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWelwjpRFgV42_5IHrpRuw.png" /></figure><p>An algorithm is fundamentally blind. It does not inherently know that a value trending upward over three consecutive days is dangerous. It only understands the numbers you feed it. True predictive signal is built, not found.</p><p><strong>High-impact feature pipelines consistently lean on five core concepts:</strong></p><p><strong>Rolling Slopes: </strong>Capturing trajectories across dynamic windows (hours, days, weeks) rather than relying on static snapshots.</p><p><strong>Peer Comparisons (Z-Scores): </strong>Evaluating an asset against its fleet. An isolated reading might look normal, but it becomes an anomaly when compared to its peers.</p><p><strong>Boundary Proximity: </strong>Explicitly mapping how close a metric is to its operational limits.</p><p><strong>Baseline Shifts: </strong>Comparing immediate behavior against long-term historical baselines to catch slow, systemic drift.</p><p><strong>Data Completeness: </strong>Tracking the volume of arriving signals, because a quiet reading is a distinct business event.</p><p><strong>Genuinely informative, domain-driven features will beat a sophisticated algorithm fed raw data almost every single time.</strong></p><h3>CHAPTER 4 · ALGORITHM CHOICE</h3><h3>Optimize for Data Shape, Not Tech Fashion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7TGfVB316MHdfosP6BG9w.png" /></figure><p>The algorithm matters far less than the industry wants you to believe. Choose your architecture based on the mathematical shape of your problem, not what is currently trending on Hacker News.</p><p>When mapping your problem to a model, follow these structural rules:</p><ul><li><strong>For Tabular, Mixed-Type Data with Rare-Event Targets:</strong> Use <strong>Gradient-Boosted Trees (XGBoost/LightGBM)</strong>. The hidden catch here is that their raw outputs are ranking scores, not true probabilities. You must apply an <strong>Isotonic Regression</strong> step afterward to calibrate the numbers so they actually mean what they say.</li><li><strong>For Small, Highly Noisy Data Prone to Overfitting:</strong> Use <strong>Random Forests</strong>. They run beautifully alongside boosting models. When a random forest disagrees sharply with your boosted model, that deep disagreement reveals exactly how fragile your signal really is.</li><li><strong>When Predicting <em>When</em> an Event Occurs, Not Just <em>If</em>:</strong> Use <strong>Survival Analysis (Cox Proportional Hazards)</strong>. This framework retains critical time-to-event information that a standard binary label throws away, though it does require specialized team familiarity.</li><li><strong>When Labeled Failure Events Are Scarce:</strong> Use <strong>Unsupervised Anomaly Detection</strong>. This strategy captures “doesn’t look like normal behavior” without requiring historical failure labels, often completely outperforming supervised models on rare events.</li></ul><h3>CHAPTER 5 · EVALUATION METRICS</h3><h3>How “95% Accuracy” Hides Systemic Failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33g8q5qcfs1tG_ljVEkgKQ.png" /></figure><p>If only 5% of your machinery actually fails, a completely broken model that blindly predicts “no failure” for every machine will score 95% accuracy. Standard accuracy is a dangerous illusion on imbalanced real-world data.</p><p>To evaluate a model honestly, look deeper:</p><p>· <strong>Precision vs. Recall: </strong>This is a business trade-off. What costs more: dispatching a technician for a false alarm (low precision), or missing a catastrophic failure entirely (low recall)?</p><p>· <strong>PR-AUC over ROC-AUC: </strong>ROC-AUC can be deceptively optimistic on imbalanced datasets because it is heavily influenced by a massive, easily predicted negative class. PR-AUC forces you to look directly at the minority class performance.</p><p>· <strong>Confusion Matrices in Raw Numbers: </strong>Percentages obscure small-sample realities. Keep the absolute counts visible.</p><p>· <strong>Cohort Segmentation: </strong>A model that looks flawless in aggregate can be completely blind when evaluating a specific asset type or geographic region.</p><h3>CHAPTER 6 · HYPERPARAMETER OPTIMIZATION</h3><h3>Search Ruthlessly, Then Lock It Down</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIxf6cLA64bxiFgKCHXesQ.png" /></figure><p>Endlessly running a full hyperparameter grid search on every routine data refresh is a wildly expensive way to re-discover the same mathematical answer.</p><p>Implement a <strong>Search, Lock, and Reuse</strong> pattern: use a structured random search across grouped folds to pinpoint the optimal configuration. Verify that the winner outperforms the baseline by a statistically significant margin, then lock that configuration. Re-open the hyperparameter search only when the underlying nature of your incoming data changes fundamentally.</p><h3>CHAPTER 7 · AUTOMATED PLATFORMS</h3><h3>Notebook Paradigms Fail in Production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f83yy2aZywEtH5nwRwhSxw.png" /></figure><p>An automated production job cannot selectively skip cells the way a human data scientist does during an interactive session. Code written “for comparison only” will run on every single production execution unless handled by explicit conditional logic. A code comment is not an execution switch.</p><p>Build explicit orchestration using distinct trigger strategies:</p><p>· <strong>Time-Based Triggers: </strong>Best for predictable batch windows where processing delays are irrelevant.</p><p>· <strong>Event-Based Triggers: </strong>Highly efficient. This fires retraining or scoring pipelines only when upstream tables register an actual change, using a debounce window to prevent rapid-fire triggers.</p><p>· <strong>Serverless Compute: </strong>Eliminates the operational overhead of cluster sizing for highly erratic, bursty batch workloads.</p><h3>CHAPTER 8 · MODEL REGISTRIES</h3><h3>Pointers are Live Wires</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znMRSIRZr0KbGDqZIuY3uA.png" /></figure><p>A model registry is a foundational tool for governance, linking every model version back to the exact code, parameters, and training data that generated it.</p><p>However, always serving the latest_version tag directly to production is incredibly dangerous. If you do not have an automated quality gate sitting between model registration and that production pointer, your registry isn’t a safety mechanism — it’s an automated express lane for deploying broken code the second a bad training run concludes.</p><h3>CHAPTER 9 · LLMS AND AGENTS</h3><h3>Guarding the Narrative Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bAupwMFcHS5SFMRqmL4Ow.png" /></figure><p>Modern ML pipelines increasingly end with a natural language sentence rather than a raw numerical score, summarizing findings for non-technical operators.</p><p>To prevent hallucinations, enforce strict constraints. Feed structured, verified facts into rigid, grounded prompt templates. The LLM should strictly act as a translator turning telemetry data into human narrative, not an independent decision-maker.</p><p>When building agentic pipelines where models choose their own tools, apply traditional production safeguards: comprehensive logging, timeouts, retries, and strict permission boundaries. An LLM agent that queries data is incredibly useful; an agent that can autonomously execute irreversible operational changes is a severe liability that must be governed accordingly.</p><h3>CHAPTER 10 · LAKEHOUSE-NATIVE APPLICATIONS</h3><h3>Kill the Export Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAkSGt8okDWSpSeZ-GpQcA.png" /></figure><p>The traditional approach to building a data application involves setting up complex ETL pipelines to sync data out of the central data store into an app-specific database. This introduces massive architectural debt: redundant data copies, distinct authorization models, synchronization lag, and drift.</p><p>A lakehouse-native application completely bypasses this debt by reading live, governed data directly from the core lakehouse layers. You maintain one single source of truth, one unified access control model, and zero brittle export pipelines.</p><h3>CHAPTER 11 · LAKEHOUSE OBSERVABILITY</h3><h3>The Invisible Failures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRZuj1SIq4Am2eA5VbTDhw.png" /></figure><p>The most dangerous failures in machine learning systems do not trigger system crashes. They are completely silent. Joins that return nulls instead of throwing errors, unchecked validation flags, and missing metrics won’t trip infrastructure alerts.</p><p>To stop silent failures, you must implement observability across four distinct layers:</p><p>· <strong>Pipeline Health: </strong>Monitoring job success, execution durations, and retry counts.</p><p>· <strong>Data Quality: </strong>Tracking null rates, anomalies, volume changes, and schema drift.</p><p>· <strong>Model Quality: </strong>Continually logging real-time validation metrics across every active version.</p><p>· <strong>Business Outcomes: </strong>Verifying if downstream predictions align with actual real-world results.</p><h3>CHAPTER 12 · SECURITY &amp; GOVERNANCE</h3><h3>Security is Architecture, Not a Perimeter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf_s0Hq60JMfnebirw1ywA.png" /></figure><p>In a modern lakehouse, security cannot be a perimeter bolted onto the outside of your network. It must be an intrinsic property of every table, query, and pipeline. The exact same governance rings must apply whether a data request originates from a human engineer, a scheduled cron job, an application, or an AI agent.</p><p>· <strong>Service Identities: </strong>Ditch shared credentials baked into scripts. Every job and agent must authenticate via dedicated service identities.</p><p>· <strong>Granular Masking: </strong>Implement row- and column-level masking so a single underlying table dynamically alters its view based on the caller’s clearance.</p><p>· <strong>Deterministic Tool Access: </strong>An AI agent’s tool access must be a hard platform permission setting, never a loose instruction hidden inside an LLM prompt.</p><p>· <strong>Unified Auditing: </strong>Every action — from ingestion to inference — must feed into a single audit log to ensure compliance is completely transparent.</p><h3>CHAPTER 13 · THE DEPLOYMENT CHECKLIST</h3><h3>Treat Production Readiness as a Gate, Not a Vibe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V91c76dJrABIRNIAeoq1_w.png" /></figure><p>Before a machine learning model is permitted to handle real-world decisions, it must pass a strict checklist:</p><p><strong>Reliable Cross-Validation: </strong>Metrics are derived from grouped, multi-fold cross-validation, not a single lucky holdout slice.</p><p><strong>Automated Quality Gates: </strong>The model clears a programmatic minimum performance bar before it can be registered.</p><p><strong>Verified Overrides: </strong>Manual business-rule safety nets have been intentionally tested against the exact data edge cases they are meant to intercept.</p><p><strong>Dual-Drift Monitoring: </strong>Active monitoring hooks are deployed to track changes in both input feature distributions and output prediction scores.</p><p><strong>Exercised Rollbacks: </strong>Reverting production traffic back to a previous stable model version is a fast, audited configuration change, not an emergency training drill.</p><p><strong>Explicit Ownership: </strong>A designated engineer or team actively owns the model’s post-deployment lifecycle.</p><h3>CHAPTER 14 · CI/CD PROMOTION</h3><h3>Code Your Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta8N_slogxJ_OWGnajuLtQ.png" /></figure><p>Your underlying code and logic should remain completely immutable as your pipeline moves across environments. Only environment-specific parameters (such as target catalogs, storage locations, schedules, and alert webhooks) should adjust.</p><p>To achieve this, treat pipelines, cluster definitions, and schedules as Infrastructure as Code (IaC). Keep them in version control where they are fully reviewable and diffable. While a merged pull request can safely auto-deploy to development environments, promotion to staging and production must require explicit, authenticated human approval.</p><h3>CHAPTER 15 · THE END-TO-END LOOP</h3><h3>Rigor Wins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9E3LpNvRKtysg6PeNqavFg.png" /></figure><p>When you step back, the entire architecture reveals itself as a closed, highly disciplined loop running seamlessly on a single platform. Sources feed bronze, bronze cleans into silver, and silver optimizes into gold. Gold data undergoes rigorous cross-validation, registers to a gated model registry, executes via event-driven batch scoring, and translates through a grounded narrative layer directly into the hands of an operational decision-maker.</p><p>None of these concepts are science fiction. Medallion architectures, calibrated probabilities, event-based orchestration, versioned registries, and IaC deployment are all established industry standards. The real engineering craft lies in the systemic discipline. It’s refusing to skip a layer for convenience, refusing to trust an uncalibrated metric, and refusing to deploy code that hasn’t been programmatically validated.</p><p><strong>The Complete Blueprint in Motion</strong></p><p>To visualize how these architectural rules fit together, the diagram below maps out the end-to-end data lifecycle we have built throughout this playbook — unified under a single control plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6eMFHJ1sD2WUj7QjHZLbw.png" /></figure><p>When tracing this pipeline from left to right, we can see exactly how the abstract concepts of MLOps crystallize into concrete platform actions:</p><ol><li><strong>Step 1: Medallion Ingestion:</strong> The foundational data engineering pipeline where raw telemetry systematically earns its way up through <strong>Bronze, Silver, and Gold</strong> checkpoints, orchestrated fully and reliably by automated <strong>Databricks Jobs</strong>.</li><li><strong>Step 2: MLflow Experiment Tracking:</strong> The data science sandbox. Gold datasets feed a robust training matrix where parameters, metrics, and models are systematically captured and logged inside an <strong>MLflow Experiment</strong>.</li><li><strong>Step 3: Governed Registry &amp; Databricks Model Serving:</strong> The deployment gate. The winning model clears automated quality controls, locks safely into a governed registry capsule, and is instantly spun up by <strong>Databricks Model Serving</strong> as a live, low-latency API endpoint.</li><li><strong>Step 4: Databricks Apps Consumption:</strong> The final business layer. A secure, production-grade <strong>Databricks App</strong> reads directly from live governed tables and endpoints, serving interactive data graphs and LLM narrative alerts to the operator making the final call.</li></ol><p>Running seamlessly beneath every single one of these steps is <strong>Unity Catalog</strong>. It acts as the load-bearing spine of the whole architecture — enforcing permission boundaries, securing identity data, logging audit metrics, and charting an unbroken lineage graph from the final sentence generated on the dashboard back to the raw row that triggered it.</p><p><strong>Rigor Wins</strong></p><p>None of the individual components highlighted in this playbook are exotic. Medallion structures, hyperparameter folds, event-driven orchestration, API model serving, and infrastructure-as-code deployment are all well-known ideas.</p><p>The real engineering craft lies purely in the <strong>sequencing and the systemic discipline</strong>. It is the absolute refusal to skip a layer for convenience, the refusal to trust an uncalibrated probability metric, the refusal to register a model that has not cleared an automated gate, and the refusal to promote code that hasn’t been proven somewhere safer first.</p><p><strong>Build your data lakehouse with that level of uncompromising rigor, and the first story — the loud one, where your machine learning system just works — is the only one your team will ever have to tell.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0bb1a43949e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day I Stopped Drawing Messy Diagrams: How C4 Model and Architecture as Code Revolutionized Our…]]></title>
            <link>https://medium.com/@smreseedabanu/the-day-i-stopped-drawing-messy-diagrams-how-c4-model-and-architecture-as-code-revolutionized-our-b852eacefb2a?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/b852eacefb2a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[c4-model]]></category>
            <category><![CDATA[artficial-intelligence]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 09:45:45 GMT</pubDate>
            <atom:updated>2026-07-13T09:45:45.321Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Day I Stopped Drawing Messy Diagrams: How C4 Model and Architecture as Code Revolutionized Our Software Engineering</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*H52zSaN3L6uxRicQ5yPTDQ.png" /></figure><p>For years, I believed that being a good software engineer meant mastering the art of the whiteboard. During feature planning cycles, I would gather requirements from stakeholders and business analysts, open up a blank digital canvas, and start drawing. I called these sketches our <strong>High-Level Design</strong> (HLD), but in reality, they were a chaotic trap. Lines crossed everywhere, infrastructure components were jammed next to business logic, and the word “API” was thrown around so casually that it lost all meaning.</p><p>The turning point came during a particularly brutal architecture review. I spent forty-five minutes trying to explain a new microservice feature to a mixed room of product managers and senior developers. Halfway through, I realized the room was completely split: the product managers were terrified by the technical complexity, and the developers were frustrated by the lack of concrete system boundaries. We were all looking at the same diagram, but we were seeing entirely different things.</p><p>That was the moment I realized software engineering has a massive communication problem. We speak in riddles of arbitrary boxes and arrows, assuming everyone shares the same mental model.</p><p>It forced me to rethink my entire approach to system design. My search for a better way led me to the <strong>C4 model</strong>, and eventually, into the cutting-edge landscape of <strong>Architecture as Code</strong> (AaC) and <strong>C4InterFlow</strong>. It completely transformed how I think about, document, and execute software design, turning documentation from a chore into our team’s ultimate competitive advantage.</p><h3><strong>The feature planning trap and the four levels of zoom</strong></h3><p>The core breakthrough of the C4 model — created by Simon Brown — is that it treats architecture documentation exactly like <strong>Google Maps</strong>. It applies a multi-level zooming abstraction to software, ensuring you show the right information to the right audience.</p><p><strong>Level 1: The context diagram (Getting business buy-in)</strong></p><p>The C4 <strong>Context</strong> diagram became our secret weapon for stakeholder and BA alignment. By treating our entire system as a single black box at the center, surrounded only by users and external dependencies, business teams could instantly grasp the scope. We could map user value flows without getting bogged down in tech-stack debates, databases, or API protocols.</p><p><strong>Level 2: The container diagram (The engineering blueprint)</strong></p><p>Once the business signed off, we zoomed into Level 2: the <strong>Container</strong> diagram. This is where engineering reality sets in. Instead of guessing where to draw architectural lines, we began segregating our containers based on <strong>bounded contexts</strong>.</p><p>This approach proved to be a lifesaver for our brownfield projects. It allowed us to clearly map out legacy systems and instantly identify which existing services could be reused versus what needed to be built from scratch. For greenfield projects, it gave the team an intentional, clean blueprint before writing a single line of code.</p><p>The container level is where the technical architecture truly comes alive. It clearly depicts:</p><ul><li><strong>Infrastructure components</strong>: The strategic placement of API gateways, databases, and message brokers like Kafka.</li><li><strong>Communication channels</strong>: Exactly how containers talk to each other and the protocols they use.</li><li><strong>Technology choices</strong>: Clear labels showing which microservice runs on Node.js, Spring Boot, or Go.</li></ul><p><strong>Level 3 &amp; 4: Component and code diagrams (Bridging design to code)</strong></p><p>From there, the model naturally flows into execution. The <strong>Component</strong> diagram zooms into an individual container, mapping out internal structural blocks like controllers, services, repositories, and inbound/outbound adaptors. Finally, the <strong>Code</strong> diagram provides the street-level view, drilling down into class diagrams or entity-relationship models showing exactly how a component is implemented.</p><h3><strong>Can containers depict complex architectural patterns and deployment strategies?</strong></h3><p>A common question I get from other architects is: <em>Can a container diagram actually handle advanced distributed patterns and modern cloud-native deployment strategies?</em></p><p>The answer is a resounding yes. Because a container diagram visualizes structural boundaries and the synchronous or asynchronous relationships between services, it naturally surfaces your architectural patterns.</p><p>When you explicitly trace how containers interact through a message broker, patterns like <strong>Event-Driven Architecture</strong> or <strong>Event Sourcing</strong> become visually obvious. You can map out distributed transactions across containers to illustrate a <strong>Saga</strong> pattern, or show data segregation to clearly model <strong>CQRS</strong>, <strong>Transactional Outbox</strong>, and messaging flows.</p><p>Crucially, the container framework scales to map physical <strong>deployment strategies</strong> to your logical runtime units. Instead of treating the cloud as a mysterious black box, your C4 container layer explicitly handles modern primitives:</p><ul><li><strong>Serverless architectures</strong>: An ephemeral cloud function is modeled as a standalone container with a clear tech label, such as Payment Processor [AWS Lambda / Go].</li><li><strong>Asynchronous background workers</strong>: Specialized compute units like <strong>Batch Jobs</strong> are given dedicated container shapes, showcasing exactly how and when they are asynchronously triggered to handle heavy workloads.</li><li><strong>Security &amp; infrastructure dependencies</strong>: Crucial cloud utilities like <strong>AWS KMS</strong> (Key Management Service) are explicitly surfaced as external systems or infrastructure nodes, making it immediately transparent which specific container initiates cryptographic handshakes for data-at-rest encryption.</li></ul><p>The diagram stops being a static picture and becomes an active blueprint of your system’s real-world behavior and security posture.</p><h3><strong>The evolutionary leap: Architecture as Code (AaC)</strong></h3><p>We have spent years mastering Infrastructure as Code (IaC) to automate our environments, but we completely ignored the documentation. Our diagrams were still trapped in static <strong>Lucidchart</strong> spaces, <strong>draw.io</strong> files, or outdated drawing canvases, dying a slow death the moment the first line of code was pushed.</p><p>To fix this, we shifted to <strong>Architecture as Code</strong> (AaC). By using C4 model tools like <strong>Structurizr</strong> or <strong>PlantUML</strong>, your diagrams become pure text. You define your software architecture using a declarative DSL (Domain Specific Language). A container isn’t a manually drawn shape anymore; it is a single line of text in an architecture file.</p><p>This text-based approach completely revolutionizes how we manage engineering knowledge:</p><ul><li><strong>Version control</strong>: Because diagrams live as text files inside your Git repository, they are versioned right alongside your source code. If a feature branch changes a system dependency, the diagram updates in that exact same pull request.</li><li><strong>Git history tracking</strong>: You can run a git diff to see exactly how your architecture evolved over the last six months. No more guessing when a database, a Lambda function, or a Kafka topic was introduced.</li><li><strong>Continuous integration</strong>: You can automatically compile, render, and publish your updated architecture diagrams to your internal engineering site every time code merges to the main branch.</li></ul><h3><strong>C4 vs. C4InterFlow: Structure vs. Flow</strong></h3><p>As our system grew, we hit a natural limitation with standard C4 text models. While the traditional C4 model solved our structural problems, we realized it answered the question of <strong>what</strong> the system looks like, but struggled to answer <strong>how</strong> data actually moves through it dynamically.</p><p>That is when we discovered <strong>C4InterFlow</strong>, an open-source extension that shifts the focus from static topologies to dynamic capabilities. A common misconception is that C4InterFlow is a replacement for the C4 model. <strong>It is not.</strong> It is an extension and an evolutionary step built directly on top of it.</p><p>Think of it this way: the traditional C4 model gives you the structural map of your ecosystem (the buildings and rooms), while C4InterFlow tracks the live traffic moving through it (the data flows and API contracts). You cannot use C4InterFlow effectively without C4, because it requires those structural boundaries to attach its behaviours to.</p><h3><strong>Supercharging AI developers with C4InterFlow</strong></h3><p>In the era of AI-assisted engineering with tools like <strong>Claude</strong>, <strong>GitHub Copilot</strong>, and <strong>Cursor</strong>, this combination of C4 structure, physical infrastructure constraints, and C4InterFlow data paths is an absolute superpower.</p><p>If you feed an AI coding assistant an image of a diagram or a massive folder of unorganized code, it has to guess the architectural intent. But when you pass it text-based <strong>C4InterFlow</strong> definitions, you give the LLM the ultimate engineering cheat sheet.</p><p>The AI instantly sees the exact REST endpoint it needs to implement, the serverless environment constraints it must write code for, the upstream systems it depends on, and the downstream Kafka events it is responsible for emitting. It doesn’t just guess or write hallucinated boilerplate. It generates highly accurate, runtime-compatible controllers, lambda handlers, and services that perfectly fit your defined architectural patterns (like CQRS, Sagas, or Outbox) because the structural boundaries and behavioural contracts are explicitly defined in the context.</p><h3><strong>Code-centric alignment: Moving ADRs out of Confluence</strong></h3><p>To truly maximize development speed, we had to eliminate the ultimate documentation silo: Confluence. Confluence is where architecture designs go to die. It requires constant context-switching, gets out of sync instantly, and engineers rarely look at it during active coding cycles.</p><p>We moved our <strong>Architecture Decision Records</strong> (ADRs) directly into the code repository as markdown files (/docs/adr/0004-use-saga-pattern.md).</p><p>By keeping our decisions next to our source code, our C4 text diagrams, and our C4InterFlow schemas, we unlocked continuous alignment. Architecture decisions are reviewed, updated, and versioned in the exact same commits as the code that implements them. When an engineer opens Cursor or VS Code, the exact rationale behind why a specific pattern, lambda trigger, or KMS decryption schema was chosen is sitting right next to the source code they are actively editing.</p><h3><strong>Conclusion: Stop drawing, start coding your design</strong></h3><p>By unifying the <strong>C4 model</strong>, <strong>C4InterFlow</strong>, <strong>ADRs as markdown</strong>, and modern <strong>AI coding tools</strong>, architecture is no longer a static blueprint trapped on a canvas or a wiki page. It becomes a living, breathing engine that drives your entire development lifecycle.</p><p>If you are still struggling to explain your software systems to stakeholders, or if your engineering team is building features that don’t match the original design, stop drawing arbitrary boxes. Turn your architecture into code, feed it to your team (and your AI), and watch your development velocity skyrocket.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b852eacefb2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Doing the Math: Why Back-of-the-Envelope Estimates are Actually Architecture Decisions]]></title>
            <link>https://medium.com/@smreseedabanu/stop-doing-the-math-why-back-of-the-envelope-estimates-are-actually-architecture-decisions-0bb382b6dbe0?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bb382b6dbe0</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 08:03:09 GMT</pubDate>
            <atom:updated>2026-06-12T08:03:09.693Z</atom:updated>
            <content:encoded><![CDATA[<p>When engineers talk about “back-of-the-envelope estimation,” the conversation usually devolves into a pure math exercise. We calculate QPS (Queries Per Second), estimate storage in terabytes, and guess network bandwidth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ipBaX-sZCS-_nx6FD-cIAw.png" /></figure><p>But math is not the end goal. Math is just the catalyst.</p><p>The true value of a back-of-the-envelope calculation lies in how it defines and solidifies your <strong>Non-Functional Requirements (NFRs)</strong> — like latency, availability, and scalability. These numbers are the invisible hand that forces you to change your tech stack, swap out databases, proactively prevent system throttling, and architect against catastrophic distributed bugs.</p><p>Let’s look at how early estimation math acts as the architectural engine, driving every layer of a system as it scales from 1 to 10 million users.</p><p><strong>The Estimation Core: How Math Dictates Your Tech Stack</strong></p><p>A common misconception is that NFRs exist independently of estimation. In reality, they form a strict dependency loop:</p><ol><li><strong>The Abstract NFR:</strong> The business dictates that the application must be fast (low latency) and reliable (high availability). This is just a goal.</li><li><strong>The Estimation Impact:</strong> Your back-of-the-envelope math translates “high availability” into concrete physical constraints. For example, if your estimate shows a peak of 50,000 write QPS, your NFR for availability suddenly requires a distributed, multi-master setup because a single database node physically cannot handle that throughput.</li><li><strong>The Tech Stack Shift:</strong> The estimation tells you exactly <em>where</em> and <em>when</em> hardware limits will break. This forces you to drop certain technologies (like relational databases or synchronous APIs) and adopt others (like NoSQL, message queues, and event-driven runtimes) to meet the NFR.</li></ol><p>Without estimation, you cannot design for NFRs. Estimation moves your architecture from guesswork to predictable engineering.</p><p><strong>The Starting Point: The Lonely Server</strong></p><p>Every system starts small. Imagine a single user on a mobile app or web browser. They hit a DNS server to resolve a domain name, get an IP address, and talk directly to one web server connected to one database.</p><p>At this stage, your NFRs are trivial because your estimation tells you traffic is near zero. Any tech stack works. Throttling is a non-issue, and race conditions are practically impossible because requests happen sequentially.</p><p>But what happens when your back-of-the-envelope estimation forecasts <strong>10 million users</strong>? Suddenly, that single server is a single point of failure. If you don’t design defensively, every layer of your application will begin throttling, unhandled concurrency will corrupt your data, and your network will collapse.</p><p><strong>1. Compute Scaling: From Vertical to Horizontal</strong></p><p>Your first estimation challenge is handling raw compute load.</p><ul><li><strong>Vertical Scaling (Scale-Up):</strong> Adding more CPU and RAM to your single server. It is simple but has a hard physical limit. It also creates a massive single point of failure.</li><li><strong>Horizontal Scaling (Scale-Out):</strong> Adding more web servers to your pool.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3lrx8hVdnnXSA375sOIWSQ.png" /></figure><p><strong>The Stack Transformation:</strong> For 10 million users, horizontal scaling is mandatory. To make this work, your web tier must shift from <strong>stateful</strong> to <strong>stateless</strong>. If your servers store user sessions locally, a user will log out the moment the system routes them to a different server. By moving session data to a shared store like <strong>Redis</strong>, your web servers become interchangeable, allowing you to scale them up and down seamlessly.</p><p><strong>2. Traffic Routing: Load Balancers, API Gateways, and Service Discovery</strong></p><p>With hundreds of web servers running, how do you distribute traffic? You introduce a <strong>Load Balancer</strong> to sit in front of your web tier and route requests evenly. As your ecosystem grows, your estimation forces the addition of an <strong>API Gateway</strong> to handle cross-cutting concerns like authentication and request routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qy6AKlHsThNRyQ26OKufHQ.png" /></figure><p><strong>Choosing Your Gateway (AWS API Gateway vs. Apigee):</strong></p><ul><li><strong>AWS API Gateway:</strong> Ideal if you are already deeply embedded in the AWS ecosystem. It integrates natively with serverless components but can become expensive at massive scales.</li><li><strong>Apigee:</strong> Better suited for complex enterprise environments, hybrid-cloud setups, or scenarios requiring advanced analytics and monetization tools.</li></ul><p><strong>Microservice Dynamic Topography: Service Registry &amp; Discovery</strong></p><p>When a system scales horizontally to support 10 million users, you no longer have a static list of IP addresses for your servers. Auto-scaling groups constantly spin up new containers and destroy unhealthy ones based on real-time traffic spikes. To maintain your <strong>Availability NFR</strong>, you must decouple service locations using a <strong>Service Registry and Service Discovery mechanism</strong>:</p><ul><li><strong>Service Registry:</strong> A centralized database containing the network locations (IP and Port) of all active microservice instances.</li><li><strong>Service Discovery:</strong> The process by which a service queries the registry to find the optimal network path to another microservice.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gzRmkgAltuqgbpiW4cpCsw.png" /></figure><p><strong>The Tech Stack Blueprint</strong></p><p>Depending on your infrastructure, your estimation of metadata traffic drives your choice of tools:</p><ul><li><strong>Cloud-Native Container Orchestration:</strong> <strong>Kubernetes CoreDNS</strong> or <strong>AWS Cloud Map</strong> handle registries natively. They reduce code overhead but can suffer from brief TTL lag during rapid scaling.</li><li><strong>Service Meshes:</strong> <strong>Istio (with Envoy Proxy)</strong> provide sidecar proxies for discovery, advanced traffic splitting, and retries.</li><li><strong>Dedicated Application-Level Tools:</strong> <strong>Netflix Eureka</strong> uses an eventually consistent approach, caching the map locally on clients so discovery still works even if the central registry experiences a brief outage. <strong>Apache ZooKeeper</strong> provides strict consistency, though a network hiccup can risk blocking registration writes.</li></ul><p><strong>Preventing Throttling at the Gateway Layer</strong></p><p>The Gateway is your first line of defense against traffic spikes. To prevent downstream web servers from being overwhelmed, implement <strong>Rate Limiting</strong> and <strong>Throttling policies</strong> (e.g., Token Bucket or Leaky Bucket algorithms) right here. Your back-of-the-envelope math tells you the maximum QPS your web servers can handle; you program the Gateway to throttle any traffic that exceeds this number.</p><p><strong>3. Connection Protocols: The Real-Time Dilemma</strong></p><p>When your application requires real-time updates, you can no longer rely on standard HTTP request-response patterns. The mechanism you choose to stream data to your 10 million users will fundamentally reshape your network layer and infrastructure spend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NV9A1geb-uebP-8ta9QFQg.png" /></figure><p><strong>The Estimation Impact on Infrastructure</strong></p><ul><li><em>Short Polling:</em> If 10 million active users poll your server every 5 seconds, your web tier must handle <strong>2 million QPS</strong> just for updates, even if there is no new data. This causes an artificial traffic storm that will quickly throttle your API gateways.</li><li><em>WebSockets/SSE:</em> Instead of high QPS, your estimation shifts to <strong>Concurrent Open Connections</strong>. If 2 million users are online simultaneously, your system must maintain 2 million persistent connections. Since each open connection consumes server memory, your estimation tells you exactly how many gigabytes of RAM your server fleet requires.</li></ul><p><strong>Real-World Trade-offs: When to Use What?</strong></p><p><strong>Short Polling (Example: Uber Driver Tracking)</strong></p><p>The client repeatedly sends standard HTTP requests at fixed intervals.</p><ul><li><strong>When to use:</strong> When data updates infrequently or precision timing isn’t critical.</li><li><strong>Analogy:</strong> A child in the back seat of a car repeatedly asking, <em>“Are we there yet? Are we there yet?”</em> every 10 seconds.</li></ul><p><strong>Long Polling (Example: Legacy Web Chat Apps)</strong></p><p>The client requests data, and the server holds the request open until new data is available or a timeout occurs. Once data is sent, the client immediately opens a new request.</p><ul><li><strong>When to use:</strong> When you need real-time data but must support old web browsers that do not support modern streaming protocols.</li><li><strong>Analogy:</strong> You text a friend asking for information, and they don’t reply immediately. They leave your chat bubble open and only hit send twenty minutes later when they actually have the answer.</li></ul><p><strong>Server-Sent Events (SSE) (Example: Live Stock Tickers or Twitter Feeds)</strong></p><p>A persistent, long-lived HTTP connection where the server streams data to the client in a unidirectional format.</p><ul><li><strong>When to use:</strong> When the client only needs to receive a continuous stream of data from the server, but does not need to send data back over that same pipe (e.g., live sports score updates).</li><li><strong>Analogy:</strong> Tuning into a live radio broadcast. You turn the radio on once and listen to a continuous stream of music, but you cannot talk back to the DJ through your radio set.</li></ul><p><strong>WebSockets (Example: Competitive Multiplayer Games or WhatsApp Web)</strong></p><p>A single, long-lived, bidirectional TCP connection established via an HTTP handshake (“protocol upgrade”).</p><ul><li><strong>When to use:</strong> When you require ultra-low latency, fast-paced, bidirectional communication where both client and server are constantly talking to each other.</li><li><strong>Analogy:</strong> A continuous, open phone call. Both you and your friend have your phones glued to your ears and can speak over each other at any split second without redialing.</li><li><strong>The Tech Stack Shift:</strong> WebSockets make your web tier <strong>stateful</strong>. Unlike a standard REST API where any server can handle any request, a WebSocket client is permanently married to the specific server instance holding its TCP socket.</li></ul><p><strong>Preventing Throttling at the Real-Time Layer</strong></p><p>If you choose WebSockets or SSE for 10 million users, you cannot use traditional multi-threaded web servers (like Tomcat), because creating one thread per user will instantly deplete server memory. Instead, your estimation forces a shift toward asynchronous, event-driven I/O architectures like <strong>Node.js, Go (goroutines), Elixir, or Netty (Java)</strong>.</p><p>To handle reconnection spikes (Thundering Herd problem) if a server dies, you must implement <strong>Connection Smearing</strong> (introducing random jitter to client reconnections) and use specialized load balancers (like HAProxy or NGINX configured with consistent hashing) to gracefully distribute the long-lived stateful load.</p><p><strong>4. Concurrency Tier: Race Conditions &amp; Sync Issues</strong></p><p>When 10 million users interact with a horizontally scaled system, multiple web servers will inevitably try to update the exact same data at the exact same millisecond (e.g., two users buying the last ticket to a concert).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UVn26WoKPT0YCPVACRB0Aw.png" /></figure><p><strong>Where do we identify this?</strong></p><p>This is identified during <strong>Trade-off Analysis</strong>, heavily driven by your <strong>NFRs</strong> and validated by your <strong>Estimations</strong>.</p><ul><li>Your <strong>Estimation</strong> reveals high concurrent write QPS, warning you that the probability of a data collision is mathematically high.</li><li>Your <strong>NFR</strong> dictates how strict your data integrity must be (e.g., financial systems require 100% accuracy; social media likes can tolerate minor temporary discrepancies).</li></ul><p><strong>How to Tackle Concurrency at Scale</strong></p><p>To resolve these synchronization bottlenecks, you must choose your weapon based on your architectural trade-offs:</p><ol><li><strong>Pessimistic Locking:</strong> The system locks the data record the moment a server reads it, preventing any other server from touching it until the transaction finishes.</li></ol><ul><li><em>Trade-off:</em> Guarantees absolute data consistency (NFR) but kills performance and causes severe database throttling at high QPS (Estimation).</li></ul><ol><li><strong>Optimistic Locking (Versioning):</strong> Records include a version number. When updating, the server checks if the version has changed since it last read it. If it has, the update fails, and the application retries.</li></ol><ul><li><em>Trade-off:</em> High performance and low latency, but requires your application tier to handle transaction retries gracefully.</li></ul><ol><li><strong>Distributed Locks (Redis/Zookeeper):</strong> When operating across multiple data centers, you use a distributed locking mechanism (like Redlock) to ensure only one microservice handles a specific entity ID at a time.</li></ol><p><strong>5. Storage Tier: Relational vs. Non-Relational</strong></p><p>As traffic grows, the database is almost always the first bottleneck. Your estimation forces a critical question: SQL or NoSQL?</p><p>If your estimation reveals <strong>massive data volume</strong>, a requirement for <strong>super-low latency</strong>, and <strong>no complex relations</strong> between data points, <strong>NoSQL (Non-Relational)</strong> is the clear winner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*22U7wx_MqsaU0xZatySFDA.png" /></figure><p><strong>The CAP Theorem Trade-off: Strong vs. Eventual Consistency</strong></p><p>Choosing NoSQL introduces a fundamental architectural trade-off regarding data synchronization. In a distributed system, you must choose between Strong Consistency and Eventual Consistency.</p><ul><li><strong>Strong Consistency:</strong> Every read returns the absolute latest write (e.g., a banking system). This introduces latency because data must sync across all nodes before a response is sent.</li><li><strong>Eventual Consistency:</strong> The system accepts writes immediately, and data propagates to other nodes over time (e.g., social media likes). This delivers the <strong>super-low latency</strong> required for millions of users, but users might occasionally see slightly outdated data for a few seconds.</li></ul><p><strong>6. Database Scaling: Replicas, Partitioning, and Sharding</strong></p><p>When a single database node can no longer handle the 10M user load, it will throttle connection pools and CPU. You must scale the data tier using three primary strategies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4LDVOstfNYXj7zyl7rQl8A.png" /></figure><ul><li><strong>Read Replicas:</strong> You have one master database for writes, which copies data to multiple replica databases for reads. <strong>Use case:</strong> When your estimation shows a high read-to-write ratio (e.g., 9:1).</li><li><strong>Partitioning:</strong> Dividing a large database table into smaller subsets within the <em>same</em> database engine (e.g., partitioning data by year) to optimize querying.</li><li><strong>Sharding:</strong> Breaking up your data and distributing it across <em>entirely separate</em> database servers based on a shard key (e.g., users A-M on Server 1, N-Z on Server 2). <strong>The Trade-off:</strong> Sharding offers infinite scalability, but it adds massive architectural complexity, making cross-shard joins nearly impossible.</li></ul><p><strong>Preventing Throttling at the Database Layer</strong></p><p>Databases throttle when they run out of open connections or disk I/O operations (IOPS). You prevent database throttling by using <strong>Connection Pooling</strong> (like HikariCP) so applications reuse existing connections rather than constantly opening new ones. Furthermore, implementing <strong>Read Replicas</strong> ensures that heavy read traffic never throttles your vital write operations.</p><p><strong>7. High-Density Storage: Retention, Purging, and Asset Types</strong></p><p>An often overlooked NFR is <strong>Data Retention</strong> — storing user data for extended periods (e.g., 5 years). At 10 million users, data retention requirements completely transform your storage hardware and purging architectures depending on the data type: <strong>Text, Images, or Video</strong>.</p><p><strong>The Impact Loop: Back-of-the-Envelope Math by Asset Type</strong></p><p>Let’s look at how back-of-the-envelope estimations explode your hardware footprint over a 5-year retention window if we assume 10 million users upload just <em>one</em> item per day:</p><ul><li><strong>Text Data (e.g., Chat messages, Logs):</strong> 1 message = 500 bytes. 10M × 500 bytes = 5 GB/day. 5-Year Total: 5GB × 365 × 5=9.1 TB. This can live comfortably in relational databases (<strong>PostgreSQL</strong>) or distributed NoSQL databases (<strong>Cassandra</strong>).</li><li><strong>Image Data (e.g., Profile pictures):</strong> 1 compressed image = 200 KB. 10M × 200 KB = 2 TB/day. 5-Year Total: 2TB × 365 × 5 = 3.65 PB (Petabytes). Storing this directly in a database will break it. You must store images in a distributed Object Store (<strong>AWS S3 / Google Cloud Storage</strong>) and save only the URL string in the database.</li><li><strong>Video Data (e.g., Short clips):</strong> 1 optimized short video = 5 MB. 10M × 5 MB = 50 TB/day. 5-Year Total: 50 TB × 365 × 5= 91.25 PB. This scale requires advanced storage lifecycle management, specialized video transcoding clusters, and multi-region object storage networks.</li></ul><p><strong>Storage Tiering: Hot, Warm, and Cold Tiers</strong></p><p>To meet your <strong>Cost Efficiency NFR</strong>, you must employ <strong>Storage Tiering</strong>:</p><ol><li><strong>Hot Tier (SSD / Active DB):</strong> Holds data from the last 0–30 days. Optimized for hyper-low latency.</li><li><strong>Warm Tier (Standard Object Storage):</strong> Holds data from 31–365 days. Data is rarely accessed but must be retrievable within seconds.</li><li><strong>Cold Tier (Archival Storage — e.g., AWS Glacier Vaults):</strong> Holds data from years 2 to 5. Retrieval takes minutes or hours, but the storage cost is up to 90% cheaper.</li></ol><p><strong>Preventing Purging Throttling</strong></p><p>Running a massive DELETE FROM table WHERE date &lt; 5_years_ago query on billions of rows will lock your tables, consume 100% of your database CPU, and throttle active traffic. To prevent this, your tech stack must use <strong>Time-To-Live (TTL)</strong> properties at the database layer where records self-destruct silently, combined with <strong>S3 Lifecycle Policies</strong> to handle object purges asynchronously in the background.</p><p><strong>8. Performance Optimization: Caches and CDNs</strong></p><p>To meet ultra-low latency goals at scale, you must prevent unnecessary database hits.</p><p><strong>L1 vs. L2 Caching</strong></p><ul><li><strong>L1 Cache (In-Memory/Application Level):</strong> Cached data lives directly inside the web server’s memory. It is blazing fast but tied to that specific server instance.</li><li><strong>L2 Cache (Distributed Level):</strong> A separate caching tier shared by all web servers (e.g., Redis).</li><li><strong>Are both needed?</strong> At 10 million users, an <strong>L2 cache is absolutely required</strong> to keep data synchronized across your stateless web tier. An L1 cache can be layered on top for hyper-frequent, static configurations, but an L2 cache handles the heavy lifting.</li></ul><p><strong>Content Delivery Networks (CDNs)</strong></p><p>A CDN caches static assets (images, video, JS/CSS files) at edge locations closer to the user geographically to reduce latency.</p><p><strong>Preventing Throttling via Code Optimization &amp; Circuit Breakers</strong></p><p>At 10 million users, micro-optimizations yield macro results. Your <strong>Estimation math</strong> dictates your data payload sizes. By choosing efficient serialization formats (like <strong>Protocol Buffers</strong> over heavy JSON) and enabling network compression (<strong>Gzip/Brotli</strong>), you significantly reduce network I/O throttling.</p><p>Furthermore, if your cache layer fails, all traffic cascades to your database (Cache Stampede). To prevent the cache itself from throttling or crashing under a stampede, use <strong>Circuit Breakers</strong> to gently reject traffic if the cache is struggling, and implement <strong>Probabilistic Early Expiration</strong> to refresh keys before they expire.</p><p><strong>9. Elastic Routing: Consistent Hashing</strong></p><p>When scaling your stateless web servers and L2 distributed caches to survive millions of users, you will constantly add and remove server nodes. Traditional routing mechanics (hash(key) % N) fail catastrophically at this scale. If a single cache node dies, the value of N changes, invalidating your entire cache tier instantly. This triggers a massive cache stampede that immediately throttles your database.</p><p>To safeguard your <strong>Availability NFR</strong>, you must implement <strong>Consistent Hashing</strong>. By mapping keys and servers onto a logical hash ring, adding or removing a node only disrupts a tiny fraction of your data.</p><p><strong>The Architectural Trade-off</strong></p><p>While consistent hashing prevents cluster-wide cascading failures, it introduces the risk of data “hotspots,” where one server accidentally handles a disproportionate amount of traffic. To mitigate this, you must adopt <strong>Virtual Nodes (Vnodes)</strong>, trading away routing simplicity to gain uniform load distribution across your infrastructure.</p><p><strong>10. Identity Tier: Unique ID Generation</strong></p><p>When scaling to 10 million users and thousands of concurrent database writes, relying on standard database auto-increment fields breaks entirely. If you force multiple database shards or global regions to talk to a single centralized machine just to fetch the next available ID number, that machine will immediately throttle and crash your system.</p><p><strong>The Estimation Impact on Bit Size</strong></p><p>Back-of-the-envelope math dictates your ID bit size. If you estimate 10 million daily active users creating 100 items each per day, you generate 1 billion IDs daily. A standard 32-bit integer overflows at ~2.1 billion (in just two days). Your calculation proves you <strong>must use a 64-bit or 128-bit ID space</strong> to ensure your system can operate for decades without running out of IDs.</p><p><strong>Tackling Distributed ID Generation: The Architectural Choices</strong></p><ol><li><strong>UUID/GUID (128-bit Random Strings):</strong> Generated independently by web servers without talking to any database.</li></ol><ul><li><em>The Trade-off:</em> UUIDs are completely out of order. Using them as database primary keys destroys index performance (causing massive disk fragmentation and database throttling during writes).</li></ul><ol><li><strong>Flicker’s Ticket Server Approach:</strong> Using a dedicated central cluster of database servers that use a modulo step (e.g., Server 1 generates 1, 3, 5…, Server 2 generates 2, 4, 6…) to issue IDs.</li></ol><ul><li><em>The Trade-off:</em> Hard to scale horizontally if write volume suddenly spikes past your back-of-the-envelope estimations.</li></ul><ol><li><strong>Twitter Snowflake Algorithm (64-bit Time-Sortable IDs):</strong> This divides a 64-bit integer into dedicated sections: 1 bit for unused/sign, 41 bits for a millisecond timestamp, 10 bits for a machine ID, and 12 bits for a local sequence counter.</li></ol><ul><li><em>The Trade-off:</em> Highly performant and <strong>time-sortable</strong>, but your NFRs must tolerate minor clock drift across distributed servers.</li></ul><p><strong>11. Fault Tolerance: Designing for Three Tiers of Outages</strong></p><p>At 10 million users, failures are guaranteed. Your <strong>Availability NFR</strong> (e.g., 99.99% uptime) means your system can only tolerate 52 minutes of downtime <em>per year</em>. You must architect specific defenses for three types of outages:</p><p><strong>Tier 1: Temporary (Transient) Outages</strong></p><p>Short-lived drops in connectivity or temporary server hiccups lasting fractions of a second.</p><ul><li><strong>The Strategy:</strong> Do not trigger an expensive failover. Instead, use <strong>Retries with Exponential Backoff and Jitter</strong>. Combine this with <strong>Circuit Breakers</strong> to fail fast if a downstream dependency is completely unresponsive.</li></ul><p><strong>Tier 2: Permanent Outages</strong></p><p>This happens when a physical hard drive dies or a server node permanently crashes.</p><ul><li><strong>The Strategy:</strong> You must have automatic <strong>Leader Election</strong> algorithms (like Raft or Paxos) built into your database tier. If a master node experiences a permanent outage, a read replica must automatically be promoted to leader within seconds.</li></ul><p><strong>Tier 3: Data Center (Regional) Outages</strong></p><p>A complete cloud provider’s availability region goes completely dark.</p><ul><li><strong>The Strategy:</strong> You must deploy a <strong>Multi-Region Active-Active</strong> or <strong>Active-Passive</strong> architecture. Traffic must be routed at the DNS/CDN layer using Geo-routing.</li><li><strong>The Estimation &amp; Trade-off:</strong> Active-Active configurations mean data must replicate across continents. Back-of-the-envelope estimation warns you that the speed of light limits cross-region replication speed. You face a strict trade-off: accept higher write latency to keep data perfectly synchronized across both regions, or choose eventual consistency and risk minor data loss during a catastrophic regional failure.</li></ul><p><strong>12. Asynchronous Processing: Message Queues &amp; Resiliency</strong></p><p>When handling millions of users, traffic spikes unpredictably. To ensure long-term resiliency, you must decouple your core services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*91dfoM-NHU-glXpFOour5g.png" /></figure><ul><li><strong>Message Queues (Kafka/RabbitMQ):</strong> Instead of a web server talking directly to a slow background service, it drops a message into a queue.</li><li><strong>Logging and Monitoring:</strong> Automated monitoring (<strong>Prometheus, Grafana</strong>) acts as your system’s smoke alarm, while centralized logging (<strong>ELK stack</strong>) tracks down issues across thousands of distributed servers.</li></ul><p><strong>Preventing Throttling at the Application/Worker Layer</strong></p><p>If your background workers cannot keep up with the incoming data from the web tier, they will throttle and fail. By placing a <strong>Message Queue</strong> in the middle, you gracefully handle spikes. To prevent the workers from crashing, implement <strong>Backpressure mechanisms</strong> where workers pull only what they can process, rather than having data forcefully pushed onto them.</p><p><strong>Conclusion: Numbers Dictate Nature</strong></p><p>Back-of-the-envelope estimation is never just an academic math exercise. It is the bridge that connects high-level business NFRs to actual, low-level technical infrastructure.</p><p>The moment your calculations show that a single server, database, or cache tier will crumble under the weight of 10 million users, those numbers dictate your choices. They force you to balance data integrity against latency, implement optimistic locking patterns, establish strategic rate-limiting at the gateway, design consistent hashing rings, evaluate real-time connection protocols, orchestrate tiered retention models for massive petabyte assets, plan for regional disasters, evaluate decentralized ID systems, and deploy decoupled messaging tiers to absorb the shock.</p><p>Design with the numbers first, understand where the bottlenecks will throttle, and the architecture will naturally follow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bb382b6dbe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From “Software Collapse” to Production-Grade: The AI Architecture Shift You Can’t Afford to Skip]]></title>
            <link>https://medium.com/@smreseedabanu/from-software-collapse-to-production-grade-the-ai-architecture-shift-you-cant-afford-to-skip-212a79d71bd5?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/212a79d71bd5</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 07:38:30 GMT</pubDate>
            <atom:updated>2026-06-09T07:38:30.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xV_L04iAu2wkZNNHDWFWfg.png" /></figure><p>Imagine you are building a house. You ask the owner what they want. They say, “I want three bedrooms, a large kitchen, and a blue front door.”</p><p>You immediately start building. The house looks beautiful. But the first time a storm hits, the roof leaks, the walls shake, and the foundation cracks right down the middle.</p><p>What went wrong? You built exactly what they asked for, but you forgot to make it strong, safe, and weatherproof.</p><p>In the software world, we make this mistake every single day. We gather the business requirements (the features), and we straight away start designing and coding. <strong>This is the wrong way to start.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*XsIQ95B-zdXtcTUt2LQm7A.png" /></figure><p>To build systems that actually survive in the real world — especially in the era of Artificial Intelligence (AI) — we must capture <strong>NFRs</strong> (Non-Functional Requirements).</p><p><strong>What on Earth is an NFR?</strong></p><p>If business requirements describe <em>what</em> the system does (e.g., “the chatbot must answer customer questions”), NFRs describe <em>how</em> the system behaves (e.g., “the chatbot must answer 5,000 users at once without slowing down, breaking the bank, or leaking data”).</p><p>If you ignore NFRs, you will choose the wrong technologies, and your AI application will crash, lag, or become too expensive to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*d9z7DPhtldX6OOaAA3Vukg.png" /></figure><p>Designing only for features builds a fragile house that collapses under stress. Designing with NFRs builds an unshakeable production fortress.</p><p><strong>The Expanded NFR Checklist &amp; Tools</strong></p><p>Before we look at AI, every modern system design must solve these fundamental NFRs. Here is what you need to consider, the architectural decisions you must make, and the tools to use:</p><p><strong>1. Security: Layered Protection (The Digital Guard Rails)</strong></p><p>Security is not a single wall; it changes depending on where the data is traveling. You must split your security strategy into two distinct zones:</p><p><strong>Zone A: From Client to API Gateway (External Security)</strong></p><ul><li><em>The Goal:</em> Protect your system from the public internet. You need to verify who the user is and encrypt the data they send.</li><li><em>How it works:</em> The client logs in through an <strong>Identity Provider (IdP)</strong>. The API Gateway intercepts the request to verify the user’s digital signature (Token).</li><li><em>Tools:</em> <strong>Amazon Cognito</strong>, <strong>Auth0</strong>, or <strong>Okta</strong> (as the IdP). <strong>AWS WAF</strong> (Web Application Firewall) to block malicious web attacks.</li></ul><p><strong>Zone B: From API Gateway to Compute (Internal Security)</strong></p><ul><li><em>The Goal:</em> Microservice isolation. Once a request is inside your cloud, components shouldn’t blindly trust each other.</li><li><em>How it works:</em> The API Gateway strips down the user token and uses secure, private cloud permissions to talk to your servers. Traffic inside must be locked down so a breach in one component doesn’t expose the whole system.</li><li><em>Tools:</em> <strong>AWS IAM (Identity and Access Management)</strong> roles, private subnets (VPC), and <strong>mTLS</strong> (Mutual TLS) to encrypt server-to-server talk.</li></ul><p><strong>2. The Great Compute Debate: AWS Lambda vs. Amazon EKS</strong></p><p>When deciding where to run your code, there is an endless debate in the tech community: <strong>Should we go Serverless (AWS Lambda) or Containerized (Amazon EKS)?</strong> There is no single right answer. Your choice entirely depends on your NFR priorities.</p><p>Let’s look at the trade-offs to justify when to choose which:</p><p><strong>AWS Lambda (Serverless)</strong></p><ul><li><em>The Pros:</em> Zero server management. It scales up from zero to thousands of requests instantly, and you only pay when code actually runs.</li><li><em>The Cons (The Cold Start Problem):</em> If no one uses your chatbot for a while, AWS shuts down the idle environment. The next user who sends a message experiences a painful <strong>Cold Start delay (5 to 10 seconds)</strong> while AWS provisions a fresh container. Furthermore, Lambda has strict execution time limits (15 minutes).</li><li><em>When to choose it:</em> Use Lambda if you are launching an internal tool, a low-to-medium traffic app, or a startup prototype where minimizing idle cloud bills is more important than absolute, sub-second latency.</li></ul><p><strong>Amazon EKS (Kubernetes Containers)</strong></p><ul><li><em>The Pros:</em> Massive, sustained performance with <strong>zero cold starts</strong>. Servers are kept “warm” and running, ensuring sub-second response times for every single request. It handles complex, long-running AI workloads seamlessly and gives you total control over the underlying hardware.</li><li><em>The Cons:</em> Highly complex. It requires significant engineering effort to set up, secure, and maintain. You also pay a baseline cost for running the cluster 24/7, even if traffic drops to zero at night.</li><li><em>When to choose it:</em> Use EKS if you are running a production-grade, enterprise-scale AI chatbot where fast, predictable latency is non-negotiable and your traffic patterns are high and steady.</li></ul><p><strong>3. The CAP Theorem (Data Strategy)</strong></p><p>In a distributed cloud network, you can only pick two out of three: <strong>Consistency</strong> (same data everywhere), <strong>Availability</strong> (always up), or <strong>Partition Tolerance</strong> (survives network drops). You must pick the right database based on this choice.</p><ul><li><strong>Tools for Consistency (CP):</strong> PostgreSQL, MySQL, Amazon Aurora (Great for financial transactions or user profiles).</li><li><strong>Tools for Availability (AP):</strong> Amazon DynamoDB, Apache Cassandra, MongoDB (Great for chat history or real-time feeds).</li></ul><p><strong>4. Performance, Latency, and Sudden Spikes</strong></p><p>Your system needs to load fast (under 2 seconds) and handle massive traffic jumps without crashing.</p><ul><li><strong>Tools for Speed &amp; Caching:</strong> Redis, Memcached, Amazon ElastiCache (Stores data in memory so you don’t hit the slow database every time).</li><li><strong>Tools for Global Speed:</strong> Cloudflare, AWS CloudFront (Content Delivery Networks that put your app physically closer to global users).</li></ul><p><strong>5. Auditing and Observability (System Metrics)</strong></p><p>You need to trace user actions for security and see inside your application to fix bugs before customers complain. For AI applications, you use these tools to monitor your infrastructure health and system traffic.</p><ul><li><strong>Tools for Logging &amp; Tracing:</strong> OpenTelemetry, Jaeger, AWS CloudTrail, Splunk.</li><li><strong>Tools for Dashboards &amp; System Metrics:</strong> <strong>Prometheus</strong> (to collect data like request rates and error codes) and <strong>Grafana</strong> (to build beautiful visual dashboards for your engineering team), alongside enterprise tools like Datadog or the Kibana (ELK Stack).</li></ul><p><strong>Before vs. After: The Evolution of a Chat System Design</strong></p><p>To see the power of NFRs in action, let’s look at how a system design completely changes before and after you take them into consideration.</p><p><strong>Before NFRs: The “Happy Path” Prototype</strong></p><p>When you only focus on business requirements (“Allow a user to chat with an AI”), your design is simple, fragile, and bound to fail in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*wxUAAGDs_jqtJkgfKOlYrg.png" /></figure><p><strong>The Flow:</strong> The user types a message → The backend server receives it → The server sends it to the AI API → The AI responds → The server sends it back to the user.</p><ol><li><strong>The Database:</strong> A basic SQL database holds everything — user data, chat messages, and configuration.</li><li><strong>The Flaws in this Design:</strong></li></ol><ul><li><strong>The Crash:</strong> If 10,000 users log in at once, the single backend server runs out of memory and crashes.</li><li><strong>The Amnesia:</strong> The AI forgets what the user said two sentences ago because there is no system tracking conversation history.</li><li><strong>The Bill:</strong> If a user repeatedly spams the chat, the system happily processes every single request, resulting in a massive cloud bill by morning.</li><li><strong>The Black Box:</strong> If a user gets an error message, the engineering team has no idea why it happened because there are no logs.</li></ul><p><strong>After NFRs: The Production-Ready Architecture</strong></p><p>When you inject NFRs into the design phase, you introduce specialized tools to handle traffic, memory, speed, and failures safely. The design transforms into a robust engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C98e2RpnvT67Y8OCBigRgg.png" /></figure><ol><li><strong>The Identity Verification:</strong> A user logs in safely using an IdP (<strong>Auth0/Cognito</strong>). The <strong>API Gateway</strong> validates this access token immediately.</li><li><strong>The Traffic Guard (Rate Limiting):</strong> Before the message touches your internal servers, the API Gateway checks your usage limits. If a user spams the chatbot, they are blocked instantly, protecting your budget.</li><li><strong>The Secure Compute Transition:</strong> The gateway hands the filtered request over to your secure container cluster (<strong>Amazon EKS</strong>). Because EKS instances are kept warm and running, there are <strong>no cold start delays</strong>, keeping your response latency ultra-low.</li><li><strong>The Brain (Memory Cache):</strong> Instead of hitting a slow database or sending a massive text history to the AI, the backend pulls the last 3 messages instantly from a fast <strong>In-Memory Cache (e.g., Redis)</strong>. It bundles this context efficiently for the AI.</li><li><strong>The Shock Absorber (Autoscaling):</strong> If traffic spikes suddenly, <strong>Autoscaling (e.g., KEDA on Kubernetes)</strong> detects the long queue of messages and automatically boots up new server instances in seconds.</li><li><strong>The Guardian Angels (Observability &amp; Alerting):</strong> Every single interaction is tracked silently by <strong>OpenTelemetry</strong>. Prometheus scrapes metrics like token counts and model generation delay, passing them to Grafana dashboards. If the AI throws errors, <strong>Prometheus</strong> triggers <strong>PagerDuty</strong> via Alertmanager to alert an engineer before users notice.</li></ol><p><strong>Making an AI Chatbot Production-Ready</strong></p><p>Building a chatbot prototype on your laptop is easy. Taking it to <strong>production</strong> — where thousands of real users interact with it — is incredibly hard. AI introduces unique bottlenecks that standard web apps do not have.</p><p>Here is how you solve AI NFRs using the right production tools:</p><p><strong>1. Chat Memory Management (Context Window)</strong></p><p>AI models do not remember past messages automatically. You must feed the previous conversation back to the AI with every new question, which quickly makes the data size massive.</p><ul><li><strong>The Goal:</strong> Keep memory fast and cheap without overloading the AI.</li><li><strong>The Tools:</strong> <strong>Redis</strong> or <strong>Upstash</strong> (for super-fast session memory storage). <strong>LangChain</strong> or <strong>LlamaIndex</strong> (to automatically summarize or trim older parts of the conversation).</li></ul><p><strong>2. Rate Limiting (Cost &amp; Abuse Control)</strong></p><p>AI API calls are highly expensive. A single malicious user or a broken loop script could spam your chatbot millions of times, racking up a massive cloud bill.</p><ul><li><strong>The Goal:</strong> Restrict users to a sensible limit (e.g., maximum 10 chatbot queries per minute).</li><li><strong>The Tools:</strong> <strong>AWS API Gateway</strong>, <strong>Kong</strong>, or <strong>Apigee</strong> (to block spam traffic before it ever reaches your expensive AI models).</li></ul><p><strong>3. Intelligent Autoscaling</strong></p><p>Standard apps scale based on basic server CPU usage. AI apps are different; they are bound by third-party API rate limits and heavy GPU processing.</p><ul><li><strong>The Goal:</strong> Spin up more servers automatically when user requests queue up.</li><li><strong>The Tools:</strong> <strong>AWS Auto Scaling</strong> combined with <strong>Amazon ECS</strong> or <strong>EKS (Kubernetes)</strong>. For AI-specific workloads, tools like <strong>KEDA</strong> (Kubernetes Event-driven Autoscaling) allow you to scale servers based on the exact number of messages waiting in your queue.</li></ul><p><strong>4. Proactive Alerting Mechanisms</strong></p><p>Observability tells you there is a problem; alerting rings the alarm bell immediately.</p><ul><li><strong>The Goal:</strong> Instantly notify the engineering team if the chatbot gets slow or starts throwing errors.</li><li><strong>The Tools:</strong> <strong>Prometheus</strong> or <strong>AWS CloudWatch</strong> to detect the errors, connected directly to <strong>PagerDuty</strong>, <strong>Opsgenie</strong>, or <strong>Slack</strong> to wake up the on-call engineer.</li></ul><p><strong>5. AI Quality &amp; Guardrails (AI-Specific Auditing)</strong></p><p>You need to ensure the AI isn’t hallucinating, giving wrong answers, or leaking sensitive system prompts.</p><ul><li><strong>The Goal:</strong> Track the accuracy of the AI responses, block harmful inputs, and monitor AI token usage.</li><li><strong>How it works with your stack:</strong> You can use specialized AI monitoring tools, or you can use open-source exporters to feed AI metrics (like LLM generation latency and token usage) directly into <strong>Prometheus and Grafana</strong>. This allows your team to view server health and AI behavior on the exact same dashboard screen.</li><li><strong>The Tools:</strong> <strong>LangSmith</strong>, <strong>Arize AI (Phoenix)</strong>, or <strong>TruLens</strong> for evaluating AI behavior, combined with <strong>Prometheus + Grafana</strong> for operational AI dashboards, and <strong>NeMo Guardrails</strong> to stop the AI from saying things it shouldn’t.</li></ul><p><strong>The Blueprint: AWS Architecture Evolution</strong></p><p>If you are deploying this architecture on AWS, here is exactly how your blueprint changes when you switch your focus from features to NFRs.</p><p><strong>The “Happy Path” AWS Prototype (Before NFRs)</strong></p><p>When an engineering team builds exclusively for a feature checklist, they design for the “Happy Path” — the unrealistic scenario where traffic is steady, users are nice, and the network never hiccups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cF0m7H0rYtam8qPiljDQaw.png" /></figure><p><strong>Architectural Justification for the Diagram (Why it collapses):</strong></p><ul><li><strong>The Compute Bottleneck:</strong> Because traffic hits the single backend instance directly, a sudden spike in concurrent users immediately exhausts the server’s thread pool. As CPU and RAM rocket toward 99%, requests queue up, leading to 504 Gateway Timeouts and a complete crash.</li><li><strong>The Storage Choke Point:</strong> Relational SQL databases are optimized for structured data, not rapid-fire stream updates. Forcing the server to read and write entire chat logs from the disk for every message creates an I/O (Input/Output) logjam. Database latency spikes past 750ms, dragging the entire application down.</li><li><strong>The Financial Risk:</strong> Without a rate-limiting layer at the perimeter, the backend is entirely vulnerable to denial-of-service (DoS) attacks or broken loop scripts, which can effortlessly trigger millions of expensive un-cached AI API calls, resulting in an unpayable cloud bill overnight.</li></ul><p><strong>After NFRs: The Production-Ready Architecture (Technical Breakdown)</strong></p><p>When you inject NFRs into the design phase, you completely isolate and protect your application logic. You introduce specialized cloud tools that act as shields, shock absorbers, and dedicated memory banks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tijQizlPFqJiPx2BkZM-LA.png" /></figure><p><strong>Architectural Justification for the Diagram (Why it survives):</strong></p><ul><li><strong>Zero Performance Delays:</strong> By opting for an autoscaled <strong>Amazon EKS</strong> cluster over Serverless Lambda functions for high-volume endpoints, the architecture eliminates the risk of “Cold Starts.” The servers are persistently active, keeping user response times ultra-fast.</li><li><strong>Elastic Shock Absorbers:</strong> The compute layer is integrated with an event-driven autoscaler (<strong>KEDA</strong>). If a massive spike of traffic hits the system, the autoscaler detects the request volume surge and instantly provisions new application tasks across the infrastructure in seconds, absorbing the blow without dropping a single user session.</li><li><strong>Unified Observability:</strong> Every interaction passes trace tokens to <strong>Prometheus</strong>. Infrastructure load and AI metrics (such as token counts and LLM latency) are scraped dynamically and funneled into a central <strong>Grafana</strong> dashboard, allowing operators to visualize system health and receive instant alarms before performance begins to decay.</li></ul><p><strong>The Golden Rule</strong></p><p>Stop rushing into the design phase the moment you get a list of features.</p><p>Take a breath. Ask the hard questions about scale, speed, costs, security boundaries, and runtime environments. Map out your NFRs first, and pick the tools from this list that match your goals.</p><p>Your users — and your cloud budget — will thank you.</p><p><strong>The Ultimate Verdict: Features Win Demos. NFRs Win Markets.</strong></p><p>It is time for a brutal reality check in modern software engineering.</p><p>Anyone can connect an API to a user interface over a weekend and call it an “AI application.” It looks beautiful in a slide deck. It wins thunderous applause during client demos. But the moment that prototype encounters the unhinged chaos of the public internet, the facade shatters.</p><p>If your backend cannot handle a sudden traffic spike, your features do not matter. If a malicious loop script spams your LLM and drains your entire company cloud budget by sunrise, your features do not matter. If a user walks away because your un-cached chatbot takes 12 seconds to respond, your beautiful code is officially worthless.</p><p>Building a product based entirely on a feature list without baking in <strong>security boundaries, rate limits, intelligent scaling, and robust memory caches</strong> isn’t just cutting corners — it is engineering an inevitable collapse.</p><p>Stop designing software for the “happy path.” Stop assuming your network is perfect, your databases are infinitely fast, and your users are nice. True architectural excellence means building a system that is deliberately designed to survive the worst days, not just the best ones.</p><p>Take a hard look at your current project blueprint. Are you actually engineering a production-grade infrastructure fortress, or are you just painting the front door of a cardboard house?</p><p>Map out your NFRs <em>before</em> you write a single line of code. Your users, your team, and your bottom line will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=212a79d71bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Code is Cheap. Governance is Expensive.]]></title>
            <link>https://medium.com/@smreseedabanu/ai-code-is-cheap-governance-is-expensive-1fb6d88cec92?source=rss-56bd78d38b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb6d88cec92</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Smreseedabanu]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 06:04:40 GMT</pubDate>
            <atom:updated>2026-06-08T06:04:40.925Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Why shipping features at warp speed is a trap. If your team uses AI without engineering guardrails, you are just accelerating toward an architectural collapse.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ptB8rZOhYLAZu9tqAdCB5g.png" /></figure><p>Walk into almost any tech company today, and you will see the same thing.</p><p>Developers have GitHub Copilot running in their IDEs. Cursor is open on a second monitor. Claude drafts are filling up their browsers. Engineering leadership is celebrating. The charts show that code velocity is up. Features are shipping faster than ever. Everyone feels like they are moving at warp speed.</p><p>But it is a trap. And most engineering teams are driving straight into it.</p><p>The harsh reality? Most AI-assisted development initiatives are doomed to fail. Not because the technology is bad, but because teams completely lack <strong>Governance</strong>.</p><h3><strong>The Trap: Speed Without Direction</strong></h3><p>We have confused fast typing with real engineering progress.</p><p>AI makes it incredibly easy to vomit code onto a screen. But it does nothing to help you think about whether that code should exist in the first place. When you prioritize raw speed over architectural discipline, your project decays in three scary ways:</p><ul><li><strong>The Technical Debt Blindspot</strong>: It is far easier to ask an AI to write a quick, messy feature around a broken foundation than it is to fix the foundation itself. The debt is simply swept under the rug. Until the system breaks.</li><li><strong>Engineering by Proxy</strong>: Developers are introducing foreign logic into production environments with absolute blind trust. If you ask them why a function works a certain way, the answer is terrifyingly consistent: <em>“The AI read the User Story and outputted this block. I assumed it was right.”</em></li><li><strong>The Death of the Peer Review</strong>: Code reviews have turned into a superficial checkbox exercise. Pull Requests are being rubber-stamped. They are no longer a place to debate architecture or share deep system knowledge.</li></ul><p>If your team is only using AI to ship brand-new features on top of a fragile core, you aren’t moving faster. You are just accelerating toward a massive architectural collapse.</p><h3><strong>Shifting the Paradigm: AI as a Refactoring Engine</strong></h3><p>What if we are using these models completely backwards?</p><p>Maybe the highest-value use of an AI tool is not spinning up new code to meet an aggressive deadline. Maybe its true power lies in tackling the heavy lifting we always push to the next sprint: cleaning up the mess we already made. Instead of treating AI like a feature factory, we should use it as an elite codebase cleaner.</p><p>To do this safely, teams must adopt a strict, disciplined engineering loop: <strong>The Resilient Refactoring Cycle</strong>.</p><ol><li><strong>Isolate and Freeze Behavior</strong>: Identify a messy, legacy component. Before touching a single line of production code, give the file to Cursor or Claude. Instruct it to write a comprehensive suite of Integration Tests to lock down exactly how the component works today.</li><li><strong>Stress-Test the Boundaries</strong>: Use the AI to find hidden landmines — null values, network failures, or unhandled exceptions — and ensure your integration tests account for them.</li><li><strong>Execute the Refactor</strong>: With your automated safety net firmly in place, ask your AI stack to refactor the messy legacy code into clean, scalable architecture. Run your integration tests. If they pass, you know you haven’t broken the system.</li><li><strong>Pin Down the Details</strong>: Instruct the AI to generate isolated, hyper-focused Unit Tests targeting the newly created, well-structured classes.</li><li><strong>Move On</strong>: Pick up the next legacy module and repeat the cycle.</li></ol><h3><strong>Enforcing AI Governance at the Tool Level: Stop Trusting Developers to Remember Code Standards</strong></h3><p>You cannot rely on developers remembering to follow your engineering loop on their own. You must bake your engineering guardrails directly into the settings of your AI tools.</p><p>We’ve all been there. You spend weeks defining architectural blueprints, configuring Checkstyle rules, and aligning on Spring Boot best practices. Then, a developer uses an AI coding assistant, accepts a lazy, hallucinated suggestion, and suddenly your clean codebase is polluted with field injection, missing @Transactional tags, or outdated boilerplate.</p><p>Here is the hard truth: Human memory is a bottleneck<strong>.</strong> Left unguided, AI engines default to generic public internet data, bringing old anti-patterns straight into your modern application. By shifting governance from a human checklist to an automated system check, the AI is programmatically bound to respect your architectural constraints.</p><p>If your team already uses a .github/copilot-instructions.md file to keep GitHub Copilot in line, you can scale that exact governance across your other tools. By utilizing a single, universal markdown file, you can enforce identical guardrails across GitHub Copilot, Cursor, and Claude Projects simultaneously.</p><h3><strong>The Unified Strategy: How It Works Across 3 Tools</strong></h3><p>Behind the scenes, all major AI assistants feed your local configurations into Large Language Models (LLMs) like GPT-4o or Claude 3.5. Because these models natively understand Markdown, you do not need to rewrite your rules. You just need to place them where each tool expects them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*T8XetKh9URrrVaA5xhBbZQ.png" /></figure><ul><li><strong>The Copilot Strategy (.github/copilot-instructions.md)</strong>: Placed at the repository root, Copilot reads this file to anchor its context window. Every time a developer triggers an inline autocompletion or an IDE chat panel, these rules are invisibly injected into the prompt prefix.</li><li><strong>The Cursor Strategy (.cursorrules)</strong>: Placed at the project root, Cursor automatically appends this file directly to its hidden System Prompt. Whether a developer uses inline generation (Cmd+I), codebase chat, or multi-file editing via Composer, the AI is bound to respect these constraints.</li><li><strong>The Claude Strategy (Claude Projects)</strong>: When managing larger architectural shifts, spin up a dedicated Claude Project. Paste your rules straight into the “Project Instructions” box. Claude will then act as an uncompromising technical advisor, rejecting lazy code generation in favor of compliant patterns.</li></ul><h3><strong>The Master Template: Java &amp; Spring Boot Example</strong></h3><p>To implement this today, use this consolidated structural format. Save it in your repository as .github/copilot-instructions.md and copy it into your Claude Project settings.</p><p><em>(Pro-Tip: Avoid duplicating files in your repo by creating a local symbolic link for Cursor: ln -s .github/copilot-instructions.md .cursorrules)</em></p><pre># Universal AI Engineering Guardrails: Java &amp; Spring Boot<br><br>## Role &amp; Persona<br>You are an expert Principal Java Engineer and Software Architect. All code generation, refactoring, and conversational advice must strictly adhere to the technical constraints and standards detailed below. Reject lazy code patterns, outdated configurations, or non-compliant structures.<br><br>## 1. Core Tech Stack Constants<br>- Java Version: 21 (Leverage modern features: switch expressions, records, pattern matching)<br>- Spring Boot Version: 3.x<br>- Data Access: Spring Data JPA (Hibernate)<br>- Build System: Maven<br><br>## 2. Code Quality &amp; Formatting Rules<br>- Formatting: Follow standard Google Java Style Guide.<br>- Imports: Optimize cleanly. Wildcard imports (e.g., `import java.util.*;`) are strictly forbidden.<br>- Modern Java: Utilize `java.util.Optional` cleanly. Avoid `.get()`; use `.orElseThrow()` or functional mapping.<br><br>## 3. Spring Boot Architectural Constraints<br>- Separation of Concerns: Strict layer isolation (Controller -&gt; Service -&gt; Repository).<br>- Dependency Injection: Always use Constructor Injection. Field injection (e.g., `@Autowired` on variables) is forbidden. Mark all dependencies as `private final`.<br>- DTO Boundary: Never expose JPA Entities directly to the API controller layer. Entities must be mapped to DTOs at the Service boundary using MapStruct.<br><br>## 4. Performance, Data, &amp; Transactions<br>- Transaction Optimization: Use `@Transactional(readOnly = true)` for all read-only Service methods.<br>- Write Safety: Use explicit `@Transactional` for state-changing operations. Let runtime exceptions bubble up naturally to trigger Spring rollbacks.<br>- Database Performance: Avoid N+1 query problems. Explicitly define `@EntityGraph` or use `join fetch` JPQL queries for entity relationships.<br><br>## 5. Validation &amp; Exception Handling<br>- Validation: Use Jakarta Bean Validation annotations (`@NotNull`, `@Size`, `@Valid`) on incoming DTOs.<br>- Error Handling: Handle exceptions globally via `@RestControllerAdvice`. Return standardized `ProblemDetail` (RFC 7807) objects for all error payloads.<br><br>## 6. Automated Testing Standards<br>- Requirements: Every new Service or Controller must be accompanied by its corresponding unit or slice test.<br>- Testing Stack: JUnit 5, Mockito, and AssertJ.<br>- Service Layer: Use `@ExtendWith(MockitoExtension.class)`. Do not boot up the full Spring context (`@SpringBootTest`) for pure unit tests.<br>- Controller Layer: Use `@WebMvcTest` paired with `MockMvc` for fast, sliced web layer verification.</pre><h3><strong>Conclusion</strong></h3><p>Velocity without direction is just a faster path to technical debt. Stop chasing the illusion of speed. Start using AI to build a codebase that lasts.</p><p>Stop chasing developers in pull requests over standard patterns that an AI should have known in the first place. Stop treating AI alignment as an individual developer habits problem. By embedding these configurations directly into your workflow infrastructure today, you transform volatile AI assistants into automated compliance officers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb6d88cec92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>