<?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 Wences Martinez on Medium]]></title>
        <description><![CDATA[Stories by Wences Martinez on Medium]]></description>
        <link>https://medium.com/@wencesms?source=rss-3181b80926fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kajt2iMkco76rpyOAZbuqg.png</url>
            <title>Stories by Wences Martinez on Medium</title>
            <link>https://medium.com/@wencesms?source=rss-3181b80926fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:50:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wencesms/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[Is Your Agent Dreaming Yet?]]></title>
            <link>https://wencesms.medium.com/is-your-agent-dreaming-yet-ed5a62af5db2?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed5a62af5db2</guid>
            <category><![CDATA[agent-engineering]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 12:56:17 GMT</pubDate>
            <atom:updated>2026-11-08T12:56:17.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>How sleep-time compute and dreaming can turn yesterday’s work into better context for tomorrow.</h4><p>If you’ve ever built an agent harness, you’ve probably spent plenty of time <strong>optimizing the context</strong> your agent receives.</p><p>What goes into the prompt, what gets retrieved, what gets cut out when the context window fills up.</p><p>And then, a new <strong>session</strong> starts, and the agent spends five tool calls rediscovering how to do the same previous task, again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NrVJiYQSSMvb8_ATYlyqg.png" /></figure><p>What if, between tasks, your agent could work on becoming <strong>faster</strong>, more <strong>efficient</strong>, and <strong>better</strong> at helping you?</p><p>While you’re away, a <strong>background process</strong> could review its recent work, like failed test commands, repeated investigations, corrections you made, and approaches that succeeded.</p><p>It could turn that experience into <strong>useful preparation</strong> for the next task.</p><p>That is the concept behind <strong><em>sleep-time compute</em></strong> and, in agent memory systems, <strong><em>dreaming</em></strong>: spending compute between interactions to prepare useful context and consolidate experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mv0BUef0Xkjmy532yiJ3eA.jpeg" /><figcaption>Dreaming prepares memory for the next session. Source: <a href="https://www.anthropic.com/research/components-of-agent-memory">Anthropic</a>.</figcaption></figure><p>For those of us building agent harnesses, this opens another dimension of <strong>context engineering</strong>: what should the agent carry forward from yesterday’s work, and how does it reach tomorrow’s context window?</p><p>This article covers how that loop works, where I’d use it, and what I’d measure before calling it an improvement.</p><p>Subscribe for free to get new posts and support my work.</p><h3>What is sleep-time compute?</h3><p>The <a href="https://arxiv.org/abs/2504.13171">Sleep-time Compute</a> paper from researchers at <a href="https://www.letta.com/">Letta</a> and UC Berkeley explores a straightforward idea: let models process a known context before the user’s next question arrives.</p><p>That preparation might involve <strong>anticipating</strong> likely questions, deriving useful information, or producing intermediate results that later answers can reuse.</p><p>“<strong>Sleep</strong>” is a metaphor for this preparation phase, it can happen between interactions or after a task finishes. It requires an <strong>explicit process</strong> and a way to preserve its output; leaving an agent idle does not automatically make it improve.</p><p>Closing your laptop is, unfortunately, not a training pipeline!</p><blockquote>An agent working with a set of documents could <strong>prepare calculations</strong> that several questions about those documents are likely to require.</blockquote><h3>Where dreaming fits</h3><p>In agent memory systems, <em>dreaming</em> describes a related process: reviewing previous experience to <strong>improve</strong> persistent memory.</p><p>As agents work, their notes can become fragmented.</p><p>Different sessions may record the same discovery, preserve conflicting information or miss a pattern that only becomes visible across several tasks.</p><p>You can end up with five notes explaining the same workaround and nobody sure which one is current. Same documentation mess, now billed per token.</p><p><a href="https://platform.claude.com/docs/en/managed-agents/dreams">Anthropic’s Dreams</a> feature reviews existing memory alongside past session transcripts and produces a separate, reorganized memory store.</p><p>It can merge duplicates, replace stale entries and surface additional insights. The original store remains available, so developers can inspect the result before adopting it.</p><blockquote><em>Sleep-time compute</em> is the broader idea of <strong>preparing useful computation</strong> ahead of a query.</blockquote><h3>How experience becomes context</h3><p>How is <strong>knowledge</strong> from previous sessions stored and how does the agent retrieve it when needed?</p><p>In a simple file-based implementation:</p><ol><li>A background <strong>consolidation</strong> job reads session transcripts and existing memory.</li><li>It writes proposed changes to a separate, versioned memory directory. Each note includes its scope and supporting evidence.</li><li>The harness <strong>evaluates</strong> the candidate version before adopting it.</li></ol><p>At the start of the next session, the harness loads a small <strong>memory index</strong> into context: a list of available notes, what they cover, and where to find them.</p><p>The agent uses file or search tools to read the relevant notes, bringing their contents into its active context window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PEqMZP257ozoWGS8.png" /></figure><p>The information persists <strong>outside</strong> the model, it becomes usable when the harness or the agent brings it into context. This workflow changes the agent’s available knowledge without updating model weights.</p><h3>Why this matters for context engineering</h3><p>Context engineering involves <strong>shaping the information</strong> an agent receives, like:</p><ul><li>Instructions.</li><li>Retrieved documents.</li><li>Tool results.</li><li>Examples.</li><li>Memory.</li></ul><p>Dreaming extends that work across time by improving the material <strong>future contexts</strong> will be assembled from.</p><h4>#1 Better representations</h4><p>A <strong>transcript</strong> records what happened; a useful <strong>note</strong> explains what a future task should take from it.</p><p><a href="https://www.anthropic.com/research/components-of-agent-memory">Anthropic’s research on agent memory</a> describes how dreaming can correct notes against transcripts and build linked representations such as wikis. Depending on the task, the useful output might be a procedure, a document map, or a concise rule linked to evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bT4qb8eskNSHTDP8.png" /></figure><h4>#2 More selective context</h4><p>Persistent memory can hold substantially more than a task needs immediately.</p><p>A <strong>small starting index</strong> can point to detailed notes and original sources, leaving the agent to retrieve the relevant material.</p><p><strong>Consolidation</strong> process helps decide what deserves immediate attention and what should remain available on demand.</p><h4>#3 Reusable operational guidance</h4><p>Reviewing several sessions can reveal <strong>repeated friction</strong>: a failed search, a confusing tool parameter, or a workaround discovered independently.</p><p>Turning that pattern into scoped, testable guidance gives the next agent a better starting point, and gives developers something concrete to evaluate.</p><h3>Use case: a coding agent running tests</h3><p>Your coding agent repeatedly fails to run tests from a monorepo’s root directory before discovering the correct package command and working directory.</p><p>Without consolidation, the next session gets to enjoy the same investigation.</p><p>A background job can review those traces and write a candidate note to memory/testing/payments.md, recording the command, directory, prerequisites and a reference to the successful runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ki8fQeNUQnJtjHU_.png" /></figure><p>A <strong>consolidated note</strong> might look like this, the commands and trace references below are illustrative:</p><pre># Running payments tests<br><br>## When to use<br>When changing code in packages/payments.<br><br>## Procedure<br>- Working directory: packages/payments<br>- Command: pnpm test<br>- Check the current package.json before running.<br><br>## Evidence from previous sessions<br>- session-021: no test script was defined at the repo root.<br>- session-034: the package-local command ran the payments unit<br>tests successfully.<br>- session-041: the same procedure succeeded again.<br><br>## Scope and freshness<br>Verified for this package only.<br>Recheck if test scripts or workspace configuration change.</pre><p>Once that memory version is adopted, the next agent working on the payments package can find the note through the memory index and read it before running tests.</p><p>This will <strong>avoid a repeated investigation</strong> while retaining the evidence needed to verify the procedure.</p><h3>Does this actually improve efficiency?</h3><p>The original <em>sleep-time compute</em> paper reports roughly <em>five times less test-time compute for comparable accuracy</em> on its modified mathematical reasoning tasks.</p><p>It also reports a <em>2.5-fold reduction in average cost per query</em> when preparation is shared across related questions. These are <strong>experimental results</strong> on specific benchmarks. <a href="https://arxiv.org/abs/2504.13171">Sleep-time Compute</a>.</p><p>Background preparation <strong>consumes resources</strong> too, its value depends on whether later tasks reuse the work; the paper finds that <strong>predictable queries benefit more</strong>.</p><p>For a deployed harness, I would <strong>check the full loop</strong>: did the agent retrieve the note, use it appropriately, and perform better?</p><p>Measure task success, repeated tool calls, correction rate, latency and total cost (including consolidation).</p><blockquote><em>Remembering past information and improving on future tasks are different things.</em></blockquote><h3>When the extra work doesn’t pay off</h3><p>The extra compute is <strong>only worth it</strong> if it improves future tasks enough to justify its <strong>cost</strong>.</p><p><a href="https://www.anthropic.com/research/components-of-agent-memory">Anthropic reports</a> a task where a <em>dreaming-built wiki</em> offered no clear improvement over direct search, and another where the wiki grew larger than its source documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8P2QLB-1rpVy4A-vXMsNLg.png" /><figcaption>The generated wiki ended up 77% larger than the original documents. Source: <a href="https://www.anthropic.com/research/components-of-agent-memory">Anthropic</a>.</figcaption></figure><p>In our testing example, a maintained repository guide, such as an AGENTS.md file containing the correct command, is a useful baseline. Consolidation should demonstrate value beyond that simpler approach.</p><p>The question to evaluate is whether the resulting memory <strong>improves future task success</strong>, latency or total cost, including the work required to create and maintain it.</p><h3>And what about Google’s SLEEP framework?</h3><p>Google explores the <em>sleep</em> paradigm at a different layer.</p><p>The paper <a href="https://arxiv.org/abs/2606.03979">Language Models Need Sleep</a>, also explained in <a href="https://research.google/blog/the-sleep-framework-a-new-way-for-llms-to-retain-knowledge-in-continual-learning/">Google Research’s overview</a>, proposes memory consolidation into <strong>model parameters</strong> and a dreaming stage involving <strong>synthetic training data</strong> and further learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E6gMZLX2sBrSpK4K.png" /><figcaption>Google’s sleep framework consolidates knowledge into model parameters. Source: Google Research</figcaption></figure><p>That differs from reorganizing external files an agent later reads. It <strong>changes the model</strong> through a training process.</p><p>Both approaches explore consolidation between periods of activity, but adding external memory does not give an application the <strong>parameter-learning</strong> capabilities studied in Google’s framework.</p><h3>Where I would start</h3><p>If you want to explore this idea in your agent harness, first, choose <strong>one recurring workflow</strong> with visible friction.</p><p>Second, preserve its execution traces and feedback, then run a <strong>consolidation job within a defined time or cost budget</strong> after a batch of sessions.</p><p>Third, generate <strong>candidate memory </strong>(note) with supporting sources, then compare it with the previous version on representative tasks, including exceptions and changed information.</p><blockquote>Keep version history so mistakes can be reversed</blockquote><p>If this process saves the agent from spending five tool calls rediscovering how to run the tests, that’s a useful result.</p><p>If it produces a longer memory file and the same five failed commands, there’s more work to do.</p><p>Thanks for reading!</p><p>Wences 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5a62af5db2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI agents in production: the signals that matter]]></title>
            <link>https://wencesms.medium.com/ai-agents-in-production-the-signals-that-matter-21119110e41f?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/21119110e41f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 18:46:01 GMT</pubDate>
            <atom:updated>2026-08-02T18:46:01.324Z</atom:updated>
            <content:encoded><![CDATA[<h4>What we measure with Langfuse to operate a DevOps agent against real infrastructure</h4><p>For the last few months at <a href="https://www.resiz.es/">Resizes</a> we have been building <em>Agentic by Resizes</em>, a conversational <strong>agent that sits on top of your cloud infrastructure</strong>.</p><p>Instead of jumping between <em>AWS</em>, <em>Kubernetes</em>, <em>Grafana</em>, <em>GitHub</em>, <em>Prometheus</em> and a dozen other tools, you talk to one agent and it works across all of them.</p><p>Building it taught us something fast: <strong>you cannot operate an agent the way you operate a normal service</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gSskcEcOmqPf0a63lkUtQ.png" /><figcaption>Agentic by Resizes — UI Overview</figcaption></figure><p>A normal service is <strong>deterministic,</strong> an AI agent is not. The same question can take a different path, call different tools, pick a different model and end up with a different cost every time. Traditional monitoring is not enough, you need <strong>signals that describe decisions</strong>, not only latency or error rates.</p><p>Early on we wired up <a href="https://langfuse.com/"><strong>Langfuse</strong></a> and the first dashboard made something uncomfortable visible. We had built complexity-based routing so <strong>cheap questions</strong> would hit a <strong>cheap model</strong> and heavy work would go to a more powerful one. But in practice, almost all traffic was landing on a single model.</p><p>Here is what we have measured, why each signal matters, and how the charts change what we do on a Monday morning (and on Fridays too).</p><h4><strong>In this post</strong></h4><blockquote>1 . The unit of observation: <strong>conversational-turn</strong><br>2. <strong>Mask</strong> before you export<br>3. The <strong>five signals</strong> that matter<br>4. Decision signals: <strong>tier</strong> and <strong>model</strong><br>5. What this <strong>changed</strong> for us<br>6. Takeaways</blockquote><h3>The unit of observation: conversational turn</h3><p>We treat <strong>each user turn</strong> as the primary span, named <strong><em>conversational-turn:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MC2NRQgtRSwqZZP9XowR4A.png" /></figure><p>Around it we attach <strong>three kinds of data</strong> and keeping them separate is the most useful decision we’ve made:</p><ul><li><strong><em>Metadata</em></strong> is for debugging a single turn.</li><li><strong><em>Tags</em></strong> are for grouping many turns in a dashboard.</li><li><strong><em>Scores</em></strong> are for tracking rates and trends over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UsBh1wirEQ7Jpdk4caf18A.png" /><figcaption>Langfuse — conversational-turn metadata overview</figcaption></figure><p>Mixing these up is how you end up opening traces one by one to answer a question a chart should have answered.</p><p><strong>Anything</strong> you want to break down week over week <strong>should be a tag</strong>. For us, the <strong>complexity tier</strong> is one of those dimensions:</p><pre>from langfuse import propagate_attributes<br><br>with propagate_attributes(tags=[f&quot;tier:{tier}&quot;]):<br>    pass</pre><p>Also,<strong> scores</strong> are for outcomes you want as rates:</p><pre>span.score_trace(<br>    name=&quot;iteration_limit_reached&quot;,<br>    value=1 if iteration_limit_reached else 0,<br>    data_type=&quot;BOOLEAN&quot;,<br>)<br>span.score_trace(<br>    name=&quot;write_tools_executed_count&quot;,<br>    value=float(len(executed_write_tools)),<br>    data_type=&quot;NUMERIC&quot;,<br>)</pre><p>If a flag only lives in metadata, you will read traces one at a time. Once it becomes a <strong>score</strong>, you can <strong>trend it across thousands of turns</strong>.</p><h3>Mask before you export</h3><p>A <strong><em>DevOps</em> agent</strong> sees tokens, keys, secrets and cloud identifiers all day long, which means <strong>your observability pipeline will see them</strong> too unless you scrub them first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*TaUVytwJ5fdiRyLI.gif" /></figure><p>So we <strong>mask sensitive patterns</strong> before any span leaves the process, and you should too, because without stripping sensitive data, your traces become another attack surface.</p><h3>The custom dashboard: five signals that matter</h3><p>We keep our custom dashboard <strong>small</strong>, adding five signals to cover most of the questions we ask day to day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hl06DCt8r-T2n1BhzqKGTg.png" /><figcaption>Langfuse — Resizes Agentic Dashboard overview</figcaption></figure><h4>1. Usage: is anyone actually talking to the agent?</h4><p>This is the boring chart that keeps you honest. Before you optimize model choice or tool latency, <strong>confirm that traffic exists</strong> and that any drop lines up with a deploy, an outage, or a product change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isjMGmOfPTIr1wWgJ6JylQ.png" /><figcaption>Langfuse — Token usage by model chart.</figcaption></figure><p>Half of “<em>the agent is broken</em>” reports are really “<em>nobody used it this week</em>”.</p><h4>2. Tools: which integrations do real work?</h4><p>For a DevOps agent, the <strong>tool ranking</strong> tells you whether <em>GitHub</em>, <em>Prometheus</em>, cloud cost or web fetch dominate real usage, and therefore <strong>which integrations are worth hardening or caching</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oc7lGqYyPkqCCm9pAoMlkw.png" /><figcaption>Langfuse — Tool usage frecuency chart.</figcaption></figure><p>One gotcha from our stack: parent generations did not always populate a <em>toolCallNames</em> field, but filtering <em>Observations by Type = TOOL</em> did. If your chart comes up empty, count tool spans, not a parent field that never gets filled.</p><h4>3. Cost: where does spend concentrate?</h4><p>Budget and flagship models still differ by roughly 10x per million tokens. If one model owns nearly all the cost, either your workload really is uniform, or your routing is not differentiating capacity.</p><pre>// Chart configuration<br>Observations → Total Cost → optional breakdown by Model</pre><p>This is the chart that caught <strong>our tier bug</strong>. Read cost next to usage and tool frequency, because cost without volume is misleading.</p><h4>4. Reliability: what is failing, and is it rising?</h4><p>A simple signal for <strong>deploy regressions</strong> or <strong>third-party services outages</strong>. When it moves, jump to the tracing view with the same filter and read the offending observation names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNnToIzFRYBeH74m40hpSQ.png" /><figcaption>Langfuse — Error rate over time chart.</figcaption></figure><pre>// Chart configuration<br>Observations → Count → filter Level = ERROR</pre><p>Worth adding later: <strong>errors broken down by tool name</strong>.</p><h4>5. Control-flow health: is the agent thrashing?</h4><p>These are <em>agent-specific</em>, traditional monitoring tools will never invent them for you:</p><ul><li><strong><em>iteration_limit_reached</em></strong> tells you the agent is burning through its loop budget.</li><li><strong><em>write_tools_executed_count</em></strong> tells you how often turns cause side effects.</li></ul><pre>// Chart configuration<br>Scores → Count Scores → filter Name = iteration_limit_reached, Value = 1</pre><p>For a DevOps agent, a write is a very different risk class from a read.</p><h4>Decision signals: tier and model</h4><p>We classify each turn into <em>SIMPLE</em>, <em>MEDIUM</em>, or <em>COMPLEX</em> and pick a model for that tier.</p><p>The point isn’t a clever taxonomy, it is making the expensive path a deliberate choice instead of something that just happens by accident.</p><pre>tier = await classify_message(user_message)  # SIMPLE | MEDIUM | COMPLEX<br>model = select_model_for_tier(tier)</pre><p>Then we chart it two ways:</p><ul><li>Tier Distribution Over Time<strong>, </strong>tells you whether <strong>real traffic matches the routing design</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Na9Gdeefq1sEboMIflSTug.png" /><figcaption>Langfuse — Tier distribution over time chart.</figcaption></figure><ul><li>P95 Latency by Tier<strong>, </strong>tells you <strong>which tier is expensive in wall-clock time</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0PzQ2gMMFTUJy16w6JFVA.png" /><figcaption>Langfuse — P95 latency by tier chart.</figcaption></figure><p>Two caveats from operating this</p><ul><li><strong>Latency mixes different jobs</strong>: a turn that opens a <em>GitHub </em>pull request can legitimately take minutes, while a turn answering “<em>what is the error rate</em>” should not. If P95 looks shocking, split read-heavy turns from write-heavy turns before you go “optimize the model.”</li><li>Check that <strong>each tier actually maps to a different model</strong> in every environment. Tagging a turn as <em>tier:simple</em> or <em>tier:complex</em> is useless if both tiers end up calling the same model.</li></ul><h3>What this changed for us</h3><p>Once we created this dashboard, the conversations about the agent got sharper:</p><ul><li>The cost chart showed that <strong>almost all spend was going to one model</strong>, which is how we found the broken tier mapping.</li><li>The <strong>tool ranking</strong> told us which <strong>integrations deserved reliability</strong> work first.</li><li>The <strong>iteration-limit score</strong> surfaced turns that “kind of worked” for the user but were quietly expensive.</li><li>Error trends gave us a deploy-day signal beyond “<em>the UI still loads</em>”.</li></ul><p>That is the whole point of this style of observability: <strong>not prettier traces, but faster and better operating decisions.</strong></p><h3>Takeaways</h3><ul><li><strong>Measure the turn</strong>, not just the final answer!</li><li>Keep<strong> metadata, tags </strong>and<strong> scores separate</strong> on purpose.</li><li><strong>Rank your tools</strong>, because for almost any agent, <strong>tool usage is a product signal</strong>.</li><li>Track the failure modes traditional monitoring cannot see: <strong>iteration budgets</strong>, <strong>write side effects</strong> and <strong>cost concentration</strong>.</li><li><strong>Keep the dashboard small</strong> enough that someone will actually look at it.</li></ul><blockquote>Operate the agent like a system with control flow, not like a single LLM call with vibes.</blockquote><h3>Building this at Resizes</h3><p>This is part of how we build agent systems at <a href="https://resiz.es/">Resizes</a>: <strong>DevOps-facing agents that call real infrastructure APIs</strong>, with enough observability to know whether tools, spend and control flow behave the way we designed them to.</p><p>If you are shipping agents against production systems, <strong>start from the questions</strong> you need answered on a Monday morning. Instrument those answers first and add another model to the router second!</p><p>If this post was useful, feel free to share it with someone who is putting agents into production.</p><p>Thanks for reading! 👋🏻<br>Wences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21119110e41f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We had 48 hours to build our own Lovable]]></title>
            <link>https://wencesms.medium.com/we-had-48-hours-to-build-our-own-lovable-ba0f8829492e?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0f8829492e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 06:06:00 GMT</pubDate>
            <atom:updated>2026-06-01T06:06:00.638Z</atom:updated>
            <content:encoded><![CDATA[<h4>A technical breakdown of the production-ready coding agent we built at an AWS hackathon.</h4><p>2025 was the year <strong>vibe coding went mainstream</strong>. Tools like <em>Lovable</em>, <em>Vercel v0</em>, and <em>Replit</em> showed that you do not need a GitHub account or a local dev environment to build a real app. Just describe what you want and something runs.</p><p>That gap between “<em>I have an idea</em>” and “<em>I have a working product</em>” got a lot smaller for a lot of people.</p><p>We saw an <strong>opportunity</strong> there. Our product, <a href="https://resiz.es/">Resizes Dash</a>, was already used by technical teams, but we also wanted to <strong>reach users who had great ideas and no coding background</strong>, and a coding agent felt like the right bridge between both worlds.</p><p>So when an AWS hackathon came up in Madrid in October 2025, my colleague Guille and I made a bet: <strong>48 hours to build our own version</strong>, on our own stack, <strong>production ready</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xV3lqR3zIP79AzsT6CjDmQ.jpeg" /><figcaption>All the great teams of the AWS Hackathon. At center, in the bottom row, Guille &amp; I.</figcaption></figure><p>After 48h, we came back home with a <strong>working prototype of a coding agent</strong> that takes a a text prompt and spits out a <strong>deployed and polished React application</strong>. A few weeks later, that prototype became a real feature inside our product, called Dash <em>Studio:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7fyYpeBcKE_a1svVFDIjw.gif" /></figure><p>This is the story of how it works, what we got right, what we cut corners on, and which patterns I think are worth stealing.</p><h3>What we actually built</h3><p>The system takes a text prompt from the user and returns a deployed and polished React frontend application.</p><p>Under the hood it <strong>runs a full build</strong>: copies a boilerplate project into a temp directory, hands it to an <strong>AI agent that writes and modifies files</strong>, runs npm run build to validate the output, and uploads the result to AWS S3 file storage to store the different versions of the app. Progress streams to the browser in <strong>real time through Server-Sent Events</strong> (SSE).</p><p>The stack we used: <em>Python 3.11</em>, <a href="https://fastapi.tiangolo.com/"><em>FastAPI</em></a>, the <a href="https://strandsagents.com/"><em>Strands Agent SDK</em></a>, <a href="https://www.litellm.ai/"><em>LiteLLM</em></a> routing to Claude Sonnet on AWS Bedrock, and a <em>Vite/React/shadcn</em> for the application boilerplate.</p><h3>The architecture in plain terms</h3><p>Before getting into the decisions, a quick note on the <strong>framework choices</strong>, because they are not arbitrary.</p><p>We chose <strong>FastAPI</strong> for a very specific reason: our core workflow involves long-running background processes (typically 60 — 70 seconds), real-time event streaming (SSE), and multiple interactions with S3.</p><p>This type of workload plays to FastAPI’s strengths:</p><ul><li>It handles <strong>async operations</strong> and streaming natively and elegantly.</li><li>It allows us to manage <strong>long-lived requests without heavy workarounds</strong>.</li><li>Since the rest of our backend is already in Python, we avoid the complexity of maintaining multiple languages.</li></ul><p>While Django could have worked, its sync-first nature would have required additional complexity (threading or Celery) to handle this flow cleanly. Node.js was also an option, but introducing a second language would have added unnecessary overhead to our stack.</p><p>FastAPI gave us the best balance of performance, developer experience, and simplicity for this specific use case.</p><p>There are three moving parts:</p><ul><li><strong>The API layer.</strong> A POST endpoint that creates an app record and immediately returns HTTP 200. The actual build runs as a background task. A separate GET endpoint opens a Server-Sent Events (SSE) stream per user where progress updates arrive.</li><li><strong>The build service.</strong> Orchestrates the full pipeline: copy boilerplate app, run the agent, push events to the SSE stream, upload to AWS S3, update usage counters, clean up temp files.</li><li><strong>The agent.</strong> A Strands agent with two tools: file operations (read, write, create, delete, list) and build validation (runs npm install + npm run build). Claude does the thinking; the tools give it hands.</li></ul><h3>The decisions that actually mattered</h3><h4>1. Respond immediately, build asynchronously</h4><p>The <em>POST</em> endpoint does one thing synchronously: create the metadata record in our API, <strong>everything else is fire-and-forget</strong>.</p><pre>asyncio.create_task(<br>    build_service.process_build_request(user_id, space_id, app_data, body.prompt)<br>)<br>return AgentApplicationCreationResponse(agentApplication=app_data)</pre><p>The client gets an app ID back in milliseconds and starts listening to the <strong>SSE stream</strong>. There is <strong>no polling endpoint</strong>, no separate “check status” call, the stream is the status mechanism.</p><p>This is a small thing to describe but it changed how the whole feature feels. The user is not waiting at a loading spinner after pressing a button. They <strong>see the stream open, and then progress events start arriving</strong>.</p><h4>2. SSE instead of WebSockets</h4><p>Every user gets a dedicated asyncio.Queue that the SSE generator reads from it and yields formatted events. If nothing arrives in 30 seconds, a keep-alive ping goes out.</p><pre>async def event_generator():<br>    while True:<br>        if await request.is_disconnected():<br>            break<br>        try:<br>            event = await asyncio.wait_for(queue.get(), timeout=30.0)<br>            yield {&quot;event&quot;: event.type.value, &quot;data&quot;: event.model_dump_json()}<br>        except asyncio.TimeoutError:<br>            yield {&quot;event&quot;: &quot;ping&quot;, &quot;data&quot;: &#39;{&quot;type&quot;:&quot;ping&quot;}&#39;}</pre><p><strong>SSE</strong> is dramatically simpler than <em>WebSockets</em> for this use case. The <strong>connection is one-directional</strong> (server to client), HTTP/1.1 compatible, and works with standard load balancers.</p><p>One production gotcha that will save you time: if <em>Nginx</em> sits in front of your service, you need this header:</p><pre>X-Accel-Buffering: no</pre><p>Without it, Nginx buffers the response body and the client sees nothing until the connection closes.</p><p>That is the <strong>most common SSE deployment bug</strong> and it took me longer than I want to admit to track down.</p><h4>3. The write, compile, self-correct loop</h4><p>This is the part I find most interesting and it is also the simplest to explain.</p><p>The agent has a tool that runs npm run build and returns the output, including errors. When the <strong>build fails</strong>, the chosen <strong>LLM</strong> sees the exact TypeScript or Vite error message and <strong>fixes it in the next iteration</strong>. No human involved.</p><pre>@tool<br>def user_validation() -&gt; str:<br>    &quot;&quot;&quot;Run npm install + npm run build to verify the project compiles.&quot;&quot;&quot;<br>    result = subprocess.run([&quot;npm&quot;, &quot;run&quot;, &quot;build&quot;], cwd=project_dir, ...)<br>    if result.returncode != 0:<br>        return f&quot;Build failed:\n{result.stderr}&quot;<br>    return &quot;Build successful&quot;</pre><p>The agent can write a component, compile, see that a type is wrong, fix it and compile again.</p><p>This feedback loop is what makes AI code generation actually reliable in practice, it is not magic. It is just giving the model a compiler and letting it iterate.</p><h4>4. Pre-configured boilerplate, not scaffold-on-demand</h4><p>Instead of having the agent run npm create vite, install packages, configure Tailwind, and set up shadcn, we keep a fully configured boilerplate in the repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*BBoz9ArEqmu6OKyH2oiI6g.png" /></figure><p>When a build starts, we copy it into a temp directory and hand it to the agent.</p><pre>shutil.copytree(<br>    boilerplate_path,<br>    destination,<br>    ignore=shutil.ignore_patterns(&quot;node_modules&quot;, &quot;.git&quot;, &quot;dist&quot;),<br>)</pre><p>The boilerplate has <em>React 19</em>, <em>TypeScript</em>, <em>Vite</em>, <em>Tailwind</em>, and <em>30+ shadcn/ui components</em> already installed. The <strong>agent never touches setup</strong>, it jumps <strong>straight to writing product logic</strong>.</p><p>This had a bigger impact than I expected as it saves real time (no <em>npm install</em> from scratch for every build), but more importantly, it saves tokens.</p><p>The agent starts with full context available for the actual feature, <strong>not project scaffolding</strong>.</p><h4>5. LiteLLM as an internal model gateway</h4><p>We do <strong>not call AWS Bedrock directly</strong> from the agent. All LLM traffic goes through a self-hosted LiteLLM proxy:</p><pre>model = LiteLLMModel(<br>    client_args={<br>        &quot;api_base&quot;: f&quot;{settings.resizes_litellm_base_url}/v1&quot;,<br>        &quot;use_litellm_proxy&quot;: True,<br>    },<br>    model_id=&quot;bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0&quot;,<br>)</pre><p>This gives us a few things: model IDs become config, not code changes; services authenticate with internal keys, not raw AWS credentials; token usage is logged per service and per user; and we can define <strong>fallback chains</strong> in the LiteLLM config without touching application code.</p><p>Switching from Claude Sonnet 3.7 to 4.5 to 4.6 is a one-line config change. This is an underused pattern in production AI systems.</p><h4>6. S3 paths as a versioning system, with free rollbacks</h4><p>There is <strong>no database for file storage</strong> and <strong>no git,</strong> every build gets its own path in AWS S3:</p><pre>s3://{bucket}/{user_id}/{project_id}/{app_id}/v{version}/</pre><p><strong>Every prompt creates a new version</strong>. The previous ones stay there. This means rollback is essentially free: it is a server-side S3 copy_object from v{N-1} to v{N+1} plus a metadata update. No re-running the agent, no extra infrastructure.</p><p>For the edit flow, the service downloads the previous version from S3, hands it to the agent as the starting point, and uploads the result under the next version number. The agent does not need to know whether it is editing or creating from scratch.</p><p>In practice this turned out to be <strong>one of the features users liked most</strong>. They could try a prompt, not like the result, and go back to the previous version in one click. The screenshot below shows the version history panel in Resizes Dash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*NDrh2yY18l14fzLl5Xi-xQ.png" /></figure><h4>7. How the frontend renders the app (with no preview server)</h4><p>This is the part of the system I am most proud of, and the one that surprised me the most when we figured it out.</p><p>When the agent finishes we <strong>upload the Vite build output</strong> (the dist/ folder) <strong>to AWS S3</strong>. The frontend then needs to show a live, interactive preview of that React app. The obvious solutions are a running container, a preview server, or a screenshot API, but <strong>we used none of them</strong>.</p><p>Instead, the entire preview runs inside a <strong><em>Service Worker</em></strong> in the browser.</p><p>We use a library called static-browser-server from the <a href="https://codesandbox.io/"><em>CodeSandbox</em></a> team.</p><p>It registers a Service Worker that acts as an HTTP server scoped to a unique subdomain. You hand it a function that resolves file paths to content, and it intercepts every fetch from an iframe pointing at that subdomain.</p><pre>const controller = new PreviewController({<br>    baseUrl: &#39;https://preview.sandpack-static-server.codesandbox.io&#39;,<br>    getFileContent: (filepath) =&gt; {<br>        return agentApplication.buildFilesMap.get(filepath);<br>    }<br>});<br>const previewUrl = await controller.initPreview();<br>iframe.src = previewUrl;</pre><p>The file map is just a Map&lt;string, string&gt; built from the <em>/dist</em> files we fetched from the backend. The Service Worker intercepts requests for index.html, main.js, styles.css and serves them from memory.</p><p>No server, no CDN, no deployment. The <strong>app runs completely inside the browser</strong>.</p><p>One more small detail: the <em>dist</em> files are cached in IndexedDB after the first fetch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2dQoP31EvZ2fvR-S18eHw.png" /><figcaption>Each application build stored in the IndexedDB for caching.</figcaption></figure><p>On revisit, the preview grid loads instantly from local storage with zero network requests. One broken app in the grid does not block the others because we load previews in parallel with Promise.allSettled.</p><h4>Why we picked Strands Agents SDK to orchestrate the agent</h4><p>The agent that ties all of this together is built with <a href="https://strandsagents.com/">Strands Agents SDK</a>, an <strong>open-source agent framework from AWS</strong>.</p><p>We were already running on AWS Bedrock for the LLM calls, so Strands was a natural fit: it is built by the same team, designed to work well with Bedrock, and is pure Python. That last part mattered. We did not want to introduce a framework that fights the language or requires you to think in its abstractions.</p><p>With Strands, tools are plain Python functions with a @tool decorator, and the agent loop is a clean async iterator.</p><pre>async for strands_event in agent.stream_async(prompt):<br>    if strands_event.get(&quot;force_stop&quot;):<br>        raise Exception(strands_event.get(&quot;force_stop_reason&quot;))<br>    if strands_event.get(&quot;result&quot;):<br>        final_result = strands_event[&quot;result&quot;]</pre><p>It is less discussed than LangChain or CrewAI, but if you are already on AWS and writing Python, it is worth a look. The API gets out of your way and lets you focus on what the agent actually does.</p><h4>What we got wrong (or left as known debt)</h4><ul><li><strong>No durable job queue.</strong> If the process restarts mid-build, the task is silently lost. The right fix is SQS or Redis + Celery. We accepted this trade-off for now.</li><li><strong>Single-instance SSE.</strong> The per-user queue lives in process memory. One pod, fine. Multiple pods, events only reach users connected to the right instance. A Redis Pub/Sub layer would fix this for horizontal scaling.</li><li><strong>npm install on every validation.</strong> The validation tool deliberately starts clean, wiping any pre-existing node_modules before running npm install. This ensures the build proves the generated code is fully self-consistent, with no state leaking from previous runs. The trade-off is around <strong>20-30 seconds of install time on every build</strong>. The obvious optimization is detecting that package.json is unchanged and skipping reinstall entirely, which the agent never modifies anyway.</li><li><strong>No concurrency control per user.</strong> Two simultaneous prompts from the same user would write to the same temp directory. We have not hit this in practice but it is a real gap.</li></ul><h4>What I would take from this to another project</h4><p>The write, compile, self-correct loop is the pattern I want people to take away from this. Giving the agent a real compiler and letting it see real errors is what separates reliable code generation from prompt engineering that mostly works. Any tool that produces <strong>structured, machine-readable feedback</strong> can slot into this pattern: linters, test runners, type checkers.</p><p>The SSE + asyncio.Queue setup with the Nginx buffering header is genuinely non-obvious in production. I had seen SSE in tutorials but nothing mentioned the buffering issue.</p><p>And <strong>LiteLLM as an internal gateway</strong> is worth considering for any team running more than one AI-powered service. The model abstraction alone pays for the operational overhead.</p><h4>Closing</h4><p>We shipped the feature to production two weeks after the hackathon.</p><p>A few weeks later we presented it at <strong>Web Summit in Lisbon</strong>, and in the months that followed, users created more than 200 applications with the coding agent in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scYSNn0xEhuGndoKk7RD4g.jpeg" /><figcaption>Showing Dash Studio at Web Summit 2025 (Lisbon)</figcaption></figure><p>Each application version took around 60 to 70 seconds end to end, most of that being npm install and the Vite build step.</p><p>Not bad for something that <strong>started as a 48-hour bet in a hackathon</strong>.</p><p>If you are building something similar and want to talk through the agent tooling, the SSE setup, or the S3 versioning pattern, drop a comment or find me <a href="https://x.com/wenchodev">on X</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCf8rnYq6ywQWMWWAQjeYw.png" /></figure><p>Thanks for reading!</p><p>Wences 👋🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0f8829492e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing code got cheap. Writing context got valuable.]]></title>
            <link>https://wencesms.medium.com/writing-code-got-cheap-writing-context-got-valuable-1188c5fa338f?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1188c5fa338f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Tue, 26 May 2026 06:31:00 GMT</pubDate>
            <atom:updated>2026-05-26T08:06:25.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>Six months ago the way we build software changed. Here’s what moved, and what didn’t.</h4><h4>The November moment</h4><p>Last November, my job quietly changed shape. If you write software for a living, yours did too.</p><p>Not in a bad way, and not all at once. I was <strong>still a software engineer</strong>, <strong>still shipping client work</strong>, still reading every line that went out, but I’d basically stopped typing code myself, and it took me a few weeks to notice.</p><p>I should be precise about that, because “<em>I stopped writing code</em>” is a line that gets misread. I <strong>didn’t stop programming</strong>, I <strong>stopped typing</strong>. Those turned out to be two different jobs, and the gap between them is the whole story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMZcfKHJdKVptz8HREUCeg.png" /></figure><p>Before that, my day was a loop: ask the agent for a chunk of code, get something close, fix the broken parts, run it, repeat. I spent most of the time in Cursor, and the feature I loved most was tab <strong>autocomplete</strong>. But that tells you where I was: the agent was a <strong>faster autocomplete</strong>, and I was still the one typing.</p><p>Then a new client project landed at Resizes. It’s November, <strong>Claude Opus 4.5 had just come out</strong>, and once I saw what it could do, I tried something I wouldn’t have risked on real client work before: I built the app from scratch with an agent, from the very first line.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/i/status/1993030546243699119&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/e424542fd404b317c8f62b6057af9223/href">https://medium.com/media/e424542fd404b317c8f62b6057af9223/href</a></iframe><p>Before writing any code, I wrote down what the agent needed to know: the <strong>specs</strong>, the <strong>boundaries</strong>, the <strong>conventions</strong>, the <strong>architecture</strong>, the “we don’t do this here.” Then I let it build, iterating in small steps with me reviewing each one.</p><p>Three hours in, I realized I’d barely touched the keyboard except to type prompts. The code in front of me was fine, not perfect but fine, and I hadn’t written it.</p><p>That was the <strong>click moment</strong>. The agent hadn’t gotten better at code, the work itself had changed: I wasn’t writing code anymore, I was writing the context the agent needed to write the code I would have written.</p><p>A few days ago I was <a href="https://www.youtube.com/watch?v=96jN2OCOfLs">watching a recent <strong>Andrej Karpathy</strong> interview</a> where he calls <strong>December 2025 his own inflection point too</strong>, the moment the <em>agentic workflow</em> finally clicked for him.</p><p>Good to know I wasn’t the only one. But the order matters to me: I didn’t read about this and then try it, I hit it on a client deadline and only later found the words for it.</p><h3>Vibe coding raised the floor. Agentic engineering raises the ceiling.</h3><p>There’s a phrase <em>Karpathy</em> used in that interview that still resonates in my head:</p><blockquote><em>“Vibe coding is about raising the floor for everyone. </em>Agentic engineering<em> is about preserving the quality bar of what existed before in professional software.”</em></blockquote><p>That distinction matters, and <strong>a lot of developers are missing it</strong>.</p><p><em>Vibe coding democratizes building</em>. Someone with zero programming background can spin up a working app over a weekend.</p><p>That’s amazing, but it’s not what I do for a living.</p><p>At <a href="https://resiz.es/">Resizes</a> we build <strong>scalable</strong> and <strong>robust software</strong> that other companies pay for, so the code we ship has to <strong>not break</strong>, has to be <strong>auditable</strong>, has to be <strong>safe</strong> to refactor in six months when I don’t remember why I wrote it (<em>calm down, most of the time I do remember why</em>)</p><p>So I’m not in the business of vibing things into existence. I’m in the business of <strong>using agents to ship professional software faster</strong>, without lowering my own quality bar.</p><p>Vibe coding makes more people developers. <strong><em>Agentic engineering</em> makes professional developers more dangerous</strong>. Both are real, but only one of them is my job.</p><p>And getting good at it is not about adopting better tools. It’s about realizing that the work itself moved.</p><h3>From typing code to engineering context</h3><p>Here’s how I’d put it now: <strong>my output used to be code</strong>, <strong>now my output is context</strong>.</p><p>The code still exists, the agent writes 90/95% of it, but the thing I’m responsible for, the thing I have to get right or the whole system falls apart, is the <strong>context</strong> the agent reads before it writes.</p><p><em>Karpathy</em> frames this as <strong><em>Software 3.0</em></strong>: the context window is how you program the model. You give it the right text, it interprets it, it executes. The <strong>text is the program</strong>, the <strong>model is the runtime</strong>.</p><p>So most of the engineering effort goes into one question: <strong><em>what does the agent need to know to make the right call here?</em></strong></p><h3>The four artifacts an agentic engineer accumulates</h3><p>Six months in, my work has produced f<strong>our kinds of artifacts</strong> that didn’t exist in my old workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7sEDXWevD17en-trX1JZiw.png" /></figure><p>Each one answers a different version of “<strong>what does the agent need to know?</strong>” And each one has a <em>tell</em>, a specific way your day feels when you don’t have it yet. Recognize the tell, and you’ve found the artifact to build first.</p><h4>The architectural contract</h4><p>The agent makes <strong>one reasonable call in the morning</strong> and <strong>the opposite reasonable call in the afternoon</strong>, and three months in nobody can explain why the codebase looks the way it does.</p><p>The fix is an AGENTS.md file at the root of the project, or a CLAUDE.md if you use Claude Code</p><p>It <strong>states the non-negotiable rules</strong>: no <em>any</em> in TypeScript, the repository pattern for data access, errors always typed.</p><p>The agent <strong>reads it once at the start of every session</strong> and follows it without me reminding. The first version is just five rules you already repeat out loud, written down. I covered this in my <a href="https://wencesmartinez.substack.com/p/your-ai-agent-needs-solid-rules">SOLID-for-agents post</a>, and it’s the cheapest, highest-impact artifact you can build.</p><h4>The living memory</h4><p>The agent invents a reason for why a file exists, says it with full confidence, and sometimes this is wrong, and dangerous.</p><p>This is one of the main reasons that I’ve built <a href="https://keystoneapp.dev/">Keystone</a> which is an <strong>intelligent memory layer</strong> that ingests GitHub activity (PRs, commits, issues, code) and lets an agent <strong>ask why a codebase is the way it is</strong>.</p><p>Every query gets a fresh answer built from the same underlying truth, the actual PRs and commits. The agent stops guessing and starts looking things up.</p><p>Anyway, you can also create a DECISIONS.md file where you log why you made the calls so the agent has a memory it can read.</p><h4>The reusable skill</h4><p>This can <strong>save you a lot of time</strong>, stop writing multiple times the same setup, the same gotcha.</p><p>These are the copy-paste blocks <em>Karpathy</em> talks about, the little markdown files that say “to do X in this codebase, here’s how.”</p><ul><li>Database migration? <em>Load the migration skill</em>.</li><li>New API endpoint? <em>Load the API service skill</em>.</li></ul><p>The skill carries the <strong>conventions</strong>, the <strong>gotchas</strong>, the worked example. I write it once, the agent reads it, and we’re aligned without me re-explaining.</p><p>The first version is the next thing you <strong>catch yourself explaining twice</strong>.</p><h4>The eval loop</h4><p>Someone asks if <strong>your agent setup got better this week</strong> and you genuinely <strong>cannot answer.</strong></p><p>This is the one nobody talks about, and the one that keeps the other three honest. If you can’t measure it, you can’t tell improvement from quiet rot, so you track a few things: retrieval quality, token usage, which tasks needed a human correction.</p><p>I’ll be honest, this is the artifact I’m weakest on.</p><p>I’m building it for <a href="https://keystoneapp.dev/">Keystone</a> right now, because <strong>I caught myself tweaking prompts and retrieval logic for weeks with no idea if any of it helped</strong>. The first version is one number you check every Friday, and <em>I’ll give this one its own post</em>, because it earns it.</p><p>These four are where my time goes now, not the code itself but the artifacts that make the code happen.</p><h3>So what goes into the contract?</h3><p>Of the four, the <strong>architectural contract</strong> is the one to start with, and in my opinion, the most important, so let me make it concrete. And the clearest example going around right now didn’t begin as a contract. It began as a complaint.</p><p>A few months ago, <a href="https://x.com/karpathy/status/2015883857489522876">Andrej Karpathy posted on X</a> about <strong>his own move to agent-heavy coding</strong>, and he was blunt about where the agents kept letting him down:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/karpathy/status/2015883857489522876&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/051ceae72929f4d831cc6f83698fe86d/href">https://medium.com/media/051ceae72929f4d831cc6f83698fe86d/href</a></iframe><p>Three patterns, and you’ll recognize all of them:</p><blockquote>“The models make <strong>wrong assumptions</strong> on your behalf and just run along with them without checking.</blockquote><blockquote>They don’t manage their confusion, don’t seek clarifications, don’t surface inconsistencies, don’t present tradeoffs, don’t push back when they should.”</blockquote><p>They also overcomplicate; in his words they “<strong><em>implement a bloated construction over 1000 lines when 100 would do</em></strong><em>.</em>” causing collateral damage, changing or removing code and comments they don’t fully understand, even when it has nothing to do with the task.</p><p>A developer, <em>Forrest Chang</em>, took those complaints and did the obvious thing with them. He turned them into a <strong>contract</strong>: a single CLAUDE.md file, <strong>four principles</strong>, each one aimed straight at a failure mode.</p><p>He put it on GitHub and it took off fast, <strong>152k stars</strong>. You can find it below:</p><p><a href="https://github.com/multica-ai/andrej-karpathy-skills">GitHub - multica-ai/andrej-karpathy-skills: A single CLAUDE.md file to improve Claude Code behavior, derived from Andrej Karpathy&#39;s observations on LLM coding pitfalls.</a></p><p>The filename depends on your tool, CLAUDE.md for <em>Claude Code</em>, AGENTS.md for others (<em>Cursor</em>), but the idea is identical: one plain markdown file of rules at the root of the repo.</p><p>Here’s why it’s worth your time. The four principles:</p><ol><li><strong>Think Before Coding</strong> answers the silent-assumptions problem. State your assumptions, surface tradeoffs, ask when something is unclear, push back when a simpler approach exists.</li><li><strong>Simplicity First</strong> answers the overcomplication. Minimum code that solves the problem, nothing speculative, no abstractions for code that runs once.</li><li><strong>Surgical Changes</strong> answers the collateral damage. Touch only what you must, don’t “improve” code you weren’t asked to touch, every changed line should trace back to the request.</li><li><strong>Goal-Driven Execution</strong> is the one I’d underline. Turn instructions into verifiable goals: “fix the bug” becomes “write a test that reproduces it, then make it pass.” Give the agent a target it can check itself against, and it will loop until it gets there.</li></ol><p>Notice what these rules don’t do: <strong>they never hand the agent a procedure</strong>.</p><p>They tell it how to think, that’s the whole trick, and it’s why the file is short and still works. A rule that explains how to reason carries over to situations you never listed. A step-by-step script only covers the case in front of you.</p><p>Here’s the full file. It’s short enough to read in a minute, it’s <em>MIT licensed</em>, and you can <strong>drop it straight into your project</strong>:</p><pre># CLAUDE.md<br>Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.<br><br>**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.<br><br>## 1. Think Before Coding<br>**Don&#39;t assume. Don&#39;t hide confusion. Surface tradeoffs.**<br><br>Before implementing:<br>- State your assumptions explicitly. If uncertain, ask.<br>- If multiple interpretations exist, present them - don&#39;t pick silently.<br>- If a simpler approach exists, say so. Push back when warranted.<br>- If something is unclear, stop. Name what&#39;s confusing. Ask.<br><br>## 2. Simplicity First<br>**Minimum code that solves the problem. Nothing speculative.**<br><br>- No features beyond what was asked.<br>- No abstractions for single-use code.<br>- No &quot;flexibility&quot; or &quot;configurability&quot; that wasn&#39;t requested.<br>- No error handling for impossible scenarios.<br>- If you write 200 lines and it could be 50, rewrite it.<br><br>Ask yourself: &quot;Would a senior engineer say this is overcomplicated?&quot; If yes, simplify.<br><br>## 3. Surgical Changes<br>**Touch only what you must. Clean up only your own mess.**<br><br>When editing existing code:<br>- Don&#39;t &quot;improve&quot; adjacent code, comments, or formatting.<br>- Don&#39;t refactor things that aren&#39;t broken.<br>- Match existing style, even if you&#39;d do it differently.<br>- If you notice unrelated dead code, mention it - don&#39;t delete it.<br><br>When your changes create orphans:<br>- Remove imports/variables/functions that YOUR changes made unused.<br>- Don&#39;t remove pre-existing dead code unless asked.<br><br>The test: Every changed line should trace directly to the user&#39;s request.<br><br>## 4. Goal-Driven Execution<br>**Define success criteria. Loop until verified.**<br><br>Transform tasks into verifiable goals:<br>- &quot;Add validation&quot; → &quot;Write tests for invalid inputs, then make them pass&quot;<br>- &quot;Fix the bug&quot; → &quot;Write a test that reproduces it, then make it pass&quot;<br>- &quot;Refactor X&quot; → &quot;Ensure tests pass before and after&quot;<br><br>For multi-step tasks, state a brief plan:<br>```<br>1. [Step] → verify: [check]<br>2. [Step] → verify: [check]<br>3. [Step] → verify: [check]<br>```<br><br>Strong success criteria let you loop independently. Weak criteria (&quot;make it work&quot;) require constant clarification.<br><br>---<br><br>**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.</pre><p>I run both: <em>Karpathy’s</em> principles for behavior, my own <strong><em>SOLID-based</em></strong> rules for where logic lives and what the architecture allows.</p><p>The file says so itself in its first line, “<em>merge with project-specific instructions.</em>” The contract isn’t a copy-paste job. It’s two layers you stack: the universal one you can borrow, and the project one only you can write.</p><h3>What this means for your role</h3><p>If you’re a developer reading this and feeling slightly behind, <strong>the move isn’t to install another tool</strong>. It’s one file, and version one takes about a minute.</p><p>Create the file your agent reads (CLAUDE.md for Claude Code, AGENTS.md for most other tools). Paste <em>Karpathy’s</em> principles at the top, that’s the behavioral layer, borrowed and done.</p><p>Then add the part only you can write. Under those principles, <strong>list the five rules you already repeat in code review</strong>: where each layer’s logic is allowed to live, the pattern you always reach for, the thing you never want to see (any, a raw fetch call, business logic in a component, pick your own), how errors get handled, when a file is too big and should be split. That’s the project layer.</p><p>Then see if the next agent session feels different. Most people I’ve talked to who tried this said something close to what I said the first time: “<em>oh, I’m doing this wrong</em>.”</p><p>The other artifacts compound from there. But the first move is to stop treating the agent like a smarter autocomplete and start <strong>treating it like a teammate that needs context before it’s any use</strong>.</p><h3>Closing</h3><p>So that’s what changed, I don’t write code the way I used to, I write the things that make it possible.</p><p><em>Karpathy</em> ended his interview with a line I keep thinking about:</p><blockquote>“You can outsource your thinking, but you can’t outsource your understanding.”</blockquote><p>The agent can run the work but <strong>you still have to understand what you’re building</strong>, why it matters, and where it can go wrong. That part stayed yours.</p><p>So, a question to leave you with: <strong>which of the four artifacts are you missing?</strong></p><p>If you’re like most people I talk to, it’s the eval loop. Tell me in the comments!</p><p>This is the first of three posts on <em>agentic engineering</em>. Next up: <strong><em>the eval loop</em></strong>, and the honest answer to a question I couldn’t answer about my own project, <strong>did my agent setup actually get better this week?</strong></p><p>Thanks for reading! Subscribe for free to receive new posts and support my work.</p><p><em>Wences 👋</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1188c5fa338f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS in production: patterns worth stealing]]></title>
            <link>https://wencesms.medium.com/nestjs-in-production-patterns-worth-stealing-1b3d197d7c85?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3d197d7c85</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Sun, 17 May 2026 17:02:04 GMT</pubDate>
            <atom:updated>2026-05-17T17:02:04.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>Six patterns I wish I’d known before shipping my first NestJS backend service.</h4><p>Most NestJS tutorials stop right where things get interesting.</p><p>You learn about <strong>modules</strong>, <strong>decorators</strong>, <strong>dependency injection</strong>, build a CRUD app, and then you ship something real and realize nobody told you how to handle a Stripe webhook without breaking your JSON parser, or why a switch statement for event types doesn’t scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JUGMIMEz8fRBLmbG.png" /></figure><p>This year I built two NestJS backend services at <a href="https://resiz.es/">Resizes</a>: an <strong>entitlements service</strong> that enforces usage limits across plans, and a <strong>billing service</strong> that handles the full Stripe subscription lifecycle. Both power the AI platform we built internally.</p><p>After a few months running them <strong>in production</strong>, here’s what I actually learned. Not “what is dependency injection”, you already know that (I hope so).</p><p>These are the <strong>patterns</strong> I’d copy directly into any new NestJS project.</p><h4>Summary</h4><blockquote>1. How to handle <strong>webhook</strong> events without breaking your JSON endpoints.<br>2. Why a <strong>factory</strong> beats a switch when you have many event types.<br>3. Why <strong>repository layer</strong> on top of Prisma ORM makes testing easier.<br>4. The <strong><em>ValidationPipe</em></strong> options most tutorials skip.<br>5. Named <strong>exceptions</strong> that make your codebase greppable.<br>6. Why <strong>validating env vars</strong> at startup saves you a 3am incident.</blockquote><h3>The module is your unit of ownership</h3><p>A <strong>module</strong> in NestJS is not just a folder convention, it’s a boundary.</p><p>In other words, a module should be something you could delete and the rest of the app wouldn’t notice (until it needs to). What <strong>happens inside stays inside</strong>.</p><p>Here’s what that looks like in practice:</p><ul><li>EntitlementsModule</li><li>BillingModule</li><li>TasksModule.</li><li>HealthModule</li><li>PrismaModule</li></ul><p>Each one is a <strong>self-contained</strong> folder with its <em>controller</em>, <em>service</em>, <em>repository</em>, <em>interfaces</em>, <em>DTOs</em> and tests.</p><p><strong>Nothing leaks out</strong> except what’s explicitly exported, and the <strong>layer separation</strong> is strict: controllers route and validate, services hold business logic, repositories are the only place that touches Prisma.</p><blockquote>One thing to watch out for: module dependencies must be <strong>uni-directional</strong>.</blockquote><p>If <em>BillingModule</em> imports from <em>EntitlementsModule</em>, that’s fine. But if <em>EntitlementsModule</em> then also imports from <em>BillingModule</em>, you’ve <strong>created a circular dependency</strong> and NestJS will tell you at <strong>startup with a cryptic error</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G90mnBzUoF9lVx4v.png" /></figure><p>The fix is usually introducing a third, higher-level module that orchestrates both, or reconsidering whether that cross-dependency is pointing at a domain boundary problem.</p><p>NestJS does have a <strong><em>forwardRef()</em></strong> escape hatch for exactly this situation, but it’s <strong>a patch, not a solution</strong>. Every time I’ve reached for it, the real answer was that I’d mixed two domains into what <strong>should have been separate modules</strong>.</p><p>For <em>PrismaService</em>, I went with <strong><em>@Global()</em></strong> to avoid re-importing it everywhere:</p><pre>// prisma/prisma.module.ts<br>@Global()<br>@Module({<br>  providers: [PrismaService],<br>  exports: [PrismaService],<br>})<br>export class PrismaModule {}</pre><p>And the service handles its own lifecycle:</p><pre>// prisma/prisma.service.ts<br>@Injectable()<br>export class PrismaService extends PrismaClient<br>  implements OnModuleInit, OnModuleDestroy {<br><br>  private readonly logger = new Logger(PrismaService.name)<br>    async onModuleInit() {<br>      await this.$connect()<br>      this.logger.log(&#39;Database connected&#39;)<br>    }<br>    async onModuleDestroy() {<br>      await this.$disconnect()<br>      this.logger.log(&#39;Database disconnected&#39;)<br>    }<br>}</pre><p>One instance, clean <strong>connect/disconnect</strong>.</p><p>I’ve seen more than one codebase with connection leaks because nobody hooked into the module lifecycle.</p><h3>The Stripe webhook pattern you should steal</h3><p>This is the most concrete thing I can give you.</p><p>As an example, webhooks from <em>Stripe</em> (or any payment provider) have a problem: to <strong>validate the signature</strong> you need the raw body as a buffer, but NestJS’s global JSON parser already consumed it by the time your controller runs.</p><p>The naive fix is enabling raw body globally. <strong>Don’t do that</strong>. It breaks your regular JSON endpoints.</p><p>The correct fix is three pieces that work together.</p><ol><li>Apply the <strong>raw body parser</strong> only on the webhook route, before NestJS starts:</li></ol><pre>// main.ts <br>app.use(&#39;/stripe/webhooks&#39;, raw({ type: &#39;application/json&#39; }))</pre><p><strong>This runs before the global JSON middleware</strong>. Only that route gets a buffer body. Everything else keeps working normally.</p><p>2. Validate the signature in a middleware:</p><pre>// stripe-webhook.middleware.ts<br>@Injectable()<br>export class StripeWebhookMiddleware implements NestMiddleware {<br>  use(req: Request, res: Response, next: NextFunction) {<br>    const sig = req.headers[&#39;stripe-signature&#39;]<br><br>    try {<br>      req[&#39;stripeEvent&#39;] = this.stripe.webhooks.constructEvent(<br>        req.body,<br>        sig,<br>        this.configService.get(&#39;STRIPE_WEBHOOK_SECRET&#39;)<br>      )<br>      next()<br>    } catch (err) {<br>      this.logger.error(`[StripeWebhook] Invalid signature: ${err.message}`)<br>      throw new BadRequestException(&#39;Invalid webhook signature&#39;)<br>    }<br>  }<br>}</pre><p>The middleware decorates the request with the parsed <em>stripeEvent</em>. The <strong>controller never touches raw bytes</strong>.</p><p>2. In the controller, process and respond… <strong>keep handlers fast</strong>:</p><pre>// stripe.controller.ts<br>@Post(&#39;webhooks&#39;)<br>async handleWebhook(@Req() req: Request) {<br>  const event = req[&#39;stripeEvent&#39;] as Stripe.Event<br>  await this.stripeService.handleEvent(event)<br>  return { received: true }<br>}</pre><ul><li>Stripe gives you up to <strong>30 seconds before it marks the delivery as failed</strong> and retries. The <em>await</em> is intentional: each individual handler is fast, just a database write and a status update, nothing close to that limit.</li><li>If your handlers were doing <strong>slower work</strong> (calling external APIs, sending emails through a third-party service), the right move is to <strong>push the event to a queue</strong> like BullMQ or a Postgres outbox table, and <strong>respond 200 immediately</strong>.<br>At our scale, staying synchronous is simpler and predictable.</li></ul><p>One more thing: since <em>NestJS v8</em> there’s a cleaner alternative to the <em>app.use(‘/stripe/webhooks’, raw(…))</em> approach:</p><ul><li>You can pass <em>{ rawBody: true }</em> to <em>NestFactory.create()</em> and <strong>access <em>req.rawBody</em> directly in the middleware</strong>, which keeps the Express-level setup out of your bootstrap file. Both work!</li></ul><h3>Event handler factory instead of a switch</h3><p>The <em>Billing Service</em> receives a dozen different <strong>Stripe event types</strong>:</p><ul><li>customer.subscription.created</li><li>customer.subscription.updated</li><li>invoice.paid</li><li>Etc.</li></ul><p>The first instinct is a switch statement. Don’t do that, there’s a <strong>better way of handling this</strong>!</p><pre>// the antipattern<br>switch (event.type) {<br>  case &#39;customer.subscription.created&#39;:<br>    await this.handleSubscriptionCreated(event)<br>    break<br>  case &#39;customer.subscription.updated&#39;:<br>    await this.handleSubscriptionUpdated(event)<br>    break<br>  // ... 10 more cases<br>}</pre><p>This is a maintenance trap; every new event type means opening this file and adding a case. The <strong>class grows without bound and testing becomes painful</strong>.</p><p>Instead, I built a <strong>factory</strong> that resolves handlers by event type, all via <em>Nest’s DI</em>:</p><pre>// stripe-event-handler.factory.ts<br>@Injectable()<br>export class StripeEventHandlerFactory {<br>  private readonly eventHandlers: Record&lt;string, StripeEventHandler&gt;<br><br>  constructor(<br>    private readonly subscriptionUpdatedHandler: CustomerSubscriptionUpdatedEventHandler,<br>    private readonly subscriptionDeletedHandler: CustomerSubscriptionDeletedEventHandler,<br>    private readonly invoicePaidHandler: InvoicePaidEventHandler,<br>    // ...<br>  ) {<br>    this.eventHandlers = {<br>      &#39;customer.subscription.updated&#39;: this.subscriptionUpdatedHandler,<br>      &#39;customer.subscription.deleted&#39;: this.subscriptionDeletedHandler,<br>      &#39;invoice.paid&#39;: this.invoicePaidHandler,<br>    }<br>  }<br><br>  resolve(eventType: string): StripeEventHandler {<br>    const handler = this.eventHandlers[eventType]<br>    if (!handler) throw new NotFoundException(`No handler for event: ${eventType}`)<br>    return handler<br>  }<br>}</pre><p>Each handler is its own class with a <strong>single <em>handle</em> method</strong>. Adding a new event type is just a new class and one line in the map. No existing file changes. Also follows the <em>Open/Closed</em> principle!</p><p>The service call ends up clean:</p><pre>const handler = this.stripeEventHandlerFactory.resolve(event.type)<br>await handler.handle(event)</pre><h3>Repository pattern on top of Prisma</h3><p>I know this sounds like over-engineering when Prisma already gives you a clean API. The point isn’t the abstraction itself, <strong>it’s the isolation</strong>.</p><p>When one of your services depends directly on Prisma, testing the service means setting up a real database or doing gymnastics with <em>jest.mock(‘prisma’)</em>.</p><p>When your <strong>service depends on a repository layer</strong>, you inject a mock in tests and the whole thing collapses into a flat unit test.</p><pre>// entitlements.repository.ts<br>@Injectable()<br>export class EntitlementsRepository {<br>  constructor(private readonly prisma: PrismaService) {}<br><br>  async incrementUsage(userId: string, entitlementId: string): Promise&lt;void&gt; {<br>    await this.prisma.entitlementUsage.update({<br>      where: { userId_entitlementId: { userId, entitlementId } },<br>      data: { currentUsage: { increment: 1 } },<br>    })<br>  }<br>}</pre><p>The corresponding service test:</p><pre>// entitlements.service.spec.ts<br>describe(&#39;EntitlementsService&#39;, () =&gt; {<br>  let service: EntitlementsService<br><br>  beforeEach(async () =&gt; {<br>    const module = await Test.createTestingModule({<br>      providers: [<br>        EntitlementsService,<br>        {<br>          provide: EntitlementsRepository,<br>          useValue: {<br>            incrementIfWithinLimit: jest.fn().mockResolvedValue(true),<br>          },<br>        },<br>      ],<br>    }).compile()<br><br>    service = module.get(EntitlementsService)<br>  })<br><br>  it(&#39;should increment usage when within limit&#39;, async () =&gt; {<br>    await service.incrementUsage(&#39;user-1&#39;, &#39;TOKENS&#39;)<br>    // assert on the mock, not the database<br>  })<br>})</pre><p>No database → No containers → Pure logic under test!</p><h3>Configure your ValidationPipe properly</h3><p>Most tutorials show only the basic <a href="https://docs.nestjs.com/techniques/validation"><em>ValidationPipe</em></a> setup. These three options are the ones that actually matter in production:</p><pre>app.useGlobalPipes(new ValidationPipe({<br>  whitelist: true,            // strips unknown properties before they reach your service<br>  forbidNonWhitelisted: true, // throws 400 if the client sends unknown fields<br>  transform: true,            // auto-transforms payloads to DTO class instances<br>}))</pre><ul><li><strong><em>whitelist</em></strong> is a silent safety net: if someone sends extra fields they shouldn’t, they never reach your business logic.</li><li><strong><em>forbidNonWhitelisted</em></strong> makes it explicit by rejecting the request outright. Both together are the right default for any API that doesn’t accept open-ended payloads.</li></ul><h3>Exceptions that tell you something</h3><p>NestJS’s built-in HTTP exceptions are good, but <strong>extending them is better</strong>.</p><p>Instead of throwing raw <em>HttpException</em> everywhere, define named exception classes:</p><pre>// exceptions/entitlement-limit-exceeded.exception.ts<br>export class EntitlementLimitExceededException extends ForbiddenException {<br>  constructor(userId: string, type: string) {<br>    super(<br>      `User ${userId} has reached the limit for entitlement: ${type}`,<br>      &#39;ENTITLEMENT_LIMIT_EXCEEDED&#39;<br>    )<br>  }<br>}<br><br>// exceptions/billing-user-not-found.exception.ts<br>export class BillingUserNotFoundException extends NotFoundException {<br>  constructor(userId: string) {<br>    super(`Billing user not found: ${userId}`, &#39;BILLING_USER_NOT_FOUND&#39;)<br>  }<br>}</pre><p>Usage in the service:</p><pre>if (!withinLimit) {<br>  throw new EntitlementLimitExceededException(userId, type)<br>}</pre><h3>Validate your config at startup</h3><p>One of the most underrated NestJS patterns: <strong>validate your environment variables when the app boots</strong>, not when a request first hits the code path that needs them.</p><pre>// app.module.ts<br>ConfigModule.forRoot({<br>  isGlobal: true,<br>  validationSchema: Joi.object({<br>    DATABASE_URL:          Joi.string().required(),<br>    STRIPE_SECRET_KEY:     Joi.string().required(),<br>    STRIPE_WEBHOOK_SECRET: Joi.string().required(),<br>    DASH_UI_URL:           Joi.string().required(),<br>    NODE_ENV:              Joi.string().valid(&#39;development&#39;, &#39;production&#39;, &#39;test&#39;).default(&#39;development&#39;),<br>  }),<br>})</pre><p>If any required <strong>variable is missing</strong> or has the wrong type, the <strong>app throws before it binds to port 3000</strong>. You find out in the deploy step, not at 3am when the first request hits that code path.</p><p>For <em>CORS</em>, same idea: no wildcards, explicit origins from env:</p><pre>app.enableCors({<br>  origin: [<br>    configService.get(&#39;DASH_UI_URL&#39;),<br>    configService.get(&#39;DASH_API_SERVICE_URL&#39;),<br>  ],<br>  methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;, &#39;PATCH&#39;],<br>})</pre><p>Reading origins from env means you don’t touch code to change them between environments.</p><h3>Closing</h3><p>The patterns above didn’t come from reading documentation, they came from <strong>running these services under real load</strong> and fixing real bugs.</p><p>The Stripe <strong>webhook pattern</strong> specifically came from a Sunday afternoon of ghost events because I had the response timing wrong.</p><p>The <strong>factory pattern</strong> for event handlers came from thinking early about how to add new event types without touching existing code.</p><p>If there’s one principle behind all of them it’s this: <strong>each piece of code should have exactly one reason to change</strong>; the controller doesn’t know about Prisma, the service doesn’t know about HTTP, the repository doesn’t know about business rules. When something breaks (and it will), you know exactly where to look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kng7PrBVwjrOhsGA.png" /></figure><p>NestJS gives you the tools to do this, whether you use them is up to you!</p><p>This post is based on the entitlements and billing services I built at <a href="https://resiz.es/">Resizes</a> as part of a larger AI platform. Both are <strong>running in production</strong> today.</p><p>If any of these patterns saved you a Sunday afternoon, I’d love to hear about it in the comments. And if you spot something technically off, even more so!</p><p><em>Thanks for reading!</em></p><p><em>Wences 👋</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3d197d7c85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Nuxt + Prisma in Docker: How we cut our image size by 84%]]></title>
            <link>https://wencesms.medium.com/optimizing-nuxt-prisma-in-docker-how-we-cut-our-image-size-by-84-ea43ffc5ae6c?source=rss-3181b80926fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea43ffc5ae6c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Wences Martinez]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 21:27:55 GMT</pubDate>
            <atom:updated>2026-03-05T08:33:11.454Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn the best way to deploy a Full-Stack Nuxt app with Docker, Prisma, and SQLite using multi-stage builds to achieve a lightweight, production-ready image.</h4><p>By now, <a href="https://nuxt.com/"><strong>Nuxt</strong></a> hardly needs an introduction as one of the most used full-stack frameworks. For those new to the Vue ecosystem, it is essentially the counterpart to <strong>Next.js</strong> in the React world.</p><p>So, Nuxt is not just a frontend framework. With <a href="https://nitro.build/">Nitro</a> as the server engine, you get SSR, API routes, server middleware… it’s a real full stack framework. We’ve been using it at <a href="https://resiz.es/">Resizes</a> for a long time to build complex applications, and it works really well!</p><p>That sounds really cool, right? But what is the most <strong>efficient</strong>, <strong>fastest</strong>, and <strong>most lightweight</strong> way to build a Docker image for a Nuxt app?</p><p><em>Let’s talk about it!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cl1_SxqDvBVfeUhY.png" /></figure><h3>Our Use Case</h3><p>At Resizes we have developed several applications with Nuxt v4, and one of them has several modules and dependencies; auth libraries, an ORM to handle database migrations and even an embedded database, so <em>dockerizing</em> it efficiently was not as straightforward as it seems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ke23PkeyuxKs94kg.png" /></figure><p>In this post I’ll share how we do it, with real numbers from our <em>GitHub Actions</em> pipeline and the hidden traps we found along the way.</p><p><em>The stack</em></p><ul><li><strong>Nuxt 4</strong> + Nitro (server engine)</li><li><a href="https://www.prisma.io/"><strong>Prisma ORM</strong></a> + <strong>SQLite</strong> via <a href="https://www.npmjs.com/package/better-sqlite3">better-sqlite3</a> (native C++ module)</li><li><strong>Docker</strong> with multi-stage build</li></ul><p>The following package.json reveals some of our most used dependencies regarding a Nuxt 4 application:</p><pre>// package.json<br>...<br>&quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;nuxt dev&quot;,<br>    &quot;build&quot;: &quot;nuxt build&quot;,<br>    &quot;generate&quot;: &quot;nuxt generate&quot;,<br>    &quot;preview&quot;: &quot;nuxt preview&quot;,<br>    &quot;postinstall&quot;: &quot;nuxt prepare &amp;&amp; prisma generate&quot;,<br>    &quot;lint&quot;: &quot;eslint .&quot;,<br>    &quot;lint:fix&quot;: &quot;eslint . --fix&quot;<br>},<br>...<br>&quot;dependencies&quot;: {<br>    &quot;better-sqlite3&quot;: &quot;~12.0.0&quot;,<br>    &quot;@prisma/client&quot;: &quot;~7.2.0&quot;,<br>    &quot;@prisma/adapter-better-sqlite3&quot;: &quot;~7.3.0&quot;,<br>    &quot;@anthropic-ai/sdk&quot;: &quot;~0.72.1&quot;,<br>    &quot;better-auth&quot;: &quot;~1.4.17&quot;,<br>    &quot;zod&quot;: &quot;~4.3.5&quot;,<br>    &quot;prisma&quot;: &quot;~7.2.0&quot;,<br>    &quot;dotenv&quot;: &quot;~17.2.3&quot;<br>    ...<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;nuxt&quot;: &quot;~4.2.2&quot;,<br>    &quot;@nuxt/ui&quot;: &quot;~4.3.0&quot;,<br>    &quot;@nuxt/eslint&quot;: &quot;~1.12.1&quot;,<br>    &quot;vue&quot;: &quot;~3.5.27&quot;,<br>    &quot;@vueuse/nuxt&quot;: &quot;~14.1.0&quot;,<br>    &quot;typescript&quot;: &quot;~5.9.3&quot;,<br>    &quot;eslint&quot;: &quot;~9.39.2&quot;,<br>    &quot;eslint-config-prettier&quot;: &quot;~10.1.8&quot;,<br>    &quot;prettier&quot;: &quot;~3.8.1&quot;,<br>    &quot;tsx&quot;: &quot;~4.21.0&quot;,<br>    ...<br>  }</pre><h3>The Dockerfile: single vs multi stage</h3><p>Can you deploy a Nuxt application with a basic Dockerfile? Of course you can! But that doesn’t mean you should.</p><p>While a single-stage Dockerfile will technically build your app, it drags a huge amount of baggage into production. We’re talking about <strong>build tools</strong>, <strong>dev dependencies</strong>, <strong>source code</strong>, and <strong>artifacts</strong>.</p><p>You end up shipping the entire kitchen sink instead of just the lean, compiled application.</p><p>An example of a basic single-stage Dockerfile:</p><pre># Single-stage Dockerfile (for comparison only — DO NOT use in production)<br>FROM node:24-slim<br>RUN apt-get update &amp;&amp; apt-get install -y python3 make g++ --no-install-recommends &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>WORKDIR /app<br>ARG DATABASE_URL=&quot;file:./dummy.db&quot;<br>COPY . .<br><br>RUN npm ci<br>RUN npx prisma generate &amp;&amp; npx nuxt build<br><br>ENV NODE_ENV=production<br>ENV NITRO_HOST=0.0.0.0<br>ENV NITRO_PORT=3000<br><br># Still need to fix Nitro stubs even in single-stage<br>RUN rm -rf .output/server/node_modules<br>RUN cp -r node_modules .output/server/node_modules<br><br>COPY docker-entrypoint.sh ./docker-entrypoint.sh<br>RUN chmod +x ./docker-entrypoint.sh<br><br>EXPOSE 3000<br><br>ENTRYPOINT [&quot;./docker-entrypoint.sh&quot;]<br>CMD [&quot;node&quot;, &quot;.output/server/index.mjs&quot;]</pre><p>We’ve done the test and we’ve built our app with the above Dockerfile vs a multi-stage Dockerfile to compare the size of the final image between them.</p><p>The results are crazy: <strong>4.05 GB</strong> vs <strong>637MB</strong>. The multi-stage Dockerfile is almost <strong><em>x7 times</em></strong> smaller than the single-stage Dockerfile 🫢</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4tWgm4jtd6B_UYiH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E1USBO5TD2fM1LZL.png" /><figcaption><em>Docker Layer Anatomy: Where Does All That Space Go?</em></figcaption></figure><h3>But… how we did it?</h3><p>Multi-stage build separates the process into phases:</p><ul><li>Build stages: have everything needed to compile. They’re temporary images that get <strong>discarded from the final image</strong>!</li><li>Runner stage: contains only the <strong>minimum code</strong> to run the app. It’s the only image pushed to the registry!</li></ul><p>The concrete benefits:</p><ol><li><strong>Smaller</strong> final image.</li><li><strong>Reduced</strong> attack surface — no compilers in production.</li><li><strong>Faster</strong> deploys — less pull time on each Kubernetes node.</li><li>Automatic <strong>parallelism</strong> — Docker runs independent stages in parallel.</li><li>Granular <strong>caching</strong> — if you only change code, the dependencies stage is fully cached.</li></ol><p>Our Dockerfile has 4 stages. Let’s go through each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*WbK_R_tuKz-HiKK6WSbh8g.png" /></figure><h3>Stage 1: Base tools</h3><pre># -------- Base --------<br>FROM node:24-slim AS base<br>RUN apt-get update &amp;&amp; apt-get install -y python3 make g++ openssl --no-install-recommends &amp;&amp; rm -rf /var/lib/apt/lists/*<br>WORKDIR /app</pre><p>You’re probably wondering why the heck do we need <em>python3,</em> <em>make</em> &amp; <em>g++ </em>dependencies.</p><p>Easy, we’re using <em>SQLite</em> as a embedded database through the super fast <a href="https://www.npmjs.com/package/better-sqlite3"><em>better-sqlite3</em></a> library, and this library needs to compile native C++ bindings.</p><p>SQLite is a library written in C, and to use it from Node.js, <em>better-sqlite3</em> includes a “binding” (a bridge between JavaScript and compiled C code).</p><p>This binding is compiled during <strong><em>npm install</em></strong> using <strong>node-gyp</strong>, which needs:</p><ul><li><em>g++</em> — C++ compiler</li><li><em>make</em> — orchestrates the compilation</li><li><em>python3</em> — because node-gyp is written in Python</li></ul><p>The result is a <em>.node</em> file (binary addon) specific to your architecture and Node version.</p><blockquote><em>These tools take up </em><strong><em>~293MB</em></strong><em>, but they won’t be in the final image 💪🏼</em></blockquote><h3>Stage 2: Full dependencies</h3><pre># -------- Dependencies --------<br>FROM base AS deps<br>COPY package.json package-lock.json ./<br>RUN npm ci --ignore-scripts</pre><p>In the second stage we’re only copying the <em>package.json</em> and <em>package-lock.json</em> and run <em>npm ci</em> with the <em>ignore-scripts flag.</em></p><p>This flag is really important if you want to avoid any unnecessary drama. Tools like <em>Prisma</em> or <em>Nuxt</em> love to run ‘<em>postinstall</em>’ scripts the second they’re downloaded, but since we haven’t copied the full source code yet, those scripts would just crash.</p><p>By skipping the installation with this flag, we keep it lightning-fast, let Docker cache the layer perfectly, and save the actual heavy lifting for the Build stage.</p><h3>Stage 3: Building the application</h3><p>This is where the heavy lifting happens!</p><p>Now that we have our dependencies ready, we perform a triple threat of critical tasks: generating the <strong>Prisma client</strong>, compiling the <strong>Nuxt bundle</strong>, and rebuilding <strong>better-sqlite3</strong>.</p><p>This last step is vital — it ensures our SQLite driver is natively compiled for the Linux environment, avoiding those dreaded “mismatched binary” errors in production.</p><pre># -------- Build --------<br>FROM base AS build<br>ENV NODE_OPTIONS=&quot;--max-old-space-size=4096&quot;<br>COPY --from=deps /app/node_modules ./node_modules<br>COPY . .<br><br>ARG DATABASE_URL=&quot;file:./dummy.db&quot;<br>RUN npx prisma generate &amp;&amp; npx nuxt build &amp;&amp; npm rebuild better-sqlite3</pre><p>Key points:</p><ul><li><strong><em>npx prisma generate</em></strong>: Generates the Prisma Client based on your schema.</li><li><strong><em>npx nuxt build</em></strong>: This command triggers the full production build, bundling the client and server-side code through the Nitro engine into a standalone directory (<em>.output folder)</em></li><li><strong><em>npx rebuild better-sqlite3</em></strong>: The “secret sauce” for SQLite. This recompiles the native C++ bindings for our database driver directly inside the Linux container. It ensures the binary perfectly matches our production environment, preventing the dreaded “mismatched architecture” errors.</li></ul><h3>Stage 5: The production image</h3><pre># -------- Runtime --------<br>FROM node:24-slim AS runner<br>RUN apt-get update &amp;&amp; apt-get install -y openssl --no-install-recommends &amp;&amp; rm -rf /var/lib/apt/lists/*<br>WORKDIR /app<br><br>ENV NODE_ENV=production<br>ENV NITRO_HOST=0.0.0.0<br>ENV NITRO_PORT=3000<br><br># Minimal Prisma CLI for migrations - must run BEFORE package.json is copied,<br># otherwise npm sees the app&#39;s package.json and installs ALL dependencies.<br>COPY package-lock.json ./<br>RUN npm install --ignore-scripts \<br>    &quot;prisma@$(node -p &quot;require(&#39;./package-lock.json&#39;).packages[&#39;node_modules/prisma&#39;].version&quot;)&quot; \<br>    &quot;dotenv@$(node -p &quot;require(&#39;./package-lock.json&#39;).packages[&#39;node_modules/dotenv&#39;].version&quot;)&quot; \<br>    &amp;&amp; npm cache clean --force \<br>    &amp;&amp; rm package-lock.json<br><br># Copy compiled app (keeps Nitro&#39;s runtime packages in .output/server/node_modules/)<br>COPY --from=build /app/.output ./.output<br><br># Replace better-sqlite3 with the Linux binary compiled in the build stage.<br>RUN rm -rf .output/server/node_modules/better-sqlite3<br>COPY --from=build /app/node_modules/better-sqlite3 ./.output/server/node_modules/better-sqlite3<br><br># Copy Prisma config + migrations folder for migrate deploy<br>COPY --from=build /app/prisma ./prisma<br>COPY --from=build /app/prisma.config.ts ./prisma.config.ts<br><br>COPY docker-entrypoint.sh ./docker-entrypoint.sh<br>RUN chmod +x ./docker-entrypoint.sh<br><br>EXPOSE 3000<br><br>ENTRYPOINT [&quot;./docker-entrypoint.sh&quot;]<br>CMD [&quot;node&quot;, &quot;.output/server/index.mjs&quot;]</pre><p>The final image uses <em>node:24-slim</em>; no compilers, no Python, no dev tools. Just Node.js and your app.</p><p>Three important details here:</p><ol><li>We leave <em>.output/server/node_modules</em> intact — except for better-sqlite3, which we delete and <strong>replace with a freshly compiled binary</strong> (in build stage).</li><li>We install only <em>prisma</em> and <em>dotenv</em> into <em>/app/node_modules</em>, the <strong>bare minimum needed</strong> to run <em>prisma migrate deploy</em> in the entrypoint script. The rest of the app’s dependencies are already bundled inside <em>.output/server/node_modules</em> by Nitro.</li><li>Automatic <strong>Prisma migrations</strong> with <em>entrypoint.sh</em><strong>, </strong>this script runs <em>prisma migrate deploy</em> every time the container starts, ensuring your database always has the latest schema:</li></ol><pre>#!/bin/sh<br><br>echo &quot;Applying database migrations...&quot;<br><br>export NODE_PATH=&quot;/app/node_modules&quot;<br>/app/node_modules/.bin/prisma migrate deploy<br><br>echo &quot;Starting application...&quot;<br>exec &quot;$@&quot;</pre><h3>GH Actions pipeline results</h3><p>These are real numbers from our GitHub Actions pipeline for <strong>AMD64 architecture </strong>when building the app’s image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YKXmwurrk6-gG_PG.png" /></figure><blockquote><strong><em>💡 Multi-arch tip:</em></strong><em> If you build ARM64 images on AMD64 runners via QEMU, expect 4–7x slower builds. Use native ARM runners if speed matters!</em></blockquote><h3>Hidden Gotchas</h3><p>Nitro <strong>can’t bundle everything</strong>… some packages must stay in <em>node_modules</em>!</p><p>Nitro uses <em>Rollup/esbuild</em> to bundle your server code into optimized <em>.mjs</em> files — but not everything can be bundled.</p><p>Modules like <em>better-sqlite3</em> contain native C++ bindings (.node files), which are platform-specific binaries that simply cannot be converted into a <em>.mjs</em> file. For those, Nitro falls back to copying them — along with their full dependency tree — into <em>.output/server/node_modules/</em>.</p><p>So, we have to leave <em>.output/server/node_modules</em> intact, except for <em>better-sqlite3</em>, which we delete and replace with a freshly compiled binary (previously generated with _npm rebuild better-sqlite3_).</p><p>We install only <em>prisma</em> and <em>dotenv</em> into the root /app/node_modules; the bare minimum needed to run <em>prisma migrate deploy</em> in the entrypoint. The rest of the app’s dependencies are already bundled inside <em>.output/server</em> folder by Nitro.</p><blockquote><em>💡 We explicitly mark </em>better-sqlite3<em>, among other dependencies, as </em><strong><em>external</em></strong><em> in the </em>nuxt.config.ts<em> file, which tells Nitro to skip bundling them entirely and copy them as-is into </em>.output/server/node_modules<em> directly:</em></blockquote><pre>// nuxt.config.ts<br>export default defineNuxtConfig({<br>  nitro: {<br>    esbuild: {<br>      options: { target: &#39;es2020&#39; }<br>    },<br>    externals: {<br>      external: [&#39;better-sqlite3&#39;, ...],<br>    },<br>  },<br>})</pre><h3>Conclusion</h3><p>Dockerizing a full-stack Nuxt application isn’t trivial when you have native modules or you want to reduce significantly the final image size, but with a solid <strong>multi-stage build</strong> it’s completely viable.</p><p>Key takeaways:</p><ul><li><strong>Multi-stage build</strong> is not optional — it’s the difference between 637MB and 4.05 GB. A <strong>84% image size reduction</strong>.</li><li>The numbers speak: <strong>~4 minutes for a complete AMD64 build</strong>, lightweight final image ready for production.</li><li><strong>Don’t delete</strong> <em>.output/server/node_modules</em> — Nitro copies the externalized packages there and needs them at runtime. Only replace the ones with native binaries (like <em>better-sqlite3</em>) that need to be recompiled for Linux.</li></ul><p>If you’re evaluating Nuxt for your next full-stack project, give it a shot. The Vue ecosystem has a first-class full stack framework, and with Docker, deploying it is just matter of minutes!</p><p>This post is based on our real experience deploying Nuxt applications in production at <a href="https://resiz.es/">Resizes</a>. All timings and data are from our GitHub Actions pipeline.</p><p>Thanks for reading The Product Pipeline! Subscribe for free to receive new posts and support my work.</p><p>Feel free to share this post among your community!</p><p>See you! 👋🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea43ffc5ae6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>