<?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 Pranay Ravi on Medium]]></title>
        <description><![CDATA[Stories by Pranay Ravi on Medium]]></description>
        <link>https://medium.com/@pranayraavi?source=rss-b6bfe45e8d45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Pranay Ravi on Medium</title>
            <link>https://medium.com/@pranayraavi?source=rss-b6bfe45e8d45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:48:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranayraavi/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[What to Keep in Mind for a Cloud Migration]]></title>
            <link>https://medium.com/@pranayraavi/what-to-keep-in-mind-for-a-cloud-migration-4276821a23ca?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/4276821a23ca</guid>
            <category><![CDATA[cloud-migration-strategy]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 06:51:01 GMT</pubDate>
            <atom:updated>2026-11-12T14:01:11.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4CJJYgCSr8fzaUy1zPQWg.png" /></figure><h3>I have led a couple of platform migrations, from on-premises to AWS and from one AWS account structure to another. Each time my job was to coordinate the application, database, DevOps and network teams from scoping to cutover.</h3><p>This is the list I would want you to keep in mind before you start one. It is grouped into seven categories. Under each I say what to think about and, where it helps, what we did.</p><h3>1. Scope: decide what changes and what waits</h3><p>A migration is a chance to modernize, and it is also the easiest place to over-engineer. Start from the rules of the target environment. Ours were no static credentials, TLS on database connections, nothing public by default, autoscaling, and tags on every resource so cost splits by application.</p><p>Then list every improvement someone wants and make a call on each one.</p><ul><li><strong>Database.</strong> Move to a managed engine? Upgrade the major version in the same move? We moved to Aurora with an engine upgrade and TLS.</li><li><strong>Runtime.</strong> Can VMs, ECS and EKS collapse into one? We consolidated on EKS.</li><li><strong>Secrets.</strong> Use a secrets manager and take passwords out of code and config files. Ours moved into AWS.</li><li><strong>Configuration.</strong> Externalize parameters so the same build deploys to every environment. We used config maps.</li><li><strong>Logging.</strong> Send application logs to a central store instead of local disk. Ours went to a central search cluster.</li><li><strong>Access.</strong> Use roles between services and drop long-lived keys. We went role-based.</li><li><strong>Pipeline.</strong> Can one pipeline deploy everything? Is GitOps in reach? We ran one CI server in a shared account. GitOps came later, once the runtime was standard.</li><li><strong>Search and loaders.</strong> Upgrade or rewrite now, or carry them over as they are? We deferred both, because they needed application code changes.</li><li><strong>Backups.</strong> Does going live need a new backup design? We deferred it. Snapshots were enough.</li></ul><p>Two columns in the task tracker kept this honest: “key project goal” and “blocker for the first environment”. A task with a no in both waited.</p><h3>2. Discovery: get the complete picture</h3><p>Get a complete application architecture diagram before anyone builds. Expect the first version to be partial, and keep asking. A platform that has run for years has connections nobody wrote down.</p><p>Build an inventory for every environment:</p><ul><li>Which component runs where, and why it runs there.</li><li>Every DNS name, with its zone, load balancer, protocol, target group and the resource behind it.</li><li>Every inbound caller and every outbound dependency.</li><li>Every loader, job and script that reads or writes the data.</li></ul><p>Check your assumptions two and three times, including the convenient ones. We worried that bucket names were stored in the database, which would have made renaming buckets painful. We checked, and they were in a properties file. We also assumed a transit gateway would cover traffic between accounts, and we needed VPC peering as well.</p><p>Compare the environments against each other. Production and non-production are rarely built the same way, and the differences are where the cutover steps change.</p><p>Even with all of this, three things found us late: another product’s web client that read our object storage directly, a data warehouse job that read a logging table we planned to retire, and a monitoring script that counted documents in the old search cluster. Leave room in the plan for your own version of these.</p><h3>3. People and calendar: one scrum, one plan</h3><p>Each team has its own backlog, its own way of working and other projects competing for the same people. Someone has to keep those plans moving as one.</p><ul><li><strong>Run one scrum across all teams.</strong> Ours started weekly, went to twice a week to clear blockers, and became daily near the first cutover.</li><li><strong>Ask every team the same three questions.</strong> What are you working on, and what is the estimate? What is blocked or likely to slip, and what is the alternative? What still has to happen for the next environment to cut over on its date?</li><li><strong>Keep one board.</strong> One epic, with each team’s own tickets linked in.</li><li><strong>Spell out requirements early.</strong> When one team settles on a solution, share what it needs from the others the same day.</li><li><strong>Post outcomes in the shared channel.</strong> Two-person working sessions are fine, but the result belongs where every team sees it.</li><li><strong>Follow up instead of waiting.</strong> It never hurts to over-communicate.</li><li><strong>Plan around the calendar.</strong> Change freezes, public holidays and time off for key people all punch holes in a quarter. Keep a tab for who is out and when, and set each environment window around it.</li></ul><p>Dates will still move, and ours did on the first environment. Build slack around the known gaps so one slip does not push every later window.</p><h3>4. Data: the part that decides the cutover</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waJb9YeBy_--183XSqvL_g.png" /></figure><p>Compute can be redeployed. Data has to be moved, kept in sync and proven correct, so it shapes the whole cutover. There is no single right method, only questions you have to answer.</p><p><strong>Can you take downtime?</strong> Decide this first, with the product owner. A short window removes a whole class of design. We could take one.</p><p><strong>One direction or two?</strong> Bidirectional replication buys an easy rollback and costs you conflict handling and weeks of testing. We tested replicating back from the upgraded engine to the old one and hit problems. We chose one direction: seed the new database from a shared snapshot, replicate old to new with native replication, and roll back by export and import. That rollback carries downtime, so tell the product team before they agree.</p><p><strong>Native or heterogeneous tooling?</strong> Every engine has its own replication. Tools such as AWS DMS or Oracle GoldenGate cover moves across engines. Pick the option with the fewest steps to script and test. For us that was native.</p><p><strong>Where else does the data live?</strong> Rarely in one place. Ours was in three, each with its own method:</p><ul><li><strong>Relational database.</strong> Seeded from a snapshot, then one-way native replication. Rollback by export and import.</li><li><strong>Search cluster.</strong> Snapshot to a shared bucket and restore, then a remote reindex of the current day during the window. Rollback by reindexing back.</li><li><strong>Object storage.</strong> Bidirectional bucket replication, left on for days after cutover. For rollback, the files were already in both accounts.</li></ul><p><strong>What feeds it and what reads it?</strong> List every inbound loader and every downstream reader. We stopped the loaders before the window and repointed them after. The downstream warehouse stayed on the old database for one more day.</p><p><strong>What can testing break?</strong> Readiness tests that write to the new database while replication is running can break the replication. Plan which tests write, and when.</p><h3>5. Network and edges: where it usually breaks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQ9Jxn_KKhsUUPYA_0gY0g.png" /></figure><p>The application and the database get the attention. The surprises come from DNS, load balancers and allowlists.</p><p><strong>DNS.</strong> If the domain’s hosting moves too, stage it so a rollback never touches the registrar. We moved ours into Route 53 like this:</p><ol><li>Create the new hosted zone as an empty shell. Not live, and no records created early.</li><li>Add temporary names in the old zone that point at the new load balancers, so the new stack can be tested before cutover.</li><li>At cutover, repoint the old zone’s records to the new load balancers.</li><li>The next day, sync the records into the new zone.</li><li>After 24 hours, publish the new name servers at the registrar next to the old ones.</li><li>After another 24 hours, remove the old name servers and watch the URL monitors.</li></ol><p><strong>Load balancers.</strong> Decide where TLS terminates, what the listener rules are, and whether each endpoint gets its own load balancer or shares one with host and path routing. Have services call each other through a load balancer or a DNS name, not through the cluster’s internal networking.</p><p><strong>Allowlists.</strong> A new account means new outbound addresses. Every partner and internal service that allowlisted the old ones needs the new ones before cutover. Give every outbound call (email delivery, analytics, partner APIs) its own line in the inventory. Check inbound routes too, such as loaders that still run on-premises.</p><p><strong>Object storage.</strong> If browser or mobile clients read buckets directly, the CORS rules move with the buckets. If bucket names change, find every place a name is stored.</p><p><strong>Edge protection.</strong> Check what sits in front of production that the lower environments lack. One of our APIs was behind a web application firewall only in production, and a deployment that rewrote its DNS record would have broken it.</p><h3>6. Cutover: rehearse it the same way every time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RE_9TT8d5a77DR2fhiz5Xg.png" /></figure><p>Cut over the lowest environment exactly the way you will cut over production. People will ask why QA needs this much ceremony. QA is the only rehearsal production gets.</p><ul><li><strong>Use one runbook format for every environment.</strong> Ours had a preparation tab, a cutover tab, a rollback tab and a DNS tab. Every row had a date, time, duration, team, owner and status.</li><li><strong>Write the application test cases before the first environment.</strong> Run the same set in every environment.</li><li><strong>Get a sign-off from each team.</strong> Once before the window and again after it.</li><li><strong>Script every cutover and rollback command.</strong> Store the scripts before the night.</li><li><strong>Say ahead of time what a lower environment cannot prove.</strong> A production-only firewall, a registrar change and a disaster-recovery copy are typical.</li><li><strong>Give cleanup its own change request.</strong> We had two people present for every bucket deletion.</li></ul><p>Our rehearsals showed that deployments had to finish before the window, that published DNS had to be checked against expected results, and that the cutover needed an application redeploy. Each of those would have been a surprise in production.</p><p>For a sense of scale, our production runbook budgeted about forty minutes from cutting traffic to sign-off.</p><h3>7. Monitoring, retention and cost: decide early</h3><p><strong>Monitoring.</strong> Set up monitoring and central logging in the new environment before the cutover. Put full coverage of databases and application URLs on the production readiness list. Stay on one approved logging path. If the cluster auto-instruments applications, a new service comes up already covered.</p><p><strong>Retention.</strong> Autoscaling without retention is a bill that grows quietly. Set retention at every layer as it is built: log indices, database logging tables, buckets and container images. We left some of these until after cutover, and I would not do that again.</p><p><strong>Cost.</strong> The cost lessons are mostly about deciding early:</p><ul><li>Pick instance classes before the build, so reserved capacity can be planned.</li><li>Run the consolidated cluster on reserved instances.</li><li>Create temporary instances with volumes that delete on termination.</li><li>Question any design that copies data between accounts more than it needs to.</li><li>Ask whether every log line is needed before paying to ship and store it.</li></ul><h3>8. Compliance: build it to pass the audit</h3><p>If the platform falls under HIPAA, SOC 2 or another framework, find out before the design starts. The framework decides encryption, access, logging and retention. Building those in costs far less than retrofitting them before an audit.</p><p><strong>Which services are allowed?</strong> In a regulated environment, confirm that every service in the design is covered by your agreement with the cloud provider. For HIPAA on AWS, that means the HIPAA-eligible services under your business associate agreement.</p><p><strong>What do the applications write to logs?</strong> Review this before the logs are shipped anywhere central. Sensitive values should be masked in the application. A migration that centralizes logging also centralizes any leak.</p><p><strong>If sensitive data does reach the logs, are the logs secure?</strong> Assume it will happen once. For CloudWatch Logs, encrypt the log groups with a KMS key and limit who can read them through IAM. Set a retention period on every group, because the default keeps logs forever. Consider a data protection policy that masks known patterns.</p><p><strong>Can the architecture produce evidence?</strong> An auditor asks for proof. Think about what the new environment will show for each control:</p><ul><li>Access by role, with no shared or static credentials.</li><li>Encryption in transit and at rest for every data store.</li><li>An audit trail for API activity and for database access.</li><li>Change records for the migration: approvals, sign-offs and the runbook.</li><li>Restore tests for backups.</li><li>No production data in lower environments, or masked data only.</li></ul><p>A multi-account structure helps here, because guardrails are set once at the organization level and every new account inherits them. An engine upgrade can help too, when the newer version brings audit features.</p><h3>9. Disaster recovery and backups: design them with the migration</h3><p>Disaster recovery is easy to leave for later. Start it at scoping, because it changes region, network and cost decisions.</p><p><strong>What are the targets?</strong> Agree a recovery time and a recovery point for each component with the product owner. Those two numbers pick the pattern: backup and restore, pilot light, warm standby or active-active. Each step up costs more.</p><p><strong>What does each layer of the stack support?</strong> Go through the stack and write down the recovery option for every layer:</p><ul><li><strong>Database.</strong> Cross-region replica or global database, or restore from copied snapshots.</li><li><strong>Object storage.</strong> Cross-region replication.</li><li><strong>Search cluster.</strong> Snapshots copied to the second region, or cross-cluster replication.</li><li><strong>Compute.</strong> Images replicated to a registry in the second region, cluster rebuilt by automation.</li><li><strong>DNS and traffic.</strong> Health checks and failover routing.</li><li><strong>Secrets and configuration.</strong> Replicated, or re-created by the same automation.</li></ul><p><strong>Can the second region hold the same design?</strong> Check that it offers the same services, the same instance classes and enough availability zones. Plan its subnets and address ranges next to the primary’s so they do not overlap. Check service quotas there too.</p><p><strong>Are snapshots enough?</strong> Decide whether platform snapshots meet the requirement, or whether a regulation asks for separate, longer-term copies. Either way, test a restore.</p><p><strong>How long is everything kept?</strong> Design retention for each class of data: backups, snapshots, logs and archives. Tie each period to the requirement behind it.</p><p><strong>What happens to the legacy data?</strong> Old on-premises or legacy backups and archives carry retention obligations that outlive the migration. Choose for each one: carry it into the new environment on an archive storage tier, keep the old system read-only until the period ends, or dispose of it with a sign-off. Answer this before the old environment is decommissioned.</p><p><strong>Has it been exercised?</strong> Rehearse a failover the way you rehearse the cutover. Until then it is only a plan.</p><h3>My take</h3><p>A migration is mostly coverage. Know what you have, decide what changes now and what waits, move the data with a rollback you have tested, and rehearse the cutover in every environment. In my experience the hard moments come from things nobody wrote down far more often than from the technology.</p><p>It is also never one person’s work. Application, database, DevOps and network engineers build it. The lead’s job is to keep the scope honest, the plan visible and the teams talking to each other.</p><p>With a clear scope, a complete architecture diagram, a regular scrum and a firm timeline, and with AI tools to speed up the inventory and runbook work, three to five months is a fair plan for most platform migrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nO082LmTDZoknR48fyr2kA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4276821a23ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not Every Slow Query Needs a New Index]]></title>
            <link>https://medium.com/@pranayraavi/not-every-slow-query-needs-a-new-index-b2e295354f4c?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e295354f4c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[performance-tuning]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 02:58:38 GMT</pubDate>
            <atom:updated>2026-11-04T02:58:38.914Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>What a SQL review taught me about assumptions, AI-written queries, and common-sense tuning</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bXnt8iua3NRN9b_g.png" /></figure><p>A development team asked me to review the SQL behind a change-data publishing job before they moved it from once a day to once an hour. In QA, one full run took 10 to 12 minutes. After the review, the same run took under 30 seconds. In production, most of its queries now finish in under a millisecond.</p><p>Almost none of that came from adding indexes. It came from reading the queries, asking what the job actually needed, and checking each assumption against real data. This post walks through what we found, in the order we found it, and what I would tell any team (or any AI assistant) writing SQL against a busy production database.</p><p>The short version:</p><ul><li>You don’t always need to tune the database. Often you need to understand the use case and explain how the database behaves.</li><li>Functions on indexed columns and “this column might be null” assumptions are the most common silent performance killers.</li><li>What is harmless in QA can be dangerous in production, because the data is shaped differently.</li><li>An index can make a query slower. Measure after every change.</li></ul><h3>The setup</h3><p>The job polls a PostgreSQL read replica for rows that changed since its last run and publishes them as events. It is a classic checkpoint pattern:</p><ol><li>Read a ceiling: the newest change timestamp in the source tables.</li><li>Count the rows changed between the last checkpoint and that ceiling.</li><li>Page through them with keyset pagination, 500 rows at a time.</li><li>Store the ceiling as the next checkpoint.</li></ol><p>I’ll use a generic schema for the examples:</p><p>TableRows (largest)What it holdsaccounts~1MUsers, organizations and partners, with an account_type columncontracts~1,100Partner contracts, keyed by the owning accountmemberships~650kWhich accounts belong to which organization, with a membership_typeorg_members~9MAccount-to-location assignmentslocations~hundreds of kOrganization addresses</p><p>Every table has created_at and updated_at. The source system also maintains updated_at_num, a numeric YYYYMMDDHHMISS copy of updated_at, and that column is indexed on every table. Keep that last detail in mind.</p><h3>Lesson 1: A function on an indexed column throws the index away</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*HmOWh95Q9-UPcBae.png" /></figure><p>Every change-window filter in the job looked like this:</p><pre>WHERE COALESCE(a.updated_at, a.created_at) &gt;  :checkpoint<br>  AND COALESCE(a.updated_at, a.created_at) &lt;= :snapshot</pre><p>The intent is reasonable: if a row was never updated, fall back to its creation time. But PostgreSQL can only use a B-tree index when the predicate matches the indexed expression. Wrap the column in COALESCE, and the index on updated_at (or updated_at_num) is no longer a candidate. Every window query became a sequential scan of the whole table.</p><p>The COALESCE also encoded an assumption: that updated_at can be null. So before changing anything, we checked:</p><pre>SELECT count(*) FROM accounts WHERE updated_at IS NULL;      -- 0<br>SELECT count(*) FROM accounts WHERE updated_at_num IS NULL;  -- 0</pre><p>Zero on every table. The source system sets both timestamps when a row is created, so the fallback could never fire. The fix was to drop the function and filter on the indexed column directly:</p><pre>WHERE a.updated_at_num &gt;  :checkpoint<br>  AND a.updated_at_num &lt;= :snapshot</pre><p>That one change turned every window query into an index range scan.</p><p>Two things to take from it:</p><ul><li><strong>Don’t defend against a condition until you’ve checked whether it exists.</strong> A one-line count(*) settled a question the code had been paying for on every run.</li><li><strong>If you really do need the fallback, write it so it can use an index.</strong> Either (updated_at &gt; x AND updated_at &lt;= y) OR (updated_at IS NULL AND created_at &gt; x AND created_at &lt;= y), or an expression index on exactly COALESCE(updated_at, created_at).</li></ul><h3>Lesson 2: What is fine in QA can bite in production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*waECdFbC4JiW5nOx.png" /></figure><p>The COALESCE wasn&#39;t the only defensive habit. One query filtered on TRIM(a.account_type) = &#39;STAFF&#39;. In QA that is harmless: small tables, fast scans, correct results. In production it does two quiet things:</p><ul><li>It stops any index on account_type from being used.</li><li>It hints that some values might be padded with spaces. If that were true, every <em>other</em> query that compares account_type without TRIM would silently miss those rows.</li></ul><p>Again, the answer was in the data:</p><pre>SELECT count(*) FROM accounts WHERE account_type &lt;&gt; TRIM(account_type);  -- 0</pre><p>No padded values, so the TRIM came out, and the queries became consistent with each other.</p><p>I want to be clear about where this comes from. The developers I work with write good SQL. But we are now in an era where a lot of SQL is drafted by AI assistants, and they are very good at producing queries that return the right answer. They are much less good at knowing your data. A model will happily add COALESCE, TRIM, LOWER or DISTINCT &quot;just in case&quot;, because in the abstract each one is safer. On a 10,000-row QA table you&#39;ll never notice. On a 10-million-row production table, each one can turn an index lookup into a full scan.</p><p><strong>The result being correct does not mean the assumptions behind it are.</strong> Before a query ships, check it against the data’s real shape: null counts, value distributions, duplicates, and how skewed the busiest keys are. Or ask a database engineer to review it. It never hurts.</p><h3>Lesson 3: Carry every filter you know into the subquery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*kFnyoX5syG2k7b0E.png" /></figure><p>The partner-count query looked like this:</p><pre>SELECT count(*)<br>FROM contracts c<br>JOIN accounts a ON a.account_id = c.account_id<br>WHERE c.org_id = :org<br>  AND a.updated_at_num &gt; :checkpoint AND a.updated_at_num &lt;= :snapshot<br>  AND c.account_id IN (<br>        SELECT DISTINCT m.parent_account_id<br>        FROM memberships m<br>        WHERE m.membership_type = &#39;PRIMARY&#39;<br>          AND m.is_deleted = false<br>          AND (m.end_date IS NULL OR m.end_date &gt;= :as_of));</pre><p>The outer query was narrowed to one organization and a one-hour window: 59 candidate rows. The subquery wasn’t narrowed at all. PostgreSQL read <strong>1.77 million</strong> membership rows, built a distinct list of 831 IDs, then matched that list against the 59 candidates. That was 31,395 buffers and 83 ms to return a count of zero.</p><p>Two changes fixed it:</p><pre>AND EXISTS (<br>        SELECT 1<br>        FROM memberships m<br>        WHERE m.parent_account_id = c.account_id   -- correlate to the outer row<br>          AND m.org_id = :org                      -- the filter the outer query already had<br>          AND m.membership_type = &#39;PRIMARY&#39;<br>          AND m.is_deleted = false<br>          AND (m.end_date IS NULL OR m.end_date &gt;= :as_of));</pre><p>IN (SELECT DISTINCT …)Correlated EXISTS with filtersExecution time83 ms0.8 msBuffers31,395181Memberships accessParallel sequential scanIndex lookup per candidate</p><p>A note on IN versus EXISTS: PostgreSQL already turns IN (subquery) into a semi-join, so the two often plan the same way. The DISTINCT adds nothing, since a semi-join never returns a row twice, and it can push the planner toward building the full list first. Switching to EXISTS helps. <strong>The bigger win is adding the filter.</strong> If the outer query is limited to something you also know about the subquery&#39;s rows, say so in the subquery too. Don&#39;t rely on the planner to infer it.</p><h3>Lesson 4: Ask what a query is for before you tune it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JzkByikErFG3wxhg.png" /></figure><p>The slowest query in the job didn’t return any data. It computed the run’s ceiling:</p><pre>SELECT max(ts) FROM (<br>    SELECT max(updated_at_num) AS ts FROM accounts WHERE account_type IN (...)<br>    UNION ALL<br>    SELECT to_char(max(password_changed_at), &#39;YYYYMMDDHH24MISS&#39;)::numeric FROM accounts WHERE account_type IN (...)<br>    UNION ALL<br>    SELECT max(updated_at_num) FROM org_members<br>    UNION ALL<br>    SELECT max(s.updated_at_num)<br>    FROM staff_links s JOIN accounts a ON a.account_id = s.account_id AND a.account_type = &#39;STAFF&#39;<br>) x;</pre><p>It took 853 ms and about 1 million buffers to return one number. The plan showed three different behaviours:</p><p>BranchHow PostgreSQL ran itCostmax(updated_at_num) on one tableBackward index scan, stops at the first row0.2 msmax(password_changed_at)Sequential scan; the column has no index~590 msmax(...) over a joinFull join of every staff account, then aggregate~270 ms</p><p>PostgreSQL has a neat shortcut here. As the CREATE AGGREGATE documentation explains, a MIN- or MAX-like aggregate can be answered from an index, because SELECT max(col) FROM tab is equivalent to SELECT col FROM tab ORDER BY col DESC LIMIT 1. The planner walks the index backward and takes the first non-null value. It also works on partitioned tables and UNION ALL views, by merging each child&#39;s index. <strong>It does not work through a join.</strong> The planner source (planagg.c) limits the shortcut to queries that reference exactly one table, so the join branch had to build the whole join just to find its largest value.</p><p>That is where understanding the use case matters more than tuning. This value is an upper bound for the next change window. It doesn’t have to be the exact newest staff row; it only has to be at least as high. Dropping the join and taking max(updated_at_num) over all of staff_links gives a bound that is never lower, and costs a single index probe. The join filter still applies in the query that reads the window.</p><p>The same review turned up a second easy win. The ceiling was global, but the job ran it once per scope, inside a loop, so it returned the same value several times per run. Computing it once per run cost nothing to change.</p><p>The password_changed_at branch I left alone. More on that in Lesson 6.</p><h3>Lesson 5: A test that returns zero rows proves nothing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Vpnj1BcsU6rpHZ9X.png" /></figure><p>My first round of EXPLAIN ANALYZE used a one-hour window, the job&#39;s steady state. Most queries looked great: under a millisecond. Then I noticed how often the plans said (never executed). In that hour, no organization had changed, so every join after the first step was skipped. The plan was cheap because there was no work, not because the work was cheap.</p><p>Widening the window to 30 days told a different story. One query that ran in 0.7 ms on the hourly window chose a completely different plan:</p><ul><li>It started from the membership table instead of the changed rows.</li><li>It read every one of the 15,368 primary memberships, then probed accounts for each.</li><li>It found 31 changed rows, after 72,522 buffers.</li></ul><p>The cause was a row estimate. The planner expected 188 primary memberships and got 15,368, about 80 times more. With 188, starting from memberships looks cheap. A likely reason is how PostgreSQL combines filters: by default it multiplies each condition’s selectivity as if they were independent, so correlated filters (type, deleted flag, end date) can be badly underestimated. Check that statistics are fresh with ANALYZE first. If the columns really are correlated, CREATE STATISTICS can tell the planner how they relate.</p><p>So I now test every change-data query with three windows:</p><p>WindowWhat it tells youNormal (one hour)Steady-state costWide (30 days)What happens after an outage or a missed runFull historyThe very first run, when the checkpoint is empty</p><p>The first run is easy to forget. Here it was fine: page one of the full-history query took about 20 ms, because the planner could stop as soon as it had 500 rows. But you only know that by running it.</p><h3>Lesson 6: “Good enough” is a valid result. Index only what doesn’t scale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dn_HCEyLuPDZOYVY.png" /></figure><p>After the rewrites, I had a list of index candidates that would have made every remaining query near-instant: one on password_changed_at, a partial index for a rare account type, and a few more. Before building any of them, I added up what an hourly run actually cost without them:</p><p>Part of the runCostCeiling queries, once per run~1.5–1.8 sChange-window queries, per scope~1.2 s for the largest<strong>Whole run~6–7 s, every buffer from cache</strong></p><p>The slowest single statement was under a second, far from any timeout. Every index you add costs writes, storage and maintenance forever, and here the database was a replication target that would pay for each one on every write. So most of the candidates were dropped. That is a fine outcome. Not every slow-looking query needs an index; sometimes it needs nothing.</p><p>One query was different, because its cost multiplied. It loaded full account details in chunks of 100 IDs, and each chunk joined org_members on account_id, a column with no index. Every chunk scanned a 9-million-row table: about 0.7 s.</p><p>ScenarioAccounts to loadChunksTimeHourly~501~0.7 s30-day catch-up~20,000~200~2.5 minFirst run~870,000~8,700<strong>~1.7 hours</strong></p><p>That is the test I use now: <strong>don’t ask whether a query is slow, ask whether its cost grows with the data or the backlog.</strong> Fixed costs can usually be tolerated. Costs that multiply need an index. We added exactly one: org_members (account_id).</p><h3>Lesson 7: A new index can make a query slower</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*f1ud-iTTmh55hdid.png" /></figure><p>The new index worked exactly as planned: the org_members step went from scanning 5.4 million rows to reading 2,217 buffers. Then I looked at the total for the chunk query. It had gone from <strong>723 ms to 26.9 seconds</strong>.</p><p>Before the indexAfter the indexorg_membersParallel sequential scan, 174k buffersIndex scan, 2,217 buffersmembershipsOne scan of the 15k primary rows, hashed7,191 index probes, each discarding ~14,000 rowsTotal723 ms, 243k buffers26,872 ms, 22.7M buffers</p><p>With org_members suddenly cheap, the planner switched to a nested loop and probed memberships once per organization row through an index on org_id. That index holds every membership in the organization, one per member account. The accounts in this chunk belonged to very large organizations, so each probe walked about 14,000 entries to find the one primary membership it needed.</p><p>The planner expected roughly one row per probe. When it knows a value in advance, PostgreSQL can look it up in its most-common-values statistics. Here each probe’s value came from the outer row at run time, so the planner estimated an average number of rows per organization. The handful of very large organizations didn’t fit that average, and re-running ANALYZE doesn&#39;t change how the estimate is made.</p><p>The fix was another index, but a very small one: a partial index containing only the rows the query asks for.</p><pre>CREATE INDEX CONCURRENTLY memberships_primary_org_idx<br>    ON memberships (org_id) INCLUDE (parent_account_id, end_date)<br>    WHERE membership_type = &#39;PRIMARY&#39; AND is_deleted = false;</pre><p>It holds about 15,000 rows instead of 650,000, so it is small and cheap to maintain, and each probe now lands directly on the row it needs. PostgreSQL uses a partial index only when it can prove, at planning time, that the query’s WHERE clause implies the index predicate. The docs point out that a bind parameter such as membership_type = $1 can&#39;t prove that. Because this query uses membership_type = &#39;PRIMARY&#39; AND is_deleted = false as literal values, the planner can match the partial index without any code change.</p><p>The lesson isn’t “avoid indexes”. It’s that <strong>an index changes the plan around it</strong>, not just the step it targets. Re-run the full EXPLAIN ANALYZE after every index, and read the total, not just the line you were fixing.</p><h3>Building the indexes online</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*kkD8xhkmSnCk_Sx1.png" /></figure><p>Both indexes went in with CREATE INDEX CONCURRENTLY, so writes kept flowing. A few things I check every time:</p><p><strong>1. Look for old transactions first.</strong> Per the CREATE INDEX docs, a concurrent build waits before each table scan for transactions that have modified the table, and after the second scan for any transaction holding a snapshot older than that scan. My pre-check found 65 sessions from a replication tool sitting idle in transaction for 28 days. Before cancelling anything, check whether they actually matter:</p><pre>SELECT count(*) AS sessions,<br>       count(backend_xmin) AS holding_snapshot,<br>       count(backend_xid)  AS holding_xid<br>FROM   pg_stat_activity<br>WHERE  state = &#39;idle in transaction&#39;<br>  AND  now() - xact_start &gt; interval &#39;1 day&#39;;</pre><p>Ours held no snapshot, no transaction ID and no locks on the target tables, so they couldn’t block the build or hold back vacuum. That’s a cleanup item, not a blocker.</p><p><strong>2. Run with autocommit on.</strong> CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and some SQL clients wrap scripts in one.</p><p><strong>3. Decide on </strong><strong>lock_timeout deliberately.</strong> It lets a build fail fast instead of queueing behind a long transaction, but a build that fails partway leaves an invalid index behind. I left it unset and watched the progress view instead.</p><p><strong>4. Check for invalid indexes afterwards.</strong> CREATE INDEX ... IF NOT EXISTS sees an invalid leftover&#39;s name and skips it with only a NOTICE. Drop it with DROP INDEX CONCURRENTLY and build again, or rebuild it with REINDEX INDEX CONCURRENTLY.</p><pre>SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;</pre><p><strong>5. Build smallest to largest</strong>, and watch replication lag during the big ones.</p><h3>A review checklist</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*YdmE6NKTAVhKyNiD.png" /></figure><p>This is what I now run through for any SQL headed to a large production table, whether a person or an AI wrote it.</p><p><strong>Predicates</strong></p><ul><li>No functions wrapped around indexed columns in WHERE or JOIN (COALESCE, TRIM, LOWER, casts, date math).</li><li>Every “defensive” expression is backed by a data check: null counts, padded values, duplicate keys.</li><li>Filters the outer query knows are repeated inside subqueries and on every joined table.</li><li>IN (SELECT DISTINCT ...) replaced with a correlated EXISTS, or at least the DISTINCT dropped.</li><li>Partial-index conditions written as literals, not bind parameters, so the planner can match them.</li></ul><p><strong>Purpose</strong></p><ul><li>For each query, what is it <em>for</em>? A ceiling, a count or a page may not need the precision it was written with.</li><li>Values that don’t change within a run are computed once per run, not inside a loop.</li><li>Keyset pagination sorts on a unique key, or ends with a unique tie-breaker.</li></ul><p><strong>Evidence</strong></p><ul><li>EXPLAIN (ANALYZE, BUFFERS) on production-sized data, for normal, wide and first-run windows.</li><li>No (never executed) hiding the parts you care about.</li><li>Estimated versus actual rows compared; a gap of 10x or more is worth chasing.</li><li>Costs that multiply (per chunk, per page, per backlog hour) indexed; fixed costs judged against the schedule.</li><li>The full plan re-run after every new index.</li></ul><h3>Closing: tuning is mostly a conversation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fc_nEUoCV01aAUVQ.png" /></figure><p>Looking back, the biggest gains came from questions, not configuration:</p><ul><li>“Can this column actually be null?” No, so the COALESCE went, and the existing index started working.</li><li>“What is this MAX used for?&quot; An upper bound, so it didn&#39;t need the expensive join.</li><li>“Does this cost grow with the backlog?” Only in one place, so we added one index instead of six.</li></ul><p>None of that needed database expertise the developers couldn’t learn. It needed someone to explain how the planner reads a predicate, why a function hides an index, and why QA data isn’t evidence for production. Once that was clear, the developer rewrote the queries himself, and the run time in QA went from 30–50 minutes to under 30 seconds.</p><p>Some tuning really is just common sense and basic troubleshooting: read the plan, check the data, and ask what the query is for. If your team writes SQL, especially with an AI assistant drafting it, get a database engineer to look at it before it meets production data. It never hurts, and sometimes it saves you an hour-long first run, or a 27-second query you didn’t know you had.</p><h3>References</h3><ul><li><a href="https://www.postgresql.org/docs/current/sql-createaggregate.html">CREATE AGGREGATE</a>: how MIN/MAX-like aggregates use an index</li><li><a href="https://doxygen.postgresql.org/planagg_8c_source.html">planagg.c</a>: the MIN/MAX optimization and its single-table restriction</li><li><a href="https://www.postgresql.org/docs/current/indexes-expressional.html">Indexes on Expressions</a></li><li><a href="https://www.postgresql.org/docs/current/indexes-partial.html">Partial Indexes</a></li><li><a href="https://www.postgresql.org/docs/current/indexes-index-only-scans.html">Index-Only Scans and Covering Indexes</a></li><li><a href="https://www.postgresql.org/docs/current/row-estimation-examples.html">Row Estimation Examples</a>: MCV lists, averages and combining conditions</li><li><a href="https://www.postgresql.org/docs/current/planner-stats.html">Statistics Used by the Planner</a>: including extended statistics</li><li><a href="https://www.postgresql.org/docs/current/using-explain.html">Using EXPLAIN</a></li><li><a href="https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY">CREATE INDEX: Building Indexes Concurrently</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e295354f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Elasticsearch Backups Are Only as Good as Their Retention Policy]]></title>
            <link>https://medium.com/@pranayraavi/your-elasticsearch-backups-are-only-as-good-as-their-retention-policy-d71f4d97f0ed?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71f4d97f0ed</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 16:57:30 GMT</pubDate>
            <atom:updated>2026-10-28T17:07:07.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7ULL_TLLmzDRdrpM.png" /></figure><p>What I learned building 15-minute-to-7-year snapshot tiers on AWS, and the one S3 setting I almost got wrong</p><p>A backup has three jobs. It has to exist, it has to be recent enough, and it has to still be there when someone needs a version from long ago. Most backup setups do the first job well and quietly fail the other two.</p><p>I recently rebuilt backups for a production Elasticsearch cluster on AWS, in an environment where audits are routine and “we think it’s backed up” is not an answer. I want to share the design, because the interesting decisions weren’t about taking snapshots. They were about time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*N5H15sdhPvoYdfIm.jpeg" /></figure><h3>Start with the questions, not the tools</h3><p>Before touching anything, I wrote down what the business would actually ask during an incident or an audit:</p><ul><li>If the cluster dies right now, how much data do we lose?</li><li>If someone deletes an index on a Friday and notices on Monday, can we get it back?</li><li>If an auditor asks for last year’s state, do we have it?</li><li>What credentials does the backup job hold, and who rotates them?</li></ul><p>Each question maps to a different time horizon. One schedule can’t serve minutes and years at once without either wasting storage or losing history. That’s what pushed me to tiers.</p><h3>Four tiers, one bucket</h3><p>Elasticsearch has a built-in scheduler called Snapshot Lifecycle Management (SLM). I created four SLM policies, each with its own schedule and retention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*Giw3WWPlOM05LAK1HBkPGA.png" /></figure><p>The 15-minute tier covers only the most critical indices, which keeps it small and fast. SLM won’t schedule anything more often than every 15 minutes by default, and that’s a useful constraint: if you need tighter recovery than that, you need replication, not backups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*900r4pl-nYM_zaAp9Lmj5Q.jpeg" /></figure><p>All four tiers write to one encrypted Amazon S3 bucket, each in its own folder and registered as its own snapshot repository. That separation costs some storage, since the long-term tiers can’t reuse files from the hourly ones. In exchange, cleaning up one tier can never damage another. For data you’re keeping for seven years, I’ll take that trade.</p><h3>No keys, anywhere</h3><p>The old pattern for this is an access key in a config file. I didn’t want any static credentials in the cluster, so every node runs with an IAM role attached through an EC2 instance profile. Elasticsearch’s S3 client picks up short-lived credentials automatically when no keys are configured.</p><p>The catch: Elasticsearch verifies a new repository from every master and data node. One node missing the role, and the whole registration fails with an unhelpful error. The IAM policy has a similar trap. It needs permissions on the bucket itself (to list it) and separately on the objects inside it (to read and write). Forget either half and you get access denied with a policy that looks correct at a glance.</p><h3>The setting I almost got wrong</h3><p>S3 has lifecycle rules that delete objects after a set number of days. It looks like the obvious way to enforce retention. It’s the wrong tool here.</p><p>Elasticsearch snapshots are incremental. A snapshot from today may depend on files written weeks ago. An S3 rule that deletes files by age has no idea which ones are still referenced, so it can silently break newer snapshots. You find out during a restore, which is the worst possible time.</p><p>So SLM owns retention. It deletes whole snapshots and only removes files nothing else needs. S3 is just durable, encrypted storage. That one decision is the difference between a backup system and a pile of files that looks like one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JS2yhpYQVcu7j_Brk7zwdg.jpeg" /></figure><h3>Restore is the real product</h3><p>Nobody wants backups. People want restores. I documented two paths: a full-cluster restore for disasters, and a selective restore that brings specific indices back under a new name, so you can compare before you swap anything live.</p><p>The call is short enough to remember under pressure:</p><pre>POST _snapshot/es-backup-daily/&lt;snapshot-name&gt;/_restore<br>{<br>  &quot;indices&quot;: &quot;app-critical-orders&quot;,<br>  &quot;rename_pattern&quot;: &quot;(.+)&quot;,<br>  &quot;rename_replacement&quot;: &quot;restored-$1&quot;<br>}</pre><h3>What I’d tell someone starting this</h3><ol><li>Write down the recovery questions first. The tiers fall out of them.</li><li>Let the database manage its own backup retention. Storage-level expiry doesn’t understand dependencies.</li><li>Use roles, not keys, and check every node, not just one.</li><li>Treat restore as the deliverable. Test it on a schedule, not during an outage.</li></ol><p>The whole system is a bucket, a role and four policies. It’s not glamorous. But when someone asks how much data you’d lose, how far back you can go and what credentials are involved, you can answer each in one sentence. That’s the real deliverable.</p><p><em>If you’ve built long-term retention for search clusters differently, I’d like to hear about it in the responses.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71f4d97f0ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Is What “AI for Everyone” Actually Means.]]></title>
            <link>https://medium.com/@pranayraavi/this-is-what-ai-for-everyone-actually-means-f05836982086?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05836982086</guid>
            <category><![CDATA[ai-for-human]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[traffic-ticket]]></category>
            <category><![CDATA[future-of-life]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 12:58:40 GMT</pubDate>
            <atom:updated>2026-08-26T01:48:22.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*0xbaON2UO0mFwuBaQGyAEA@2x.jpeg" /></figure><p><em>I had a vague memory, a 16-year-old traffic ticket, and no idea which county it was in. One conversation changed that.</em></p><p>There’s a version of this story where I spend three weeks cross-referencing Florida county boundary maps with Google Maps, calling clerk’s offices one by one, getting transferred, leaving voicemails that go unanswered, and eventually giving up — accepting that something from 2010 is simply gone.</p><p>That version didn’t happen. And the reason it didn’t is something I’m still a little amazed by.</p><h3>June 2010. Tampa to Virginia Beach.</h3><p>I was driving up to see my fiancée for the weekend.</p><p>Anyone who has ever made a road trip fueled by that specific kind of excitement — the kind where you’re counting miles instead of watching them — knows the feeling. I was young, I was happy, and I was looking for a route that avoided the toll roads because, well, why pay when you don’t have to?</p><p>So I took US-301 north out of Tampa — a long, winding state highway that cuts through small Florida towns instead of the interstate. It was scenic. It was free. And somewhere along the way, somewhere in Florida, the speed limit dropped. Fast. From 55 to 45 to 30 in what felt like the span of a few hundred yards. There were police waiting. It felt, frankly, like a trap.</p><p>I got a ticket. I paid it. I drove on, got to Virginia Beach, and didn’t think about it much after that.</p><h3>2026. A Box of Old Memories, and a Search With No Map.</h3><p>Sixteen years later, I needed to find that ticket.</p><p>I was pulling together documentation for some important government paperwork, and I needed to account for every traffic citation going back years. Most I could reconstruct easily — I had records, receipts, memories clear enough to work from. But this one? I had almost nothing.</p><p>What I had was a feeling.</p><p><em>Somewhere in Florida. No-toll route. Speed limit kept dropping. They seemed to be pulling over a lot of out-of-state drivers. I was on my way to Virginia Beach. I paid it. I think I paid it.</em></p><p>That’s not exactly a filing system.</p><p>The traditional approach would have been brutal. Florida has 67 counties. The ticket could have been in any one of a dozen that sit along that north-south corridor between Tampa and Jacksonville. I would have had to somehow overlay a 2010 road trip route with a county boundary map, guess which jurisdiction I might have been in, find the right clerk’s website, hope they had records going back that far, and repeat — county by county — until something matched or I ran out of patience.</p><p>I’ve done that kind of research before. It’s the kind of thing that makes you feel like a detective and a bureaucrat at the same time, and not in a good way. It’s exactly the kind of thing that ends with giving up.</p><h3>What AI Did Instead.</h3><p>I described what I remembered to an AI assistant. Not in a structured, precise way — just the way you’d tell a story to a friend over coffee. <em>I was driving from Tampa to Virginia Beach, avoiding tolls, probably US-301, and somewhere the speed limit dropped suddenly from 55 to 45 to 30 and they were pulling over a bunch of drivers.</em></p><p>Within moments, the AI came back with something I hadn’t expected: a name.</p><p><strong>Waldo, Florida.</strong></p><p>It explained that Waldo — a small town on US-301 in Alachua County — was one of the most infamous speed traps in the entire United States. For years, it had up to six different speed limits within a span of just a few miles. Drivers coming off the highway at 65 would find themselves suddenly, technically, in violation. The town’s police department eventually became the subject of a state investigation for illegal ticketing quotas and was formally disbanded in 2014. The AAA had declared it a speed trap as far back as 1995.</p><p>The AI told me the county (Alachua), the court (Alachua County Courthouse in Gainesville), and where to look online — all from a vague memory and a driving direction.</p><p>I called the clerk’s office on the first try. One call. Right county. Right case.</p><h3>The Part That Stays With Me.</h3><p>I say this as someone who is very much a tech person. I’ve spent the last four years building with AI daily — writing code, designing APIs, spinning up local LLMs, shipping full-scale applications. I use it at work and I use it at home. I’ve even used it to write bedtime stories for my son, to generate coloring pages customized exactly to whatever he’s obsessed with that week, tweaked and iterated until they’re just right for him.</p><p>I know what these tools can do in professional contexts. I know their limits. I’ve pushed on both.</p><p>And yet this moment — a mundane, personal, bureaucratic moment — is the one that made me pause.</p><p>What struck me was this: the AI didn’t just search. It <em>reasoned</em>. It took something fragile — a feeling, a half-memory, a sense that something sketchy had happened on a road I couldn’t quite name — and it connected that to real history, real geography, real institutional knowledge about how a small Florida town had operated in 2010.</p><p>It knew that out-of-state drivers on US-301 had a particular experience in Waldo. It knew the pattern. And when I described my experience, it recognized it.</p><p>That’s not a database lookup. That’s something closer to what happens when you describe a situation to someone who has read widely, remembers well, and can say — <em>oh, I know exactly what you’re describing, and here’s where to look.</em></p><h3>The Quietly Revolutionary Part.</h3><p>When we talk about AI, we tend to talk about it in contexts that feel distant from ordinary life — coding assistants, enterprise software, research tools for specialists. The stories are usually about scale and speed and productivity in professional settings.</p><p>But I think the more quietly revolutionary thing is happening in moments like mine.</p><p>A weekend trip from 16 years ago. A ticket in a speed trap town that no longer even has a police department. A document I needed, buried in a county I couldn’t name, for paperwork that mattered.</p><p>Without AI, I would have started with guesswork, made a handful of wrong calls to wrong county clerks, and probably abandoned the search. With it, I made one call, to the right office, with the right case number, on the first try.</p><p>That’s not magic. But it’s also not nothing.</p><p>It’s the kind of help that used to require knowing the right person, or having the money to hire someone who did, or simply being lucky. Now it’s a conversation.</p><h3>A Note on That Drive.</h3><p>I did make it to Virginia Beach that weekend. The ticket didn’t ruin anything. My fiancée became my wife. We’ve built a life together, in a house in Northern Virginia, far from that stretch of US-301 and the speed trap I drove through on the way to her.</p><p>What I didn’t mention earlier: it happened again on the same trip. Virginia Beach wasn’t the final stop — I continued north to New York. And somewhere in Delaware, on that stretch of road, another sudden speed limit drop, another officer waiting exactly where the signs gave you the least possible time to react. Same feeling. Same outcome. Another ticket paid and filed away in the back of my mind for sixteen years.</p><p>When I went looking for that one too, I described it the same way — vague, directional, a sense of geography more than a fact. And again, the AI placed it. Different state, same pattern, same result: one call, right office, right case.</p><p>Two states. Two traps. Both found.</p><p>When I called the Florida clerk and confirmed that first case was closed — paid, resolved, gone — I felt something I hadn’t expected to feel about a decade-and-a-half-old traffic fine.</p><p>Relief. And a little gratitude.</p><p>Gratitude for a tool that treated my incomplete, imperfect memory as something worth working with — and found what I was looking for. Twice.</p><p><em>If you’ve ever had a moment where you needed to find something you almost couldn’t describe — a record, a document, a fact buried in time — you already know the problem this solves. The tool has changed. The feeling of finally finding something you thought was lost? That’s timeless.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05836982086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Auditing on AWS Aurora PostgreSQL]]></title>
            <link>https://medium.com/@pranayraavi/database-auditing-on-aws-aurora-postgresql-ee758aad3fe3?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee758aad3fe3</guid>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[pgaudit]]></category>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Fri, 22 May 2026 01:20:02 GMT</pubDate>
            <atom:updated>2026-05-22T01:20:02.365Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What a mature audit pipeline looks like, why PostgreSQL on AWS requires more assembly to get there, and every sharp edge encountered along the way</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQnkr6v9FthNsj716J_qaQ.png" /></figure><h3>Where This Came From</h3><p>Most operational infrastructure starts this way: a requirement appears before the architecture does.</p><p>One day, the team needed a database audit solution. Not in a planning doc — someone asked, and I had to build something. I’d already owned the Oracle audit pipeline, so I knew what the destination looked like. The question was what it would take to get there on Aurora PostgreSQL and AWS.</p><p>The experience revealed something worth documenting: the gap between what Oracle Unified Auditing gives you natively and what you have to assemble yourself on PostgreSQL is real, and the assembly process has sharp edges that aren’t surfaced in documentation. This article is the honest account of both.</p><h3>Defining the Audit Scope — and Why It Shapes Everything</h3><p>Before discussing tools, the scope needs to be precise.</p><p><strong>We are not auditing application traffic.</strong> Application service accounts are expected to read and write data — that’s their defined function. Auditing them generates noise at scale and produces no meaningful signal. The operational cost of sifting through application query logs looking for anomalies is prohibitive, and the likelihood of missing a real event in that volume is high.</p><p><strong>We are auditing individual human users with direct database access.</strong> In a regulated environment, this is the actual risk surface: a developer connected via psql running an exploratory query against production data, a support engineer making an undocumented change, a credential that was provisioned for troubleshooting and never revoked. These are low-frequency, high-consequence events — exactly what a well-designed audit system is built to catch.</p><p>This scope decision drives the implementation: pgAudit is enabled per individual user account, not cluster-wide. Service accounts are excluded entirely. The expected audit volume is low, which keeps overhead minimal and signal quality high.</p><h3>The Oracle Reference: What a Mature Audit Pipeline Looks Like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqCPH-2Zbw1x0qNldDhmTQ.png" /><figcaption><em>Oracle audit pipeline</em></figcaption></figure><p>Oracle Unified Auditing, an Enterprise-tier feature, provides policy-based audit configuration at the intersection of three independently filterable dimensions: <strong>user, action, and object</strong>. The combination is powerful because each dimension is an independent variable:</p><pre>-- Audit INSERT/UPDATE/DELETE on a specific table by all users except the service account<br>CREATE AUDIT POLICY user_dml_changes<br>  ACTIONS INSERT, UPDATE, DELETE ON app_schema.orders<br>  WHEN &#39;SYS_CONTEXT(&#39;&#39;USERENV&#39;&#39;,&#39;&#39;SESSION_USER&#39;&#39;) != &#39;&#39;APP_SVC_ACCOUNT&#39;&#39;&#39;<br>  EVALUATE PER SESSION;</pre><pre>AUDIT POLICY user_dml_changes;</pre><p>You can audit all writes by a specific user on any table, or all deletes across an entire schema, or a single sensitive table by everyone — defined in one statement. The audit record lands immediately in UNIFIED_AUDIT_TRAIL, a queryable SQL view:</p><pre>SELECT db_user, action_name, object_name, sql_text, event_timestamp<br>FROM unified_audit_trail<br>WHERE action_name IN (&#39;INSERT&#39;,&#39;UPDATE&#39;,&#39;DELETE&#39;)<br>  AND event_timestamp &gt; SYSDATE - INTERVAL &#39;5&#39; MINUTE;</pre><p>From there, export to any downstream platform on a schedule — the data is already structured. An Elasticsearch Watcher, a Splunk scheduled search, a query against a dedicated audit database — the downstream tooling choice is flexible precisely because the upstream is clean SQL. Most teams already operate a log analytics platform. The export is a standard query and a bulk insert.</p><p><strong>One critical operational risk with this approach:</strong> if the Oracle audit tablespace reaches capacity, the database halts rather than silently dropping audit records. This guarantees audit completeness at the cost of availability — a deliberate design choice that ensures the audit trail is never partially truncated. It means tablespace monitoring is not optional; it becomes a hard operational dependency. pgAudit writing to the PostgreSQL log stream sidesteps this failure mode entirely: if log delivery has issues, the database keeps running.</p><p><strong>On PostgreSQL with pgAudit</strong>, there’s no policy-based targeting at the object or action level. You set a log class per user: read, write, ddl, or all. The audit records flow into the PostgreSQL log stream — on Aurora, that means CloudWatch Logs. There&#39;s no queryable view. The raw output is text:</p><pre>2025-10-27 16:38:22 UTC:10.0.1.15(54321):john_doe@production:[1234]:LOG:<br>AUDIT: SESSION,1,1,WRITE,INSERT,TABLE,public.orders,<br>&quot;INSERT INTO orders (customer_id, amount) VALUES ($1, $2)&quot;</pre><p>It works. But extracting a structured, alertable signal from a log stream requires deliberate engineering — which is what the rest of this article covers.</p><h3>The Full Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmWg9YdZ9G-WD-MVxms2Lw.png" /><figcaption>Complete AWS pipeline</figcaption></figure><pre>Aurora PostgreSQL  (pgAudit per-user logging)<br>        │  pgAudit → PostgreSQL log stream<br>        ▼<br>CloudWatch Logs   /aws/rds/cluster/&lt;cluster&gt;/postgresql<br>        │<br>        ├──► CloudWatch Dashboard  (real-time Log Insights view)<br>        │<br>EventBridge  rate(5 minutes)<br>        │<br>        ▼<br>Lambda Function<br>  ├── Runs Log Insights query against last 5-minute window<br>  ├── Applies noise filter (tool queries, system catalogs excluded)<br>  ├── Counts remaining user DML operations<br>  └── Publishes UserDMLOperationCount → RDSAudit/UserActivity<br>        │<br>        ▼<br>CloudWatch Custom Metric  UserDMLOperationCount<br>        │<br>        ▼<br>CloudWatch Alarm  threshold: count &gt; 0<br>        │<br>        ▼<br>SNS Topic  rds-user-audit-alerts<br>  ├── HTTPS endpoint → incident management platform<br>  └── Email → engineering team</pre><p>The Lambda layer exists because of a fundamental limitation: <strong>CloudWatch Alarms cannot evaluate Log Insights query results directly.</strong> They evaluate metrics. Log Insights queries produce result sets. There is no native integration between them. Lambda bridges that gap: it runs the query, extracts the count, and publishes it as a standard metric that the alarm evaluates on the next cycle.</p><p>The Lambda invocation logs are also a second audit artifact. Every execution is recorded in CloudWatch with its output — the count of detected operations, the query window, the timestamp. This provides an independent, durable record of detection separate from the raw pgAudit stream, which matters when a compliance review asks “when was this activity first detected and by what mechanism?”</p><blockquote><strong><em>Full implementation:</em></strong><em> Lambda code, IAM policies, SNS resource policy, KMS key policy, CloudWatch alarm definition, and Terraform module → </em><a href="https://github.com/pcraavi/PostgreSQL-Audit"><em>github.com/pcraavi/PostgreSQL-Audit</em></a></blockquote><h3>Enabling pgAudit — and the Silent Failure Mode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl3olwLcoDNm9Uz_3oUSsg.png" /><figcaption>pgAudit setup sequence</figcaption></figure><p>Adding pgaudit to shared_preload_libraries in the cluster parameter group and rebooting is step one. What isn&#39;t obvious: shared_preload_libraries loads the library binary into PostgreSQL shared memory. It does not install the extension into the database catalog. That requires a separate statement:</p><pre>CREATE EXTENSION pgaudit;</pre><p>If this statement is skipped, the result is zero audit records and zero error messages. Nothing in CloudWatch. No warnings. The cluster appears healthy. The production issue this caused: the parameter was confirmed set, the cluster had been rebooted, log export was enabled, and queries against the CloudWatch log group returned nothing. The diagnostic was straightforward once we thought to look:</p><pre>SELECT * FROM pg_extension WHERE extname = &#39;pgaudit&#39;;<br>-- Returned 0 rows. That was the entire problem.</pre><p>One missing CREATE EXTENSION statement.</p><p>After the extension is installed, enable per-user logging for each individual human account:</p><pre>ALTER USER john_doe SET pgaudit.log TO &#39;all&#39;;</pre><pre>-- Confirm the configuration is applied<br>SELECT usename, useconfig FROM pg_user WHERE usename = &#39;john_doe&#39;;<br>-- useconfig: {pgaudit.log=all}</pre><p>Apply this to every individual human user with direct database access. Service accounts and application roles are deliberately excluded.</p><h3>The Noise Problem: Why Raw pgAudit Output Isn’t Enough</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZN3bY2FczjkSf_8fTh30ZA.png" /><figcaption><em>Signal vs noise funnel</em></figcaption></figure><p>The first query against raw audit logs in a production environment is clarifying. The signal-to-noise ratio is poor:</p><pre>AUDIT: SESSION,...,READ,SELECT,,,&quot;SELECT version()&quot;<br>AUDIT: SESSION,...,READ,SELECT,,,&quot;SELECT * FROM pg_shdescription JOIN pg_description...&quot;<br>AUDIT: SESSION,...,READ,SELECT,,,&quot;SET application_name=&#39;DBeaver 23.2.0&#39;&quot;<br>AUDIT: SESSION,...,READ,SELECT,,,&quot;SELECT oid, typarray FROM pg_type WHERE typname=$1&quot;<br>AUDIT: SESSION,...,READ,SELECT,,,&quot;SELECT current_schema()&quot;</pre><p>Every database client tool fires a sequence of catalog queries on connect. DBeaver, DataGrip, pgAdmin — each one runs multiple pg_* queries before displaying the schema tree. Every JDBC driver runs initialization SELECTs on connection establishment. Connection pools run health check queries continuously.</p><p>If you alert on the raw stream, you’re alerting on tool initialization constantly. Alert fatigue develops immediately, engineers start ignoring notifications, and the audit system stops serving its purpose. The filter query is the operational core of this architecture:</p><pre>fields @timestamp, @message, @logStream, @log<br>| filter @message like /AUDIT:/<br>| filter (<br>    @message like /SELECT/ or @message like /INSERT/ or<br>    @message like /UPDATE/ or @message like /DELETE/<br>  )<br>| filter @message not like /SELECT version()/<br>| filter @message not like /pg_shdescription/<br>| filter @message not like /pg_catalog/<br>| filter @message not like /information_schema/<br>| filter @message not like /SET application_name/<br>| filter @message not like /SHOW search_path/<br>| filter @message not like /SELECT current_schema/<br>| filter @message not like /DBeaver/<br>| filter @message not like /PostgreSQL JDBC Driver/<br>| filter @message not like /datname = \$1/<br>| sort @timestamp desc</pre><p>This was built incrementally — not designed upfront. Each exclusion pattern corresponds to a real noise source observed in production. Your environment will have additional patterns specific to your application stack. The exclusion list grows over the first few weeks as new noise sources are identified.</p><h3>The KMS + CloudWatch Alarms Incompatibility</h3><p>SNS topic security in a HIPAA-covered environment requires encryption at rest. The natural choice is alias/aws/sns, the AWS-managed SNS key. Simple, no additional management overhead.</p><p>The CloudWatch alarm stopped delivering after the key was applied:</p><pre>CloudWatch Alarms does not have authorization to access the SNS topic encryption key</pre><p>AWS-managed KMS keys have immutable key policies. The key is managed by AWS; you cannot modify the policy to grant additional principals access. CloudWatch Alarms needs kms:GenerateDataKey and kms:Decrypt to publish to an encrypted SNS topic. With a managed key, there&#39;s no mechanism to grant it.</p><p>The fix is a customer-managed KMS key with an explicit CloudWatch service principal grant in the key policy. The AWS-managed key works correctly when Lambda publishes directly to SNS — the limitation is specific to the <strong>CloudWatch Alarms → SNS</strong> delivery path.</p><p>The SNS topic also requires:</p><ul><li>DenyInsecureTransport: explicit deny of HTTP delivery, enforcing HTTPS at the policy level</li><li>Source account restriction: prevents cross-account confused deputy attacks where a service in another AWS account publishes through a permissive principal and limit the topic creation only to trusted AWS services, in this case it is CloudWatch</li></ul><blockquote><em>Full SNS policy, KMS key policy, and the reasoning behind each statement: </em><a href="https://github.com/pcraavi/PostgreSQL-Audit/tree/main/sns"><em>github.com/pcraavi/PostgreSQL-Audit/tree/main/sns</em></a></blockquote><h3>The Incident Platform Deduplication Problem</h3><p>The first alarm trigger fired an alert in the incident management platform correctly. The second, third, and fourth did not.</p><p>The integration logs showed requests arriving and the “Create Alert” action starting — but no alert created. The issue: incident management platforms (Opsgenie, PagerDuty, VictorOps) use the alarm name as the alert deduplication key (alias). If an alert with that key is already open or acknowledged, subsequent triggers are suppressed — they update the existing alert rather than creating a new incident.</p><p>This is correct, desirable behavior for most alarm types. A disk-full alarm should not create 500 separate incidents while the disk remains full. For an audit alert that should fire independently on every detection window, it requires explicit handling.</p><p>Three approaches:</p><p><strong>Timestamp the alarm name at deploy time.</strong> Using $(date +%s) as a suffix ensures each deployment creates a unique alarm identity. Deduplication keys don&#39;t collide across deployments.</p><p><strong>Configure auto-close on alarm resolution.</strong> When the CloudWatch alarm transitions back to OK state (no user DML detected in the next window), the incident platform closes the alert. The next ALARM transition creates a fresh incident with no deduplication collision.</p><p><strong>Override the alias template in the integration configuration.</strong> Most platforms allow the deduplication key to be templated from the incoming payload. Including a timestamp field from the CloudWatch alert payload makes every alert definitionally unique.</p><h3>Why Not the Native Alternatives?</h3><p>Experienced AWS engineers will have questions at this point. Database Activity Streams is the obvious one.</p><p><strong>Database Activity Streams (DAS)</strong> provides near-real-time activity streaming to Kinesis with structured, decryptable output. It’s a more capable solution in several respects. The reason this architecture doesn’t use it: DAS requires Kinesis as a dependency, adds per-event cost, and needs a consumer layer for decryption and event processing. For teams without an existing Kinesis pipeline, that’s meaningful additional operational surface area.</p><p>The guiding principle here was simplicity and portability. pgAudit is part of PostgreSQL. CloudWatch is where Aurora logs land regardless of whether you audit. Lambda and SNS are general-purpose services that most AWS teams already operate. There is no proprietary tooling, no specialized operational knowledge required beyond standard AWS familiarity. When deploying across multiple accounts, that portability compounds in value — the same Terraform module, the same operational playbook, the same team knowledge applies everywhere.</p><p><strong>GuardDuty RDS Protection</strong> is complementary rather than equivalent — it addresses threat detection (credential anomalies, known malicious IPs) rather than structured audit trails. Both can and should coexist.</p><p><strong>OpenSearch subscription filters</strong> would work technically but introduce an OpenSearch cluster as a hard dependency. Additional cost, additional operational surface, and a specialized operational skill requirement for a problem that CloudWatch + Lambda already solves within existing infrastructure.</p><h3>Operational Considerations</h3><h3>pgAudit overhead</h3><p>At the audit scope defined here — individual human users, not application accounts — overhead is minimal. Human users in a regulated production environment are not expected to generate high transaction volumes. The audit target is ad-hoc access, not application traffic. Per-session logging overhead at this scope is negligible.</p><p>For high-volume clusters where audit is a compliance requirement and cannot be scoped narrowly: account for logging overhead in instance sizing decisions upfront. This is an operational fact of regulated database environments, not a deficiency of pgAudit specifically.</p><h3>Log volume and retention</h3><p>Audit log volume at this scope is low. Set CloudWatch log retention explicitly — the default is indefinite, which accumulates cost. Retention window should match your compliance requirement (90 days, 1 year, 7 years). Apply and enforce it:</p><pre>aws logs put-retention-policy \<br>  --log-group-name /aws/rds/cluster/YOUR-CLUSTER/postgresql \<br>  --retention-in-days 365</pre><h3>Log Insights query behavior</h3><p>Log Insights queries are asynchronous. The Lambda polls with a 60-second timeout on a 300-second function timeout. On first run against a large log group, queries may be slower as CloudWatch builds its index — subsequent runs are faster. Lambda concurrency at a 5-minute EventBridge schedule is inherently low: one invocation per cluster, per 5 minutes.</p><h3>What I’d Do Differently</h3><p><strong>Structure the audit store.</strong> CloudWatch Log Insights is a query tool, not an audit database. The Lambda architecture makes it natural to extend: in addition to publishing the count metric, write each filtered record to DynamoDB or an RDS audit table. This gives you the closest equivalent to Oracle’s UNIFIED_AUDIT_TRAIL — a structured, indexed, long-term queryable audit history. Kinesis Firehose → S3 → Athena is an alternative path for columnar performance over large historical windows.</p><p><strong>Terraform from the first deployment.</strong> The full stack — Lambda, EventBridge rule, SNS topic, IAM role, CloudWatch alarm, KMS key — fits cleanly in a parameterized Terraform module. Deploying to a new account should be terraform apply with environment-specific variables. CLI commands are useful for understanding the mechanics; they&#39;re not a deployment strategy at scale.</p><p><strong>Tag every resource.</strong> Environment, ClusterName, Owner on every Lambda, alarm, SNS topic, and KMS key. Untagged audit infrastructure across multiple accounts becomes, practically speaking, unauditable infrastructure — you lose track of what&#39;s deployed where and whether it&#39;s functioning correctly.</p><h3>Closing Observation</h3><p>The individual components here — pgAudit, CloudWatch, Lambda, SNS — each have clean, well-documented interfaces. The engineering complexity is in the integration contracts between them, none of which are prominently documented: Log Insights results cannot flow to alarms without mediation; AWS-managed KMS keys break CloudWatch delivery; incident platform deduplication suppresses repeated alarm transitions. Each constraint is resolvable, but none surfaces until the components are operating together under production conditions.</p><p>What made the Oracle approach simpler isn’t that Oracle is a better database — it’s that the audit system there was designed as a cohesive feature rather than assembled from general-purpose infrastructure components. The PostgreSQL approach trades that coherence for flexibility, portability, and freedom from proprietary tooling. Whether that trade is worth it depends on what your team already operates and what your compliance requirements actually mandate.</p><p>For most AWS-native engineering organizations with standard CloudWatch and Lambda operational knowledge: this architecture works, it’s maintainable, and it costs under $5 per cluster per month.</p><p>Build the Log Insights query first. Validate the signal before instrumenting anything around it. The filtering logic is the foundation — everything else is plumbing on top.</p><blockquote><strong><em>Full implementation:</em></strong><em> Lambda function, IAM policies, SNS topic policy, KMS key policy, CloudWatch alarm, Terraform module → </em><a href="https://github.com/pcraavi/PostgreSQL-Audit"><em>github.com/pcraavi/PostgreSQL-Audit</em></a></blockquote><p><em>Questions or different approaches to long-term audit retention on Aurora? Comments open. Particularly interested in experience with the Lambda → structured audit table extension or Kinesis Firehose → Athena for compliance retention.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee758aad3fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Observability Last Mile: How to Plug Enterprise Monitoring’s Blind Spot with AI Agents]]></title>
            <link>https://medium.com/@pranayraavi/the-observability-last-mile-how-i-plugged-my-enterprise-monitorings-blind-spot-with-an-ai-agent-d386fd92fd59?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/d386fd92fd59</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-observability]]></category>
            <category><![CDATA[claude-cowork]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Wed, 20 May 2026 00:44:03 GMT</pubDate>
            <atom:updated>2026-05-20T05:40:40.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyFzHdUaZjCjYHvIQnaRag.png" /></figure><p><em>Most APM stacks cover 80% of your monitoring story. This is about the other 20% — and why it matters more than it looks.</em></p><h3>The Gap Nobody Talks About</h3><p>Every serious engineering org I’ve worked in has some version of the same split personality.</p><p>On one side: a modern observability stack. AppDynamics, Datadog, whatever the current favorite is. Real-time metrics, distributed tracing, beautiful dashboards, and alert routing. Years of investment, multiple platform migrations, and org-wide adoption. It works.</p><p>On the other side: a long tail of legacy monitoring tools that predate the current stack by a decade. Tools that don’t speak OpenTelemetry. Tools that can’t push to a webhook. Tools whose output format is, and will remain, a 73-row HTML table emailed at 11:15 UTC every morning.</p><p>These two sides don’t talk to each other. The gap between them isn’t a technology problem — it’s a structural one. Legacy monitoring systems get replaced on decade-long cycles, not sprint cycles. Until the replacement happens (and sometimes after), someone has to be the integration layer. In most orgs, that someone is a human being doing manual triage for 25–30 minutes every morning.</p><p>That’s the pattern I decided to fix. Not by replacing the legacy tools — that’s a multi-year program nobody has budget for — but by making the seam visible first, then closing it cheaply. The insight is that this gap isn’t a technology problem. It’s an <strong>architectural surface area that nobody drew on the diagram</strong> — the box that should say “Dave reads his email for 25 minutes” but never does. Once you see it as an architectural problem, the solution becomes tractable: insert a layer that reads the legacy outputs and joins them with the modern stack. The result is a single consolidated report, delivered at 9 AM, that took about 25 minutes to produce by hand.</p><p>This post is about the architecture of that solution, why the pattern generalizes across enterprise environments, and what it revealed about how we think about observability as a discipline.</p><h3>What the Legacy Tail Actually Looks Like</h3><p>Before getting into the solution, it’s worth being precise about the problem, because “legacy monitoring” gets hand-waved in architecture discussions.</p><p>In this environment, the legacy tail consisted of four distinct data sources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90Z9adSTK-O0S36B5WT0cQ.png" /></figure><p>None of these feed AppDynamics or the observability stack. None of them have APIs. Two of them have predictable subject-line schemas. One of them is a structured HTML table. One of them is a JIRA-backed Confluence page. All four require a human to look at them and decide whether anything needs action.</p><p>The technical challenge isn’t that the data is hard to parse. It’s that there’s no existing integration surface to parse it — no Kafka topic, no REST endpoint, no shared schema. The only integration surface is: it arrives as email, or it lives at a known URL.</p><p>That constraint is also the opportunity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVfOe9aAVDz710AIqJDX5w.png" /></figure><h3>The Architecture: Agent as Operational Synthesis Layer</h3><p>The core architectural decision was to treat the AI agent not as a productivity tool but as an <strong>integration layer</strong> — specifically, a layer that sits between heterogeneous, unstructured legacy outputs and a human who needs a consistent, actionable summary.</p><p>Here’s the system diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRHKQT1G6dqzDAj9VwDgVg.png" /></figure><p>The agent does four things, in order, each morning:</p><p><strong>1. Replication latency — signal extraction from noise</strong> Finds the latest Replication latency alert, read its body, and report whether the body is actually populated. This last point sounds trivial. It isn’t. Replication alerts sometimes fire with empty bodies — the email arrived, but the content didn’t. Manually, this is easy to miss because you see the email and assume it’s fine. The agent makes “body is empty” an explicit state that gets flagged in bold. That’s catching a monitoring failure, not just monitoring an alert.</p><p><strong>2. Backup report — structured extraction from semi-structured HTML</strong> The BI Publisher report is a 73-row HTML table. The agent parses it, tallies the BACKUP_STATUS column, and surfaces only the rows that didn&#39;t complete. Output: &quot;69 completed, 0 failed, 3 with no backup — db01, db02, db05.&quot; Reading time: three seconds. A human eyeballing the table to catch those three rows in seventy-three is slower and occasionally misses them.</p><p><strong>3. Infrastructure /AWS event notifications — classification at scale:</strong> Twenty to fifty emails daily, each following the pattern STATUS - Alert (Server Name : X and DB Name : Y). The agent classifies every subject line, counts by status, and surfaces only the non-SUCCESS entries with a direct link to each email. Today: 21 SUCCESS, 1 WARNING on SERVER04U / DB09. That one line is the entire actionable output of fifty emails. Point out the AWS Notification that the PostgreSQL database version reached end of support</p><p><strong>4. Deployment Review — live data from a known source</strong> The Confluence Deployment Review page is a dashboard of JIRA macros. The agent reads the page, identifies the macro structure, and where the JIRA connector is available, queries the underlying filters directly to pull live issue counts. This bridges the gap between “someone updated a Confluence page” and “here’s the actual current state of production deployments.”</p><p>The implementation uses Claude’s Cowork mode with Microsoft 365 (Outlook) and Atlassian (Jira + Confluence) connectors, triggered by a scheduled task at 9:00 AM local time.</p><h3>Why an LLM instead of a script?</h3><p>A reasonable engineer will ask: couldn’t this be a Python script with IMAP, regex, and a cron job? Yes — and in many cases that’s the right answer. Large enterprises already run Airflow, Power Automate, Splunk SOAR, and Logic Apps. This isn’t automation entering a vacuum.</p><p>The honest comparison is this:</p><p>ApproachStrengthBreaks when…Python + regex + cronDeterministic, auditable, fastEmail format changes, new alert pattern appearsETL / SOAR pipelineScalable, governed, integratedRequires schema agreement upstreamLLM agentTolerates format variance, low setup costOutput is nondeterministic, harder to audit</p><p>What the LLM reduces is <strong>integration friction</strong> — not the need for integration. The backup report column order can shift, the AWS notification subject-line pattern can vary, and a new data source can be added in a sentence of English rather than a week of schema work. That flexibility has a cost: you trade determinism for adaptability. For a morning triage digest where a missed edge case surfaces in the next run, that tradeoff is acceptable. For a system that triggers automated remediation, it isn’t.</p><p>The right mental model is: LLM agents lower the cost of closing observability seams. They don’t replace deterministic pipelines where correctness guarantees matter.</p><h3>The Design Principles Worth Keeping</h3><p>Several architectural choices in this system are worth naming explicitly, because they’re transferable:</p><p><strong>Independent section isolation.</strong> Each of the four sources is handled as an independent subsection. A connector outage in one section doesn’t abort the others — the agent renders an “unavailable” note for that section and continues. This is a fault-isolation pattern: the partial report is vastly more valuable than a silent failure. In a monitoring context, a partial report also tells you something useful — which connector is down.</p><p><strong>Absence as a signal.</strong> Each section includes a sanity check that fires if no emails are found for that source. “No replication alerts received today” is bolded as a warning, not silently skipped. This is the failure mode that manual triage consistently misses: the monitoring system itself breaking quietly. The agent treats the absence of expected input as an anomaly worth surfacing. In practice, this paid off in month two, when the backup report email silently stopped arriving after a mail routing change. The sanity check flagged it immediately. Manual triage would have assumed a clean run.</p><p><strong>Delta orientation.</strong> The report is not a status dashboard — it’s a delta surface. The question it answers is “what changed or failed since yesterday,” not “what is the current state of everything.” This is a deliberate design choice: confirming sameness has no information value but costs the same attention as confirming change. A delta-oriented report routes attention only where it’s needed.</p><p><strong>Runtime date resolution.</strong> The prompt never hardcodes a date. “Today” is resolved against the local clock at execution time. This is a small thing that prevents a class of subtle bugs where a stale prompt runs with yesterday’s scope.</p><h3>Why This Pattern Matters Beyond My Use Case</h3><p>What I’ve described above is a specific implementation. The underlying pattern is more general, and I think it represents an underappreciated class of platform engineering problem.</p><p>Every mature enterprise has <strong>observability seams</strong> — boundaries between monitoring systems where data doesn’t flow automatically and a human fills the gap. These seams exist because:</p><ul><li>Legacy tools were built before modern observability conventions existed</li><li>Integration work is lower priority than feature work, permanently</li><li>The cost of the seam is diffuse (distributed across many humans’ mornings) rather than concentrated, so it never rises to “fix it” priority</li><li>The seam is invisible in architecture diagrams, because nobody draws the box that says “Dave reads his email for 25 minutes”</li></ul><p>An agent layer addresses observability seams without requiring platform replacement. The agent doesn’t care whether the source is a REST API or an HTML table in an email — it can read both. It doesn’t require the legacy tool to be modified or migrated. It doesn’t require a shared data model. It requires a prompt that describes the sources, the parsing logic, and the output format.</p><p>This is meaningful at an org level because it means the ROI on addressing observability seams is no longer proportional to the engineering cost of replacing the legacy tool. A prompt is cheaper than a migration. The pattern scales well for human-in-the-loop operational summarization — less so for high-volume ingestion, regulated automation, or deterministic remediation workflows.</p><h3>The Broader Applicability: Same Shape, Different Domain</h3><p>Once you see the pattern — <em>agent reads heterogeneous sources at a known cadence, filters to deltas, surfaces only what requires human action</em> — it appears in a surprising number of recurring workflows:</p><p><strong>Operations and engineering:</strong></p><ul><li>On-call handoff summaries (PagerDuty + Slack + Jira + APM, joined and summarized)</li><li>Sprint health reports (blocked tickets, aging tickets, no-owner tickets — weekly, automated)</li><li>PR review queue prioritization (open PRs scored by whether they need review or are noise)</li><li>Security alert triage (SOC mailers often emit 200 events to find 3 that matter)</li><li>Compliance evidence collection (SOC 2 and ISO renewals are largely a gathering problem, not an analysis problem)</li></ul><p><strong>Business operations:</strong></p><ul><li>Customer support pattern clustering (weekly themes rather than per-ticket queue)</li><li>Vendor renewal pipeline (SaaS auto-renewals, especially the long tail of small contracts)</li><li>Recruiter outreach triage (deduplicated, scored by company, actionable replies flagged)</li></ul><p><strong>Personal and home:</strong></p><ul><li>School and daycare notification digests (format changes, closure announcements, permission slips)</li><li>Financial sweep (end-of-month invoice and payment confirmation reconciliation — with explicit flagging of expected payments that didn’t arrive)</li><li>Travel itinerary assembly (flight confirmations, hotel addresses, confirmation codes — joined from email into a single pre-trip brief)</li></ul><p>In every case, the pattern is identical: known sources, known cadence, filter to delta, surface what needs action. The domain changes; the architecture doesn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PnWAzqRwk7KOrpoyKACRQ.png" /></figure><h3>The Mental Model Shift</h3><p>The efficiency gain is real — roughly 25 minutes a day across 250 working days is around 100 hours annually — but it’s not the most interesting outcome. **From push to pull.** Most monitoring tools were designed on the assumption that the system sends you everything and you decide what matters. The cost of sending was zero for the system and enormous for the human. An agent flips that: don’t tell me anything — I’ll ask each morning for the delta. You become the consumer of the digest, not the noise. **From dashboards to digests.** A dashboard is only valuable if someone looks at it. A daily digest that synthesizes five sources and filters to a single page is more operationally useful than five perfect dashboards, because it solves the actual constraint — attention — rather than the assumed one — visualization. **From checklists to deltas.** The morning health check used to be: open these five places, confirm each is green. That’s cognitive load spent confirming sameness. The version that should exist is *only tell me what changed*. Most days the answer is “nothing of note.” That answer is fine — and fast. Routing consistency-dependent tasks to systems that can guarantee consistency isn’t laziness; it’s architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlhcKIsculvN1kYi8k--8w.png" /></figure><h3>The Question Your Security Team Will Ask First</h3><p>Before any of the architecture discussion lands in an enterprise context, one question comes first: <em>“If we wire this agent into Outlook and Confluence, does our data get used to train the model?”</em></p><p>The answer, on commercial plans, is no — with one exception worth knowing.</p><p>By default, Anthropic will not use inputs or outputs from commercial products (Claude for Work, Anthropic API, etc.) to train their models. The exception is explicit feedback: if a user submits feedback via the thumbs up/down button, Anthropic may store and use that conversation for up to five years for model training and research purposes. Importantly, feedback data does not include raw content from connectors such as Google Drive or MCP servers — data is only included if it’s directly copied into the conversation.</p><p>For organizations that want to remove even that surface: Primary Owners and Owners on Team and Enterprise plans can disable the feedback button entirely via Organization Settings &gt; Data and Privacy, which prevents members from submitting rated chats to Anthropic.</p><p>Why this matters architecturally: when you wire an agent to internal tools — Outlook, Confluence, Jira, internal MCP servers — the connector data flowing through that agent session is not training data by default. That’s the answer your ops or security team needs before you can have the broader conversation about rolling this pattern out at scale.</p><p>The practical recommendation: get onto a Team or Enterprise plan before you connect internal systems, disable the feedback rating if your security posture requires it, and bring the <a href="https://trust.anthropic.com/">Anthropic Trust Center</a> link to your IT conversation. That documentation covers data handling, retention, and compliance in the level of detail a security review requires.</p><p>This isn’t a blocker. It’s a prerequisite conversation — and it’s a short one when you arrive with the right answers already in hand.</p><h3>Honest Tradeoffs</h3><p>This wouldn’t be a useful technical post without naming the downsides.</p><p><strong>Enterprise adoption requires a security conversation.</strong> MCP connectors that give an agent access to Outlook, Confluence, and Jira require IT sign-off on data handling, audit trail, and retention policy. That conversation is appropriate — it’s not bureaucracy, it’s due diligence. Plan for it. Large regulated enterprises will move slowly, and the right response is to bring a clear data-handling story to the conversation, not to route around it.</p><p><strong>The desktop-up dependency is real.</strong> Scheduled tasks fire when the desktop app is open. A laptop asleep at 9 AM means the report runs when you open it, not when it was scheduled. For a daily report this is acceptable; for time-critical monitoring it’s not. A server-side scheduler would close this gap; until that option exists, this constraint is worth factoring into your reliability expectations.</p><p><strong>Brittle to upstream format changes.</strong> The backup report parser relies on column ordering in an HTML table. If BI Publisher reorders columns in a future release, the parser breaks silently. Defensive prompting (e.g., always verify the column header before using the index) mitigates this, but doesn’t eliminate it. Any parsing logic applied to semi-structured inputs carries this risk.</p><p><strong>Trust takes time to calibrate.</strong> The first week I ran this, I verified everything manually anyway. That’s appropriate — you should validate before you trust. By week four, I’d stopped double-checking, and I had enough incident data to know the report was reliable. That calibration period is part of the deployment, not a sign that something is wrong.</p><p><strong>What production-grade looks like here.</strong> A few reliability realities worth naming: LLM output is nondeterministic, which means identical inputs can produce slightly different summaries across runs. Token truncation is real — a 73-row HTML table pushed through a context window can get silently trimmed. And misclassification is possible: a WARNING buried in a subject line that doesn’t match the expected pattern may get counted as SUCCESS. My mitigations are lightweight: I spot-check the raw email count against the agent’s tally once a week, the sanity-check block catches the most dangerous failure mode (no emails received), and each source email is linked directly so I can verify any flagged item in one click. For higher-stakes environments, you’d want output snapshotting, confidence thresholds, and a validation layer before any automated action triggers. This system produces a human-read digest — the human remains in the loop, which is the right call at this stage of maturity.</p><h3>The Prompt Artifact</h3><p>The prompt itself is the deliverable worth preserving. Below is the sanitized version. In practice it lives at ~/Documents/Claude/Scheduled/&lt;task-id&gt;/SKILL.md:</p><pre>---<br>name: daily-morning-report<br>description: Daily 9 AM operations report — replication latency, DB backups, infra notifications, deployment review<br>cronExpression: 0 9 * * *<br>notifyOnCompletion: true<br>---</pre><pre>You are producing the daily 9 AM operations report. Run silently — this prompt is self-contained.</pre><pre>REQUIRED CONNECTORS<br>- Microsoft 365 / Outlook (email search + read_resource on mail:// URIs)<br>- Atlassian (getConfluencePage; optionally searchJiraIssuesUsingJql)<br>If any connector is missing or errors out, render that section with a clear<br>&quot;⚠ connector unavailable&quot; note and continue. Never abort the whole report.</pre><pre>SCOPE OF &quot;TODAY&quot;<br>&quot;Today&quot; = the calendar day the task fires, in local time.<br>Always pass afterDateTime: &quot;today&quot; to outlook_email_search.</pre><pre>============================================================<br>SECTION 1 — Replication Latency Monitoring (latest alert today)<br>============================================================<br>1. outlook_email_search query=&quot;Replication Latency Monitoring&quot;,<br>   afterDateTime=&quot;today&quot;, limit=50.<br>2. Sort by receivedDateTime desc; pick the first.<br>3. read_resource on its URI for the full body.<br>4. Report: count of alerts today, latest receivedDateTime, sender, and<br>   either the body text or &quot;Body is empty&quot; if it&#39;s only whitespace.</pre><pre>============================================================<br>SECTION 2 — DB Backup Report (failure check)<br>============================================================<br>1. outlook_email_search query=&quot;DB Backup Report&quot;, afterDateTime=&quot;today&quot;, limit=5.<br>2. Take the latest; read_resource on its URI.<br>3. Parse rows with regex &lt;tr&gt;...&lt;/tr&gt; then cells &lt;td&gt;...&lt;/td&gt;.<br>   BACKUP_STATUS is at column index 8 — verify against your report format.<br>4. Tally BACKUP_STATUS values. Flag anything NOT &quot;COMPLETED&quot;.<br>5. State explicitly: &quot;X completed, Y failed, Z with no backup.&quot;<br>   **Bold** the failure count if &gt; 0.</pre><pre>============================================================<br>SECTION 3 — Infra notifications today<br>============================================================<br>1. outlook_email_search sender=&quot;&lt;alerts-sender@example.com&gt;&quot;,<br>   afterDateTime=&quot;today&quot;, limit=50. Page if exactly 50 returned.<br>2. Parse subject pattern: &quot;STATUS - Alert (Server Name : X and DB Name : Y)&quot;<br>3. Summarize counts by status. **Bold** anything not SUCCESS.<br>4. List non-SUCCESS items with a webLink to each.</pre><pre>============================================================<br>SECTION 4 — Deployment Review (Confluence)<br>============================================================<br>1. getConfluencePage cloudId=&quot;&lt;tenant&gt;.atlassian.net&quot;,<br>   pageId=&quot;&lt;page-id&gt;&quot;, contentFormat=&quot;html&quot;.<br>2. Report macro structure and header note.<br>3. If JIRA tool is available, run each filter via searchJiraIssuesUsingJql<br>   and include live issue counts.</pre><pre>============================================================<br>OUTPUT FORMAT<br>============================================================<br>- Plain markdown. One H1 with today&#39;s date. Four H2 sections in order.<br>- Tables for tabular data. Inline-link each source email.<br>- **Bold** anything requiring attention.<br>- End with a &quot;Sources:&quot; section — no duplicate links.<br>- Tone: factual. No filler. No apology lines.</pre><pre>============================================================<br>SANITY CHECKS<br>============================================================<br>- Section 1 zero results: **&quot;No replication alerts today — monitoring may be down.&quot;**<br>- Section 2 zero results: **&quot;Backup report email not received yet.&quot;**<br>- Section 3 zero results: **&quot;No infra notifications today — verify alerting pipeline.&quot;**<br>- Section 4 failure: include the direct Confluence URL for manual access.</pre><p>Three things worth noting in this prompt design:</p><p>First, <strong>section independence is explicit</strong> — each section is instructed to fail gracefully and continue. This is a reliability design choice encoded in the prompt itself.</p><p>Second, <strong>sanity checks are the highest-value lines in the document</strong>. Flagging “no email received today” catches the failure mode where the <em>upstream monitoring system</em> has broken silently — the exact failure mode that checklist-style human review tends to miss, because a human scanning for problems assumes the alerts will arrive if there are problems.</p><p>Third, <strong>the prompt is a versioned artifact</strong>. As the environment changes — new email formats, new Confluence pages, connector upgrades — the prompt evolves. Treating it as a living document rather than a one-time configuration is part of how you maintain a system like this over time.</p><h3>What This Is, and Isn’t</h3><p>This is not an argument for replacing observability infrastructure with LLM prompts. Observability stack is doing things this agent will never do: real-time anomaly detection, distributed trace correlation, infrastructure topology mapping. The agent doesn’t compete with that.</p><p>What the agent does is address the seam — the gap between the modern observability stack and the legacy outputs it can’t ingest. In every enterprise environment I’ve worked in, that seam exists. It’s just usually invisible, because the cost is distributed across individuals doing manual work each morning rather than concentrated in a system that fails visibly.</p><p>Making the seam visible is the first step. Closing it is the second. The agent is the bridge.</p><p>If you’re running operations at any scale and your morning starts with “let me just check a few things in my email” — you have an observability seam. The tooling to close it is available now, and the implementation cost is a well-written prompt.</p><p>That’s the bet worth making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qM1zyPMdNSYIrOgc_GggQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d386fd92fd59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can AI Agents Replace Enterprise Workflow Orchestration?]]></title>
            <link>https://medium.com/@pranayraavi/i-heard-ai-could-replace-workflows-8b71e8290ff0?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b71e8290ff0</guid>
            <category><![CDATA[openclaw]]></category>
            <category><![CDATA[n8n-workflow]]></category>
            <category><![CDATA[calude-cowork]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Sun, 17 May 2026 18:32:50 GMT</pubDate>
            <atom:updated>2026-05-17T20:34:53.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Can AI Agents Replace Enterprise Workflow Orchestration? A Real-World Test <strong>— OpenClaw. n8n. Claude Dispatch. A side-by-side comparison..</strong></h3><h4><em>A database administrator’s honest investigation into whether the new wave of AI automation tools can handle enterprise-grade workflows — or whether the boring answer is still the right one.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQlhw9TzMZfS1FEO4I4uJg.png" /><figcaption><em>The workflow that started the question — and ended up answering it</em></figcaption></figure><h3>Everyone was talking about these tools. I got curious.</h3><p>I work as a database administrator. I support hundreds of databases across multiple environments — dev, staging, non-prod, production — in a HIPAA-regulated organization. Access management is a constant, grinding operational burden. Developers need access. Analysts need access. Application owners need access. And every single request needs to be approved, documented, and auditable.</p><p>For a long time, the process looked like this: someone would message the DBA, the DBA would manually create a Jira ticket and a Word document, chase down approvals from a manager, a database manager, and the security team, manually create the account, and email the credentials back. Days could pass. Follow-ups stacked up. The security team had to trust that the paperwork was right.</p><p>Then I started hearing about Claude Dispatch. And OpenClaw. Both were being described as AI tools that could receive a message and take action — automate tasks, call APIs, connect to services. The demos looked impressive. The communities were excited.</p><blockquote>And I thought: could AI-agent-style automation actually replace deterministic workflow orchestration for this kind of regulated operational process?</blockquote><p>I had already built something with n8n — a workflow automation tool. But I genuinely wanted to know whether I had picked the right tool, or whether something newer and smarter had passed it by. So I did what any engineer would do: I used my actual problem as the test.</p><h3>The problem I needed to solve</h3><p>Before comparing any tools, let me describe the workflow precisely, because the details are what make the comparison meaningful.</p><p>A developer — or a data analyst, or a product manager — needs access to a specific database. The request needs to:</p><ul><li>Go to their direct manager for approval</li><li>Then to the database manager for approval</li><li>Then to the security team for final approval</li><li>Create a full audit trail at every step</li><li>Call a pre-existing API to provision the account with the correct access level</li><li>Deliver the credentials back to the requester</li><li>Spin up a Jira ticket for the network team to open the firewall port</li></ul><p>Every approval is sequential — no step fires unless the previous one passes. If anyone says no, the chain stops and the requester is notified. If security does not approve, no account gets created. Full stop.</p><p>This is not a hypothetical. It runs in a regulated environment where access to production data is governed by HIPAA. The audit trail is not nice-to-have. It is required.</p><p>The access levels themselves are structured — not free text. Read only. Read/write. Dev owner. Application owner. DBA. Each maps to a specific API endpoint. Each produces a deterministic result. The central database inventory that drives all of this is a relational database populated automatically when infrastructure is created through Terraform.</p><p><strong>Nobody should be able to bypass it.</strong></p><p>This is an important constraint on the comparison itself. I am not evaluating these tools for personal productivity, research assistance, or flexible delegation. I am evaluating whether current AI-agent-centric systems can reliably act as the orchestration layer for a regulated, approval-driven operational workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ahcdz0jXimTepqG3fV2BuQ.png" /><figcaption><em>The complete approval chain — from Webex message to provisioned credentials and dual Jira audit trail</em></figcaption></figure><h3>First candidate: Claude Dispatch</h3><p>Claude Dispatch is Anthropic’s answer to the question: what if you could delegate tasks to your AI from your phone and come back to find them done? It lives inside Claude Cowork — a desktop agent product — and creates a persistent connection between your mobile app and the Claude Desktop app running on your computer.</p><p>The pitch is genuinely compelling. Send a message from your phone, Claude acts on your desktop: reads files, calls APIs, summarizes documents, delivers results. For personal productivity this is interesting. For ad-hoc delegation it is actually useful.</p><p>So I asked the obvious question: could Dispatch receive a Webex message, run an approval chain, call my database API, and write to Jira?</p><p>Here is where the investigation got honest quickly.</p><ul><li>Dispatch requires the Claude Desktop app to be running on your computer. The moment the laptop sleeps, it stops.</li><li>There is no server. There is no always-on process. There is no execution log.</li><li>The workflow behavior depends partly on probabilistic LLM reasoning rather than fully deterministic execution. For exploratory or flexible tasks this can be useful, but it creates challenges for tightly governed operational workflows where consistency and auditability matter.</li><li>Sequential approval orchestration is not implemented as a first-class deterministic workflow primitive.</li><li>There is no compliance-oriented execution audit trail comparable to what traditional workflow orchestration systems provide.</li></ul><blockquote><em>A workflow that depends on a laptop staying awake is not an enterprise workflow. It is a personal convenience. There is nothing wrong with that — but it is a different category of tool entirely.</em></blockquote><p>Cost-wise, Dispatch is bundled with Claude Pro at $20 per month or Max at $100 per month. Accessible pricing. But the architecture disqualifies it for this use case before the price even matters.</p><h3>Second candidate: OpenClaw</h3><p>OpenClaw is a different kind of tool. It is open-source, self-hostable, and designed as a personal AI assistant that runs on your own infrastructure. You can connect it to Webex, Telegram, Slack, WhatsApp — it listens on those channels and uses an LLM to decide what action to take in response to a message.</p><p>The self-hosted angle immediately made it more interesting for regulated environments. If you run it on a VPS rather than your laptop, it can operate 24/7. And because it is open-source under an MIT license, the software itself costs nothing. Your real costs are the VPS — roughly $5 to $15 per month — and the API tokens from whichever LLM provider you connect.</p><p>So OpenClaw gets past the first disqualification that knocked out Dispatch. It can stay on. Good start.</p><p>But then I pushed further:</p><ul><li>OpenClaw does not provide deterministic approval orchestration as a built-in workflow capability. It reasons about what to do. If I ask it to get manager approval before proceeding, it will try — but there is no guarantee it handles every edge case the same way every time.</li><li>There is no built-in error handling or retry logic. If an API call fails, the agent may or may not handle it gracefully.</li><li>There are no execution logs in any structured, auditable format. The LLM reasoning logs are not equivalent to compliance-grade audit artifacts.</li><li>There is no native Jira integration. You can make API calls, but you are building that logic yourself in an environment with no visual workflow editor.</li><li>Setup requires real DevOps experience — Docker, VPS configuration, model routing. Not a weekend project for someone who just needs automation.</li></ul><p>OpenClaw is genuinely impressive for what it is: a powerful, flexible personal AI assistant for technical users who want to automate their own workflows. It is not what I needed.</p><p>That does not mean AI has no place in workflows like this. In fact, AI could be valuable inside bounded parts of the process: interpreting vague requests, classifying access levels, generating Jira descriptions, detecting anomalous access patterns, or assisting reviewers. The distinction is that the orchestration layer itself still needs deterministic execution, durable state management, and auditable control flow.</p><blockquote><em>The core tension is this: OpenClaw lets an AI decide what to do. In a regulated environment, I need a system that does exactly what it is configured to do — every single time.</em></blockquote><h3>The one I already had: n8n</h3><p>n8n is not the newest tool in this comparison. It is not the most talked-about. It does not have a viral GitHub repository or a growing community of people sharing AI agent demos. It is a workflow automation platform — visual, node-based, deterministic.</p><p>I had already built the database access workflow in n8n before I started this investigation. What the investigation forced me to do was articulate why it works where the others do not.</p><ul><li>n8n runs on a server. Always on. No desktop dependency.</li><li>Every workflow execution is logged — step by step, with timestamps. If something fails, you know exactly where and why.</li><li>The approval chain is explicit: manager node fires, waits for a webhook response, branches on yes or no. Database manager node fires. Security node fires. The orchestration logic is explicitly defined in configuration rather than inferred dynamically by an LLM.</li><li>Jira, Webex, and REST API integrations are native — no custom code required to connect them.</li><li>When security approves, a Jira ticket is created automatically with every approval documented: who approved, their role, the timestamp. A second ticket fires for the network team. The requester receives credentials via Webex.</li></ul><p><strong>The entire chain — from chat message to provisioned account — is deterministic, auditable, and server-side.</strong> It does not matter whether my laptop is on. The workflow behavior remains stable regardless of variations in LLM output or reasoning. The workflow does what it is built to do.</p><h3>Putting them side by side</h3><p>Here is what the investigation produced — not as opinion, but as a structured comparison against the actual requirements of the problem.</p><p>At this point, the comparison stopped being about whether the tools were ‘good’ or ‘bad.’ The real distinction was architectural: AI-agent systems optimize for flexible delegation and adaptive behavior, while workflow orchestration systems optimize for deterministic execution, governance, and operational reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86XakZeVN-c6bd7f_SMgag.png" /></figure><p>The green cells are not a coincidence. n8n was built for exactly this category of problem — structured, multi-step, multi-system, always-on automation with governance requirements. Dispatch and OpenClaw were built for a different problem: intelligent, flexible, personal task delegation.</p><p>Neither of those things is wrong. They are just different categories.</p><h3>But is n8n actually accessible? Or is it just the enterprise answer no one wants to hear?</h3><p>This is the question I kept coming back to. Because n8n has a reputation for requiring technical knowledge. Webhooks, JSON payloads, API authentication, conditional branching. It is not a no-code tool in the purest sense.</p><p>And yet — compared to OpenClaw, which requires DevOps expertise to host and configure, and compared to Dispatch, which requires you to trust an LLM to handle regulated processes — n8n is actually the most accessible path to a production-grade solution.</p><p>The visual builder is genuinely good. The template library covers most common patterns. The community is large. And the self-hosted Community Edition is free — you pay only for the server, which can be as little as $4 a month.</p><p>What n8n asks for is clarity of thought. You need to understand your process before you can automate it. That is not a technical barrier. That is just good engineering.</p><p>Ironically, this may also be where some AI-native tooling struggles today. Flexible delegation can compensate for ambiguity in personal workflows, but regulated operational systems often require processes to be made explicit rather than inferred.</p><blockquote><em>In 2008, I had my first exposure to BPM tools — business process management software. Back then, automating a multi-step approval workflow required consultants, enterprise licenses, and six-month implementation projects. n8n in 2026 is that same capability, accessible to a single engineer on a modest budget, in a weekend.</em></blockquote><p>The AI-native tools will get there. The direction is right. But for workflows where consistency and auditability are non-negotiable, deterministic automation still wins. Not because AI is not impressive — it is. But because a HIPAA auditor does not accept “the AI usually does it right” as an answer.</p><h3>What the real world added that no tool comparison captures</h3><p>There is one thing I did not discover until the workflow was running: some users have managers on paper who are not actually the owners or decision-makers for the systems being requested.</p><p>Organizational charts say one thing. Actual accountability sits somewhere else. When the approval request went to the wrong person, the workflow stalled — not because the automation failed, but because the data it depended on was wrong.</p><p>No tool comparison surfaces this. You only find it when you run the thing on real people in a real organization.</p><blockquote><em>This is one of the most useful things a well-designed workflow can do: make your organizational data gaps visible. The automation did not hide the problem. It exposed it. And that forced the fix.</em></blockquote><h3>So — can the new AI tools replace n8n for this?</h3><p>No. Not yet. Not for this class of problem.</p><p>Claude Dispatch is a remote control for your desktop. It is well-designed and genuinely useful for personal delegation. But it has no server, no audit trail, and no deterministic logic — three things that are non-negotiable in a regulated environment.</p><p>OpenClaw is a powerful personal AI assistant that technical users can self-host and extend. It can call APIs and respond to messages. But it has no structured approval chain, no execution logging, and no enterprise governance features.</p><p>n8n is not the flashiest answer. It did not go viral. It does not use an LLM to decide what to do next. But it runs reliably, it logs everything, it integrates natively with Jira and Webex, and it does exactly what you configure it to do — every single time.</p><blockquote><em>The right tool is not the newest tool. It is the tool that matches the shape of your problem. And some problems have a shape that requires determinism, not intelligence.</em></blockquote><p>The question I started with — can these AI tools solve what n8n solves — turned out to be the wrong question. The better question is: what kind of automation are you building? If the answer involves regulated data, sequential human approvals, and a legal requirement to prove who did what and when, the answer is still n8n. If the answer involves personal productivity, intelligent delegation, and flexible task handling, Dispatch and OpenClaw are worth a serious look.</p><p>I also suspect these categories will increasingly converge. Workflow platforms are rapidly embedding AI capabilities, while AI-agent systems are gradually adding more durable execution and orchestration features. The long-term architecture may not be AI agents replacing workflow engines, but workflow engines incorporating AI reasoning inside deterministic execution frameworks.</p><p>Both of those things can be true at the same time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b71e8290ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Completely Free Local AI Stack — Inspired by a 60-Second YouTube Short]]></title>
            <link>https://medium.com/@pranayraavi/how-i-built-a-completely-free-local-ai-stack-inspired-by-a-60-second-youtube-short-0c3b8829bf42?source=rss-b6bfe45e8d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c3b8829bf42</guid>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[open-webui]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[gemma-4]]></category>
            <dc:creator><![CDATA[Pranay Ravi]]></dc:creator>
            <pubDate>Sat, 16 May 2026 16:26:33 GMT</pubDate>
            <atom:updated>2026-05-16T16:39:41.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUmoiMTDAAOVvyJ9zSIfsA.png" /></figure><p>It started with a YouTube Short. Someone on my feed casually demonstrated connecting a local AI model to Claude Code and I stopped mid-scroll. No API key. No subscription. No code leaving their machine. I had to know how it worked.</p><p>What followed was a deep dive into local AI — Ollama, Gemma4, Docker, Open WebUI, vector databases, context windows, and a Python script that made my local model generate an ASCII diagram of the Earth and Moon. This post documents everything I learned, every question I asked, and every mistake I made along the way. If you’re curious about running AI entirely on your own hardware, this one is for you.</p><h3>First Question: Wait, Is This Actually Free?</h3><p>My first instinct was skepticism. Claude Code is Anthropic’s product. Surely using it requires a Claude subscription?</p><p>The short answer is <strong>no — not when you pair it with Ollama and a local model.</strong></p><p>Here’s what I learned: Claude Code is the <em>agent</em> — the tool that reads your files, runs commands, edits code, and manages multi-step tasks in your terminal. By default it calls Anthropic’s API, which costs money. But Claude Code exposes environment variables that let you redirect those API calls anywhere you want — including a local Ollama server running on your own machine.</p><p>Ollama added official support for Anthropic’s Messages API format, meaning Claude Code can talk to it natively. No hacks, no middleware, no subscription. The only cost is your own electricity and hardware.</p><pre>Claude Code  →  talks to  →  Ollama (local server)  →  runs  →  Your model<br>                              (no Anthropic servers involved)</pre><h3>So What Exactly Is Ollama?</h3><p>Before I could set anything up I needed to understand what Ollama actually is, because “install Ollama” doesn’t tell you much.</p><p>Think of Ollama as two things in one:</p><p><strong>1. A model manager</strong> — it downloads, stores, and organizes AI models on your machine. Like a package manager but for AI brains.</p><p><strong>2. A local API server</strong> — once running, it exposes an endpoint at http://localhost:11434 that any application can call. Your code, Claude Code, Open WebUI, VS Code extensions — anything that speaks the Anthropic or OpenAI API format can connect to it.</p><p>This is the key insight I kept coming back to: <strong>Ollama itself has no intelligence</strong>. It’s an empty engine. You have to download a model — a large file containing all the AI’s weights and knowledge — before anything useful happens.</p><pre>Without a model:   Ollama = empty server, useless<br>With a model:      Ollama = fully local AI, free forever</pre><h3>Downloading Your First Model — Which One?</h3><p>This is where hardware matters. I have:</p><ul><li><strong>32GB RAM</strong></li><li><strong>NVIDIA GPU with ~11GB VRAM</strong></li><li><strong>Core i9 processor</strong></li></ul><p>With an NVIDIA card, Ollama automatically uses CUDA — no setup needed. Your GPU handles inference and it’s dramatically faster than CPU-only.</p><p>The key concept here is <strong>VRAM vs RAM</strong>:</p><pre>Model fits in VRAM  →  GPU handles everything  →  Very fast ✅<br>Model too big for VRAM  →  spills into system RAM  →  Slower ⚠️</pre><p>With 11GB VRAM I can fit most 7B–13B parameter models entirely in GPU memory, which means fast, snappy responses.</p><p>After thinking through my use cases — coding help, image analysis, document review — I landed on <strong>Gemma4</strong> (Google’s multimodal model, ~12GB). Here’s why it beat out alternatives like Qwen3.6 (28GB):</p><p>Gemma4 Qwen3.6 Size ~12GB ~28GB Fits in 11GB VRAM Nearly (tiny RAM overflow) Partial (big RAM spill) Image understanding ✅ Yes (multimodal) ❌ No Coding quality Good Better Speed on my hardware Fast Slower</p><p>My use cases included image-to-text extraction and converting images to coloring pages — Qwen3.6 can’t do either because it’s text-only. Gemma4 won.</p><pre>ollama pull gemma4</pre><p>One command. It downloads, verifies, and stores the model. You can see progress in the terminal.</p><h3>The Architecture in Plain English</h3><p>Before going further, I want to share the mental model that made everything click for me:</p><pre>┌─────────────────────────────────────────────────────┐<br>│                    YOUR COMPUTER                    │<br>│                                                     │<br>│  ┌─────────────┐    ┌──────────────┐               │<br>│  │ Claude Code │───▶│    Ollama    │               │<br>│  │  (terminal) │    │ :11434 (API) │               │<br>│  └─────────────┘    └──────┬───────┘               │<br>│                            │                        │<br>│  ┌─────────────┐    ┌──────▼───────┐               │<br>│  │  Open WebUI │───▶│   Gemma4    │               │<br>│  │  (browser)  │    │  (the brain) │               │<br>│  └─────────────┘    └─────────────┘               │<br>│                                                     │<br>│  ┌─────────────┐                                   │<br>│  │  Python API │───▶ http://localhost:11434        │<br>│  │   scripts   │                                   │<br>│  └─────────────┘                                   │<br>└─────────────────────────────────────────────────────┘<br>              Zero data leaves your machine</pre><p>Three different interfaces. One local model. Everything private.</p><h3>Context Windows — What Are They and Why Do They Matter?</h3><p>One of the most important concepts I clarified was the <strong>context window</strong> — the model’s working memory. It’s the maximum amount of text a model can “see” at once in a conversation. Exceed it and it starts forgetting the beginning.</p><p>Here’s the reality check comparison:</p><p>Claude Sonnet 4.5 Gemma4 (local) Context window 200,000 tokens ~8,000–32,000 tokens Approximate pages ~150,000 words ~6,000–24,000 words 6 years of tax docs Handles comfortably Would overflow</p><p>Your VRAM directly affects how large a context window your local model can hold. More VRAM = more of the model loaded = bigger context available.</p><p>You can manually increase it:</p><pre>ollama run gemma4 --ctx-size 32768</pre><p>For single documents, images, or focused coding tasks — perfectly fine. For analyzing six years of tax filings all at once? That’s where Claude’s 200k context is a genuine advantage local models can’t match yet.</p><h3>Can Local Models Search the Internet?</h3><p>Short answer: <strong>No, not by default.</strong></p><p>Local models are frozen at their training date. They have no internet connection during your conversation. This was an important distinction to understand.</p><pre>Claude (this chat)  →  Has web search tool  →  Knows current events ✅<br>Gemma4 (local)     →  No internet          →  Knowledge frozen at training ❌</pre><p>This raised an interesting follow-up question though. When I used Gemini to analyze my tax filing and it spotted mistakes — was it searching the internet to find them?</p><p><strong>No.</strong> And this was a real misconception I had.</p><p>Gemini found tax errors because tax law, IRS rules, and common filing mistakes were baked into the model during training. It learned from millions of tax documents, accounting textbooks, and IRS publications. During your session it’s not googling anything — it’s applying trained knowledge to your specific document.</p><p>Think of it like a tax accountant. They studied tax law for years. When reviewing your return they’re not searching Google — they’re applying what they already know to what you show them.</p><p>Local models work the same way. The difference is:</p><ul><li><strong>Gemini/Claude</strong>: More recent training data, larger knowledge base, up-to-date tax law changes</li><li><strong>Gemma4 local</strong>: Good foundational knowledge, may be slightly behind on very recent rule changes, but <strong>your documents never leave your machine</strong></li></ul><p>For sensitive financial documents, that privacy trade-off is significant.</p><h3>Connecting Claude Code to Gemma4</h3><p>This was surprisingly simple. Claude Code reads three environment variables:</p><pre>export ANTHROPIC_AUTH_TOKEN=ollama<br>export ANTHROPIC_API_KEY=&quot;&quot;<br>export ANTHROPIC_BASE_URL=http://localhost:11434</pre><p>Or using Ollama’s built-in launcher:</p><pre>ollama launch claude</pre><p>When Claude Code started up I saw this at the bottom of the welcome screen:</p><pre>gemma4 · API Usage Billing · pranayraavi@gmail.com&#39;s Organization</pre><p>That confirms it’s using Gemma4 through Ollama. No Anthropic billing. No subscription.</p><p>What you get with this setup:</p><ul><li>✅ File reading and editing across your project</li><li>✅ Terminal command execution</li><li>✅ Multi-step agentic coding tasks</li><li>✅ Git operations</li><li>✅ MCP connectors and plugins</li><li>✅ Project context awareness</li><li>⚠️ Intelligence capped at Gemma4’s capability (weaker than Claude Sonnet/Opus)</li></ul><h3>The Python API Test</h3><p>Before setting up a GUI I wanted to confirm the raw API worked. Here’s the script I wrote:</p><pre>import requests</pre><pre>def chat(prompt):<br>    response = requests.post(<br>        &quot;http://localhost:11434/api/generate&quot;,<br>        json={<br>            &quot;model&quot;: &quot;gemma4&quot;,<br>            &quot;prompt&quot;: prompt,<br>            &quot;stream&quot;: False<br>        }<br>    )<br>    return response.json()[&quot;response&quot;]</pre><pre>print(chat(&quot;Write a hello world in ascii diagram of moon and earth&quot;))</pre><p>Output:</p><pre>(           )<br>         /              \<br>  ----(---O---)    (------)  &lt;-- Orbit Path<br> /  /   \    /  /   \<br>|   |     | | |     |   |</pre><p>Gemma4, running entirely on my machine, responding to a Python script. No API key. No internet. Completely local. This was the moment it really clicked.</p><h3>Setting Up Open WebUI — The ChatGPT-Like Interface</h3><p>For a proper GUI I went with <strong>Open WebUI</strong> — a beautiful, feature-rich interface that runs locally and connects to Ollama.</p><p>First attempt using pip failed because I had Python 3.13 and Open WebUI requires Python 3.11 or 3.12:</p><pre>ERROR: Could not find a version that satisfies the requirement open-webui</pre><p>So I went the Docker route instead.</p><h3>Installing Docker Desktop</h3><p>Docker Desktop is free for personal use. Download from docker.com/products/docker-desktop. During install, WSL 2 backend gets configured automatically on Windows.</p><h3>Running Open WebUI</h3><pre>docker run -d `<br>  -p 127.0.0.1:3000:8080 `<br>  --name open-webui `<br>  -v open-webui:/app/backend/data `<br>  --add-host=host.docker.internal:host-gateway `<br>  ghcr.io/open-webui/open-webui:main</pre><p>I initially tried -p 3000:80 which caused a port conflict (another process was using port 3000 on my machine). Switching to -p 127.0.0.1:3000:8080 fixed it.</p><p>Confirmed it was running:</p><pre>netstat -ano | findstr :3000<br># TCP  0.0.0.0:3000  LISTENING  ← Docker up and running</pre><pre>curl <a href="http://localhost:3000/">http://localhost:3000</a><br># StatusCode: 200 OK  ← Server responding</pre><p>Then opened http://localhost:3000 in Chrome and saw the Open WebUI interface with Gemma4 auto-detected.</p><h3>First Real Test — Image to Text Extraction</h3><p>One of the reasons I picked Gemma4 over Qwen3.6 was its multimodal capability — it can actually <em>see</em> images. I put this to the test immediately.</p><p>I had a photo of handwritten chess notes and uploaded it directly into the Open WebUI chat. The prompt was simple: <em>“convert this image to text”</em>.</p><p>Gemma4 thought for 11 seconds and returned:</p><pre>FORK/DOUBLE ATTACK</pre><pre>When we attack two or more pieces at the same time then it is known<br>as fork or double attack</pre><pre>Note- Knights are good at making fork.</pre><p>That’s a perfect transcription of handwritten text — extracted entirely locally, no cloud OCR service, no API key, nothing leaving my machine. It even generated a relevant follow-up suggestion: <em>“Are there other kinds of tactical attacks besides forks, like pins or skewers?”</em></p><p>This is the multimodal capability in action:</p><ul><li>✅ Handwritten text extracted accurately</li><li>✅ Context understood (chess notes)</li><li>✅ Intelligent follow-up suggested</li><li>✅ 100% local — image never left my PC</li><li>✅ Free</li></ul><p>For anyone with scanned documents, handwritten notes, receipts, or any image containing text — this works out of the box with Gemma4 in Open WebUI.</p><h3>Document Upload and RAG — How It Actually Works</h3><p>One of the most powerful features of Open WebUI is document upload with <strong>RAG (Retrieval Augmented Generation)</strong>. This is how you can upload your AWS docs, tax returns, or any PDFs and chat with them.</p><p>Here’s what happens under the hood:</p><pre>You upload PDF<br>      ↓<br>Open WebUI splits it into chunks<br>      ↓<br>Converts chunks to embeddings (mathematical vectors)<br>      ↓<br>Stores in ChromaDB (local vector database)<br>      ↓<br>You ask a question<br>      ↓<br>ChromaDB finds the most relevant chunks<br>      ↓<br>Sends chunks to Gemma4 as context<br>      ↓<br>Gemma4 answers based on YOUR document</pre><p>Everything is stored locally at:</p><pre>C:\Users\lavan\AppData\Roaming\open-webui\data\<br>  📁 vector_db    ← document embeddings (ChromaDB)<br>  📁 uploads      ← original files<br>  📄 webui.db     ← chat history (SQLite)</pre><p>Your documents never leave your machine. ChromaDB is completely free and open source.</p><p><strong>One important limitation</strong>: RAG finds <em>relevant chunks</em>, not the entire document. If an answer spans many sections of a large document, it might miss some context. The workaround is to upload smaller, focused documents rather than one giant PDF.</p><h3>The Full Stack — What I Now Have Running</h3><pre>✅ Ollama          — model manager and local API server<br>✅ Gemma4          — the AI model (multimodal, ~12GB)<br>✅ Claude Code     — agentic coding with local model<br>✅ Open WebUI      — browser-based chat interface with document upload<br>✅ Python API      — scripts calling the model directly</pre><p>Total monthly cost: <strong>$0</strong></p><h3>When to Use What</h3><p>After going through all of this, here’s the practical split I settled on:</p><p>Task Use Coding with file editing Claude Code + Gemma4 Image analysis / image to text Open WebUI + Gemma4 Document Q&amp;A (private) Open WebUI + RAG + Gemma4 Web research / current events Claude.ai or Perplexity Complex reasoning / large context Claude.ai (paid) Tax doc analysis (all years) Claude.ai or NotebookLM Quick Python scripts calling AI Direct Ollama API</p><h3>Honest Reflections</h3><p><strong>What surprised me</strong>: How straightforward the setup actually was once I understood the mental model. Ollama is the server, the model is the brain, everything else just connects to it.</p><p><strong>What I underestimated</strong>: The quality gap between local models and Claude Sonnet/Opus is real. For simple tasks Gemma4 is impressive. For complex multi-step reasoning, Claude’s frontier models are noticeably stronger.</p><p><strong>What I’d tell myself at the start</strong>: Local AI is not a replacement for cloud AI — it’s a complement. Use local for private, repetitive, or experimental tasks. Use cloud AI for research, complex reasoning, and anything that benefits from a larger context window.</p><p><strong>The privacy win is real</strong>: For sensitive documents — financial records, personal data, proprietary code — local AI is genuinely better from a privacy standpoint. Your data does not leave your machine. Full stop.</p><h3>Resources</h3><ul><li>Ollama: <a href="https://ollama.com/">ollama.com</a></li><li>Open WebUI: <a href="https://openwebui.com/">openwebui.com</a></li><li>Claude Code: <a href="https://claude.ai/code">claude.ai/code</a></li><li>Ollama + Claude Code docs: <a href="https://docs.ollama.com/integrations/claude-code">docs.ollama.com/integrations/claude-code</a></li><li>Docker Desktop (free): <a href="https://docker.com/products/docker-desktop">docker.com/products/docker-desktop</a></li></ul><p><em>All of this runs on a Windows machine with 32GB RAM, an NVIDIA GPU with ~11GB VRAM, and a Core i9 processor. If you have similar hardware you can replicate this entire stack in an afternoon.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c3b8829bf42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>