<?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 Pablo Beltran on Medium]]></title>
        <description><![CDATA[Stories by Pablo Beltran on Medium]]></description>
        <link>https://medium.com/@pabbelt?source=rss-a80b673a51ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pAX02hs5KPjWyu0e.jpg</url>
            <title>Stories by Pablo Beltran on Medium</title>
            <link>https://medium.com/@pabbelt?source=rss-a80b673a51ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:06:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pabbelt/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 You’re Probably Using the Wrong Agent Library]]></title>
            <link>https://medium.com/@pabbelt/why-youre-probably-using-the-wrong-agent-library-2c2789008518?source=rss-a80b673a51ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2789008518</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Pablo Beltran]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 20:07:59 GMT</pubDate>
            <atom:updated>2025-08-12T20:07:59.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*boFKIr0CUUEsjFte4Qbf8Q.jpeg" /></figure><p>Here’s an uncomfortable reality: that agent library you just adopted might not exist in two years.</p><p>This isn’t meant to disparage the impressive work being done in this space. We’re seeing <a href="https://opendatascience.com/top-10-open-source-ai-agent-frameworks-to-know-in-2025/">10+ major AI agent frameworks</a> competing for developer mindshare, each bringing innovative ideas to the table. But the rapid pace of change — with frequent breaking changes requiring complex migrations, constant API updates, and steep learning curves across the ecosystem — combined with <a href="https://www.gartner.com/en/newsroom/press-releases/2025-06-25-gartner-predicts-over-40-percent-of-agentic-ai-projects-will-be-canceled-by-end-of-2027">Gartner’s prediction that 40% of agent projects will be canceled by 2027</a>, suggests we’re in for a major shakeout.</p><p>The challenge isn’t the quality of these tools — many are excellent. It’s that <strong>the agent library space is too new, too fragmented, and too rapidly evolving for anyone to make a safe long-term bet right now.</strong></p><h3>The Fragmentation Challenge</h3><p>Every framework has taken a fundamentally different philosophical approach:</p><ul><li><strong>LangChain</strong>: Sequential chains and tools</li><li><strong>LangGraph</strong>: Stateful directed graphs</li><li><strong>CrewAI</strong>: Role-based teams and crews</li><li><strong>AutoGen</strong>: Conversational multi-agent systems</li></ul><p>These aren’t just naming differences — they represent incompatible architectures. There’s no interoperability. Switching frameworks means a significant rewrite.</p><p><a href="https://mubashirullahd.medium.com/migrating-away-from-langchain-lessons-learned-from-upgrading-our-ai-codebase-2f8fe1cb14f3">One developer documented</a> spending weeks trying to upgrade LangChain before deciding to go custom: “Coding in LangChain felt unnecessarily complex, and I saw LangSmith as a solution to a self-inflicted problem.”</p><h3>The Simplicity Alternative</h3><p>Here’s something that might surprise you: <strong>core agent functionality can be implemented in just 200–300 lines of code</strong>.</p><p><a href="https://www.pondhouse-data.com/blog/ai-agents-from-scratch">A detailed breakdown</a> shows the basic pattern of an AI agent — an LLM with tools and memory — requires surprisingly little code:</p><ul><li>40 lines for a database tool</li><li>30 lines for search functionality</li><li>100 lines for orchestration</li><li>150 lines for memory</li></ul><p>That’s 320 lines of code you fully understand and control versus importing large frameworks with their own learning curves and constraints.</p><p><a href="https://www.anthropic.com/engineering/building-effective-agents">Anthropic’s research</a> supports this approach: “The most successful implementations weren’t using complex frameworks… they were building with simple, composable patterns.”</p><p>The trade-off is clear: frameworks save initial development time but add complexity and migration risk. Custom implementations require more upfront work but offer complete control and flexibility.</p><h3>The Build-vs-Buy Consideration</h3><p>Given that <a href="https://www.pondhouse-data.com/blog/ai-agents-from-scratch">building a basic agent system requires just 200–300 lines of code</a>, teams now have a genuine choice between frameworks and custom implementations.</p><p>The potential benefits of going custom are clear:</p><ul><li>Avoiding breaking changes and migrations</li><li>Understanding every line of code in production</li><li>Integrating cleanly with existing systems</li><li>Maintaining flexibility as requirements evolve</li></ul><p>Whether to take this path depends on your specific needs and resources. But the fact that it’s even a viable option for small teams suggests something important about the current state of agent frameworks.</p><h3>A Different Philosophy: Infrastructure Over Abstractions</h3><p>Here’s a pattern worth considering: instead of frameworks that impose their own agent abstractions, look for tools that provide tangible infrastructure improvements while letting you build your own abstractions.</p><p><a href="https://temporal.io/">Temporal</a> exemplifies this approach. Rather than dictating how agents should work, it provides durable execution — agents can crash and resume exactly where they left off. You get scheduling guarantees, automatic retries, and state management without being locked into someone else’s idea of what an agent should be.</p><p>The key insight is that <strong>frameworks should solve hard infrastructure problems, not create new abstraction layers</strong>. Durable execution, reliable scheduling, distributed coordination — these are genuinely difficult problems worth offloading. But “agent” abstractions that could change next month? Those you might want to own yourself.</p><p>This principle extends beyond Temporal. Any framework that provides concrete infrastructure benefits while maintaining flexibility in implementation might weather the coming consolidation better than those focused purely on AI-specific abstractions.</p><h3>What Should You Do?</h3><p>Three strategic approaches make sense today:</p><ol><li><strong>Build custom for production</strong>: If you need full control and have specific requirements, 300 lines of custom code might serve you better than a large framework dependency.</li><li><strong>Use libraries strategically</strong>: These tools excel at rapid prototyping and experimentation. Just be prepared for potential migrations as the landscape evolves.</li><li><strong>Consider waiting</strong>: By 2027, we’ll likely have 3–5 dominant platforms with clearer standards and better stability.</li></ol><h3>The Bottom Line</h3><p>Choosing an agent library today is genuinely difficult. The ecosystem is evolving rapidly, with impressive innovations happening across multiple frameworks. But this same dynamism creates risk.</p><p>The frameworks designed to accelerate development sometimes require significant migration efforts with each update. The abstractions meant to simplify can occasionally obscure important implementation details. And with the ecosystem still finding its footing, today’s popular choice might not be tomorrow’s standard.</p><p>My suggestion? Consider your specific needs carefully. If you’re prototyping, these libraries can be incredibly valuable for rapid iteration. If you need production reliability, consider either infrastructure-focused solutions like Temporal or a lightweight custom implementation. And if you can afford to wait, the picture will likely be much clearer in 12–18 months.</p><p>The agent library ecosystem will mature and consolidate — that’s inevitable. Some of today’s frameworks will emerge as industry standards. But right now, we’re still in the experimental phase, and it’s worth acknowledging that before making long-term technical commitments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2789008518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Less Infrastructure, Ship More Product]]></title>
            <link>https://medium.com/@pabbelt/build-less-infrastructure-ship-more-product-17b94b47e95f?source=rss-a80b673a51ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/17b94b47e95f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pablo Beltran]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 16:01:55 GMT</pubDate>
            <atom:updated>2025-08-11T16:01:55.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*isCILF3uARSljl1SMto44Q.jpeg" /></figure><p>Six months in, the team was in trouble. They had built their own workflow engine from scratch, low-level, highly flexible, and completely unsupported. On paper, it was powerful. In practice, every new feature broke something. On-call alerts spiked. Customers complained.</p><p>Eventually, they scrapped months of work and switched to a hosted platform just to keep the lights on.</p><p>This happens more often than people admit. Pick the wrong level of abstraction and you can burn months of engineering time, get stuck with brittle infrastructure, or face a painful migration later. But here’s the thing: sometimes the “wrong” abstraction that ships is better than the “right” one that takes six months to build.</p><p>When you set out to build a new service, whether it is a workflow orchestrator, a customer communications tool, an identity provider, or a monitoring stack, the question is not just <em>what</em> it should do. It is also <em>how</em> you should build it.</p><h3>The Ladder of Abstraction</h3><p>Here is the spectrum most teams choose from:</p><ul><li><strong>No-code / low-code</strong> — Zapier, Airtable Automations, Make. Drag-and-drop logic, little or no code. Great for prototypes, internal tools, and non-engineer ownership.</li><li><strong>SaaS-hosted</strong> — Temporal Cloud, Intercom, Auth0, New Relic. Fully managed with SLAs, scaling, and security updates included.</li><li><strong>Self-hosted off-the-shelf</strong> — Apache Airflow, Mattermost, Keycloak, Prometheus + Grafana. You control deployment and configuration, but you also own maintenance, scaling, and uptime.</li><li><strong>In-house with high-level OSS</strong> — Celery + Redis orchestration, Matrix chat, Ory Hydra auth, OpenTelemetry monitoring. More customization without reinventing the wheel.</li><li><strong>Fully in-house</strong> — Build the entire stack yourself. Total control and total responsibility.</li></ul><h3>Why Starting High Often (But Not Always) Works</h3><p>The conventional wisdom says start high on the ladder with SaaS or no-code. This makes sense when:</p><ul><li><strong>You’re exploring</strong> — You genuinely don’t know your requirements yet</li><li><strong>Speed matters most</strong> — You need to ship yesterday</li><li><strong>Your team lacks ops expertise</strong> — Your engineers are product-focused, not infrastructure experts</li><li><strong>It’s not core differentiation</strong> — Your auth system probably isn’t your competitive advantage</li></ul><p>But there are even stronger reasons to default high:</p><ul><li><strong>Unknown unknowns</strong> — You don’t know what you don’t know. That edge case that takes down production at 2am? The SaaS vendor already fixed it three years ago after another customer hit it.</li><li><strong>Opportunity cost</strong> — Every engineer working on infrastructure isn’t working on your product. If you’re a 10-person startup, do you want 2 engineers maintaining Kubernetes?</li><li><strong>Compliance is built-in</strong> — SOC2, GDPR, HIPAA — many SaaS platforms have these certifications already. Building compliant infrastructure yourself can take years.</li><li><strong>Best practices by default</strong> — Rate limiting, circuit breakers, observability, gradual rollouts — these come standard with good SaaS platforms. Building them yourself means rediscovering every lesson the hard way.</li><li><strong>Focus compounds</strong> — Teams that stay focused on their core product move faster and faster. Teams maintaining infrastructure move slower over time as complexity grows.</li></ul><p>That said, starting lower sometimes makes sense:</p><ul><li><strong>Regulatory requirements</strong> — Healthcare or financial services often can’t use multi-tenant SaaS</li><li><strong>Data sovereignty</strong> — Some data legally cannot leave your infrastructure</li><li><strong>Known scale requirements</strong> — If you know you’ll process billions of events daily, SaaS costs can be prohibitive from day one</li><li><strong>Team expertise</strong> — A team of ex-Google SREs might actually ship faster with Kubernetes than learning a new SaaS platform</li></ul><p>But these are exceptions. Most teams overestimate their special requirements and underestimate the cost of running infrastructure.</p><h3>The Real Trade-offs Nobody Talks About</h3><p><strong>Moving down isn’t always easier than moving up.</strong> While stepping down the ladder might seem gradual in theory, reality is messier:</p><ul><li><strong>Data migration nightmares</strong> — Moving years of data from a SaaS platform can take months</li><li><strong>Feature gaps</strong> — That SaaS feature you rely on? Good luck rebuilding it</li><li><strong>Sudden responsibilities</strong> — Congrats, you now own security patches, compliance audits, and 3am outages</li><li><strong>Hidden dependencies</strong> — Your SaaS vendor’s API rate limiter was actually protecting your database</li><li><strong>Exponential cost curves</strong> — SaaS pricing often starts at $500/month for 10,000 users but jumps to $15,000/month at 100,000 users. Meanwhile, self-hosted costs your DevOps team’s time regardless of scale</li></ul><h3>Common Patterns in Practice</h3><h3>Example 1: The Gradual Descent (Temporal)</h3><p>A startup needs orchestration.</p><ul><li><strong>Phase 1</strong> — Start on <strong>Temporal Cloud</strong> to ship features quickly</li><li><strong>Phase 2</strong> — At $50k/month, switch to <strong>self-hosted Temporal</strong> (same workflows, more control)</li><li><strong>Phase 3</strong> — Build <strong>custom orchestration</strong> for unique workload patterns</li></ul><p>This worked because Temporal’s programming model is consistent across deployment options.</p><h3>Example 2: Starting Low Was Right (Financial Services)</h3><p>A trading firm needs order routing.</p><ol><li><strong>Phase 1</strong> — Build on <strong>low-level OSS</strong> (ZeroMQ + custom logic) from day one</li><li><strong>Why it worked</strong> — Sub-millisecond latency requirements, regulatory data controls, team of HFT veterans</li></ol><p>Starting with a SaaS solution would have been impossible due to latency and compliance.</p><h3>Example 3: The Lock-in Trap (Communication Platform)</h3><p>A marketplace builds on a customer communication SaaS.</p><ol><li><strong>Year 1</strong> — Fast deployment, happy stakeholders</li><li><strong>Year 2</strong> — Costs hit $200k/month, want to migrate</li><li><strong>Year 3</strong> — Still on SaaS because migration would break thousands of notification workflows</li></ol><p>Sometimes you can’t move down even when you want to.</p><h3>Making the Decision</h3><p>Before choosing a level, understand your constraints and escape hatches.</p><p><strong>Key questions to ask:</strong></p><ul><li>Is this core to our differentiation?</li><li>Do we have hard constraints (compliance, latency, cost)?</li><li>What does our team know how to operate?</li><li>Can we afford the migration cost if we’re wrong?</li><li>What’s the real cost of delay?</li></ul><p><strong>Know your escape hatches:</strong></p><ul><li><strong>Data export</strong> — Can you get your data out? In what format?</li><li><strong>API compatibility</strong> — Does an open-source alternative exist with similar APIs?</li><li><strong>Feature parity</strong> — Which features would you lose? Which matter?</li><li><strong>Migration cost</strong> — Not just engineering time, but customer disruption</li></ul><p>Some platforms deliberately make leaving expensive. Others (like Temporal) maintain compatibility across deployment models. Know which you’re choosing.</p><p><strong>Rule of thumb:</strong> Start as high as your constraints allow. Move down when the pain (cost, limitations, performance) exceeds the pain of migration. But remember — shipping an imperfect solution often beats analyzing the perfect architecture for months.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17b94b47e95f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just use cloud storage]]></title>
            <link>https://medium.com/@pabbelt/just-use-cloud-storage-be20a2740be9?source=rss-a80b673a51ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/be20a2740be9</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <dc:creator><![CDATA[Pablo Beltran]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 00:13:41 GMT</pubDate>
            <atom:updated>2025-08-03T00:13:41.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*88IuX86kfalpM3TyQOZjRg.jpeg" /></figure><p>Cloud storage solutions (S3, GCS, ADLS2, etc.) are unreasonably effective. During system design interviews, I’ve noticed candidates often reach for traditional databases like Postgres, NoSQL, or Cassandra, but leave blob storage untouched. Yet, industry trends increasingly favor blob storage solutions for good reasons: cost-efficiency, reliability, and simplicity. Before reaching for another option, ensure you have a compelling reason to avoid blob storage.</p><h3>Cost of Cloud Storage</h3><p>Let’s examine blob storage costs beyond just money, focusing also on development and maintenance.</p><h4>Development Cost</h4><p>Creating a new bucket requires minimal upfront configuration. Connecting, reading, and writing data is straightforward across languages, with no infrastructure management afterward.</p><p>Contrast this with setting up a database — where you must decide on storage size, machine types, memory configurations, and more. Blob storage has a significantly lower learning curve, leveraging familiar abstractions like files and folders.</p><h4>Maintenance Cost</h4><p>Buckets require minimal upkeep. Auto-tiering automatically optimizes storage costs, and lifecycle policies effortlessly manage data expiration. Buckets scale seamlessly — you can suddenly ingest massive amounts of data without encountering scaling issues or needing migrations.</p><p>Databases, conversely, demand continuous monitoring, tuning, scaling considerations, and potentially costly migrations as data grows.</p><h4>Monetary Cost</h4><p>Blob storage is cost-effective, storing 1TB typically costs about as much as a premium Netflix subscription. The same storage capacity in traditional databases often costs 10 times more.</p><p>However, be cautious about read/write operations. Frequent reads and writes can add up quickly. Often, batching operations can help minimize these costs.</p><h3>Industry Trends and Examples</h3><h4>WarpStream</h4><p><a href="https://medium.com/@warpstream/zero-disks-is-better-for-kafka-7bb56ba2cd7d">Built entirely on object storage, WarpStream eliminates local disks and inter-AZ replication.</a> Its “Zero Disk Architecture” enables stateless scaling, agents auto-scale easily like web services, significantly simplifying deployment and reducing costs. Although it introduces slightly higher tail latency (~400–600 ms p99 writes, ~1.5 s end-to-end), this trade-off is acceptable for many use cases considering the simplicity and operational efficiency achieved.</p><h4>RisingWave</h4><p>A cloud-native streaming SQL database utilizing S3 as primary storage. <a href="https://risingwave.com/blog/sub-100ms-stream-processing-s3-cloud-native/">RisingWave achieves sub-100ms processing through a three-tier architecture</a>: an in-memory cache, local disk cache, and S3 for persistent storage. This allows independent scaling of compute and storage, resulting in optimal cost and elasticity. Real-time queries are efficiently served from local caches, significantly minimizing expensive S3 reads.</p><h4>Apache Iceberg</h4><p>Apache Iceberg provides an open-table format specifically designed to optimize analytics workloads on cloud storage. By efficiently managing metadata and supporting incremental data processing, Iceberg enables rapid querying of massive datasets stored economically in blob storage. This approach avoids the complexity and expense of traditional data warehouses, making blob storage an ideal foundation for modern analytical workloads.</p><h3>Blob Storage as a Simplifier</h3><p>Even when specific database features are needed (such as low latency or transaction guarantees) blob storage often simplifies architecture. For instance:</p><p><strong>Large file storage with pointers:</strong> Store binary content (e.g., media or logs) in blob storage, maintaining only metadata or pointers in your primary database.<br><strong>Primary storage with caching layer:</strong> Use blob storage for persistence and an in-memory or disk cache (Redis, Memcached, local disk) to ensure rapid reads and writes.<br><strong>Event sourcing and state snapshots:</strong> Store immutable events or regular state snapshots in blob storage, rebuilding in-memory models as needed. This reduces dependency on constantly active databases and simplifies complex aggregation logic.</p><p>Unless you have a strong, specific reason to avoid it, blob storage should be your default choice. It’s effective, cost-efficient, and simplifies your architecture significantly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be20a2740be9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should use SQLGlot to manage your SQL codebase]]></title>
            <link>https://medium.com/@pabbelt/why-you-should-use-sqlglot-to-manage-your-sql-codebase-82d841c0d450?source=rss-a80b673a51ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/82d841c0d450</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sqlglot]]></category>
            <category><![CDATA[warehouse]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Pablo Beltran]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 04:41:58 GMT</pubDate>
            <atom:updated>2024-03-05T04:42:36.649Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I started to look around for a way to provide better CI checks for our SQL codebase. We had recently migrated the majority of our code from PySpark over to pure SQL. While PySpark was very flexible, it also was easy for people to write data transformations that were inefficient or difficult to maintain. On the other hand SQL, by its nature, offers less flexibility in how tasks should be accomplished. The ‘how’ of data transformations are left to the warehouse due to SQLs declarative approach.</p><p>Event with these benefits, there was still difficulties in standardizing how the SQL is written and testing the SQL itself without having a hard dependency on the warehouse seemed impossible. And then I stumbled upon SQLGlot, which claimed that it could parse SQL from most of the popular warehouses and even go so far as to translate between them. The claim was so impressive that I was kinda skeptical that it would be true but I was really blown away as I started to mess around with it.</p><h3>What is SQLGlot?</h3><p><a href="https://github.com/tobymao/sqlglot">SQLGlot</a> allows you to gain a programmatic understanding of the SQL within your codebase. It enables the creation of tests and checks to examine the intricacies of your SQL, identifying errors or anti-patterns at their source. SQLGlot offers APIs that standardize SQL structure across different data warehouses, making it a versatile tool for developers.</p><p>Utilizing SQLGlot to parse your SQL results in the generation of a SQL Abstract Syntax Tree (AST). This AST can be navigated to identify virtually any issue. Given the task’s complexity — translating over 20 evolving SQL dialects into a unified structure — it’s understandable that SQLGlot may occasionally misinterpret valid SQL as erroneous. However, based on my experience, issues reported to the repository are typically resolved within a day.</p><h3>Catching Anti-Patterns</h3><p>To give an example of what can be done with SQLGlot, I’ll share a CI test that I created to stop people from using ‘SELECT *’ when reading from a table/view. It was important that people could still ‘SELECT *’ when selecting from a CTE or a subquery so using a simple regex wasn’t going to work, I needed a tool that could understand the structure of the SQL itself.</p><p>The code bellow show how I implemented this test, I iterate over all select statements, determine if they are selecting from a table/view and determine if it is selecting ‘*’ and if so it raises an exception.</p><pre>parsed_query = parse_one(sql, dialect=&quot;bigquery&quot;)<br># Identify CTEs<br>cte_names = {cte.alias for cte in parsed_query.find_all(exp.CTE)}<br># Function to check if the selection is from a CTE or an external table<br>def is_from_cte_or_subquery(select_expression):<br>    froms = select_expression.find_all(exp.Table)<br>    tables = [x.args.get(&quot;this&quot;).args.get(&quot;this&quot;) for x in froms]<br>    subqueries = select_expression.find_all(exp.Subquery)<br>    num_subqueries = len([_ for _ in subqueries])<br>    if len(tables) &gt; 1 or num_subqueries &gt; 0:<br>        return True<br>    # If any of the tables are in the CTE names, then it&#39;s a CTE<br>    if len(set(tables) &amp; set(cte_names)) &gt; 0:<br>        return True<br>    return False<br>for select in parsed_query.find_all(exp.Select):<br>    for selection in select.args.get(&quot;expressions&quot;, []):<br>        if isinstance(selection, exp.Star) and not is_from_cte_or_subquery(select):<br>            raise Exception(<br>                &quot;select * is only allowed when selecting from a CTE.&quot;,<br>                select,<br>            )</pre><h3>Beyond the Basics</h3><p>SQLGlot’s utility extends beyond syntax checking and anti-pattern identification. It can be used to compare two SQL queries to ensure unchanged behavior, translate SQL to different dialects, or even execute SQL locally for testing without an external database connection.</p><p>SQLGlot is an incredibly powerful tool that continues to evolve. I look forward to seeing how it develops further and the innovative ways in which it will be applied to enhance SQL workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d841c0d450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Databricks Structured Streaming Queries in Datadog]]></title>
            <link>https://blog.statsig.com/monitoring-databricks-structured-streaming-queries-in-datadog-9b066b61ffe2?source=rss-a80b673a51ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b066b61ffe2</guid>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[structured-streaming]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Pablo Beltran]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 22:38:02 GMT</pubDate>
            <atom:updated>2022-04-29T22:38:02.473Z</atom:updated>
            <content:encoded><![CDATA[<p>At Statsig, we recently transitioned to using structured streaming for our ETL. As the number of streaming queries grew, we wanted a centralized place where we could quickly view a snapshot of all our pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*dyWatPiqL5UzorBppDTcRg.png" /></figure><h3>What we want to monitor</h3><p>When it comes to monitoring our queries, we are primarily interested in answering three questions:</p><ol><li>What is the input rate?</li><li>What is the processing rate?</li><li>What is the age of the freshest data being processed?</li></ol><h3>Pre-existing Structured Streaming UI</h3><p>Structured Streaming queries on Databricks already come with a UI attached to them when they are started, which helps monitor the input rate and processing rate (#1 and #2) at the job level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFTcI51hu_-RZhnd17ecNA.png" /></figure><p>These graphs help look at the performance of a specific job, but when you have a lot of queries, it is not practical to individually check each one. Additionally, this UI does not answer question number three: What is the age of the freshest data being processed?</p><h3>Setting up the Datadog Agent</h3><p>Before monitoring the query, we first need to install the Datadog Agent on the cluster. You can follow the ‘Driver only’ instructions on the <a href="https://docs.datadoghq.com/integrations/databricks/?tab=driveronly">Datadog Databricks integration guide</a>. <strong>Before</strong> running the script provided by Datadog, you need to modify it to set ‘<a href="https://github.com/DataDog/integrations-core/blob/47d3179ead1fec090195d989ed7583d48a8c1d9e/spark/datadog_checks/spark/data/conf.yaml.example#L146">enable_query_name_tag</a>’ to <strong>true</strong>. This is placed under ‘instances’ like this:</p><pre>instances:<br>    - spark_url: http://\$DB_DRIVER_IP:\$DB_DRIVER_PORT<br>      spark_cluster_mode: spark_standalone_mode<br>      cluster_name: \${hostip}<br>      streaming_metrics: true<br>      enable_query_name_tag: true &lt;----</pre><p>This will tag your metrics with the QueryName you provide, allowing you to view them individually even if there is more than one query per cluster. You also need to enable `dogstatsd` by adding the following two lines to the script:</p><pre># Enable dogstatsd<br>echo &quot;use_dogstatsd: true&quot; &gt;&gt; /etc/datadog-agent/datadog.yaml<br>echo &quot;dogstatsd_port: 8125&quot; &gt;&gt; /etc/datadog-agent/datadog.yaml</pre><h3><strong>Running the Datadog agent on your cluster</strong></h3><p>To run the Datadog agent on your cluster, you need to have the install script you generated run as an init script as well as enable streaming metrics and pass in your Datadog API key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGDvsvN01SEidqsFSQWtCg.png" /><figcaption>How to set the install script to run at startup</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOsD3WHHX-hzQ5kcao5gJg.png" /><figcaption>Enable streaming metrics and provide your API key</figcaption></figure><h3>Setting up the query for monitoring</h3><p>In order to select a specific query when making a dashboard, we need to provide a QueryName for the query to use. This can be done when writing the query:</p><pre>.writeStream<br>.queryName(query_name) &lt;---<br>.outputMode(&quot;append&quot;)<br>.format(&quot;delta&quot;)<br>.option(&quot;checkpointLocation&quot;, checkpoint)<br>.toTable(tablename)</pre><h4>Checking the data freshness</h4><p>Input rate and processing rate are automatically tracked for you. However, if you want to know your data freshness, you need to track it using foreachBatch. First, you need to pip install datadog. Then you can track the freshness like this:</p><pre>from datadog import statsd<br>.writeStream<br>.queryName(query_name) &lt;---<br>.format(&quot;delta&quot;)<br>.option(&quot;checkpointLocation&quot;, checkpoint)<br>.toTable(tablename)</pre><pre>def record_freshness(df, epoch_id):<br>    timestamp = df.limit(1).collect()[0][&#39;enqueued_time&#39;]<br>    freshness = (datetime.now() - timestamp).total_seconds()<br>    statsd.gauge(<br>        &#39;streaming.freshness_seconds&#39;, <br>        freshness, <br>        tags=[&#39;query_name:&#39;+query_name]<br>    )</pre><pre>(<br>    query<br>    .writeStream<br>    .queryName(query_name) <br>    .outputMode(&quot;append&quot;)<br>    .foreachBatch(record_freshness)<br>    .format(&quot;delta&quot;)<br>    .option(&quot;checkpointLocation&quot;, checkpoint)<br>    .start()<br>)</pre><p>If your query does not use ‘foreachBatch’, you can create a second query that reads the updates from your first query and records metrics:</p><pre>spark.readStream<br>.option(&#39;startingVersion&#39;, &#39;latest&#39;)<br>.format(&quot;delta&quot;)<br>.table(tablename)<br>.select(&quot;event_time&quot;)<br>.writeStream<br>.foreachBatch(update_freshness)<br>.start()</pre><h3>Creating the dashboard</h3><p>Now that we have all the metrics we care about being tracked, we can build a dashboard on Datadog. We can track all of these metrics using time-series graphs. <a href="https://scribehow.com/shared/Creating_a_chart_in_Datadog__Rdm_iXi-TLiC_i3F6IoKzQ">Here is a quick guide</a> on setting up a graph.</p><h3>Final Results</h3><p>This is what the dashboard could look like when all the charts are set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPseiqpVTuLWGjgYfq1vIg.png" /></figure><p>You can quickly swap to a different $query_name to view graphs for different queries. These dashboards will allow you to ensure that your queries are keeping up with incoming data and track how changes are affecting performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b066b61ffe2" width="1" height="1" alt=""><hr><p><a href="https://blog.statsig.com/monitoring-databricks-structured-streaming-queries-in-datadog-9b066b61ffe2">Monitoring Databricks Structured Streaming Queries in Datadog</a> was originally published in <a href="https://blog.statsig.com/">Statsig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>