<?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 Fazalul Haque on Medium]]></title>
        <description><![CDATA[Stories by Fazalul Haque on Medium]]></description>
        <link>https://medium.com/@vfazal?source=rss-b7636548300f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FC4BNgFss99Q2kxdAsvUBw.jpeg</url>
            <title>Stories by Fazalul Haque on Medium</title>
            <link>https://medium.com/@vfazal?source=rss-b7636548300f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:21:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vfazal/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[Why Senior Data Engineers Write SQL Differently]]></title>
            <link>https://medium.com/towards-data-engineering/why-senior-data-engineers-write-sql-differently-9547a76ac3bf?source=rss-b7636548300f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9547a76ac3bf</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[maintainable-sql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[cte]]></category>
            <dc:creator><![CDATA[Fazalul Haque]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 01:31:45 GMT</pubDate>
            <atom:updated>2026-07-23T01:31:45.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Good SQL isn’t About Results. It’s About the Next Change" src="https://cdn-images-1.medium.com/max/1024/1*_1GaUZ8vfQbAtp0EM2VHAA.png" /></figure><p>Every experienced data engineer has opened a SQL file, stared at a wall of nested subqueries, and wondered, “Who wrote this?”</p><p>Then they check the Git history.</p><p>It was them. Six months ago.</p><p>Two engineers are asked to pull a list of high-value repeat customers for the marketing team. Both write a query. Both get the right answer. One query gets merged in a single review pass. The other comes back with three comments, two of which are just “what does this do?”</p><p>Same result set. Same database. Completely different outcomes. The difference has nothing to do with whether the SQL is correct, because it is, in both cases. It has to do with whether the query is easy for someone else to read, understand, and change when business requirements inevitably evolve, or whether even the original author can make sense of it six months later.</p><p>That is the gap this article is about.</p><p>We will use one running example throughout: a PostgreSQL e-commerce schema with customers, orders, order_items, and products tables, and a single business question: find repeat customers who have spent over $500 in the last 90 days, excluding refunded orders. We&#39;ll start with a query that works, then refactor it into one that&#39;s easier to understand, review, debug, and maintain.</p><h3>Working SQL vs. Maintainable SQL</h3><p>Here is a version that works.</p><pre>SELECT *<br>FROM customers c<br>WHERE c.customer_id IN (<br>  SELECT o.customer_id<br>  FROM orders o<br>  WHERE o.order_date &gt;= CURRENT_DATE - INTERVAL &#39;90 days&#39;<br>    AND o.status != &#39;refunded&#39;<br>  GROUP BY o.customer_id<br>  HAVING COUNT(*) &gt; 1<br>     AND SUM(<br>       (SELECT SUM(oi.quantity * oi.unit_price)<br>        FROM order_items oi<br>        WHERE oi.order_id = o.order_id)<br>     ) &gt; 500<br>);</pre><p>Run it, and it returns the correct customers. Put it into production, and three things will eventually go wrong. Someone adds a column to customers and the SELECT * silently pulls in data nobody asked for. Someone needs to know why the threshold is 90 days and $500, and there is no comment to tell them. Someone needs to debug why a known repeat customer is missing from the results, and the only way to check is to mentally execute a query with a subquery nested inside a HAVING clause nested inside an IN clause.</p><p>This query works today. It may even work tomorrow. What it doesn’t do is make tomorrow’s change easy.</p><p>Maintainable SQL is written with future readers in mind. It assumes schemas evolve, business rules change, teammates rotate, and production issues eventually happen. Senior engineers optimize for that reality. Their goal isn’t simply to write SQL that returns the right rows. They write SQL that someone else can confidently modify without introducing new bugs.</p><blockquote><strong><em>Good SQL doesn’t minimize the number of lines. It minimizes the amount of information the reader has to keep in their head.</em></strong></blockquote><h3>Structure SQL as a Sequence of Transformations</h3><p>The query optimizer cares about execution plans; your teammates care about readability. Modern database query optimizers can often transform different SQL formulations into similar execution plans by flattening subqueries, reordering joins, and applying other optimizations. When performance is comparable, the version that’s easier for humans to understand is usually the better engineering choice.</p><p>Here is the same logic, restructured.</p><pre>-- Repeat customer definition: more than one qualifying order<br>-- in the trailing 90 days, excluding refunds.<br>WITH recent_orders AS (<br>    SELECT order_id, customer_id, order_date<br>    FROM orders<br>    WHERE order_date &gt;= CURRENT_DATE - INTERVAL &#39;90 days&#39;<br>      AND status != &#39;refunded&#39;<br>),<br>order_totals AS (<br>    SELECT<br>        ro.order_id,<br>        ro.customer_id,<br>        SUM(oi.quantity * oi.unit_price) AS order_total<br>    FROM recent_orders ro<br>    JOIN order_items oi ON oi.order_id = ro.order_id<br>    GROUP BY ro.order_id, ro.customer_id<br>),<br>customer_summary AS (<br>    SELECT<br>        customer_id,<br>        COUNT(*) AS order_count,<br>        SUM(order_total) AS total_spend<br>    FROM order_totals<br>    GROUP BY customer_id<br>),<br>high_value_repeat_customers AS (<br>    SELECT customer_id, order_count, total_spend<br>    FROM customer_summary<br>    WHERE order_count &gt; 1<br>      AND total_spend &gt; 500<br>)<br>SELECT<br>    c.email,<br>    hvrc.order_count,<br>    hvrc.total_spend<br>FROM high_value_repeat_customers hvrc<br>JOIN customers c ON c.customer_id = hvrc.customer_id<br>ORDER BY hvrc.total_spend DESC;</pre><p>Nothing about the output changed. Everything about the experience of reading it did. A few things are doing the work here, and they generalize well beyond this one query.</p><p>The nested subquery is gone. The original query asked the reader to hold three levels of logic in their head at once: which orders qualify, what each order is worth, and which customers clear the bar. Splitting that into sequential CTEs means each block answers exactly one question, and the next block builds on a clean answer instead of a buried calculation.</p><p>Each CTE has a name that describes what it produces, not what it technically is. recent_orders, order_totals, customer_summary, and high_value_repeat_customers tell you the shape of the data at each stage without opening the block. Compare that to cte1, t, or temp_data, which tell you nothing and force a re-read every time they appear later in the query.</p><p>The transformation is broken into logical stages that mirror how a person would actually reason through the problem by hand: filter the orders, total the orders, summarize by customer, then apply the business threshold. That sequence is also the order someone would naturally debug in.</p><p>Which leads to the real payoff: easier debugging. If a customer who should qualify is missing, you do not have to mentally execute the whole query. You run SELECT * FROM recent_orders WHERE customer_id = 1042 and check whether their orders show up. Then order_totals. Then customer_summary. Each CTE is a checkpoint you can inspect in isolation, which is exactly why this structure is easier to maintain than a single dense expression.</p><h3>Select Only the Columns You Need</h3><p>I once reviewed a query that produced the correct report for over a year. Then a new column was added to the source table. Because the query used SELECT *, a downstream export silently changed shape and broke another team’s pipeline. Nothing was “wrong” with the SQL. It simply wasn’t written with future changes in mind. Nobody intentionally changed the business logic, yet downstream systems still break because the query’s contract was never explicit.</p><p>The same is happening here. Look back at the original query and notice what SELECT * FROM customers actually returns. Every column on that table, including ones that have nothing to do with the question being asked, and ones that might not exist yet.</p><pre>-- Before: pulls every column on customers, including ones<br>-- nobody asked for and some that may not even be safe to expose.<br>SELECT *<br>FROM customers c<br>WHERE c.customer_id IN (...)</pre><pre>-- After: explicit about exactly what&#39;s needed downstream.<br>SELECT<br>    c.customer_id,<br>    c.email,<br>    c.signup_date<br>FROM customers c<br>WHERE c.customer_id IN (...)</pre><p>The explicit version costs three extra lines and buys real protection. If someone adds an marketing_preferences or gdpr_deletion_requested column to customers next quarter, the SELECT * version starts leaking it into every downstream dashboard and export that consumes this query, without anyone deciding that should happen. The explicit version is unaffected, because it only ever returns what it was written to return.</p><p>There is also a performance and cost angle. Most modern cloud data warehouses, such as Snowflake, BigQuery, Redshift, and Databricks, store data in a columnar format, allowing the query engine to read only the columns required by a query. When you use SELECT *, the execution engine has to read every selected column, including ones you don’t actually need. On wide tables, that can mean scanning large JSON documents, audit fields, or other bulky columns that downstream consumers never use. Selecting only the columns you need not only makes the intent of the query clearer, but can also reduce I/O, lower query costs, and improve performance in column-oriented systems.</p><p>There is a reviewability cost too. A reviewer looking at SELECT * has to go check the table definition to know what they are actually approving. A reviewer looking at an explicit column list can see the entire contract of the query in the query itself.</p><h3>Validate Results Before Shipping</h3><p>A query that runs without an error is not the same thing as a query that is correct, and senior engineers tend to have been burned by that distinction at least once. Before this query is delivered to the marketing team, it is worth a few minutes of sanity checking.</p><p>Check that the row count is plausible.</p><pre>SELECT COUNT(*) FROM high_value_repeat_customers;</pre><p>If the customer base is 40,000 people and this query returns 38,000 of them as “high-value repeat customers,” the threshold logic is almost certainly wrong somewhere, even though the query executed cleanly.</p><p>Check for nulls in fields the downstream team will rely on, like email. A join that silently drops or nulls out a field is invisible until someone tries to use the data.</p><p>Check the aggregate against something independently known. If finance reports total revenue for the last 90 days as roughly $1.2M, and summing total_spend across all customers in this result set comes out to $4M, something is double-counting, most likely a join fanning out rows somewhere upstream of order_totals.</p><p>Here is a quick checklist to mentally walk through before sharing a query:</p><ul><li>Does the row count look reasonable?</li><li>Did any joins accidentally multiply rows?</li><li>Are unexpected NULL values appearing?</li><li>Do aggregates roughly match a trusted source?</li><li>Have obvious edge cases been tested?</li></ul><p>These checks may not guarantee correctness, but they dramatically reduce the chance of discovering problems after someone has already acted on the results.</p><h3>Make Intent Obvious</h3><p>A query that only the author can parse is not really finished, because someone else is going to have to read it during code review, during an incident, or during onboarding. Formatting consistency does a lot of the work here: consistent capitalization for keywords, consistent indentation for joins and conditions, and CTEs that are visually separated so the eye can find the boundaries between stages at a glance. None of these changes what the query does. It changes how quickly a reviewer can understand the query. That is the real cost being paid every time SQL is reviewed.</p><p>Instead of compressing multiple joins, filters, and conditions into dense blocks of SQL, keep related logic together, align joins consistently, and format predicates predictably. Reviewers should be able to scan the query and immediately identify filtering, aggregation, and business rules without mentally reformatting the code first.</p><p><strong>Good formatting doesn’t make SQL execute faster. It makes people understand it faster.</strong></p><p>Comments matter, but only in the right place. A comment explaining what a GROUP BY does is noise, because the SQL already says that. A comment explaining why orders are filtered to the last 90 days, or why refunded orders are excluded, is signal, because that logic comes from a business decision the code itself cannot express. The CTE names in the example above already do a lot of that explanatory work for free. Comments should fill in what names cannot carry.</p><h3>Make Assumptions Explicit</h3><p>Every business query is full of decisions that are invisible in the result set. Why 90 days and not 60. Why a refunded order does not count toward spend even though it briefly existed as a completed order. Why “repeat” means more than one order rather than two or more, which is the same threshold expressed differently but easy to get wrong if someone has to guess at it later.</p><p>Senior engineers do not just write queries, they encode these assumptions so the next reader does not have to reverse-engineer them from the logic. That can be a comment block at the top of the query, like the one above the recent_orders CTE. It can be a CTE name that states the assumption directly, the way high_value_repeat_customers tells you the threshold logic lives in that block before you even read it. What it cannot be is silence, because silence forces the next person to either guess or go find the original author and ask.</p><p>This matters more as a query gets reused. The first time someone copies this logic into a new dashboard, they will copy the assumptions along with it, whether those assumptions are documented or not. Making them explicit is the only way to make sure they get copied correctly.</p><h3>Write SQL for the Next Engineer</h3><p>None of the techniques in this article are particularly advanced. Naming CTEs well, avoiding SELECT *, validating results, or breaking complex logic into smaller steps won&#39;t make you the smartest SQL developer in the room.</p><p>What they do is make your SQL easier for the next engineer to understand, review, debug, and safely change.</p><p><strong>Junior engineers often optimize for making the query run. Senior engineers optimize for making the next change easy.</strong> They write SQL that explains itself, surfaces assumptions, and reduces the amount of information another engineer has to keep in their head.</p><p>SQL is read far more often than it is written. Optimize for the reader first, and maintainability naturally follows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9547a76ac3bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/why-senior-data-engineers-write-sql-differently-9547a76ac3bf">Why Senior Data Engineers Write SQL Differently</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying AI Agents to Production: Cloud, Self-Hosted, or Hybrid?]]></title>
            <link>https://pub.towardsai.net/deploying-ai-agents-to-production-cloud-self-hosted-or-hybrid-6ce8e2905ee2?source=rss-b7636548300f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ce8e2905ee2</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-deployment]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Fazalul Haque]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 11:31:00 GMT</pubDate>
            <atom:updated>2026-06-30T11:31:00.723Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The infrastructure decision behind your AI agent strategy carries more weight than most teams realize, and it compounds over time.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0atPbI3B0a-MCzYdgGQnoA.png" /></figure><h3>The Problem Nobody Talks About Before the Demo</h3><p>There’s a familiar pattern in AI projects. Someone builds an agent that works brilliantly in a notebook or local development environment. It answers questions, calls tools, handles edge cases, and impresses everyone in the demo. Then someone asks the inevitable question:</p><p>“Great. When can we put this into production?”</p><p>That’s where the easy part ends.</p><p>Deploying an AI agent to production isn’t like deploying a REST API or a microservice. Agents maintain state, execute multi-step workflows, invoke external tools, and often process sensitive data. The infrastructure decisions you make at this stage shape everything that follows — cost, latency, security, compliance, and how easily the system scales months or years later.</p><p>In practice, most production deployments fall into one of three architectures: cloud, self-hosted (local), or hybrid. None is universally better for every workload. Each optimizes for a different set of constraints. This article will help you understand those trade-offs so you can choose the architecture that best fits your workload.</p><h3>Why Agent Deployment Is Different</h3><p>A traditional model deployment is stateless: you send a prompt in, you get a response out. An agent is different. It’s a system that runs a loop — perceiving context, reasoning, calling tools, observing results, and repeating — potentially five to twenty times per user interaction.</p><p>What this means practically is that when you deploy an agent, you’re not just deploying a model. You’re deploying an orchestration layer that drives that loop, the model backend it calls, the tools and external systems it can invoke, the memory and state it uses to retain context across steps, and the observability instrumentation needed to understand what happened when something goes wrong.</p><p>Every one of those components has a deployment home. Where you put them — and how they connect — is the core of the decision this article addresses.</p><h3>Option 1: Cloud Deployment</h3><p>In a cloud deployment, everything runs on managed infrastructure provided by a cloud vendor. Your agent’s orchestration logic runs on the cloud provider’s platform, the model lives on a hosted API, tools call cloud-connected services, and memory is handled by a managed vector store — all from the same provider or ecosystem.</p><figure><img alt="Cloud Deployment Architecture" src="https://cdn-images-1.medium.com/max/761/1*ctfl841OAdhgwE8hCe9OgQ.png" /><figcaption>Cloud Deployment Architecture</figcaption></figure><p>Managed agent platforms from AWS, Azure, and Google abstract most of this complexity. You configure prompts and tools; the platform handles orchestration, scaling, and uptime. If your organization is already deep in one cloud ecosystem, cloud agent deployment integrates naturally with the services already there.</p><h3>Why teams choose this</h3><p>The single biggest advantage is speed. You can move from a working prototype to a production deployment in days rather than weeks, without provisioning hardware or configuring inference servers. There’s no GPU to manage, no scaling infrastructure to build. When traffic spikes, the platform handles it.</p><p>For teams without dedicated ML infrastructure experience, this matters enormously. The expertise required to run a production inference stack is real and expensive to build. Cloud deployment sidesteps that requirement entirely.</p><p>There’s also an ecosystem argument. Managed vector stores, queueing, secret management, monitoring — the tooling is already built and integrated.</p><h3>What you’re trading away</h3><p>Data exposure is the most significant concern, and it’s not just a compliance checkbox. Every prompt your agent sends, every tool call input and response, every piece of retrieved memory travels through the cloud provider’s infrastructure. For workloads that touch customer financial records, healthcare data, or confidential business information, that’s a fundamental design concern — not a footnote.</p><p>The cost picture is more complicated than it appears at first. Agents are talkative: a single user session that involves multi-step reasoning and tool calls can result in fifteen or twenty model invocations. Per-token costs that feel manageable in development multiply fast at production volume. Teams routinely discover their monthly bills are 3–5× what early testing suggested.</p><p>Vendor lock-in is real. The more your agent depends on a managed platform’s orchestration layer, tool integrations, identity model, and deployment abstractions, the more expensive migration becomes. Switching providers may require redesigning significant parts of your orchestration layer — not just changing the model endpoint. When your provider has an outage, your agents go down with them. When they deprecate a model or change pricing, you’re downstream of those decisions.</p><p>There’s also a latency consideration that only surfaces under real load. When an agent makes eight chained model calls, each with a network round trip, the time adds up quickly. For applications with strict response-time requirements, that stacking is hard to engineer around without fundamental architectural changes.</p><h3>Best suited for</h3><p>Cloud is the right default for teams that haven’t built ML infrastructure and aren’t planning to — where the priority is getting something into production quickly, the data involved isn’t regulated or confidential, and traffic is unpredictable enough that elastic scaling is a genuine advantage rather than a marketing feature. If none of your constraints push you toward local, start here.</p><h3>Option 2: Self-Hosted (Local) Deployment</h3><p>Self-Hosted (Local) deployment means everything runs on infrastructure you own and operate. The model weights live on your machines, the agent runtime runs on your servers, and nothing leaves your network unless you decide it should.</p><figure><img alt="Self-Hosted Deployment Architecture" src="https://cdn-images-1.medium.com/max/761/1*vg7CQuh4cdPS2OybvjWFcg.png" /><figcaption>Self-Hosted Deployment Architecture</figcaption></figure><p>This is the approach taken by most regulated industries — finance, healthcare, legal, defense — where the question isn’t “do we prefer full control?” but often “do we have a choice?”</p><h3>The genuine advantages</h3><p>Data sovereignty is the headline. Prompts, tool responses, and retrieved memory stay entirely within your perimeter. Compliance with GDPR, HIPAA, and sector-specific regulations can be structurally enforced rather than contractually promised. Audit logs are yours. Access controls are yours.</p><p>The economics improve significantly at scale. Once the hardware investment is amortized, the marginal cost per inference drops from a per-token API charge to a predictable infrastructure cost — you’re not watching a billing meter tick while the agent reasons. For organizations with high, consistent volume, this shift can be substantial.</p><p>You also own the model version. There’s no provider deprecating your model on a schedule that doesn’t match your release cycle. And when your data center is up, your agents are up — no dependency on a third party’s reliability.</p><h3>Where it gets difficult</h3><p>The upfront capital cost is real. A server configuration capable of running a meaningful open-weight model at acceptable throughput requires significant hardware investment before you’ve written a line of agent code. Smaller models cost less but come with capability trade-offs.</p><p>The most capable frontier models are simply not available for local deployment. Open-weight models are improving rapidly and closing the gap with every new release, but for tasks requiring the strongest multi-step reasoning — complex synthesis, handling genuinely ambiguous instructions — there is still a gap.</p><p>The operational burden is easy to underestimate. Running models in production requires expertise in inference optimization, memory management, and hardware maintenance. You need to handle security patching, hardware failures, power redundancy, and cooling. That’s a meaningful set of skills to either hire for or develop.</p><p>Scaling up quickly is hard. If your volume doubles next month, you can’t just click a button. You’re waiting on hardware procurement, racking, and configuration. Self-hosted infrastructure scales in steps, not continuously.</p><h3>Best suited for</h3><p>Self-hosted deployment earns its operational burden in two scenarios: when compliance makes it non-negotiable, and when volume makes cloud inference economics unsustainable. Often these arrive together — regulated industries with high-frequency workloads, where keeping data on-premises and controlling inference cost are both requirements rather than preferences. The team capability to run this stack isn’t optional; it’s a prerequisite for the choice to hold.</p><h3>Option 3: Hybrid Deployment</h3><p>Hybrid deployment splits your agent’s workload deliberately across cloud and local infrastructure, based on the nature of each task and the data involved. A self-hosted orchestration and routing layer sits in the middle, deciding where each request goes.</p><figure><img alt="Hybrid Deployment Architecture" src="https://cdn-images-1.medium.com/max/797/1*ykRruYS8EbIkmxodLu0UDg.png" /><figcaption>Hybrid Deployment Architecture</figcaption></figure><p>Hybrid is the most complex option. It’s also the most powerful when implemented well, and the most likely to accumulate technical debt when implemented hastily.</p><h3>How routing actually works</h3><p>The practical value of hybrid comes from intelligent, task-aware routing. Not all agent tasks are equal.</p><p>Simple, high-frequency tasks (classification, structured extraction, metadata tagging, short summarization) route to the local model. The quality difference between a locally-running model and a frontier cloud model is minimal for these tasks, and the cost difference is significant. This is where hybrid earns its complexity premium.</p><p>Tasks that genuinely require frontier capability ( multi-hop reasoning, synthesis across large contexts, handling genuinely ambiguous instructions) route to a cloud API. You pay the higher per-call cost, but only when the task actually justifies it.</p><p>Tasks involving sensitive data — regardless of their complexity — stay local. PII should be identified and removed or masked before anything reaches a cloud endpoint.</p><p>Production systems also route based on latency requirements, cost budgets, customer tier (for example, free versus paid users), and model availability, allowing them to balance user experience, cost, and resilience dynamically.</p><p>The key insight is that a “hybrid deployment” isn’t a compromise between cloud and local. It’s an optimization strategy that assigns each task to the environment best suited to handle it.</p><h3>What makes it worth it — and what doesn’t</h3><p>When the routing logic is well-designed and well-maintained, hybrid deployments can deliver cloud-level capability for complex tasks, local-level data protection for sensitive tasks, and meaningfully lower cost overall. For organizations with genuinely heterogeneous workloads — some routine, some complex, some regulated — it’s often the right architecture.</p><p>But the routing layer becomes its own engineering challenge. It needs to correctly classify every task, enforce data governance rules, handle failures on both sides independently, and produce consistent behavior even when one backend is slower or less capable than the other. Different models behave differently; output quality from a local model on a complex task and a cloud model on the same task won’t be identical, and your agent needs to handle both gracefully.</p><p>Debugging hybrid deployments spans multiple systems with different log formats, different failure modes, and different performance characteristics. This is not a simple system to operate.</p><p>The most common mistake is going hybrid too early — reaching for the complexity of a hybrid architecture before a single-environment deployment has been successfully stabilized. Teams that struggle with hybrid have usually inherited the routing layer’s problems before they’ve finished solving the basic deployment problems.</p><h3>Best suited for</h3><p>Hybrid makes sense when your workload is genuinely split — some tasks routine, some complex, some regulated, some not — and a single environment can’t serve all of it well. It’s also the right answer when you need frontier-model capability for certain tasks but can’t send the underlying data to a cloud endpoint. What it requires, more than anything else, is operational maturity. Teams that haven’t stabilized a single-environment deployment yet should treat hybrid as a destination, not a starting point.</p><h3>Risk Comparison</h3><p>Each deployment model carries a distinct risk profile. Understanding which risks matter most in your context is essential to making the right choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*k3VGEecTqLghmbsEw03IJg.png" /></figure><p>A note on a risk that often goes overlooked: PII leaking through tool call <em>responses</em>. The original user query might be innocuous, but a tool call that retrieves data from a CRM, a support ticket system, or an internal database can return sensitive information that then flows into the model’s context. This is true regardless of deployment model — every tool integration needs to be evaluated not just for what it intentionally exposes, but for what it might return.</p><h3>Cost Dynamics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*X3mHaHDqXyXDQvcQSIyEvg.png" /></figure><p>Cloud looks cheapest to start. Self-hosted wins at sustained high volume once infrastructure is amortized. The break-even point depends heavily on your specific volume and model choices, but it arrives sooner than most teams expect. Hybrid is a cost optimization play that requires upfront engineering investment to yield savings. It doesn’t reduce costs unless the routing logic is well-maintained and the task distribution genuinely justifies the added complexity.</p><h3>Observability: What Every Option Needs</h3><p>This is an area where deployment option matters less than teams expect. The requirements are broadly similar across all three deployment options, but the implementation effort differs significantly.</p><p>You need to be able to trace every step of every agent run: the input, the model’s reasoning and tool selection, what each tool call sent and received, and the final output. Without this, debugging production failures is guesswork.</p><p>You need cost attribution at the run level, not the aggregate level. Cost anomalies are invisible until the bill arrives if you’re not tracking usage per agent, per task type, per workflow.</p><p>You need tool health monitoring. Tools are the most common failure surface in production agents: they call external systems, hit rate limits, and return data in unexpected formats. Treating tool reliability as a first-class signal separates teams that catch problems before users do from teams that find out from support tickets.</p><p>Cloud deployments often include managed observability tooling. Local and hybrid deployments need explicit instrumentation because it doesn’t come built in. Without end-to-end traces, reproducing failures in multi-step agent workflows becomes nearly impossible.</p><h3>Mistakes Teams Make When Choosing</h3><p>Defaulting to cloud because it was fastest for the demo. What works for a prototype doesn’t define what’s right for production. The data sensitivity, compliance requirements, and volume profile of a production system are different problems than getting something working in a notebook.</p><p>Choosing local because it “sounded more rigorous.” Local deployment is the right choice for specific reasons — data sovereignty, sustained high volume, regulatory mandate. It’s not inherently more serious or professional than cloud. The operational burden is real, and choosing it without the infrastructure capability to match is a reliable way to generate production incidents.</p><p>Going hybrid before stabilizing a single environment. Hybrid rewards operational maturity. If you haven’t figured out how to run one deployment cleanly, adding a second and a routing layer between them makes things harder before they get better.</p><p>Underestimating inference volume in production. Agents in production make far more model calls than agents in development. Error handling, retry logic, chain-of-thought reasoning, tool call loops — all of these add invocations that don’t show up in testing. Budget and architect based on expected production call patterns.</p><p>Treating the deployment decision as reversible. Managed runtimes, proprietary tool integrations, and cloud-specific tool integrations all create migration friction. It’s worth making the right choice early, because changing it later is non-trivial work.</p><h3>Decision Framework</h3><p>Rather than a scoring formula, here are the four questions that actually determine which option is right.</p><p>What are your data sensitivity requirements? If the data your agent handles is regulated or confidential ( medical records, financial data, legal documents, internal strategy), that constrains the decision toward local or hybrid before anything else is considered.</p><p>What’s your volume profile? Low volume and variable traffic favor cloud. High, sustained, predictable volume shifts the economic case toward local. Mixed or spiky volume may favor hybrid or cloud with burst handling.</p><p>What’s your team’s operational capability? Do you have the infrastructure expertise to run a production inference stack? If not, cloud removes that dependency. If yes, local or hybrid becomes viable.</p><p>What model capability do you need? If your use case requires frontier-model reasoning for the most complex multi-step tasks, cloud or hybrid is necessary. If open-weight models meet your requirements today, local becomes fully viable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*vjwVVZLc8BlHDJRHsH64IQ.png" /></figure><h3>How Deployment Strategies Are Evolving</h3><p>The deployment decisions discussed in this article aren’t static. As models, tooling, and infrastructure continue to mature, the trade-offs between cloud, local, and hybrid deployment strategies continue to shift.</p><p>One notable change is the rapid improvement in open-weight models. Tasks that previously required a frontier cloud model, such as classification, extraction, summarization, and many retrieval-augmented workflows, can increasingly be handled by locally deployed models. That doesn’t eliminate the need for frontier cloud models, but it does move the break-even point for hybrid and self-hosted deployments.</p><p>Regulatory pressure on data residency and AI governance is increasing, not decreasing. Organizations in regulated industries should assume that current compliance requirements are a floor, not a ceiling.</p><p>At the same time, organizations are becoming more deliberate about avoiding provider lock-in. Rather than embedding orchestration logic directly into a cloud platform, many teams are keeping the agent runtime portable while treating model providers as interchangeable inference backends. Emerging standards such as the Model Context Protocol (MCP) are designed to make tool integrations more portable across models and platforms, and early adoption suggests this could meaningfully reduce integration lock-in as the ecosystem matures.</p><p>Another emerging trend is purpose-built AI infrastructure: platforms that combine cloud-like operational simplicity with stronger control over where models run and where data resides. As this ecosystem matures, organizations may no longer have to choose between operational convenience and data sovereignty as strictly as they do today.</p><p>The result is that deployment architecture is becoming less about committing to a single platform and more about preserving flexibility. Teams that keep their agent runtimes portable today will have far more options as the ecosystem continues to evolve.</p><h3>The Bottom Line</h3><p>There is no universally right answer. Cloud deployment is the right default for most early-stage or low-volume deployments — it gets you to production fastest without capital risk. Local deployment earns its cost for organizations with strict data requirements or genuinely high, stable volume. Hybrid is the right answer when your workload genuinely has heterogeneous requirements, not as a way to avoid making a decision.</p><p>The decisions that age poorly are the ones made by default: choosing cloud because it was easiest to demo, or local because it sounded serious, without mapping the choice to actual compliance posture, scale expectations, and team capability.</p><p>Start with those constraints, and the right option becomes considerably clearer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ce8e2905ee2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/deploying-ai-agents-to-production-cloud-self-hosted-or-hybrid-6ce8e2905ee2">Deploying AI Agents to Production: Cloud, Self-Hosted, or Hybrid?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow 3.x Architecture Explained: A Practical Guide for Data Engineers]]></title>
            <link>https://medium.com/towards-data-engineering/airflow-3-x-architecture-explained-a-practical-guide-for-beginners-27fd0be8df19?source=rss-b7636548300f------2</link>
            <guid isPermaLink="false">https://medium.com/p/27fd0be8df19</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[gda]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Fazalul Haque]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 04:10:11 GMT</pubDate>
            <atom:updated>2026-06-13T14:45:10.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>What Actually Happens When a DAG Runs</h4><h3>What Is Airflow?</h3><p>Let me be honest about how I first encountered Airflow. My team had a bunch of Python and SQL scripts running on cron jobs. One script would download data, another would load it into a staging database, a third one would transform it, and a fourth one would ingest it into our data warehouse. The scripts were chained together with some fragile shell glue. When things worked, nobody noticed. When things broke — and they broke often — figuring out <em>where</em> it broke and <em>why</em> was a nightmare.</p><p>Someone on the team said “we should use Airflow.” I nodded like I understood, then spent the next three evenings reading documentation.</p><p>Here’s what I wish someone had told me then: <strong>Airflow is a platform for authoring, scheduling, and monitoring workflows — workflows that you define as Python code</strong>. That’s it. No magic. You write a Python file describing what tasks to run and in what order, and Airflow takes care of the scheduling, retries, logging, and visibility.</p><p>The thing that took me a while to internalize is that Airflow is not a data processing engine. It doesn’t move your data around. It <em>orchestrates</em> the things that do. It’s the conductor, not the orchestra.</p><h3>The DAG — Everything Starts Here</h3><p>Before diving into the architecture, you need to understand what a DAG is, because the whole system revolves around it.</p><p>DAG stands for <strong>Directed Acyclic Graph</strong>. Sounds fancy. In practice it just means: a set of tasks with dependencies between them, where you can’t have circular dependencies (task A depends on task B depends on task A — that would be a cycle, and Airflow won’t allow it).</p><p>A simple DAG might look like this:</p><pre>extract_data → transform_data → load_to_warehouse</pre><p>You define this in a Python file. Each step is a <strong>Task</strong> — a single unit of work, like running a Python function, executing a SQL query, or calling an external API. The arrows between them are <strong>dependencies</strong>. Airflow reads your Python file, figures out the task ordering, and then knows how and when to execute things.</p><p>In Airflow 3.x, DAG files still live in a dags/ folder, but there have been some meaningful changes to how they&#39;re parsed and distributed — we&#39;ll get to that when we talk about the DAG Processor.</p><h3>The Architecture: A Bird’s Eye View</h3><p>Before we look at each component individually, here’s a high-level view of how they fit together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gHeelnQNgvFf83yRpqTag.png" /></figure><p>Every component reads from or writes to the <strong>Metadata Database</strong> in some way. That database is the single source of truth for the entire system. Let’s now go through each piece.</p><h3>Why Understanding the Architecture Matters</h3><p>If you’re running Airflow locally, many of these components may live on the same machine and feel invisible.</p><p>So why spend time learning the architecture?</p><p>Because most real-world Airflow problems come down to understanding which component is responsible for what.</p><p>For example:</p><ul><li>DAG not showing up in the UI? Look at DAG parsing.</li><li>Tasks stuck in queued state? Check the executor and workers.</li><li>No new tasks are starting? Investigate the scheduler.</li><li>UI errors or failed API requests? Check the API Server.</li><li>Everything seems broken? The metadata database is often the first place to look.</li></ul><p>You don’t need to memorize every component. But having a mental model of how they fit together makes troubleshooting much easier as you move beyond simple local deployments.</p><h3>The Metadata Database</h3><p>I’m starting here because once you understand this, everything else makes sense.</p><p>The metadata database is a relational database — Postgres in production (please use Postgres, not SQLite outside of local dev). It stores:</p><ul><li>All your DAG definitions and their current state</li><li>Every DAG Run — every time a DAG has executed or is scheduled to execute</li><li>Every Task Instance — every individual task run, its state (queued, running, success, failed), pointers to logs, and timing</li><li>User information, connections, variables, and more</li></ul><p>Every other component in Airflow talks to this database. The Scheduler reads from it to decide what to run. Workers write to it when tasks finish. The API Server and UI read from it to show you that nice UI. The database is the glue that holds the distributed system together.</p><p>One practical implication: if your database is slow or down, your entire Airflow cluster is effectively crippled. Invest in your database setup.</p><h3>The Scheduler</h3><p>The Scheduler is the brain of the operation. It’s a long-running process that continuously checks the metadata database, figures out which tasks are ready to run, and sends them off to be executed.</p><p>Here’s a rough version of what it does in a loop:</p><ol><li>Check all DAG schedules — is there a DAG that’s supposed to have run in the last interval and hasn’t started yet?</li><li>Create <strong>DAG Runs</strong> and <strong>Task Instances</strong> in the metadata database for anything that needs to run</li><li>Look at all Task Instances that are in a “scheduled” state and evaluate their dependencies — are the upstream tasks done?</li><li>Move eligible tasks to “queued” state and submit them to the executor</li></ol><p>The Scheduler doesn’t run tasks itself. It <em>decides</em> that tasks should run and tells the executor to handle the actual execution. That’s an important distinction.</p><p>In Airflow 3.x, the Scheduler has become more reliable and scalable. You can run multiple schedulers (active-active setup) for high availability. If one scheduler process dies, another picks up the work.</p><p>One gotcha with the Scheduler: it needs up-to-date DAG metadata in order to schedule work. In Airflow 3.x, DAG parsing responsibilities can be delegated to a dedicated DAG Processor component. More on that below.</p><h3>The DAG Processor (New in Airflow 3.x)</h3><p>This is one of the more significant architectural changes in Airflow 3.x, and one that beginners often don’t realize exists.</p><p>In older versions of Airflow, the Scheduler also handled parsing your DAG files. This was problematic. If a DAG file had a slow import or a bug that caused it to hang, it could slow down the Scheduler itself. Not great.</p><p>In Airflow 3.x, DAG parsing has been extracted into its own <strong>DAG Processor</strong> component. It runs as a separate process, continuously scanning your dags/ directory, importing the Python files, and extracting DAG metadata (schedule, tasks, dependencies) into the metadata database.</p><p>The Scheduler then just reads from the database — it doesn’t need to parse Python files directly anymore. Cleaner separation of concerns.</p><p>To be precise, in a basic single‑machine setup the scheduler still spawns subprocesses to parse DAGs for you; the dedicated DAG Processor is mainly a production pattern. The important idea is that, in 3.x, you can keep user DAG code out of the core scheduler process and scale DAG parsing independently when you need to.</p><h3>The API Server</h3><p>Airflow 3.x introduced a proper standalone API Server. In earlier versions, the REST API was bundled into the Webserver.</p><p>The API Server exposes Airflow’s REST API — it’s what the UI uses to fetch DAG information, trigger runs, clear tasks, etc. It’s also what you’d use if you want to trigger DAG runs programmatically from another system. CI/CD pipelines kicking off DAGs, external services triggering workflows — all of that goes through the API Server.</p><p>What changed from 2.x is that the REST API is now a first-class interface rather than a secondary feature attached to the Webserver. This separation gives Airflow a cleaner architecture and makes it easier to evolve the UI and API independently over time.</p><h3>The Webserver (Airflow UI)</h3><p>In Airflow 3.x, the traditional standalone webserver role has largely been replaced by a UI that communicates with the API Server.</p><p>You use Airflow UI to:</p><ul><li>See all your DAGs and their last run status</li><li>View the graph of a DAG — which tasks ran, which failed, which are running right now</li><li>Look at logs for individual task runs</li><li>Manually trigger DAG runs or clear failed tasks to retry them</li><li>Manage connections and variables</li></ul><p>In Airflow 3.x, the UI has been significantly revamped. It’s faster, cleaner, and the new <strong>Grid View </strong>is much more useful than the old tree view for understanding the history of a DAG across many runs.</p><p>The Airflow UI is stateless with respect to actual scheduling. It doesn’t schedule anything. It’s purely a read/write interface to the metadata database (via the API Server). If the API Server or the UI crashes, your DAGs keep running. Your visibility goes away, but the work continues.</p><h3>The Executor</h3><p>The Executor is one of the most misunderstood Airflow concepts.</p><p>The Executor is not a separate process you run — it’s a component <em>within</em> the Scheduler that determines how tasks actually get executed. Think of it as the strategy the Scheduler uses for dispatching work, not something you run independently.</p><p>There are a few executor types:</p><p><strong>LocalExecutor</strong> — Tasks run as subprocesses on the same machine as the Scheduler. Simple, works well for small setups. Not suitable for real scale because everything shares one machine.</p><p><strong>CeleryExecutor</strong> — Tasks are sent to a Celery task queue (backed by Redis or RabbitMQ), and picked up by Worker processes that can run on different machines. This is the classic horizontally scalable setup.</p><p><strong>KubernetesExecutor</strong> — Each task spins up a new Kubernetes Pod to run in, and the pod is destroyed when the task finishes. Very clean isolation, great for containerized environments. More overhead per task but excellent for bursty workloads.</p><p>Some deployments use hybrid execution models that combine Celery workers with Kubernetes-based execution.</p><p>The choice of executor has massive implications for how you deploy and scale Airflow. Start with LocalExecutor if you’re just learning. Move to CeleryExecutor or KubernetesExecutor as you grow.</p><h3>The Workers</h3><p>Workers are the things that actually <em>execute</em> your task code. They’re separate processes (or pods, in the Kubernetes case) that pull tasks from the queue and run them. They only exist as separate processes if you’re using CeleryExecutor or KubernetesExecutor. With LocalExecutor, there isn’t a separate worker service: tasks run as subprocesses inside the scheduler machine.</p><p>When a task runs on a Worker:</p><ol><li>The Worker picks up the task from the queue</li><li>It executes your Python function (or Bash command, or Spark job, or whatever the operator does)</li><li>It writes the result back to the metadata database — success or failure</li><li>It ships logs to wherever logs are configured to go (local filesystem, S3, GCS, etc.)</li></ol><p>Workers don’t need to know about your full DAG structure. They just need to know “run this task.” All the DAG context they need is passed along with the task message.</p><p>One important thing: in a multi-worker setup, every worker machine needs access to the same DAG files. Otherwise, the worker won’t be able to find the code it’s supposed to run. This is commonly solved by mounting a shared filesystem or using Git Sync to pull DAGs onto every worker.</p><h3>The Triggerer</h3><p>One component I haven’t mentioned yet: the Triggerer. It’s an optional process that handles deferred tasks — tasks that are waiting on some external event (like a file landing in S3, or a sensor waiting for a condition) without occupying a worker slot while they wait. It runs deferred tasks in an asyncio event loop, which is far more efficient than a worker sitting idle. If you’re not using deferrable operators, you don’t strictly need it — but most production setups run it.</p><h3>Connections and Variables</h3><p>These aren’t really “architecture” in the strict sense, but they’re part of the runtime infrastructure and worth understanding early.</p><p><strong>Connections </strong>are how Airflow stores credentials and connection info for external systems — your database host/port/user/password, your AWS credentials, your Snowflake account info. When you use an operator (like PostgresOperator or S3Hook), it looks up a named connection from the metadata database rather than you hardcoding credentials in your DAG.</p><p><strong>Variables </strong>are just key-value pairs stored in the metadata database. Useful for config values you want to change without editing DAG code.</p><p>Both connections and variables can be managed through the UI, the API, or environment variables (the latter being preferred in production from a secrets management perspective).</p><h3>Putting It All Together</h3><p>Let’s see what actually happens when a scheduled DAG runs, so all these pieces connect:</p><ol><li>Your DAG file lives in the dags/ folder. The <strong>DAG Processor</strong> picks it up, parses it, and writes the DAG structure to the <strong>Metadata Database</strong>.</li><li>The <strong>Scheduler </strong>wakes up (it’s running in a loop, typically every few seconds). It checks the database and sees that your DAG is scheduled to run at 2:00 AM. It’s now 2:00 AM. The Scheduler creates a <strong>DAG Run</strong> record and individual <strong>Task Instance</strong> records in the database.</li><li>The Scheduler evaluates task dependencies. Task A has no upstream dependencies, so it becomes eligible. The Scheduler flips its state to “queued” and tells the <strong>Executor </strong>to execute it.</li><li>The Executor places Task A into the<strong> task queue</strong> (Redis/RabbitMQ when using CeleryExecutor).</li><li>An available <strong>Worker </strong>picks up Task A from the queue. It executes your Python function. If it succeeds, the Worker marks the Task Instance as “success” in the database.</li><li>Back to the Scheduler — on the next loop, it sees Task A is done. Task B was waiting on Task A. Now Task B’s dependencies are satisfied, so it becomes eligible. The cycle repeats.</li><li>Throughout all of this, the <strong>API Server</strong> is answering requests from your browser, showing you the DAG Run and its task states in real time.</li><li>Everything is written to the <strong>Metadata Database</strong> along the way.</li></ol><h4>What if one of the components is down?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*p_U6FmxpJMV-SKzCo2ifQw.png" /></figure><h3>A Note on Airflow 3.x Specifically</h3><p>Airflow 3.x brought a bunch of changes, and if you’re reading older tutorials, some things will look different. The key differences to be aware of:</p><p>The DAG authoring syntax got cleaner — the @dag and @task decorators (from the TaskFlow API) are now first-class citizens and the recommended way to write most DAGs. The old Operator-heavy style still works but new code should prefer TaskFlow.</p><p>The UI was rebuilt from scratch — it’s a modern React app now, not the old Flask/Jinja UI. Grid view is the default and it’s significantly better.</p><p>The Scheduler and DAG Processor are now clearly separated — as described above. Relevant if you’re configuring a production deployment.</p><p>The REST API is now the proper interface for programmatic access — no more hacking around with CLI commands for automation.</p><h3>Where to Go From Here</h3><p>If you’ve followed this far, you understand the fundamental architecture. The next things worth digging into:</p><ul><li>Write your first DAG using the TaskFlow API (@dag, @task decorators)</li><li>Understand what Operators are — they’re the building blocks of tasks (PythonOperator, BashOperator, and so on)</li><li>Set up a local Airflow environment with Docker Compose (the official docker-compose.yaml from the Airflow docs is a good start)</li><li>Learn about XComs — that’s how tasks pass data to each other</li><li>Understand task retries and the on_failure_callback — essential for production use</li></ul><p>The architecture seems complex at first, but once you’ve run Airflow a few times, you start to develop intuition for which component is causing problems when things go wrong. And things will go wrong. That’s part of the fun. Good luck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27fd0be8df19" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/airflow-3-x-architecture-explained-a-practical-guide-for-beginners-27fd0be8df19">Airflow 3.x Architecture Explained: A Practical Guide for Data Engineers</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a LangGraph Agent on AWS Bedrock AgentCore]]></title>
            <link>https://towardsaws.com/how-to-deploy-a-langgraph-agent-on-aws-bedrock-agentcore-75844cbeea58?source=rss-b7636548300f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75844cbeea58</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Fazalul Haque]]></dc:creator>
            <pubDate>Tue, 19 May 2026 11:23:08 GMT</pubDate>
            <atom:updated>2026-05-20T04:39:24.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3EZ2vnegReVuTBHeC0ijA.png" /></figure><p>You’ve built a LangGraph agent that works fine on your laptop. The next challenge is getting it running in a scalable, serverless production infrastructure without having to redesign the whole thing.</p><p>That’s where AWS Bedrock AgentCore comes in. In this guide, I’ll show you how to put a wrapper for your existing agent to make it run on AgentCore, set up an AgentCore project, test it locally, deploy it to AWS, and invoke it after deployment.</p><h3>What Is AWS Bedrock AgentCore?</h3><p>AgentCore is a serverless hosting platform designed by AWS to deploy, scale, and operate your AI agents securely without you managing the infrastructure. It works with any open-source framework like LangGraph, Strands, CrewAI, or LlamaIndex and supports Large Language Models like OpenAI’s GPT, Google’s Gemini, or Anthropic’s Claude. So you don’t have to rewrite the agent logic. It also provides session isolation, persistent memory, observability and identity management.</p><p>The deployment is managed through the AgentCore CLI, a Node.js tool that scaffolds projects, runs a local dev server, and deploys to AWS using CDK under the hood.</p><h3>Prerequisites</h3><p>Before you start, make sure you have the following in place:</p><ul><li>Python 3.12+</li><li>uv or pip for Python dependency management</li><li>Node.js 20+ — the AgentCore CLI is an npm package</li><li>AWS CDK installed globally (npm install -g aws-cdk)</li><li>An AWS account with credentials configured locally (aws configure)</li><li>Your existing LangGraph agent code that creates a compiled StateGraph object</li></ul><h3>Step 1 — Install the AgentCore CLI</h3><p>The AgentCore workflow starts with a single command-line tool. You’ll use it to create the project, run the app locally, and deploy it to AWS cloud.</p><p>Install the CLI:</p><pre>npm install -g @aws/agentcore</pre><p>Verify it after the installation:</p><pre>agentcore --help</pre><h3>Step 2 — Add Additional Dependencies</h3><p>Add the following packages to your agent’s dependencies: — bedrock-agentcore - the Python SDK that provides the BedrockAgentCoreApp wrapper class. - aws-opentelemetry-distro - AWS-supported distribution of the OpenTelemetry Python Instrumentation package.</p><pre># pyproject.toml<br>[project]<br>name = &quot;my-agent&quot;<br>version = &quot;0.1.0&quot;<br>requires-python = &quot;&gt;=3.12&quot;<br>dependencies = [<br>    &quot;aws-opentelemetry-distro==0.17.0&quot;,<br> &quot;bedrock-agentcore&gt;=1.6.3&quot;,<br>    &quot;boto3&gt;=1.42.0&quot;,<br>    &quot;langgraph&gt;=1.1.0&quot;,<br>    &quot;langchain-core&gt;=1.2.0&quot;,<br>    # ... your other existing dependencies<br>]</pre><p>Install all dependencies with your usual workflow:</p><pre>uv sync<br># or: pip install -e .</pre><h3>Step 3 — Write the AgentCore Entrypoint (main.py)</h3><p>AgentCore expects a single Python file as the entrypoint with a BedrockAgentCoreApp instance and a function decorated with @app.entrypoint. The important part is that your LangGraph logic does not need to change much; you’re just wrapping it in a small runtime entrypoint.</p><p>Here is the basic structure:</p><pre># main.py<br>from langchain_core.messages import HumanMessage<br>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br>from graphs.my_agent_graph import build_my_agent  # your existing graph builder<br><br># 1. Instantiate the AgentCore app and logger<br>app = BedrockAgentCoreApp()<br>log = app.logger<br><br># 2. Build your graph at module load time (startup)<br>#    AgentCore initialises the module once, then handles concurrent invocations.<br>#    Any failure here will prevent a broken agent from going live.<br>def create_agent():<br>    log.info(&quot;Initialising agent...&quot;)<br>    graph = build_my_agent()   # returns your compiled LangGraph StateGraph<br>    log.info(&quot;Agent ready&quot;)<br>    return graph<br>try:<br>    graph = create_agent()<br>except Exception as e:<br>    log.error(f&quot;Critical failure during agent initialisation: {e}&quot;)<br>    raise  # fail fast - don&#39;t let a broken agent start serving requests<br><br># 3. Async helper that drives the LangGraph streaming loop<br>async def run_agent(user_input: str, session_id: str = &quot;default-session&quot;) -&gt; str:<br>    responses = []<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: session_id}}<br>    async for chunk in graph.astream(<br>        {&quot;messages&quot;: [HumanMessage(content=user_input)]},<br>        config=config,<br>        stream_mode=&quot;values&quot;,<br>    ):<br>        messages = chunk.get(&quot;messages&quot;, [])<br>        if messages:<br>            last = messages[-1]<br>            if getattr(last, &quot;type&quot;, None) == &quot;ai&quot;:<br>                responses.append(last)<br>    if not responses:<br>        return &quot;No response&quot;<br>    content = getattr(responses[-1], &quot;content&quot;, &quot;&quot;)<br>    return content if isinstance(content, str) else str(content)<br><br># 4. The entrypoint - this is what AgentCore calls on every invocation<br>@app.entrypoint<br>async def invoke(payload, context):<br>    try:<br>        log.info(&quot;Invoke received&quot;)<br>        user_input = payload.get(&quot;prompt&quot;, &quot;&quot;)<br>        session_id = payload.get(&quot;session_id&quot;, &quot;default-session&quot;)<br>        if not user_input.strip():<br>            return {&quot;error&quot;: &quot;Prompt cannot be empty&quot;}<br>        response = await run_agent(user_input, session_id)<br>        return {&quot;response&quot;: response}<br>    except Exception as e:<br>        log.error(f&quot;Error: {e}&quot;)<br>        return {&quot;error&quot;: str(e)}<br><br># 5. Run the app (only executed when running locally using agentcore dev)<br>if __name__ == &quot;__main__&quot;:<br>    app.run()</pre><h4>A few things that matter</h4><p>BedrockAgentCoreApp() gives you the AgentCore runtime wrapper. It sets up the HTTP server, health check endpoints, and structured logging for you.</p><p>Module-level graph initialisation — the graph is created once when the module loads, not on every request. That catches startup failures early, which is good because it prevents a broken app from going live.</p><p>@app.entrypoint — this decorator registers the function as the handler for incoming invocations. It receives payload (the parsed JSON body) and context (AgentCore request context). It should return a plain JSON-serializable dictionary, not a raw string or a custom object.</p><p>session_id → thread_id — The session_id is passed into LangGraph as thread_id, which enables per-session memory with MemorySaver.</p><h3>Step 4 — Create an AgentCore Project</h3><p>Next, we need to generate our project layout. Run the initialization wizard inside a clean root folder and let it create the basic project layout for you.</p><pre>agentcore create</pre><p>The setup wizard will ask a few simple questions, like the project name, language, Python version, entrypoint file, etc. The important part is that the entrypoint and the Python version matches your app.</p><p>After the project is created, you’ll get an agentcore.json file (in agentcore folder) that tells AgentCore where your code lives and how to run it.</p><pre>{<br>  &quot;name&quot;: &quot;MyAgentOnAgentcore&quot;,<br>    &quot;runtimes&quot;: [<br>    {<br>      &quot;name&quot;: &quot;my-agent&quot;,<br>      &quot;build&quot;: &quot;CodeZip&quot;,<br>      &quot;entrypoint&quot;: &quot;main.py&quot;,<br>      &quot;codeLocation&quot;: &quot;app/my-agent/&quot;,<br>      &quot;runtimeVersion&quot;: &quot;PYTHON_3_12&quot;,<br>      &quot;networkMode&quot;: &quot;PUBLIC&quot;,<br>      &quot;protocol&quot;: &quot;HTTP&quot;,<br>	  &quot;envVars&quot;: []<br>	}<br>  ]<br>}</pre><h3>Step 5 — Put Your Source Code to the Code Location</h3><p>Copy or move your agent source into the directory specified by codeLocation in agentcore.json. This part is easy to get wrong, and when it’s wrong, deployment becomes unnecessarily frustrating. I struggled for a while after accidentally putting it in the agentcore folder.</p><p>A typical layout should look like this:</p><pre>MyAgentOnAgentcore/<br>├──agentcore<br>	└── agentcore.json<br>├──app/<br>	└──my-agent/          			 ← codeLocation <br>		├── main.py                  ← entrypoint (matches agentcore.json)<br>		├── pyproject.toml           ← or requirements.txt<br>		├── src/<br>		│   └── my_agent_graph.py    ← your LangGraph graph builder<br>		│   └── tools.py             ← your tools, utilities, etc.<br>		└── .env					 ← your configuration variables</pre><p>Make sure main.py sits at the top level of codeLocation and matches the entrypoint in agentcore.json exactly.</p><h4>Environment variables</h4><p>AgentCore can pass environment variables into the runtime container. For local testing, a .env file is usually the easiest option.</p><p>For production, you can put values in agentcore.json under envVars (.env file also works). But secrets like passwords and API keys are better stored in AWS Secrets Manager and loaded at runtime. If you do that, the AgentCore execution role needs permission to read those secrets.</p><p>Note: envVars should be an array of JSON objects with name and value fields.</p><h3>Step 6 — Validate the Project</h3><p>Before you try to run anything, use AgentCore CLI to validate the project configuration:</p><pre>agentcore validate</pre><p>This catches the common mistakes early, like a missing entrypoint file or a bad path in the config.</p><h3>Step 7 — Run and Test Locally</h3><p>Start the local runtime to test the agent locally:</p><pre>agentcore dev</pre><p>This spins up a local HTTP server that closely mirrors the production environment for testing. If everything is wired up properly, you should see that the app is ready and listening on a local port.</p><h4>Test on Local Server</h4><p>You can test an invocation using either the AgentCore CLI or curl:</p><pre>agentcore invoke &quot;Summarise last month sales&quot;</pre><p>Or</p><pre>curl -X POST http://localhost:8080/invocations \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;prompt&quot;: &quot;Summarise last month sales&quot;, &quot;session_id&quot;: &quot;test-001&quot;}&#39;</pre><p>A successful response should come back as JSON with the agent’s answer in it.</p><pre>{&quot;response&quot;: &quot;Last month, total sales were $1.2M across 3 regions...&quot;}</pre><h3>Step 8 — Deploy to AWS</h3><p>Once local testing looks solid, deploy to AWS Bedrock AgentCore Runtime:</p><pre>agentcore deploy</pre><p>Under the hood, the CLI:</p><ol><li>Packages your code</li><li>Provisions an S3 bucket for direct code deploy</li><li>Creates an IAM execution role</li><li>Deploys the AgentCore Runtime via CDK</li></ol><p>The first deploy takes a few minutes. Subsequent deploys tend to be faster.</p><p>When it’s successfully completed, check the runtime status. It will display the runtime ARN and HTTP URL to invoke the deployed agent.</p><pre>agentcore status</pre><h3>Step 9 — Invoke the Deployed Agent</h3><p>The easiest way to test the deployed version is with the CLI:</p><pre>agentcore invoke --prompt &quot;Who are the top 5 customers by revenue?&quot; --session-id &quot;session-id-with-length-greater-than-or-equal-33&quot;</pre><p>If you want to call it using HTTP, you’ll need to sign the request with AWS SigV4.</p><pre>curl -X POST &quot;https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/arn-of-MyAgentOnAgentcore-xxxx/invocations&quot; \<br>  --user &quot;$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY&quot; \<br>  --aws-sigv4 &quot;aws:amz:us-east-1:bedrock-agentcore&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;x-amzn-bedrock-agentcore-runtime-session-id: session-id-with-length-greater-than-or-equal-33&quot; \<br>  -d &#39;{&quot;prompt&quot;: &quot;Who are the top 5 customers by revenue?&quot;}&#39;</pre><p>Use the HTTP URL displayed by agentcore status.</p><p>When integrating your agent with other Python applications, using the SDK is usually the cleanest approach. You can keep the runtime ARN in an environment variable, send the prompt, and pass the same session ID back on follow-up requests.</p><pre># invoke_agent.py<br>import json<br>import boto3<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>client = boto3.client(&quot;bedrock-agentcore&quot;, region_name=&quot;us-east-1&quot;)<br>runtime_arn = os.getenv(&quot;AGENTCORE_RUNTIME_ARN&quot;)<br><br>def invoke(prompt: str, session_id: str) -&gt; str:<br>    payload = json.dumps({&quot;prompt&quot;: prompt, &quot;session_id&quot;: session_id})<br>    response = client.invoke_agent_runtime(<br>        agentRuntimeArn=runtime_arn,<br>        payload=payload,<br>        contentType=&quot;application/json&quot;<br>    )<br>    body = json.loads(response[&quot;response&quot;].read().decode())<br>    return body[&quot;response&quot;]<br><br>if __name__ == &quot;__main__&quot;:<br>    session_id = &quot;&quot;<br>    print(&quot;Ready. Type &#39;exit&#39; to quit.&quot;)<br><br>    while True:<br>        prompt = input(&quot;Your question: &quot;).strip()<br>        if prompt == &quot;exit&quot;:<br>            break<br><br>        if not prompt:<br>            continue<br><br>        params = {<br>            &quot;agentRuntimeArn&quot;: runtime_arn,<br>            &quot;payload&quot;: json.dumps({&quot;prompt&quot;: prompt}),<br>            &quot;contentType&quot;: &quot;application/json&quot;<br>        }<br>        if session_id:<br>            params[&quot;runtimeSessionId&quot;] = session_id<br><br>        try:<br>            response = client.invoke_agent_runtime(**params)<br>            body = json.loads(response[&quot;response&quot;].read().decode())<br>            session_id = response.get(&quot;runtimeSessionId&quot;, session_id)<br>            print(f&quot;Agent: {body[&#39;response&#39;]}\n&quot;)<br>        except Exception as e:<br>            print(f&quot;Error: {e}&quot;)</pre><p>Set AGENTCORE_RUNTIME_ARN in your .env file:</p><pre>AGENTCORE_RUNTIME_ARN=arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/MyAgentOnAgentcore-xxxx</pre><h4>Maintaining session state across invocations</h4><p>Notice runtimeSessionId in the boto3 example. AgentCore returns a runtimeSessionId in every response. Passing it back in the next request tells AgentCore to route subsequent calls to the same session context — which, combined with LangGraph&#39;s MemorySaver, gives the agent full conversation memory across multiple HTTP calls.</p><h3>Common Gotchas</h3><p>Startup failures are intentional. If create_agent() raises at module load, AgentCore will refuse to start the runtime. This is a feature, not a bug — it prevents an incorrectly configured agent (missing credentials, wrong DB URL) from going live silently.</p><p>The execution role AgentCore creates needs explicit permissions for any AWS service your agent touches, including Secrets Manager and S3. Add those permissions after the first deploy.</p><p>The Python version in pyproject.toml should match the runtime version in agentcore.json.</p><p>The entrypoint should return a JSON-serialisable dictionary. If it returns a plain string or a custom object, the runtime boundary will reject it.</p><h3>Conclusion</h3><p>The transition from a local LangGraph agent to an AgentCore deployment really comes down to a few practical changes: add the right dependencies, wrap the graph in BedrockAgentCoreApp, scaffold the project, test locally, then deploy and invoke it.</p><p>Everything else — the graph, the tools, the model calls, and the memory setup — stays mostly the same. AgentCore handles the runtime side, and LangGraph handles the agent logic.</p><p>A full working example is available at <a href="https://github.com/thedataengr/data-agent-on-aws-agentcore">github.com/thedataengr/data-agent-on-aws-agentcore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75844cbeea58" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/how-to-deploy-a-langgraph-agent-on-aws-bedrock-agentcore-75844cbeea58">How to Deploy a LangGraph Agent on AWS Bedrock AgentCore</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>