<?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 Neelesh Roy on Medium]]></title>
        <description><![CDATA[Stories by Neelesh Roy on Medium]]></description>
        <link>https://medium.com/@neeleshroy.2013?source=rss-24f69a331015------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X3zTsEwtcJuAG9g8uGYD3w.png</url>
            <title>Stories by Neelesh Roy on Medium</title>
            <link>https://medium.com/@neeleshroy.2013?source=rss-24f69a331015------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:44:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neeleshroy.2013/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[A Step Functions Decision Guide for engineers who keep chaining Lambdas]]></title>
            <link>https://medium.com/@neeleshroy.2013/a-step-functions-decision-guide-for-engineers-who-keep-chaining-lambdas-1e62e72b338b?source=rss-24f69a331015------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e62e72b338b</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[aws-architecture]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Neelesh Roy]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 13:03:26 GMT</pubDate>
            <atom:updated>2026-12-05T13:03:26.094Z</atom:updated>
            <content:encoded><![CDATA[<p>You get this requirement from the product:</p><blockquote>Users will upload files. The system has to extract information from the files and save it to our systems. Also, There should be validations before saving.</blockquote><p>I&#39;ll keep the design simple on purpose. This requirement could grow into an architecture that handles every edge case, but that&#39;s not the point here. The point is a decision rule that sticks.</p><p>Let’s break this down:</p><ol><li>Upload Docs in S3</li><li>Validate Docs</li><li>Extract information</li><li>Save in DynamoDB</li><li>Notify via SNS</li></ol><p>If the constraints are serverless, what is the first thought that comes to your mind?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKQp5YKqxKstARSio49iXA.png" /></figure><p>The User uploads the file in S3 and sets up an event notification which passes it to Validate lambda. Validate Lambda passes it to Extract and so on until it reaches the SNS notification service.</p><p>This is <strong>bad</strong> and AWS calls this an anti-pattern because of four main reasons:</p><ol><li>The first lambda (Validate) keeps executing until the last one finishes. Each one waits for its child to return, similar to recursive functions.</li><li>Because of above your Lambdas are getting billed without any reason meaning, the Validate Lambda gets billed even if the Save Lambda is currently running</li><li>Since, Lambdas have a timeout of 15 min, the whole workflow must complete within 15 minutes</li><li>If step 2 fails at night 2 AM, nobody knows which records passed through</li></ol><h4>Other ways people chain lambdas</h4><ol><li><strong><em>Async invoke / Lambda destinations</em></strong>: <br>This avoids double billing but the state is spread across lambdas, and async has its own problems to deal with</li><li><strong><em>SQS between steps</em></strong>:<br>Achieves loose coupling but now you have N queues and N retries with DLQs</li><li>EventBridge between Steps:<br>Loose Coupling again but no single step shows where is the request is right now</li></ol><h3>Enter Step Functions</h3><p>Step functions provide you a visual graph of flow, plus an execution history for each run. It also holds retry and catch per state and as a result no retry logic is needed inside the Lambdas. Moreover, it’s wait state has no cost and it has direct service integrations like writing to DDB, publish to SNS or Start an ECS task without lambda intervention.</p><h3>Solution with Step Functions:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9Ur-O3BkhH8MVxUJB5wfw.png" /></figure><ol><li>The user uploads the file straight to S3 using a pre-signed URL</li><li>S3 sends an “Object Created” event to EventBridge, and an EventBridge rule starts a Step Functions execution with the bucket name and file key.</li><li>The first state calls a Validate Lambda that checks file type, size and format.</li><li>A Choice state reads the result. If the file is bad, Step Functions publishes a “rejected” message to SNS directly and ends the run as a success, because bad input is a normal business outcome, not a system failure in this case.</li><li>If the file is good, an Extract Lambda pulls the data out.</li><li>Step Functions then writes it to DynamoDB and publishes a “processed” message to SNS.</li></ol><p>The result: only two Lambdas instead of four or five, no retry code inside them, and when something breaks at 2 AM, you open the execution and see the exact failed state with its input and error in red.</p><p>Also, If you observe closely, every step has its own retry rules in the state machine definition, and any error that survives the retries is caught and sent to a failure notification.</p><h3>When Step Functions are an overkill?</h3><ol><li>If there are two steps and no branching. Just plain SQS + Lambda will do</li><li>If the data is large, Step function workflows would not work because they have a 256 KB payload limit.</li><li>If the team doesn’t know Amazon States Language, you may want to reconsider, unless you want to blind code with Claude.</li><li>If you are already using standard step functions, switch to Express only if you see a large volume of tiny workflows.</li></ol><h3>The Decision Checklist</h3><p>Use Step Functions if <strong>any two </strong>are true:</p><ol><li>More than three steps in the workflow + Branching</li><li>In each step you need different rules with retries</li><li>A step is human-in-the-loop or an outside system</li><li>You need to report “Where is this request right now?”</li><li>The whole flow will potentially run longer than 15 minutes</li></ol><p>Ultimately,</p><p>Chaining Lambdas feels faster on day one, but you pay for it later in billing, in retry code copied across functions, and in the 2 AM hunt through CloudWatch logs. Step Functions moves that cost to the start, where it’s cheaper.</p><p>How do you orchestrate your serverless flows? Tell me in the comments.</p><p>About Me:</p><p>Hi, Neelesh and I am a Solutions Architect specialized in AWS and I love to chat about architectures, client stories, production failures, AI tooling and Disaster Recovery.</p><p>Feel free to drop me a message in <a href="https://www.linkedin.com/in/neeleshroy/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e62e72b338b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your LLM Isn’t Dumb. It’s Blind.]]></title>
            <link>https://medium.com/@neeleshroy.2013/your-llm-isnt-dumb-it-s-blind-f83ea4490c2a?source=rss-24f69a331015------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83ea4490c2a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Neelesh Roy]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 10:39:25 GMT</pubDate>
            <atom:updated>2026-06-21T15:00:46.802Z</atom:updated>
            <content:encoded><![CDATA[<p>How a context injector module grows up, and why you shouldn’t reach for the fancy pattern on day one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npYiC3NMPkuS0e9wjAYdLg.gif" /></figure><p>A review came in on a Tuesday:</p><blockquote><em>“Fell apart after one wash.”</em></blockquote><p>Our classifier tagged it praise.</p><p>It wasn’t a model problem. We swapped models. Same result. The model read four words and guessed, because four words was all it had. It didn’t know the item was a $4 phone case and not a $400 jacket. It didn’t know the reviewer returns about half of what they buy. It didn’t know the thing had been sitting on clearance for a month. Strip away everything a human would carry into that sentence and you’d guess too.</p><p>The model wasn’t dumb. It was blind. What it needed wasn’t more parameters. It was <strong>context</strong>.</p><p>This is the story of the little module that gives the model its eyes, how that module rotted, how we straightened it out, and the one pattern everybody wants to reach for too early. Of Course, due to NDA I cannot share the exact details of the project.</p><p><strong><em>But, this story is close to what happened.</em></strong></p><h3>The first patch</h3><p>So we gave it eyes. A product lookup, dropped straight into the function that builds the prompt:</p><pre>def build_prompt(review):<br>    product = catalog.get(review.product_id)<br>    return (<br>        f&quot;Product: {product.name}\n&quot;<br>        f&quot;Description: {product.description}\n&quot;<br>        f&quot;Avg rating: {product.avg_rating}\n\n&quot;<br>        f&quot;Classify this review:\n{review.text}&quot;<br>    )</pre><p>The clearance-jacket review started landing as complaint. The demo worked. We shipped it. For about a week, everyone was happy.</p><h3>The rot</h3><p>Then the asks started.</p><p>The PM wanted reviewer tier in the prompt: <em>gold</em> and <em>platinum</em> customers complain loud, and the team wanted to weight that. A week later someone noticed sale items skew sentiment, so an on-sale flag went in. Around week five a second engineer added product specs and didn’t notice the product lookup already sitting six lines up, so now we fetched the same row twice.</p><p>Here is what build_prompt looked like by the end:</p><pre>def build_prompt(review):<br>    prompt = f&quot;Classify this review:\n{review.text}\n\n&quot;<br><br>    # product context — added week 1<br>    product = catalog.get(review.product_id)<br>    if product is not None:<br>        prompt += f&quot;Product: {product.name}\n&quot;<br>        prompt += f&quot;Description: {product.description}\n&quot;<br>        prompt += f&quot;Rating: {product.avg_rating}\n&quot;<br><br>    # reviewer tier — added week 3, by someone else<br>    if review.user_id:<br>        u = users.get(review.user_id)<br>        if u and u.tier in (&quot;gold&quot;, &quot;platinum&quot;):<br>            prompt += f&quot;VIP reviewer ({u.tier})\n&quot;<br>        elif u:<br>            prompt += f&quot;tier: {u.tier}\n&quot;<br><br>    # on-sale flag — added week 4, in a hurry<br>    snap = pricing.at(review.product_id, review.created_at)<br>    if snap and snap.on_sale:<br>        prompt += &quot;was on sale at purchase\n&quot;<br><br>    # product specs — added week 5, different dev, didn&#39;t see the lookup above<br>    p2 = catalog.get(review.product_id)<br>    if p2:<br>        prompt += f&quot;specs: {p2.specs}\n&quot;   # no length cap — quietly blows the token budget<br><br>    return prompt</pre><p>Read it and count the problems.</p><ul><li>The product row gets pulled twice.</li><li>Tier handling forks three ways for a reason nobody remembers.</li><li>The specs line has no length limit, so a product with a long spec sheet pushes us past the token budget and the tail of the prompt gets truncated by the API, silently, with no error.</li><li>The reviewer’s email, which lives on the user record, gets pasted into one path and scrubbed in another, because the two people who wrote those paths never talked.</li></ul><p>Nobody designed this. It accreted. Every addition was one reasonable if. Stack enough reasonable ifs and you get a big swamp.</p><h3>The reframe</h3><p>We almost fixed it the usual way</p><p>Refactor the ifs, pull out a few helpers, leave a comment. That treats the symptom. The disease is that our context sources are welded to the prompt-building logic. <em>Where do we get product data</em> and <em>how do we lay out the prompt</em> are two different jobs sharing one function, and every new source tangles them tighter.</p><p>Look at what those sources actually are. Product data, reviewer tier, the sale snapshot each one is independent. None needs the others to do its job. None should care how the prompt gets assembled. They aren’t branches in a function. They’re <strong>pluggable units</strong>, and the function’s only job should be to run whichever ones are switched on and stitch the results together.</p><p><strong>That reframe is the whole post.</strong></p><blockquote>Each source becomes a small object with one method. The assembler holds a list of them.</blockquote><h3>The shape</h3><p>First, the thing a review is:</p><pre>from dataclasses import dataclass<br>from datetime import datetime<br><br>@dataclass<br>class Review:<br>    text: str<br>    product_id: str<br>    user_id: str<br>    created_at: datetime</pre><p>Now the contract every source obeys. It takes a review and hands back a chunk of context or nothing, if it has nothing to add:</p><pre>from abc import ABC, abstractmethod<br><br>@dataclass<br>class ContextFragment:<br>    label: str        # &quot;product&quot;, &quot;pricing&quot;, &quot;user&quot;<br>    body: str         # the text we splice into the prompt<br>    priority: int     # lower wins when we have to trim<br><br>class ContextProvider(ABC):<br>    @abstractmethod<br>    def fetch(self, review: Review) -&gt; ContextFragment | None:<br>        &quot;&quot;&quot;This source&#39;s slice of context, or None if it has nothing to say.&quot;&quot;&quot;</pre><p>Then three small objects, one per source. Each knows exactly one thing: how to turn a review into its slice of context. None knows about prompts, token budgets, or each other.</p><pre>class ProductProvider(ContextProvider):<br>    def __init__(self, catalog):<br>        self._catalog = catalog<br><br>    def fetch(self, review):<br>        product = self._catalog.get(review.product_id)<br>        if product is None:<br>            return None<br>        body = (<br>            f&quot;Name: {product.name}\n&quot;<br>            f&quot;Price band: {product.price_band}\n&quot;<br>            f&quot;Description: {product.description}\n&quot;<br>            f&quot;Avg rating: {product.avg_rating} ({product.rating_count} reviews)&quot;<br>        )<br>        return ContextFragment(label=&quot;product&quot;, body=body, priority=10)<br><br><br>class PricingProvider(ContextProvider):<br>    def __init__(self, pricing):<br>        self._pricing = pricing<br><br>    def fetch(self, review):<br>        snap = self._pricing.at(review.product_id, review.created_at)<br>        if snap is None:<br>            return None<br>        state = &quot;on clearance&quot; if snap.on_sale else &quot;full price&quot;<br>        body = f&quot;At purchase: {state}, paid {snap.paid}&quot;<br>        return ContextFragment(label=&quot;pricing&quot;, body=body, priority=20)<br><br><br>class UserTierProvider(ContextProvider):<br>    def __init__(self, users):<br>        self._users = users<br><br>    def fetch(self, review):<br>        user = self._users.get(review.user_id)<br>        if user is None:<br>            return None<br>        body = (<br>            f&quot;Tier: {user.tier}\n&quot;<br>            f&quot;Lifetime orders: {user.order_count}\n&quot;<br>            f&quot;Return rate: {user.return_rate:.0%}&quot;<br>        )<br>        return ContextFragment(label=&quot;user&quot;, body=body, priority=30)</pre><p>(catalog, pricing, and users are whatever data access you already have:</p><ul><li>Repositories</li><li>ORM</li><li>HTTP client</li></ul><p>The providers don’t care.</p><p>A Protocol works here too if you&#39;d rather not inherit. The shape is what matters, not the base class.</p><h3>The pipeline</h3><p>Now the assembler. It takes the list of sources, runs them, and merges what comes back. They don’t depend on each other, so we run them at once instead of one after another:</p><pre>from concurrent.futures import ThreadPoolExecutor<br><br>class ContextPipeline:<br>    def __init__(self, providers, redactor, token_budget):<br>        self._providers = providers<br>        self._redactor = redactor<br>        self._budget = token_budget<br><br>    def run(self, review) -&gt; str:<br>        with ThreadPoolExecutor() as pool:<br>            raw = pool.map(lambda p: self._safe_fetch(p, review), self._providers)<br><br>        fragments = [f for f in raw if f is not None]<br>        fragments.sort(key=lambda f: f.priority)<br>        fragments = [self._redactor.scrub(f) for f in fragments]<br>        return self._render(fragments)<br><br>    def _safe_fetch(self, provider, review):<br>        try:<br>            return provider.fetch(review)<br>        except Exception:<br>            log.warning(&quot;provider %s failed&quot;, type(provider).__name__, exc_info=True)<br>            return None   # one bad source never sinks the whole prompt<br><br>    def _render(self, fragments) -&gt; str:<br>        out, spent = [], 0<br>        for f in fragments:<br>            cost = self._budget.size(f.body)<br>            if spent + cost &gt; self._budget.limit:<br>                break     # sorted by priority, so we keep the ones that matter most<br>            out.append(f&quot;[{f.label}]\n{f.body}&quot;)<br>            spent += cost<br>        return &quot;\n\n&quot;.join(out)</pre><p>The part you live in day-to-day</p><pre>pipeline = ContextPipeline(<br>    providers=[<br>        ProductProvider(catalog),<br>        PricingProvider(pricing),<br>        UserTierProvider(users),<br>    ],<br>    redactor=PiiRedactor(),<br>    token_budget=TokenBudget(limit=1500),<br>)<br><br>context = pipeline.run(review)<br>prompt = f&quot;{context}\n\nClassify this review:\n{review.text}&quot;</pre><p>Want reviewer tier in the prompt? Add one line to the list. Want it gone for an experiment? Delete one line.</p><p><strong>The Swamp is gone.</strong></p><h3>The stuff you only want to solve once</h3><p>Look again at what moved into the pipeline:</p><ul><li>failure handling</li><li>ordering</li><li>redaction</li><li>the token budget</li></ul><p>Those aren’t per-source concerns. You want one redaction policy, not one per engineer who happened to write a provider. You want one place that decides what to drop when the budget is tight. You want one source failing to never take down the whole prompt.</p><p>In the swamp, every one of those was a matter of discipline. Each if had to remember to scrub PII, had to remember not to blow the budget, and the moment someone forgot you got a leak or a silent truncation. In the pipeline they&#39;re guarantees. A provider can&#39;t forget to redact, because redaction doesn&#39;t live in the provider. It can&#39;t blow the budget, because the budget is enforced after the fact in priority order so the product data survives and the least important slice is what gets cut.</p><h3>The horizon: Where the fancy pattern comes in</h3><p>Here’s the part most pattern posts skip.</p><p>You may have read this far waiting for <strong>Abstract Factory</strong>, because a context-injection module is the textbook place to reach for it. Hold on.</p><p>Abstract Factory earns its place when you have more than one <em>family</em> of context, and each family has to stay internally consistent.</p><pre>class ContextFactory(ABC):<br>    @abstractmethod<br>    def providers(self): ...<br><br>    @abstractmethod<br>    def redactor(self): ...<br><br>    @abstractmethod<br>    def token_budget(self): ...<br><br>    def build(self) -&gt; ContextPipeline:<br>        return ContextPipeline(<br>            providers=self.providers(),<br>            redactor=self.redactor(),<br>            token_budget=self.token_budget(),<br>        )<br><br><br>class ReviewContextFactory(ContextFactory):<br>    def __init__(self, catalog, pricing, users):<br>        self._catalog = catalog<br>        self._pricing = pricing<br>        self._users = users<br><br>    def providers(self):<br>        return [<br>            ProductProvider(self._catalog),<br>            PricingProvider(self._pricing),<br>            UserTierProvider(self._users),<br>        ]<br><br>    def redactor(self):<br>        return PiiRedactor(policy=&quot;ecommerce&quot;)<br><br>    def token_budget(self):<br>        return TokenBudget(limit=1500)</pre><p>The call site collapses to one line, and a ClaimContextFactory would slot in beside it without touching anything downstream:</p><pre>pipeline = ReviewContextFactory(catalog, pricing, users).build()</pre><p>Notice the seam. The pipeline already takes a list. Wrapping the construction of that list inside a factory changes nothing below it the pipeline doesn’t know or care whether its providers came from a literal list or a factory method. That isn’t luck. <strong>It’s why we built the pipeline first</strong>. The factory is a door we left unlocked.</p><p><strong>But you have one classifier.</strong></p><p>So build the pipeline. It solves the problem you actually have: a blind model, and a function rotting into a swamp. Leave the factory on the horizon, and walk to it the day a second family forces your hand.</p><p>You arrive at Abstract Factory. You don’t start there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83ea4490c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Reinventing AI Guardrails: Build Reusable LLM Text Safety with the Builder Pattern]]></title>
            <link>https://awstip.com/stop-reinventing-ai-guardrails-build-reusable-llm-text-safety-with-the-builder-pattern-a238ed4011eb?source=rss-24f69a331015------2</link>
            <guid isPermaLink="false">https://medium.com/p/a238ed4011eb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Neelesh Roy]]></dc:creator>
            <pubDate>Mon, 25 May 2026 15:38:43 GMT</pubDate>
            <atom:updated>2026-06-08T14:05:54.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>Every LLM feature ends up re-implementing the same PII checks, injection filters, and schema validation. Here’s how to write them once — and chain them together with a single .add().</h4><figure><img alt="Guardrails using Builder pattern" src="https://cdn-images-1.medium.com/max/1024/1*Fq01O6rcRH1S5e0kmvafGQ.png" /></figure><p>If you’ve shipped more than one LLM feature, you’ve felt this pain.</p><p>Feature one needs PII redaction. Feature two needs PII redaction <em>and</em> prompt-injection defense. Feature three needs all of that, plus output-schema validation and a confidence floor. So you copy-paste. You fork the helper. Six weeks later you fix a regex bug in one place and forget the other four.</p><p>Guardrails are cross-cutting by nature. Treating them as one-off if blocks bolted onto each call is how you end up with five slightly-different copies of the same safety logic, and no single place to test them.</p><p>The fix isn’t a heavier framework. It’s a design pattern most of us already know from our Java days: the <strong>builder pattern</strong>.</p><p>This post walks through a small, composable guardrail layer for text data. The same approach scaled into a full eval/guardrails platform I built for insurance LLMs, but the core idea fits in ~80 lines.</p><h3>What a “guardrail” actually is</h3><p>Strip away the buzzwords. A guardrail is a function that takes text and either passes it through, transforms it, or blocks it. That’s it.</p><p>In practice they fall into three buckets:</p><ul><li><strong>Input guards</strong> — run on user/source text <em>before</em> it hits the model. Redact PII, strip injection attempts, reject oversized input.</li><li><strong>Output guards</strong> — run on the model’s response <em>before</em> it reaches a user or downstream system. Validate schema, enforce a confidence floor, block prohibited claims.</li><li><strong>Policy guards</strong> — domain rules. In insurance: don’t let the model say “you’re covered” unless a verification tool was actually called.</li></ul><p>The mechanics are identical across all three. So the abstraction should be too.</p><h3>Why the builder pattern fits</h3><p>The builder pattern separates <em>what</em> you want from <em>how</em> it runs. You declare a pipeline by chaining steps, then execute it.</p><p>That gives you three things guardrails desperately need:</p><ol><li><strong>Composability</strong> — add or remove a guard without touching the others.</li><li><strong>Reuse</strong> — define a config once (base_guardrail), reuse it everywhere, extend per-feature.</li><li><strong>Readability</strong> — the chain <em>is</em> the documentation. Anyone can read the pipeline top to bottom.</li></ol><pre>guardrail = (<br>    Guardrail()<br>    .add(PIIRedaction(entities=[&quot;SSN&quot;, &quot;POLICY_NUMBER&quot;, &quot;EMAIL&quot;]))<br>    .add(PromptInjection(block=True))<br>    .add(ConfidenceFloor(threshold=0.6, action=&quot;escalate&quot;))<br>)</pre><p>You can read that out loud and understand exactly what it does. No framework knowledge required.</p><h3>The core: one interface, many guards</h3><p>Start with the contract every guard obeys. Each guard takes a Context and returns one — possibly modified. If it can&#39;t allow the text, it raises.</p><pre>from dataclasses import dataclass, field<br>from abc import ABC, abstractmethod<br><br>@dataclass<br>class Context:<br>    text: str<br>    metadata: dict = field(default_factory=dict)<br><br>class GuardrailViolation(Exception):<br>    &quot;&quot;&quot;Raised when a guard blocks the text.&quot;&quot;&quot;<br><br>class Guard(ABC):<br>    @abstractmethod<br>    def check(self, ctx: Context) -&gt; Context:<br>        ...</pre><p>One method. Transform-or-raise. That’s the whole interface — and it’s why new guards are trivial to add later.</p><h3>A few concrete guards</h3><p>These are deliberately simple. In production you’d swap the regex for a real PII model (e.g. Presidio / AWS Guardrails) and the keyword list for a proper classifier — but the <em>shape</em> stays the same.</p><pre>class PIIRedaction(Guard):<br>  def __init__(self, entities):<br>          self.entities = entities<br>    def check(self, ctx: Context) -&gt; Context:<br>        text = ctx.text<br>        for ent in self.entities:<br>            # Check for SSN, Phone number etc. Basically, this happens for every input<br>        ctx.text = text<br>        return ctx<br><br>class PromptInjection(Guard):<br>    # init here...<br>    def check(self, ctx: Context) -&gt; Context:<br>        # Write your prompt injection logic here<br>        return ctx<br><br>class ConfidenceFloor(Guard):<br>    &quot;&quot;&quot;An output guard. &quot;&quot;&quot;<br>    # init here...<br>    def check(self, ctx: Context) -&gt; Context:<br>        # Code the model output guard here<br>        return ctx</pre><p>Notice each guard knows nothing about the others. That isolation is the point — it’s what makes them unit-testable in seconds.</p><h3>The builder itself</h3><p>The Guardrail class collects guards and runs them in order. The trick that makes the chain work: <strong>every </strong><strong>.add() returns </strong><strong>self.</strong></p><pre>class Guardrail:<br>  def __init__(self):<br>      self._guards: list[Guard] = []<br>  def add(self, guard: Guard) -&gt; &quot;Guardrail&quot;:<br>      self._guards.append(guard)<br>      return self  # ← enables chaining<br>  def run(self, text: str, metadata: dict | None = None) -&gt; Context:<br>      ctx = Context(text=text, metadata=metadata or {})<br>      for guard in self._guards:<br>          ctx = guard.check(ctx)<br>      return ctx</pre><p>That’s the entire engine. ~12 lines. Everything else is just guards plugging into it.</p><h3>Using it around a real LLM call</h3><p>Here’s the pattern wrapping an actual classification call — the kind of intent classifier where source text arrives, gets cleaned, hits the model, and the response gets validated before anyone trusts it.</p><pre># Define once, reuse across features<br>base_guardrail = (<br>    Guardrail()<br>    .add(PIIRedaction(entities=[&quot;SSN&quot;, &quot;EMAIL&quot;, &quot;POLICY_NUMBER&quot;]))<br>    .add(PromptInjection(block=True))<br>)<br><br>def classify_text(text: str) -&gt; dict:<br>    # 1. Input guard - clean before the model sees it<br>    safe = base_guardrail.run(text)<br>    # 2. Call the model on sanitized text<br>    result = call_llm(safe.text)<br>    # 3. Output guard - gate the response<br>    out_guard = Guardrail().add(<br>        ConfidenceFloor(threshold=0.7, action=&quot;escalate&quot;)<br>    )<br>    checked = out_guard.run(<br>        result[&quot;category&quot;],<br>        metadata={&quot;confidence&quot;: result[&quot;confidence&quot;]},<br>    )<br>    if checked.metadata.get(&quot;route&quot;) == &quot;human_review&quot;:<br>        result[&quot;route&quot;] = &quot;human_review&quot;<br>    return result</pre><p>The model call sits in the middle, blissfully unaware of safety logic. Input guards clean what goes in; output guards gate what comes out. Same Guardrail class, two different configs.</p><h3>Where the pattern earns its keep</h3><p><strong>Per-feature extension.</strong> A higher-risk feature just extends the base, no copy-paste:</p><pre>high_risk = (<br>    Guardrail()<br>    .add(PIIRedaction(entities=[&quot;SSN&quot;, &quot;EMAIL&quot;, &quot;POLICY_NUMBER&quot;]))<br>    .add(PromptInjection(block=True))<br>    .add(ConfidenceFloor(threshold=0.85, action=&quot;block&quot;))<br>)</pre><p><strong>Testing — </strong>Each guard is a pure-ish function — feed it text, assert the output. No mocking the LLM, no network. Your safety layer becomes the easiest thing in the codebase to test.</p><p><strong>Fail strategy is explicit — </strong>A guard either transforms (redact), flags (set metadata), or blocks (raise). Make that choice per-guard via an action arg instead of burying it in conditionals.</p><p><strong>One place to fix bugs — </strong>Patch a regex in PIIRedaction, every pipeline gets it. That alone justifies the abstraction.</p><h3>A few things I’d add for production</h3><p>This is the skeleton. Before trusting it with real traffic:</p><ul><li><strong>Swap toy detectors for real ones</strong> — Presidio or a fine-tuned NER model for PII; a classifier (not keywords) for injection.</li><li><strong>Log every guard decision</strong> — which guard fired, what it did, with a trace ID. In regulated domains this is non-negotiable.</li><li><strong>Async-friendly guards</strong> — if a guard calls an LLM-as-judge, you’ll want async check().</li><li><strong>Attack simulation</strong> — a suite of known injection/jailbreak prompts run against your guardrail in CI, measuring block rate over time.</li></ul><p>But none of that changes the core. The interface stays check(ctx) -&gt; ctx. The builder stays .add().add().run(). That stability is exactly what you want from a safety layer.</p><h3>The takeaway</h3><p>Guardrails fail in production not because the logic is hard, but because it’s <em>scattered</em>. Five copies, no tests, no single source of truth.</p><p>The builder pattern gives you one interface, composable steps, and configs you define once and reuse everywhere. It’s old, boring, and proven — which is precisely what you want standing between your model and your users.</p><p>Write the guard once. Chain it forever.</p><p><em>If you’re building LLM features in a regulated domain — insurance, health, fintech — the guardrail layer is the difference between “it worked in the demo” and “it works in production.” Start small. One </em><em>Guard, one </em><em>.add(), and grow from there.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a238ed4011eb" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/stop-reinventing-ai-guardrails-build-reusable-llm-text-safety-with-the-builder-pattern-a238ed4011eb">Stop Reinventing AI Guardrails: Build Reusable LLM Text Safety with the Builder Pattern</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an LLM-Powered Insurance Support Classifier That Saved $200K Annually]]></title>
            <link>https://medium.com/@neeleshroy.2013/how-i-built-an-llm-powered-insurance-support-classifier-that-saved-200k-annually-a15f0c015c26?source=rss-24f69a331015------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15f0c015c26</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[insurance]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Neelesh Roy]]></dc:creator>
            <pubDate>Sat, 23 May 2026 09:20:31 GMT</pubDate>
            <atom:updated>2026-06-06T13:20:38.253Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From 3 Human Support agents manually triaging 16,000 emails/month to an $8/month AI pipeline</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Og1m3grSuTB3oETOLDDytQ.png" /></figure><p>At <a href="https://withlayr.com/">Layr</a>, we sell commercial insurance to small businesses. That means every day, hundreds of emails land in our support queue — billing questions, policy changes, mid-term endorsements, and one category that absolutely dominates the inbox: <strong>COI requests</strong>.</p><p>COI = Certificate of Insurance. It’s the document a landlord, vendor, or general contractor demands before they let your business set foot on their property. For a small business, it’s urgent. For a support team, it’s repetitive.</p><p>When I dug into our ticket volume, I found that COI-related emails accounted for nearly <strong>40% of all inbound support traffic</strong> — and our team was hand-routing every single one. No auto-classification. No queue routing. Just a person reading emails and clicking buttons.</p><p>This is the story of how we changed that.</p><h3>The Problem Worth Solving</h3><p>Before touching any code, I needed to understand what “COI request” actually means in the wild. It’s not as simple as if email.contains(&quot;COI&quot;).</p><p>Real COI emails look like:</p><ul><li><em>“Our new landlord at 450 Park Ave needs to be added as additional insured before we move in next Friday.”</em></li><li><em>“Forwarding a request from our general contractor — they need a certificate showing waiver of subrogation.”</em></li><li><em>“The certificate holder address on file is wrong. Can you update it?”</em></li><li><em>“Hi, can you re-send our COI? We misplaced it.”</em></li></ul><p>And then there are the traps — emails that <em>mention</em> COI but aren’t COI requests:</p><ul><li><em>“I paid my bill. Also my COI on file has our old address, will fix that later.”</em> → This is a <strong>billing</strong> issue. The COI mention is deferred noise.</li></ul><p>Keyword matching fails hard here. You need intent detection, not grep.</p><h3>Why Claude Haiku</h3><p>We evaluated a few paths:</p><ul><li><strong>Rule-based / regex</strong>: Fast, but brittle. We’d be patching it forever as email language evolved.</li><li><strong>Fine-tuned classifier</strong>: High upfront cost, training data requirements, maintenance overhead.</li><li><strong>GPT-4o</strong>: Good quality, higher cost, no caching support that fit our pattern.</li><li><strong>Claude Haiku + structured output</strong>: Low latency (~400ms p95), cheap, excellent instruction-following, native prompt caching.</li></ul><p>At <strong>~16,000 emails/month</strong>, cost mattered. And so did reliability — structured output with JSON schema enforcement meant no parsing failures, no hallucinated categories.</p><p>Haiku won.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgYH1FLJYIi1eMBEp7u50g.png" /></figure><p>The pipeline is simple by design:</p><pre>Inbound Email<br>    ↓<br>Security/Redaction Layer  ← PII stripped, replaced with [redacted:TYPE] tokens<br>    ↓<br>Classifier Lambda  ← Calls Haiku via Anthropic SDK<br>    ↓<br>Structured JSON Response  ← { ai_category, ai_confidence, ai_reasoning }<br>    ↓<br>Routing Logic  ← COI queue or general queue<br>    ↓<br>Support Platform</pre><p>No vector DB. No RAG. No orchestration framework. This is a classification problem — the right tool is a well-prompted LLM with constrained output, not an agent.</p><h3>The Prompt Architecture</h3><p>This is where the real work happened.</p><h3>System/User Split</h3><p>We split the prompt into two layers:</p><p><strong>System prompt (static, cacheable):</strong> Role, definitions, redaction handling rules, classification logic, few-shot examples. ~1,050 tokens. This never changes between calls.</p><p><strong>User turn (dynamic):</strong> Just the email subject and body, wrapped in XML tags.</p><pre>&lt;email&gt;<br>  &lt;subject&gt;Need updated COI for new lease - [redacted:address]&lt;/subject&gt;<br>  &lt;body&gt;Hi, our landlord at [redacted:address] requires we add them<br>  as additional insured. Policy number is [redacted:policy_number].<br>  Can you send this by [redacted:date]? Thanks&lt;/body&gt;<br>&lt;/email&gt;</pre><p>Why XML tags in the user turn? Prompt injection defense. If an email body contains “Ignore previous instructions,” the XML boundary makes it much harder for it to bleed into system context.</p><h3>The Redaction Problem</h3><p>Our email pipeline scrubs PII before anything downstream touches it. So Haiku sees [redacted:phone] instead of an actual phone number.</p><p>This created a subtle problem: in testing, Haiku would occasionally lower its confidence because redaction tokens “looked like missing data.” We had to explicitly handle this in the system prompt:</p><pre>Treat these tokens as valid, meaningful placeholders — they represent<br>real data that existed in the original email. Do NOT treat them as<br>missing information or reasons to lower confidence. A redacted phone<br>number is still a phone number.</pre><pre>Ignore redaction tokens when forming your decision unless the TYPE<br>itself carries classification signal (e.g., [redacted:policy_number]<br>confirms the sender is a policyholder).</pre><p>That last sentence matters: [redacted:policy_number] in a COI context is actually <em>useful signal</em> — it tells you this is a policyholder making an authenticated request.</p><h3>Intent-Based Decision Framework</h3><p>The core classification logic is intent-driven, not keyword-driven:</p><pre>COI if:<br>  - Explicit COI request (new issuance, re-send, download)<br>  - COI modification (holder update, address change, expiry extension)<br>  - Coverage verification (third party confirming active coverage)<br>  - Endorsement adds that trigger COI (additional insured, wavier of subrogation)<br>  - Third-party requests on behalf of a policyholder</pre><pre>Decision rule for ambiguous cases:<br>  - For reply chains/forwards, weight the most recent message heaviest<br>  - When mixed-intent, classify by the PRIMARY action requested<br>  - &quot;I paid my bill, also when does my COI expire?&quot; → N/A (billing is primary)</pre><h3>Few-Shot Examples</h3><p>We included exactly two examples — both adversarially chosen to represent the hard cases, not the easy ones:</p><p><strong>Example 1 (COI — implicit request):</strong></p><pre>Email: &quot;Our new landlord at 450 Park Ave needs a certificate showing<br>them as additional insured before we move in next Friday.&quot;</pre><pre>Output: {&quot;ai_category&quot;: &quot;COI&quot;, &quot;ai_confidence&quot;: 98,<br>&quot;ai_reasoning&quot;: &quot;Explicit COI request with additional insured<br>endorsement for landlord&quot;}</pre><p><strong>Example 2 (N/A — COI mentioned but not primary):</strong></p><pre>Email: &quot;Following up on my payment from last week — the autopay didn&#39;t<br>go through. Can someone check? Also my COI on file has our old address,<br>will fix that later.&quot;</pre><pre>Output: {&quot;ai_category&quot;: &quot;N/A&quot;, &quot;ai_confidence&quot;: 88,<br>&quot;ai_reasoning&quot;: &quot;Primary intent is billing issue; COI mention is deferred aside&quot;}</pre><p>We deliberately didn’t include “easy” examples (obvious COI request = COI). Haiku doesn’t need help with those. The examples should teach it the <em>hard edges</em>.</p><h3>Structured Output Implementation</h3><p>We use Anthropic’s native JSON schema enforcement via output_config. No prompt-based JSON instructions, no regex parsing on the output:</p><pre>SCHEMA = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;ai_category&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;enum&quot;: [&quot;COI&quot;, &quot;N/A&quot;]<br>        },<br>        &quot;ai_confidence&quot;: {<br>            &quot;type&quot;: &quot;integer&quot;,<br>            &quot;minimum&quot;: 0,<br>            &quot;maximum&quot;: 100<br>        },<br>        &quot;ai_reasoning&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;description&quot;: &quot;12-15 words max, cite the signal driving the decision&quot;<br>        }<br>    },<br>    &quot;required&quot;: [&quot;ai_category&quot;, &quot;ai_confidence&quot;, &quot;ai_reasoning&quot;],<br>    &quot;additionalProperties&quot;: False<br>}</pre><pre>response = client.messages.create(<br>    model=&quot;claude-haiku-4-5&quot;,<br>    max_tokens=200,<br>    temperature=0,<br>    system=[<br>        {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: SYSTEM_PROMPT,<br>            &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}<br>        }<br>    ],<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;&lt;email&gt;\n{email_text}\n&lt;/email&gt;&quot;}<br>    ],<br>    output_config={<br>        &quot;format&quot;: {<br>            &quot;type&quot;: &quot;json_schema&quot;,<br>            &quot;schema&quot;: SCHEMA<br>        }<br>    }<br>)</pre><p>Key decisions:</p><ul><li>temperature=0 — classification should be deterministic</li><li>max_tokens=200 — output is tiny; cap it to avoid runaway costs</li><li>additionalProperties: False — strict schema enforcement</li></ul><h3>Prompt Caching</h3><p>This is where the economics flip completely.</p><p>Our traffic is bursty — most emails arrive during business hours in clusters. The system prompt (~1,050 tokens) is static across every call. With Anthropic’s prompt caching at a 1-hour TTL (cache_control: {&quot;type&quot;: &quot;ephemeral&quot;}), the static system prompt gets read from cache on ~90% of calls.</p><p>Cache hits cost <strong>10× less</strong> on input tokens. At 16,000 emails/month:</p><p>Without Cache With Cache (90% hit rate) Monthly cost ~$80 <strong>~$8</strong> Per email ~$0.005 <strong>~$0.0005</strong></p><p>We monitor cache performance on every response via usage.cache_read_input_tokens. If that number drops significantly, something is wrong — likely a deploy that changed the system prompt hash.</p><p>One critical detail: Anthropic’s cache requires a <strong>minimum of 1,024 tokens</strong> in the cacheable block to activate. Our system prompt is ~1,050 tokens. We deliberately don’t trim it below the threshold, even if there are minor optimizations available.</p><h3>Confidence Bands and Routing Logic</h3><p>We use three confidence bands for downstream routing:</p><p>Band Range Action High 90–100 Auto-route, no human review Medium 70–89 Route + flag for spot check Low 0–69 Route to general queue, manual review</p><p>Low-confidence classifications don’t fail — they degrade gracefully into manual review. The system never makes a hard wrong call; at worst it says “I’m not sure” and routes conservatively.</p><h3>The Numbers</h3><p>Before this system, COI routing required <strong>~3 hours/day</strong> of support agent time (across the team) just for triage. At fully-loaded support agent cost:</p><ul><li>Annual triage cost: <strong>~$200K</strong></li><li>Classifier cost: <strong>~$100/year</strong></li><li>Build + integration time: ~3 weeks</li></ul><p>The ROI conversation was short.</p><p>What surprised us wasn’t the cost savings — it was the <strong>consistency</strong>. Human routing has variance: agents have bad days, edge cases get mis-categorized, new hires need weeks to learn the nuances. The classifier is the same at 9am Monday and 5pm Friday. It never misremembers that “additional insured” is a COI trigger.</p><h3>What We’d Do Differently</h3><p><strong>Test adversarially from day one.</strong> We built our test set from “easy” examples initially and were overconfident about accuracy. The hard cases — mixed-intent emails, reply chains, third-party forwards — are where it matters most and where you need explicit examples.</p><p><strong>Log everything, especially cache metrics.</strong> usage.cache_read_input_tokens is the single most important operational metric for this system. A sudden drop tells you the system prompt changed (even accidentally) and you&#39;re burning uncached tokens.</p><p><strong>Don’t fine-tune prematurely.</strong> We had early discussions about fine-tuning Haiku on our historical tickets. Unnecessary. The classification task is well-defined enough that a strong system prompt with good examples outperforms a weakly fine-tuned model, with zero maintenance overhead.</p><h3>What’s Next</h3><p>This is the first production AI component we’ve shipped at Layr. COI classification is a narrow, well-bounded problem — a good first target for exactly that reason.</p><p>Next on the roadmap: extending the classifier to a <strong>multi-class router</strong> across more support categories (billing, mid-term changes, cancellations, claims). Same architecture, wider taxonomy, more few-shot examples per class.</p><p>The underlying principle holds: when you have a classification problem with a stable taxonomy and high volume, a well-prompted LLM with structured output and caching is almost always the right call over a bespoke model or a rules engine.</p><p>Start simple. Ship it. Measure it. Expand.</p><p><em>If you’re building AI systems in insurtech and want to compare notes, I’m on </em><a href="https://linkedin.com/in/neeleshroy"><em>LinkedIn</em></a><em>. Always happy to talk production LLM architecture with people working in the same domain.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15f0c015c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced State Management Architectures: Event Sourcing, CQRS, and Distributed State]]></title>
            <link>https://medium.com/@neeleshroy.2013/advanced-state-management-architectures-event-sourcing-cqrs-and-distributed-state-e6f8a823ba98?source=rss-24f69a331015------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f8a823ba98</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[modern-data-architecture]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Neelesh Roy]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 11:17:55 GMT</pubDate>
            <atom:updated>2025-09-10T11:17:55.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*rOsb_HXIJf0aYfbEwWyJ7Q.png" /></figure><h3>Core Concept</h3><ul><li><strong>Event Sourcing</strong> captures all state changes as immutable events, creating an append-only log of what happened rather than storing current state. This enables time-travel debugging, audit trails, and replay capabilities.</li><li><strong>CQRS (Command Query Responsibility Segregation)</strong> separates read and write models, allowing optimized data structures for each operation type. Commands modify state while queries retrieve data from potentially denormalized views.</li><li><strong>Distributed State Synchronization</strong> ensures consistency across multiple clients and servers through techniques like operational transformation, conflict-free replicated data types (CRDTs), or vector clocks</li></ul><h3>Implementation Details</h3><ul><li>Event sourcing implementations maintain an event store containing chronologically ordered events. State reconstruction happens by replaying events from the beginning or from snapshots.</li><li>CQRS typically involves separate command handlers that validate and generate events, plus query handlers that maintain read-optimized projections. Event handlers update these projections asynchronously, enabling eventual consistency between command and query sides.</li><li>Distributed synchronization requires conflict resolution strategies. There are operations which are to be implemented in correct order on all clients. CRDTs are mathematics. They guarantee convergence without coordination.</li></ul><h3>Basic Example: Simple Event Store</h3><pre>class EventStore {<br>  constructor() {<br>    this.events = [];<br>  }<br>  <br>  append(event) {<br>    this.events.push({<br>      ...event,<br>      timestamp: Date.now(),<br>      version: this.events.length<br>    });<br>  }<br>  <br>  getEvents(aggregateId) {<br>    return this.events.filter(e =&gt; e.aggregateId === aggregateId);<br>  }<br>}</pre><h3>Intermediate Example: CQRS Command Handler</h3><pre>class UserCommandHandler {<br>  constructor(eventStore) {<br>    this.eventStore = eventStore;<br>  }<br>  <br>  async createUser(command) {<br>    const events = [<br>      { type: &#39;UserCreated&#39;, aggregateId: command.id, data: command }<br>    ];<br>    <br>    events.forEach(event =&gt; this.eventStore.append(event));<br>    return { success: true, version: events.length };<br>  }<br>}</pre><pre>class UserQueryHandler {<br>  constructor() {<br>    this.users = new Map();<br>  }<br>  <br>  handleUserCreated(event) {<br>    this.users.set(event.aggregateId, event.data);<br>  }<br>}</pre><h3>Advanced Example: CRDT for Distributed Sync</h3><pre>class GCounter {<br>  constructor(nodeId) {<br>    this.nodeId = nodeId;<br>    this.counters = new Map();<br>  }<br>  <br>  increment() {<br>    const current = this.counters.get(this.nodeId) || 0;<br>    this.counters.set(this.nodeId, current + 1);<br>  }<br>  <br>  merge(other) {<br>    for (const [nodeId, value] of other.counters) {<br>      const current = this.counters.get(nodeId) || 0;<br>      this.counters.set(nodeId, Math.max(current, value));<br>    }<br>  }<br>  <br>  value() {<br>    return Array.from(this.counters.values()).reduce((a, b) =&gt; a + b, 0);<br>  }<br>}</pre><h3>Production Example: Event Sourcing with Snapshots</h3><pre>class AggregateRoot {<br>  constructor(id) {<br>    this.id = id;<br>    this.version = 0;<br>    this.uncommittedEvents = [];<br>  }<br>  <br>  static async fromHistory(eventStore, id, snapshot = null) {<br>    const aggregate = new this(id);<br>    <br>    if (snapshot) {<br>      Object.assign(aggregate, snapshot.data);<br>      aggregate.version = snapshot.version;<br>    }<br>    <br>    const events = await eventStore.getEventsAfter(id, aggregate.version);<br>    events.forEach(event =&gt; {<br>      aggregate.apply(event);<br>      aggregate.version = event.version;<br>    });<br>    <br>    return aggregate;<br>  }<br>  <br>  commit(eventStore) {<br>    this.uncommittedEvents.forEach(event =&gt; eventStore.append(event));<br>    this.uncommittedEvents = [];<br>  }<br>}</pre><h3>Best Practices</h3><p>Choose event sourcing for domains requiring audit-ability or complex temporal queries, but <strong>avoid for simple CRUD operations</strong> due to complexity overhead. Implement proper event versioning strategies early.</p><p>For CQRS, <strong>ensure clear boundaries between command and query responsibilities</strong>. Use eventual consistency judiciously and communicate consistency models clearly to users.</p><p>In distributed systems, design for network partitions and implement proper conflict resolution UX.</p><p><strong>Always consider the operational complexity these patterns introduce.</strong></p><h3>Conclusion</h3><p>These advanced patterns solve complex state management challenges but introduce operational complexity. Choose event sourcing for auditability needs, CQRS for read/write optimization, and distributed sync for collaboration requirements. Success depends on matching architectural complexity to actual business needs and team capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f8a823ba98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>