<?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 Abhay Bansal on Medium]]></title>
        <description><![CDATA[Stories by Abhay Bansal on Medium]]></description>
        <link>https://medium.com/@abhaybansal.1988?source=rss-4bb2ad5da6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Mhhuh6PT5GiHT4kn.jpg</url>
            <title>Stories by Abhay Bansal on Medium</title>
            <link>https://medium.com/@abhaybansal.1988?source=rss-4bb2ad5da6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:33:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhaybansal.1988/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[When the Servers Don’t Come Back in the Morning]]></title>
            <link>https://medium.com/@abhaybansal.1988/when-the-servers-dont-come-back-in-the-morning-f445bac9c249?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f445bac9c249</guid>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 00:01:03 GMT</pubDate>
            <atom:updated>2026-11-23T00:02:02.174Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month, some of our servers did not come back in the morning for one of the services.</p><p>Nothing had failed. We had scaled a set of workloads down for the night, the way we have for years. When traffic returned, the auto-scaling policy asked for the instances back, and the cloud provider did not have them to give.</p><p>It is one of the more uncomfortable things to watch, whether it happens in production or in QA. It also made me look again at a set of cost tactics I have relied on for a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jldPBE8rCZfNL5Jg5S6uGw@2x.png" /></figure><h3>What elasticity used to buy us</h3><p>Anyone who runs on the cloud long enough ends up with a few standard cost levers. Off-peak downscaling is one of the simplest.</p><p>Traffic tends to follow daylight. If you run regions in Australia, the UK and the US to serve customers close to home, each region is busy in its own daytime and quiet at night. So you run more servers while people are awake and fewer while they sleep.</p><p>Some teams fill the quiet hours with batch processing and keep the compute busy. Many do not have enough of that kind of work, so they shrink the fleet instead. Done steadily across regions, this alone can take 15 to 20 points off the hosting bill over time.</p><p>When I leaned into the cloud between roughly 2013 and 2015, this was the main reason. You launched boxes when demand arrived and gave them back when it left. That elasticity was what made the model work.</p><h3>What changed</h3><p>The chip shortage is not only about the AI accelerators in the headlines. It has reached the ordinary memory and CPUs that most of our workloads run on.</p><p>Memory is the sharpest part. TrendForce reports that server DRAM contract prices rose 64% in the second half of 2025, with a further rise of about 270% expected across 2026. It estimates memory and flash at 47% of major cloud providers’ capex this year, rising to 68% in 2027 (<a href="https://iconnect007.com/article/151322/memory-prices-soar-dram-and-nand-flash-to-account-for-68-of-major-csp-capex-in-2027/151319/ein">TrendForce, Aug 2026</a>).</p><p>All three providers have said, in their own words, that supply is tight:</p><ul><li><strong>AWS.</strong> In his April shareholder letter, Andy Jassy wrote that two large customers had asked to buy all of AWS’s Graviton capacity for 2026, and that AWS still had constraints leaving demand unserved (<a href="https://www.theregister.com/2026/04/10/amazon_may_sell_homegrown_chips/">The Register</a>). In October he said “2027 is largely sold out,” while noting that AWS always keeps some capacity back for on-demand EC2 and Bedrock (<a href="https://www.infoq.com/news/2026/11/aws-capacity-sold-out/">InfoQ</a>).</li><li><strong>Google Cloud.</strong> On the April earnings call, Sundar Pichai said Google was compute constrained in the near term and that cloud revenue would have been higher with more supply (<a href="https://techcrunch.com/2026/04/29/google-cloud-surpasses-20b-but-says-growth-was-capacity-constrained/">TechCrunch</a>). In August, Google pointed customers to its scheduler for reserving scarce resources, including some CPU-based VM families (<a href="https://itbrief.com.au/story/google-cloud-urges-fallback-planning-for-ai-workloads">IT Brief</a>).</li><li><strong>Azure.</strong> On the October earnings call, Amy Hood said Microsoft still has more demand than supply (<a href="https://fortune.com/2026/10/28/microsofts-cloud-growth-accelerates-and-so-too-does-the-spending/">Fortune</a>). A November analyst report describes customers increasingly unable to get VM capacity in numerous Azure regions (<a href="https://www.directionsonmicrosoft.com/?p=177044">Directions on Microsoft</a>).</li></ul><p>General-purpose CPUs are in the same squeeze. Practitioners report that spot discounts on CPUs have largely gone, reservations need months of lead time, and server orders that took one to two weeks now take around six months (<a href="https://blog.pragmaticengineer.com/the-pulse-a-new-trend-of-cpu-shortages/">The Pragmatic Engineer</a>).</p><p>Prices have started to move as well. In January, AWS raised prices on its EC2 Capacity Blocks for ML by about 15%, a straight increase of a kind it has rarely made (<a href="https://www.theregister.com/2026/01/05/aws_price_increase/">The Register</a>).</p><h3>The newer instances are a smaller step</h3><p>For years, moving to the next instance generation was one of the easiest cost wins. You paid a similar hourly rate and got noticeably more work done per dollar. Teams planned migrations around it.</p><p>Azure’s Intel-based D-series shows how that has changed. These are list prices for a 4 vCPU, 16 GiB general-purpose VM in East US, Linux pay-as-you-go, as of November 2026:</p><p><a href="https://cloudprice.net/vm/Standard_D4s_v5">D4s_v5</a> $0.192</p><p><a href="https://cloudprice.net/vm/Standard_D4s_v6">D4s_v6</a> $0.202 +5%</p><p><a href="https://cloudprice.net/vm/Standard_D4s_v7">D4s_v7</a> $0.265 +31%</p><p>Microsoft describes the Intel v7 family as delivering up to 20% better general compute performance than v6 (<a href="https://techcommunity.microsoft.com/blog/azurecompute/announcing-general-availability-of-azure-dldesv7-series-vms-based-on-intel%C2%AE-xeon/4516907">Microsoft</a>). So the hourly price rose by more than the headline performance gain. That is not something I remember seeing before. The memory-optimized line moved the same way: <a href="https://cloudprice.net/vm/Standard_E4s_v6">E4s_v6</a> to <a href="https://cloudprice.net/vm/Standard_E4s_v7">E4s_v7</a> goes from $0.265 to $0.347 per hour, also about 31%.</p><p>Not every family follows this pattern. Microsoft says its AMD-based v7 VMs bring up to 35% better CPU performance and price-performance than the v6 equivalents (<a href="https://techcommunity.microsoft.com/blog/azurecompute/announcing-general-availability-of-azure-daeafasv7-series-vms-based-on-amd-&#39;turi/4488627">Microsoft</a>). Which family you pick now matters more than it used to.</p><p>Staying on older hardware is also getting harder. Azure began restricting capacity growth on many previous-generation VM series from July 2026, including Dv3, Dv4, Ev3 and Ev4, and recommends moving to v5, v6 or v7 (<a href="https://learn.microsoft.com/en-us/azure/virtual-machines/migration/sizes/previous-gen-series-capacity-limitations">Microsoft Learn</a>). So the move to newer generations is becoming less of a choice, even where the savings are thinner.</p><h3>Two ways it breaks</h3><p>In a tight market, elastic capacity can let you down in two places.</p><ol><li><strong>Coming back after a scale-down.</strong> You release instances at night on the assumption that you can get them back. Someone else may take them in the meantime, and the morning ramp fails. This is the one we hit.</li><li><strong>Growing during a surge.</strong> Even if you never scale down, a traffic spike needs new instances quickly. If the zone has nothing to give, the surge lands on a fleet that cannot grow.</li></ol><p>The first turns a cost tactic into a reliability risk. The second goes deeper, because on-demand burst capacity is a large part of why many of us moved to the cloud in the first place.</p><h3>Where we have landed for now</h3><p>For now, we are pausing off-peak downscaling on the workloads where a failed morning ramp would hurt. Those fleets stay at daytime size through the night.</p><p>That comes at a clear cost. We give back much of the 15 to 20 points that downscaling used to save. In return, the capacity we hold is capacity we know we have.</p><p>There are other tools, and each comes with a trade-off. Capacity reservations guarantee instances in a zone, but you pay for them whether you use them or not. Spreading across more instance types and zones improves the odds of finding capacity, at the cost of a less uniform fleet. Neither gives back what elasticity used to give for free.</p><p>This will not be the right call for every team. A team with plenty of batch work, or with different reliability needs, may reasonably land somewhere else.</p><h3>What may need to change</h3><p>I think this is something AWS, Google Cloud and Azure will need to work out in some form. One option is a clearer pool of spare on-demand capacity that customers can plan around. AWS already says it keeps some capacity back for on-demand. How much, and how reliably it is there in the morning, is what matters to anyone running elastic workloads.</p><p>Everything above is about the general-purpose chips most of us have used for the last four or five years. I have not touched the AI accelerators at all. Nvidia’s CFO said a year ago that “the clouds are sold out” (<a href="https://www.cio.com/article/4094300/nvidia-chips-sold-out-cut-back-on-ai-plans-or-look-elsewhere.html">CIO</a>), and Google announced its eighth-generation TPUs in April (<a href="https://cloud.google.com/blog/products/compute/tpu-8t-and-tpu-8i-technical-deep-dive">Google Cloud</a>). Blackwell GPUs and the newest TPUs are a separate market, and a much tighter one.</p><p>My guess is that the next three to six months get harder before they get easier. Memory prices are still rising, and much of next year’s capacity is already spoken for. I may be wrong about the timing, and I would be glad to be. For now, a steady system seems worth more than the last few points of savings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f445bac9c249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What If the Agent Wrote Its Own Runbook?]]></title>
            <link>https://medium.com/@abhaybansal.1988/what-if-the-agent-wrote-its-own-runbook-cf773f0fd074?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf773f0fd074</guid>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 08:15:58 GMT</pubDate>
            <atom:updated>2026-08-26T18:10:13.491Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been experimenting with agents against enterprise data and workflows for some time now. One of those experiments was around deep data analysis, where an agent was given enough tools to inspect schemas, understand tables, run queries and answer fairly open-ended questions about the data.</p><p>The agent was usually able to get to the answer, but the more interesting part was the path it took to get there. On the first run, the agent knew almost nothing about the data model. It would inspect one table, query another, make an assumption about a relationship, realise the assumption was wrong, change the join, inspect sample rows and continue until it had enough context to answer the question. It worked, but it was expensive.</p><p>If the right path was: 1 → 2 → 3 → 4 → 5</p><p>the agent might take: 1 → 2 → 14 → 6 → 3 → 17 → 4 → 11 → 9 → 7 → 8 → 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYs88udc4UgKHmMTh7Tvog.png" /></figure><p>Eventually it still gets to 5, and that is actually one of the reasons agents are useful. If the exact path to 5 were already known, it could probably be written as a workflow. The value of the agent is that it can explore an environment where every step is not known beforehand.</p><p>The uncomfortable part was that the next run started from zero again.</p><h3>Why should every run rediscover the same system?</h3><p>Suppose the first execution discovers that a particular table is irrelevant, another table is actually the authoritative source, and two columns that look like obvious join keys are not the right ones. That is useful knowledge, but a new agent invocation can easily repeat all of that exploration because the two executions are independent.</p><p>As engineers, our instinct is usually to fix this by making the agent more deterministic. We improve the prompt, describe the schema, add examples, create skills and tell the agent which tools to call and in what order. For a well-understood workflow, that is probably the right thing to do. The question is whether it scales. The long tail inside enterprises is enormous: thousands of APIs, different schemas, customer-specific configurations and internal tools. If every useful execution path has to first be understood by an engineer and then encoded into a prompt or a skill, we are creating a fairly significant manual bottleneck.</p><p>What if we could pass on the learning from one session to another.</p><h3>Let one run leave something behind for the next one</h3><p>The agent ran from a persistent folder, and inside that folder was a simple file called runbook.md. There is nothing special about this file. It was chosen because it was simple, inspectable and easy to experiment with.</p><p>The more important part was how the file got written. The working agent should not finish the task and dump everything it had done into the runbook. A successful execution can contain a lot of useless exploration, wrong assumptions and accidental paths. Persisting all of that would probably make the next run worse.</p><p>Instead, after the worker finished, a second agent ran over the complete execution. This second agent is the teacher. The worker has one job, which is to solve the problem. The teacher has another, which is to look at how the worker solved the problem and decide what is worth remembering.</p><p>The teacher sees the observable execution trace: tool calls, Snowflake queries, responses, errors, retries and the final answer. From that it extracts what may actually help the next run: which table is normally the right starting point, which relationship between two entities is useful, which assumption turned out to be wrong.</p><p>The teacher is a larger or more capable model than the worker, since this step does not sit in the latency-sensitive path, and the agent that performed the work is not the best judge of what should be learned from it. A worker can arrive at the correct answer using a bad method.</p><p>That distilled knowledge goes into the runbook. The runbook is not a history of previous executions. It is closer to a distilled view of how to approach the task next time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkaTVL5MIFDpqFPGV_g43w.png" /></figure><p>And it worked. The number of queries reduced across subsequent runs, because later runs already knew which parts of the schema mattered and which dead ends had been explored. Nothing else had changed: not the underlying model, not the tools, and no new skill was manually written after every run.</p><h3>The runbook should create a prior, not a constraint</h3><p>The next problem is obvious: what happens when the schema changes?</p><p>Imagine the runbook says that a particular metric is available from Table A. That may have been correct for the last hundred executions, but tomorrow Table A changes, an API changes, or a customer has a different configuration. If the worker blindly follows the runbook, the architecture becomes fragile very quickly.</p><p>So the environment always has to win. The runbook should create a prior, not a constraint. It tells the agent that previous executions learned a particular way of approaching the problem and that this is probably a good starting point. It should never mean that the problem must be solved in exactly that way.</p><p>If the runbook stops making sense, the worker has enough freedom to inspect the current environment, realise that the previous knowledge is stale, and take another path. That new execution then becomes another input to the teacher, and the runbook changes again. Any procedural memory that cannot be challenged will eventually become stale.</p><h3>What if we learn a suboptimal path too?</h3><p>There is another problem that shows up once the runbook starts working well. When an agent runs, there are two things we care about: the output of the analysis, and the path taken to produce it.</p><p>The path largely takes care of itself. If a shorter route exists, the agent will skip steps and take it. The real risk is in the output. A runbook distilled from early runs can quietly encode an approach that produces a weaker result, and every future agent then repeats it. We found something that works and locked it in, without knowing if something better exists.</p><p>So the system cannot only learn and exploit. Every so often, we let the agent have the freedom of choice and not accept the runbook as the only way to reach the milestone. Maybe that happens every N executions, maybe randomly, maybe when quality starts to drift. If a free run produces a better result, the teacher now has two approaches to compare and can refine the runbook again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjq1vBv7Z1wdgdhEu6Koeg.png" /></figure><p>There is a matching trap on the efficiency side. If the first run uses ten Snowflake queries and the next uses three, it is tempting to declare success. But a three-query answer that is wrong is worse than a ten-query answer that is correct. The order has to be Correctness → Reliability → Efficiency. Only after the outcome is good should tool calls, tokens, latency or cost come down.</p><h3>Where do skills fit?</h3><p>This does not replace skills. In fact, some runbooks should eventually become skills.</p><p>Consider the lifecycle of a completely new task. In the beginning, the agent knows very little and explores heavily. Over multiple executions, useful patterns start appearing, and the teacher captures them. If the procedure becomes stable enough and continues to work reliably, at some point it may make sense to turn it into something more deterministic.</p><p>The progression could look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvUquWaMAQ7Iz9uyIOCt0g.png" /></figure><p>For important, well-known paths, humans may still create the skill directly, and that is completely fine. The more interesting case is the long tail, where the problem space is too large to define by hand: the agent discovers the procedure, the teacher refines it over multiple executions, and only the procedures that prove useful and stable become formal skills.</p><h3>Why this matters as agents scale</h3><p>Agent memory or reflection is not new. There is already a lot of work happening around both. What was useful was seeing this behaviour in a fairly practical experiment against real use cases. When an agent takes an inefficient path, the first instinct is usually to improve the worker’s prompt or write another skill. Sometimes the better answer may be to leave the worker capable of exploring and build a much better teacher around it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf773f0fd074" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talking to the Data]]></title>
            <link>https://medium.com/@abhaybansal.1988/talking-to-the-data-c6aa00599a97?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6aa00599a97</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 05:00:22 GMT</pubDate>
            <atom:updated>2026-08-21T05:20:12.388Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why I keep coming back to ETL pipelines and a context layer in a world of MCP servers</em></p><p>There is a perception taking hold right now that if you have MCP servers for all your systems, you have solution to every problem. Connect system A, connect system B, connect system C, and the agent will stitch the answers together. I believed a version of this too. Then I spent time with both patterns on real problems, and one of them worked noticeably better for the questions I actually had. This piece is me trying to explain why, and what I took from it.</p><p>One thing before I start. My argument is not that one approach beats the other. It is that a familiar pattern from data engineering, ETL pipelines landing data in one queryable place, pairs surprisingly well with what these models are naturally good at, and I think the pairing deserves more attention than it gets. I am borrowing from what data teams have built over the years and adding my own context on top. Take it as a thought process, not a verdict.</p><p>My teams run platforms where the context needed to answer any interesting question is spread across many systems: cloud infrastructure, application backends, tickets, pull requests, cost data. Exactly the setup MCP was designed for. So we have MCP servers. We use them every day. This is not an anti-MCP article.</p><h3>What actually happens when you chain MCP calls</h3><p>Say the question is: <em>why did error rates spike last Tuesday?</em></p><p>The context lives in three places. Infrastructure events sit in system A. Deployments and pull requests sit in system B. Application metrics sit in system C. Each one has an MCP server. On paper, the agent calls all three and connects the dots.</p><p>Here is what happens under the hood. Every tool definition gets loaded into the model’s context before it does anything. Then the agent starts calling tools, and every intermediate result comes back as a JSON blob that also flows through the context window. The list of deployments. The pages of tickets. The metric snapshots. All of it, serialized as text, sitting in the prompt. And then the model does the filtering, the matching, the joining, and the aggregating. Token by token. In its head.</p><p>A large language model, the most expensive compute in the stack, ends up doing work a database engine does in milliseconds. Without quite meaning to, we have made the model our join engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGRNAfmVs5GXgJqUedVfCA.png" /></figure><p><em>Left: intermediate result flows through the context window, and the model does heavy lifting. Right: the engine does the joins, and only the answer travels.</em></p><p>This is not just my observation. Anthropic, published an engineering post in November 2025 called “Code execution with MCP” that quantified it. Tool definitions and results can eat 50,000+ tokens before the agent has even read your request. Their example workflow consumed around 150,000 tokens with direct tool calling. Restructured so the work happens outside the model and only results come back, the same workflow took about 2,000 tokens. A 98.7% reduction. Cloudflare’s Code Mode team reached a similar conclusion around the same time: models are better at writing code that calls tools than at calling tools directly, one call at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ua1aab6ZxvvjrG_uhMCxw.png" /></figure><p>And tokens are only half of it. Aggregation gets hard: most MCP servers expose list-and-get style tools, so a question like “average resolution time by team over the last 90 days” means paginating through thousands of records and hoping the model sums them correctly, where SQL would make it one GROUP BY. Reproducibility suffers too: a fifteen-step chain of tool calls is not an artifact you can inspect, version, or re-run, and the same question asked tomorrow may take a different path to a different answer.</p><p>Part of this already has an answer inside the MCP world. The model can write a small script that makes the tool calls itself, so the payloads stay out of the context window and the arithmetic happens in code. It helps, genuinely. But the script is still ad hoc glue over per-system APIs, one script per question, with no shared schema or engine underneath.</p><h3>The context layer</h3><p>In an earlier piece I argued that SaaS platforms survive the AI wave because AI needs something to reason over. The context layer stays, I wrote. I have been chewing on what that context layer actually is ever since, and I think the honest answer is simpler than I expected.</p><p>Under the hood it is nothing exotic. ETL and streaming pipelines land every system’s data in one queryable place. A semantic layer teaches the model what that data means. SQL is the interface. Ten years ago we would have called this a data lake and used it for dashboards. The name deserves an upgrade because the job changed. This is not a reporting backend anymore. It is the memory your AI reasons over. It is the difference between an agent that has to phone three departments for every question and one that already knows the company.</p><p>What makes this pattern so interesting right now is who sits on top of it. Modern LLMs write SQL the way they write English. It is native to them. Give the model the schema, and the chain of thought that used to be three MCP calls and a prayer becomes a single statement with two joins and a GROUP BY. The database executes it in seconds, the way databases have been optimized to do for fifty years, and only a small result set comes back through the context window.</p><p>The experience is hard to describe until you have it. You have 30 or 40 tables from different systems in one place. You stop writing SQL yourself. You just talk to the data as if you are talking to someone who has all the context. It creates the joins. It handles the time windows. It follows up on its own results with narrower queries. The context layer holds what the company knows, and the model becomes the interface to it.</p><h3>An answer with receipts</h3><p>We had an incident-style question recently: why did a particular behavior show up in production? The context sat in three different places: infrastructure data, application data, and development activity. All of it was already flowing into the context layer.</p><p>I asked the question in plain English. A few minutes later I had an answer, and more importantly, I had receipts. The reasoning was a short sequence of SQL queries, each one visible and re-runnable, joining deployments to the pull requests behind them and to the metrics that followed them, and narrowing down from there. Nothing exotic, a couple of joins and an aggregation over a time window. The kind of query any of us could write, except nobody had to.</p><p>With three separate MCP servers, I am honestly not sure how I would have gotten there. I would be paginating deployment lists into the context window and asking the model to eyeball timestamps. Here the whole correlation was one statement, executed by an engine built for exactly this.</p><p>And the answer is an asset. Any query in that chain can be saved as a dashboard, scheduled as a report, or reviewed by a human. A chain of tool calls evaporates. A SQL statement compounds.</p><h3>The semantic layer is the gold</h3><p>Here is the part I underestimated at first, and it is the part I would gently flag for anyone trying this.</p><p>It is tempting to think the hard part is the SQL. Increasingly, it is not. On BIRD, the long-standing benchmark for text-to-SQL on large, messy databases, the human expert baseline sits at about 93%. In early 2026, research systems crossed it, with one reporting 93.2% execution accuracy on an expert-verified subset. Follow-up work also found the benchmark’s automated scoring had been undercounting models all along, disagreeing with human expert judgment on nearly four out of ten answers, mostly by rejecting queries a human would accept. At this point the models write SQL at least as well as most of us.</p><p>So why do many text-to-SQL deployments still disappoint? Because writing SQL was rarely the real bottleneck. Understanding the schema is. BIRD itself shows this: when the original evaluation handed the model curated hints about what the columns actually mean, accuracy jumped by 20 points on the same questions. The difference is not syntax. It is meaning. Context is the swing factor.</p><p>Which is what the semantic layer provides. A context layer is not just data in one place. It is data plus meaning: what each table represents, what each column means in business terms, which values are dirty, how things relate. In our setup this lives as skills, structured notes the model reads before it writes a single query. Without that layer of meaning, you have storage and a model making educated guesses about what acct_st_cd stands for. With it, you have context.</p><p>If there is one tactical takeaway I would offer, it is this: treat the semantic layer as a first-class product. The SQL is no longer the weak link. The schema documentation usually is. Review it, version it, keep it honest.</p><h3>Where MCP still fits, and should</h3><p>The obvious questions for this setup are freshness, actions, feasibility.</p><p>What remains genuinely live-only are point lookups: the status of one ticket, right now, this second. Keep an MCP server for that. On actions: SQL reads. It does not create tickets or send messages or update records. That part stays on MCP.</p><p>Also not every dataset belongs in the central place. Some data you cannot move, some is too niche to justify a pipeline, some belongs to another team. Data you choose not to centralize stays behind its MCP server, and the agent still reaches it there, just not through SQL. What you end up with is a hybrid: for the workloads where cross-system questions matter, the data comes into the middle, and everything else stays where it is. The more you bring in, the richer the middle gets and the more the whole thing feels like talking to the data. It is a dial, not a switch.</p><p>Which settles, for me at least, into a shape I keep coming back to. The context layer is itself exposed as one tool among the agent’s tools. One big, expressive tool that carries what you chose to centralize, next to MCP servers for live lookups, for actions, and for the data that stays outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpzW1GaeTTwGaYu2FQ614Q.png" /></figure><p><em>Some systems feed the context layer; some stay behind their MCP servers. Cross-system questions go to SQL, everything else goes where it always went.</em></p><p>One practical detail that matters more than it looks: put freshness metadata into the semantic layer itself.</p><p>And one honest caveat: none of this is free. Pipelines need building and owning. Schemas drift. In regulated environments, centralizing data means doing real work on row-level security and masking, where per-system MCP calls inherit each system’s permissions automatically. MCP is cheap to set up and expensive per question. The context layer is expensive to set up and cheap per question. Where the break-even sits will depend on how many cross-system questions your organization asks. In my experience, it is more than we assume.</p><h3>What changed</h3><p>None of the ingredients here are novel. Data lakes, ETL, SQL: data teams have relied on them for decades. What changed is the interface: a model that speaks SQL natively and never gets tired of writing it. That is what turns a warehouse into a context layer.</p><p>The industry seems to be converging on this from both ends. Warehouse vendors are shipping natural-language interfaces over governed semantic layers. Products like Databricks Genie and Snowflake Cortex Analyst are already selling this promise; what I am describing is what it takes to make that promise hold inside your own data. And on the agent side, the MCP server I find myself reaching for most is not thirty narrow tools for thirty systems. It is one tool, run_sql, pointed at a well-documented context layer. With data sharing and open table formats, the data does not even need to live in one physical place anymore. It needs one queryable interface and one semantic layer. Zero-copy shares and federation handle the geography.</p><p>I keep coming back to a simple framing. Every narrow tool you give an agent is a small lever. A context layer is one big lever. The next time your agent chains a dozen tool calls to answer one question, ask what that question would look like if the data lived together behind a single interface with a good semantic layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6aa00599a97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building is getting cheap. That changes everything]]></title>
            <link>https://medium.com/@abhaybansal.1988/building-is-getting-cheap-that-changes-everything-982534f560c8?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/982534f560c8</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 02:06:19 GMT</pubDate>
            <atom:updated>2026-02-26T04:27:09.557Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been thinking about what happens to software when building it stops being the hard part. Not in a grand, <em>future-of-the-industry</em> way, but more like I just experienced something that made me rethink a few things, and I wanted to share.</p><p>We run cloud infrastructure at scale, with multi-cloud deployments across AWS, Azure, and GCP, Kubernetes clusters, databases, and the whole stack. Like any cloud ops team, we spend a significant chunk of time on cost optimization, resource efficiency, and making large systems run leaner.</p><p>I wanted a tool for Kubernetes cost optimization, especially because a major source of waste often sits in the application layer and remains untouched. I knew exactly what we wanted it to do. I wrote out a detailed plan, handed it to an AI model, and with a few iterations, about a week later, I had a working application that I could deploy in my environment.</p><p>It found real savings, and they were meaningful.</p><p>What stuck with me wasn’t the tool itself. It was how little friction there was between having the idea and having the thing. That gap used to be months and teams. This time, it was just me, a plan, and some iterations.</p><p>It got me thinking. Not just about our infrastructure, but about what this means for how software gets built and sold more broadly.</p><p>If the cost of building software keeps dropping, and I think it’s pretty clear that it will, some interesting things follow.</p><p>Think about why most B2B SaaS products look the way they do. A company hires hundreds of engineers, builds a product, and sells it to thousands of customers. For the economics to work, the product has to be general enough to serve all of them. Everyone gets the same dashboards, the same workflows, more or less the same experience. You can configure things here and there, but you’re fundamentally adapting your process to fit their product.</p><p>We’ve all just accepted this. But it’s worth asking is that because generic software is better for the customer? Or is it just because custom software was too expensive to be practical?</p><p>I think it’s the latter. And I think that constraint is loosening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7XtCyn5qbH-dGNcQU2w5w.png" /></figure><p>With building getting cheaper, what if it becomes feasible? What if you have engineers who deeply understand a customer’s problem and can use AI to build exactly the experience that customer needs, in their terminology, for their process, within their workflow? Not a configuration. An actual tailored application sitting on top of the same platform and data.</p><p>Now, if we map this to the most important question, ‘<em>is SaaS dying?</em>’ I don’t think so. An AI model by itself doesn’t replace what these platforms do. I work with platforms that sit on billions of records: customer interactions, support conversations, behavioral signals, transaction data, context. That data is the foundation. AI needs something to reason over.</p><p>So the context layer stays. The platform stays. The APIs, the integrations, the security, the compliance, all of that infrastructure remains essential. What I think changes is the layer on top. The part you actually see and interact with every day.</p><p>There’s a quiet problem in enterprise software that everyone knows about but rarely talks about honestly. Companies buy platforms and then barely use them. Adoption is always the challenge. You buy something with 200 features and use maybe 30 because the other 170 were built for someone else’s workflow.</p><p>I’ve seen this from both sides: building platforms and buying them. The gap between what’s sold and what’s actually used is enormous. And the reason is almost always the same. The software wasn’t built for how that specific team actually works.</p><p>If the application layer is built in your context, for your team, your process, your specific problems, that adoption gap starts to close. And when people actually use the software they’re paying for, the value equation changes pretty fundamentally. You’re not paying for a platform you hope to get value from. You’re paying for something that’s already wired into how you work.</p><p>I don’t have a neat conclusion here. Mostly, I have questions.</p><p>If building keeps getting cheaper, do you still need enormous engineering teams building one product for everyone? Or do smaller groups of people who deeply understand customer problems become more valuable?</p><p>What happens to SaaS pricing when every customer is getting something a little different? Does per-seat still make sense? What would consumption-based pricing look like?</p><p>If the people who win are the ones who can think clearly and plan well, not necessarily the ones who can write the most code, what does that mean for how we think about engineering talent?</p><p>I keep coming back to a simple idea. Software has always been generic because custom was too expensive. That trade-off is shifting. And I think the implications are bigger than most people realize.</p><p>Maybe I’m wrong. But with the way things are going, it’s hard to unsee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=982534f560c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Night We Stopped Burning Money on Backups]]></title>
            <link>https://medium.com/@abhaybansal.1988/the-night-we-stopped-burning-money-on-backups-e43adfebe54f?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43adfebe54f</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cost]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 03:24:50 GMT</pubDate>
            <atom:updated>2025-09-06T03:34:02.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>How staggering backups across 8 off-peak slots saved us &gt;$250K a year — without buying a single new tool</h3><h3>The problem no one “owned” (until the bill arrived)</h3><p>We run hundreds of clusters across regions, storing tens of terabytes. Backups were “set and forget,” all scheduled at the same default time. At 02:00, the entire estate woke up and started pushing data. Links saturated, retries spiked, multipart uploads left partial versions, and cross-region replication faithfully copied the mess to DR.</p><p>We weren’t just paying for the clean, final artifacts. We were also paying for:</p><ul><li>Extra object versions created by retries (primary region)</li><li>The same extra versions in DR (replication)</li><li>Inter-region transfer triggered by failures</li></ul><p>This wasn’t a tooling failure. It was a concurrency problem masquerading as reliability and cost.</p><h3>Follow the money, then the traffic</h3><p>We decomposed the bill by service and time. Cost spikes aligned with the nightly backup window. Network graphs showed saturation; object storage metrics showed elevated 4xx/5xx and retries; replication queues jumped immediately after.</p><p>The hard truth: we had created a self-inflicted DDoS.</p><h3>The smallest change with the biggest impact</h3><p>We didn’t replatform or buy a new product. We changed <strong>when</strong> the work happened.</p><ol><li><strong>Define an off-peak window.</strong> We picked the quietest eight hours.</li><li><strong>Slice it into 8 equal slots.</strong> One hour each to start.</li><li><strong>Bucket clusters by size.</strong> Large/medium/small by expected bytes and duration.</li><li><strong>Distribute fairly.</strong> Place the largest backups first and round-robin them across slots so no single hour carries all the “elephants.”</li><li><strong>Add jitter.</strong> Within each slot, start jobs with a random 5–20 minute offset to prevent micro-spikes at :00.</li></ol><p>Think of it like ramp meters on a freeway: same number of cars, fewer traffic jams.</p><h3>Results</h3><ul><li><strong>Retries collapsed</strong> as link pressure dropped.</li><li><strong>Versioning waste fell</strong> in both primary and DR.</li><li><strong>Inter-region churn eased</strong> because we stopped manufacturing failed fragments.</li><li><strong>Net savings:</strong> <strong>&gt;$250,000 annually.</strong></li></ul><p>No heroic refactors. No vendor switch. Just scheduling.</p><h3>What made this work (the principles)</h3><ul><li><strong>Backups are production traffic.</strong> If they can degrade availability or inflate cost, give them the same SLOs and observability as customer queries.</li><li><strong>Concurrency is a cost lever.</strong> The same bytes at a different time can be radically cheaper.</li><li><strong>Versioning is a double-edged sword.</strong> It saves your day during incidents, and quietly drains your budget when retries explode.</li><li><strong>Replication multiplies mistakes.</strong> DR will mirror inefficiencies unless you fix the source.</li><li><strong>Default schedules are legacy decisions.</strong> “That’s how we’ve always done it” is a recurring expense.</li></ul><h3>The playbook (you can copy this)</h3><p><strong>Baseline first</strong></p><ul><li>Map every backup job: start time, average duration, bytes written, retry rate, bandwidth used.</li><li>Correlate cost and errors to the backup window.</li></ul><p><strong>Design the schedule</strong></p><ul><li>Choose a data-driven off-peak window (don’t rely on tribal knowledge).</li><li>Start with <strong>4–8 slots</strong>; you can refine.</li><li>Place <strong>large jobs first</strong>, then round-robin the rest.</li><li>Add <strong>5–20 minutes of jitter</strong> to avoid slot-boundary spikes.</li></ul><p><strong>Guardrails</strong></p><ul><li>Alert on <strong>retry rates, multipart aborts, replication lag, egress utilization</strong>.</li><li>Cap <strong>concurrent backups per AZ/region</strong> for very large estates.</li><li>Roll out gradually and <strong>rebalance weekly for a month</strong>.</li></ul><h3>Pseudo-code (the allocation idea)</h3><pre>clusters = fetch_all_clusters_with(size, expected_bytes, avg_duration)<br>slots    = [0..7]  // 8 off-peak slots</pre><pre>// Sort largest first to spread heavy hitters<br>clusters.sort_by(size desc, expected_bytes desc)</pre><pre>assignment = {slot: [] for slot in slots}<br>slot_load  = {slot: 0  for slot in slots}</pre><pre>for c in clusters:<br>    s = slot_with_min(slot_load)  // lowest current load<br>    assignment[s].append(c)<br>    slot_load[s] += c.expected_bytes / c.avg_duration  // approximate write rate</pre><pre>// For each cluster, start at: slot_start + random(5..20 minutes)</pre><p>You don’t need this exact heuristic; any approach that flattens bandwidth and write IOPS over time will get you most of the win.</p><h3>Edge cases we handled</h3><ul><li><strong>Long-running backups:</strong> Place them earlier so any spillover doesn’t collide with morning traffic.</li><li><strong>Critical datasets:</strong> Keep RPO/RTO intact — stagger relative to peers without changing protection goals.</li><li><strong>Audit/recovery requirements:</strong> We didn’t disable versioning or replication; we stopped generating trash versions.</li></ul><h3>Operational notes (what we’d do next)</h3><ul><li><strong>Concurrency budgets:</strong> Enforce a global “backup concurrency” budget per region that jobs must acquire before starting.</li><li><strong>Admission control:</strong> If real-time egress exceeds a threshold, queue non-critical backups automatically.</li><li><strong>First-class dashboards:</strong> “Backup SLO” panel with retry rate, effective throughput, replication lag, and cost per GB protected.</li></ul><h3>The quiet satisfaction (and a cleaner bill)</h3><p>The next invoice was the proof: smoother graphs, fewer alerts, cleaner replication, and a line item that finally made sense.</p><p><strong>Lesson:</strong> You can’t optimize what you don’t schedule. If all your backups start together, so do your problems.</p><h3>Steal this checklist</h3><ul><li>Inventory backup jobs and durations</li><li>Identify the true off-peak window</li><li>Create 4–8 slots and assign by size</li><li>Add jitter to start times</li><li>Monitor retry/replication/egress during rollout</li><li>Review and rebalance weekly × 4</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43adfebe54f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache comparison: Benchmarking HashMap, Guava, and Caffeine Under Heavy Load]]></title>
            <link>https://medium.com/@abhaybansal.1988/cache-comparison-benchmarking-hashmap-guava-and-caffeine-under-heavy-load-8345cba9e318?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8345cba9e318</guid>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 01:06:07 GMT</pubDate>
            <atom:updated>2025-08-31T01:06:07.310Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of high-performance Java applications, caching is king. But when multiple threads are simultaneously trying to read from and write to a cache, the choice of implementation can dramatically impact your application’s scalability and responsiveness. Beyond simple HashMap lookups, modern caching libraries like Google’s Guava Cache and Ben Manes’ Caffeine Cache offer intelligent eviction policies, time-based expiration, and robust concurrency features.</p><p>But how do these solutions stack up when pushed to their limits in a multithreaded environment? In this article, we’ll dive into a benchmark comparing:</p><ul><li>ConcurrentHashMap: Java’s built-in concurrent map, a solid baseline for concurrent key-value storage without advanced caching features.</li><li>Guava Cache: A mature and widely adopted caching library with a rich feature set.</li><li>Caffeine Cache: A newer, high-performance caching library often considered the spiritual successor to Guava Cache, known for its aggressive optimizations.</li></ul><p>We’ll run these benchmarks under heavy concurrent lookup pressure and analyze their performance with varying data sizes and thread counts.</p><h3>The Concurrent Benchmark Setup</h3><p>To simulate a realistic concurrent caching scenario, we designed the following test:</p><ul><li>Total Lookups: 10,000,000 (10 million) lookup operations per test.</li><li>Initial Data Size: We tested with two different initial data sizes: 1,000,000 entries and 100,000 entries. This data is used to pre-populate the caches/maps.</li><li>Cache Capacity: 50% of the Initial Data Size. For instance, if the data size was 1,000,000, the cache capacity was 500,000. This ensures the caches experience evictions, making the tests more realistic.</li><li>String Value Length: Each cached value was a string of 100 characters.</li><li>Lookup Pattern: Random access of keys within the dataSize range, ensuring a mix of cache hits and misses due to the capacity limits.</li><li>Concurrency: We varied the number of concurrent threads performing lookups: 1, 2, 4, 8, and 16 threads.</li><li>Execution: For each combination, we measured the total time (in milliseconds) required for all threads to complete their assigned portion of the 10 million lookups. A ThreadPoolExecutor was used to manage the worker threads, and CountDownLatch ensured all tasks completed before timing.</li></ul><h3>Benchmark Results: Deep Dive</h3><p>Let’s examine the performance of each cache type as concurrency increases.</p><h4>Scenario 1: Large Dataset (Initial Data Size: 1,000,000)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9esyXCUMlyUskeTK0xCug.png" /></figure><p>Key Observations for Large Dataset:</p><ul><li>ConcurrentHashMap Dominates at Low Concurrency: For 1 and 2 threads, ConcurrentHashMap is significantly faster. Its raw map operations with minimal overhead shine when contention is low.</li><li>Performance Degradation with ConcurrentHashMap: As concurrency increases beyond 2 threads, ConcurrentHashMap’s performance starts to degrade, indicating increased contention on its internal segments or locking mechanisms.</li><li>Caffeine Cache Scales Best: Caffeine Cache consistently maintains a strong position, and by 16 threads, it <em>surpasses</em> ConcurrentHashMap to become the fastest. This is a testament to its highly optimized concurrent algorithms and efficient cache management under heavy load.</li><li>Guava Cache is Robust, but Slower: Guava Cache delivers reliable performance but is generally the slowest in this high-concurrency, large-dataset scenario.</li></ul><h4>Scenario 2: Smaller Dataset (Initial Data Size: 100,000)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaVWrPGpzNWLxHun23D7EA.png" /></figure><p>Key Observations for Smaller Dataset:</p><ul><li>Overall Faster Times: As expected, all implementations are faster with a smaller dataset due to better CPU cache locality and potentially fewer actual cache misses (even with a 50% capacity, the smaller dataSize means fewer distinct keys need to be tracked).</li><li>ConcurrentHashMap Still Leads at Lower Threads: Similar to the larger dataset, ConcurrentHashMap is fastest for 1, 2, and even 4 threads.</li><li>Caffeine Cache Overtakes at High Concurrency: The trend of Caffeine Cache outperforming ConcurrentHashMap at higher thread counts holds true. By 16 threads, Caffeine Cache again emerges as the fastest, demonstrating its superior scalability.</li><li>Guava Cache Consistent, But Third: Guava Cache maintains its position as a reliable option, but consistently trails Caffeine Cache in performance.</li></ul><h3>The Verdict: Choosing Your Concurrent Cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_byi8cJQfe4br0zLF08YSg.png" /></figure><p>These benchmarks provide critical insights for selecting a caching solution in concurrent Java applications:</p><p>ConcurrentHashMap is excellent for raw concurrent map operations at low to moderate concurrency. If your application has minimal caching features (no eviction, expiration, etc.) and contention isn’t extremely high, it’s a very fast and low-overhead choice. However, its performance degrades noticeably under heavy multithreaded pressure.</p><p>Caffeine Cache is the undisputed champion for high-performance, feature-rich concurrent caching. It offers an unparalleled combination of speed and scalability. Its highly optimized internal algorithms allow it to manage evictions and concurrent access with remarkable efficiency, even outperforming ConcurrentHashMap when the number of concurrent threads is high. If your application demands intelligent caching with robust performance under heavy load, Caffeine is the top recommendation.</p><p>Guava Cache is a solid, mature, and feature-rich caching solution. It performs reliably, but in direct performance comparisons, it generally trails Caffeine Cache. It remains a good choice if you have existing Guava dependencies or if its specific feature set aligns perfectly with your needs and the absolute highest performance isn’t the sole driving factor.</p><p>In summary: When building concurrent Java applications that rely on caching, evaluate your workload carefully. For simple concurrent maps with low contention, ConcurrentHashMap is hard to beat. But when you need advanced caching features and superior scalability under heavy multithreaded access, Caffeine Cache should be your go-to choice. It’s built for the modern era of highly concurrent systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8345cba9e318" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Java’s ThreadPoolExecutor: Understanding Thread Growth with Real-World Benchmarks]]></title>
            <link>https://medium.com/@abhaybansal.1988/understanding-javas-threadpoolexecutor-understanding-thread-growth-with-real-world-benchmarks-e9f7d73ac0bd?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f7d73ac0bd</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 14:43:02 GMT</pubDate>
            <atom:updated>2025-08-31T00:51:54.062Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing concurrency in Java applications is crucial for performance and responsiveness. The java.util.concurrent.ThreadPoolExecutor is a powerful tool for this, but its optimal configuration often feels like a dark art. Developers frequently grapple with questions like: <em>When does the thread pool actually grow to its maximum size? How does the queue size interact with core and maximum threads? </em>In this article, we’ll dive deep into these questions using a series of benchmarks. We’ll simulate various workloads to observe how ThreadPoolExecutor creates new threads and what factors drive its expansion.</p><h3>A Quick Refresher: ThreadPoolExecutor Essentials</h3><p>Before we jump into the benchmarks, let’s quickly review the core components of a ThreadPoolExecutor:</p><ul><li><strong>corePoolSize</strong>: The number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set.</li><li><strong>maxPoolSize</strong>: The maximum number of threads that the pool is allowed to create.</li><li><strong>workQueue</strong>: A queue that holds tasks before they are executed. If all corePoolSize threads are busy, new tasks go into this queue.</li><li><strong>RejectedExecutionHandler</strong>: A strategy for handling tasks that cannot be executed (because the maxPoolSize threads are busy and the workQueue is full). Common policies include AbortPolicy, CallerRunsPolicy, DiscardPolicy, and DiscardOldestPolicy. For our tests, we’ll use CallerRunsPolicy, which makes the submitting thread run the task, ensuring all tasks are eventually processed.</li></ul><p>The thread creation logic follows a specific order:</p><ul><li>If active threads &lt; corePoolSize, a new thread is created.</li><li>Else if workQueue is not full, the task is added to the queue.</li><li>Else if active threads &lt; maxPoolSize, a new thread is created.</li><li>Else (queue is full and active threads = maxPoolSize), the task is handled by the RejectedExecutionHandler.</li></ul><h3>The Experimental Setup</h3><p>Our benchmark is designed to stress the ThreadPoolExecutor and observe its thread growth. Here’s how we configured our tests:</p><ul><li>Total Tasks: 10,000 tasks were submitted in each test run.</li><li>Task Duration: Each task simulated work by sleeping for 10 milliseconds.</li><li>Task Submission Contention: To mimic real-world scenarios where tasks don’t arrive perfectly synchronously, we introduced a random delay of 0 to 1 millisecond before submitting each task. This small, inconsistent delay proved to be a critical factor.</li><li>Maximum Pool Size (maxPoolSize): Fixed at 500 throughout all tests.</li><li>Core Pool Sizes Tested (corePoolSize): We ran separate sets of tests for corePoolSize values of 20, 50, and 100.</li><li>Queue Sizes Tested (queueSizes): For each corePoolSize, we varied the queue capacity: 0 (direct hand-off), 1, 5, 10, 100, 500, and 1000.</li></ul><p>The primary metric we focused on was the Maximum pool size reached, which tells us how many threads the ThreadPoolExecutor actually created at its peak.</p><h3>Benchmark Results and Analysis</h3><p>Let’s break down the results for each corePoolSize configuration.</p><h4>1. corePoolSize = 20</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qT8j_iM46YzQXtwHUppiAA.png" /></figure><h4>2. corePoolSize = 50</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYlSD85t6wBS3EERAu0ZUg.png" /></figure><p>3. corePoolSize = 100</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxZ9cxoQcfTSjFaF3rwnpQ.png" /></figure><h3>Key Takeaways for ThreadPoolExecutor Tuning</h3><p>These benchmarks offer valuable insights into configuring ThreadPoolExecutor effectively:</p><ul><li>Queue Size is Paramount for Burst Handling: The most significant factor influencing maxPoolSize utilization is the workQueue size, especially when tasks arrive in bursts (even with minimal, random delays).</li><li>Small/Zero Queues: Lead to rapid scaling up to maxPoolSize as tasks immediately overflow the core pool. This is suitable for latency-sensitive applications that prioritize immediate processing over thread creation overhead.</li><li>Large Queues: Effectively buffer task bursts, allowing the corePoolSize to process tasks steadily without the need to create additional threads. This is ideal for throughput-oriented applications that can tolerate some queuing delay and want to minimize thread creation/destruction overhead.</li><li>corePoolSize Sets the Baseline: A higher corePoolSize means the executor can handle more concurrent tasks <em>before</em> resorting to the queue or expanding the pool. It shifts the “tipping point” for maxPoolSize expansion to smaller queue sizes.</li><li>Contention Matters (Even Subtle Contention): Even a very small, random delay (0–1ms) before submitting tasks can create enough contention to trigger maxPoolSize expansion if the queue is too small. Understanding your application’s task <em>submission rate</em> (not just task execution time) is crucial.</li><li>CallerRunsPolicy as a Safeguard: Using CallerRunsPolicy ensures that even if the pool and queue are saturated, tasks are not lost but are instead executed by the submitting thread. While this can impact the submitting thread’s performance, it’s a robust way to guarantee task completion in overloaded scenarios.</li></ul><h3>Conclusion</h3><p>Tuning ThreadPoolExecutor is not a one-size-fits-all problem. It requires a deep understanding of your application’s workload characteristics:</p><ul><li>Are your tasks CPU-bound or I/O-bound? (Affects task duration and optimal corePoolSize).</li><li>Do tasks arrive in bursts, or at a steady rate? (Crucially impacts queueSize choice).</li><li>What are your latency and throughput requirements? (Guides the trade-off between thread creation and queuing).</li></ul><p>By carefully considering these factors and leveraging benchmarks like the ones presented here, you can configure your ThreadPoolExecutor to optimize performance, manage resources efficiently, and avoid unexpected thread growth or task rejections.Experiment with different configurations that reflect your application’s real-world behavior to find the sweet spot for your ThreadPoolExecutor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f7d73ac0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java JSON Serialization Shootout: Which Library Reigns Supreme?]]></title>
            <link>https://medium.com/@abhaybansal.1988/java-json-serialization-shootout-which-library-reigns-supreme-5ffd66018fe4?source=rss-4bb2ad5da6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ffd66018fe4</guid>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhay Bansal]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 12:08:16 GMT</pubDate>
            <atom:updated>2025-08-30T12:08:16.432Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive performance benchmark of Jackson, Gson, Fastjson, Fastjson2, and org.json for serialization and deserialization in Java.</h4><h4>1. Introduction</h4><ul><li>In the world of modern Java applications, JSON is king for data interchange. But with several powerful JSON libraries available, how do you choose the fastest one for your specific needs?</li><li>Different libraries have different strengths and weaknesses. This article aims to provide a data-driven comparison of popular Java JSON serialization and deserialization libraries.</li><li>Libraries Covered: We’ll put Jackson, Gson, Fastjson, Fastjson2, and the built-in org.json through rigorous tests.</li><li>Key Question: Which library offers the best performance for various data structures and workloads?</li></ul><h4>2. Methodology</h4><ul><li>Test Environment:</li><li>Java Version: 21</li><li>Gradle Version: (Latest)</li><li>Dependencies: Explicitly list the versions used (e.g., org.json:json:20231013, com.fasterxml.jackson.core:jackson-databind:2.13.0, com.google.code.gson:gson:2.10.1, com.alibaba:fastjson:1.2.78, com.alibaba.fastjson2:fastjson2:2.0.43).</li><li>Benchmarking Approach:</li><li>Iteration Counts: 10,000 iterations for Map&lt;String, String&gt; tests, 1,000 iterations for List&lt;CustomObject&gt; tests.</li><li>Data Size: Used “very large string values” to simulate real-world data and test scalability.</li><li>Data Structures:</li><li>Map&lt;String, String&gt;: Simple key-value pairs.</li><li>List&lt;CustomObject&gt;: More complex, nested data involving a custom CustomObject POJO (mention it has a no-arg constructor and getters/setters).</li><li>Measurements: System.nanoTime() for precise timing, converting to milliseconds for readability.</li><li>No JVM Warm-up (yet): Acknowledge that for true production benchmarks, JVM warm-up phases would be crucial, but for this comparison, direct timing was used. (This sets up a potential “Next Steps” section).</li></ul><h4>3. Performance Results: Serialization</h4><p>Let’s first look at how efficiently each library converts Java objects into JSON strings.</p><p>Benchmarking List&lt;CustomObject&gt; serialization with varying object counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5nOpjN-cZaPsFcaWUTO4Q.png" /></figure><p>Fastjson2 shows excellent scalability for serializing lists of custom objects, especially with higher object counts. Jackson and Fastjson (1.x) are strong contenders. Briefly explain why org.json is slower (manual mapping).</p><h4>4. Performance Results: Deserialization</h4><p>Now, let’s examine the reverse process: converting JSON strings back into Java objects.</p><p>Benchmarking Map&lt;String, String&gt; deserialization with varying entry counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7YeVgJnxtNWryJ2BPLHDA.png" /></figure><p>For deserializing simple Map&lt;String, String&gt; structures, Fastjson2 generally leads, particularly with more entries. Jackson is also very competitive.</p><p>Benchmarking List&lt;CustomObject&gt; deserialization with varying object counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGuHJmsgG1U4nXYHAYViKw.png" /></figure><p>Fastjson2 is remarkably fast for deserializing lists of custom objects, especially at higher object counts. Fastjson (1.x) also performs very well.</p><h4>5. Overall Conclusions &amp; Recommendations</h4><ul><li>Fastjson/Fastjson2: Excellent overall performance, often leading or very competitive in both serialization and deserialization, especially for custom objects and higher data volumes. Fastjson2 has a notable edge in some custom object scenarios.</li><li>Jackson: A consistently strong and reliable performer, usually a close second or third. A robust choice for general use.</li><li>Gson: A solid, general-purpose library, though typically not the top performer in these benchmarks.</li><li>org.json.JSONObject: Consistently the slowest due to its more manual approach and less optimized internal implementation for complex objects. Best avoided for performance-critical applications.</li></ul><p>When to use which:</p><ul><li>For absolute top performance with large, complex data, especially custom objects, Fastjson2 (or Fastjson) appears to be a strong contender.</li><li>For a balance of performance, features, and widespread adoption/ecosystem, Jackson remains an excellent and safe choice.</li><li>Gson is a good alternative, particularly if already integrated into your ecosystem or for simpler use cases.</li><li>Final Thought: Always benchmark in your specific environment with your specific data to make the most informed decision.</li></ul><h4>6. Next Steps</h4><ul><li>JVM Warm-up: For even more robust benchmarks, a JVM warm-up phase should be implemented to allow JIT optimizations to stabilize before measuring.</li><li>Thread Safety/Concurrency: Performance under concurrent access is another critical aspect to explore.</li><li>More Complex Data Structures: Investigate serialization/deserialization of deeply nested or polymorphic data structures.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ffd66018fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>