cancel
Showing results for 
Search instead for 
Did you mean: 
Lakebase Articles
A structured knowledge hub for Lakebase. Find in-depth technical content, how-to guides, and reference material to support your development and learning journey.
cancel
Showing results for 
Search instead for 
Did you mean: 

Test on a Branch, Not on Patients: Agentic Drug Substitution with Lakebase

SumanthGhanta
Databricks Employee
Databricks Employee

An agent tests the fix on a Lakebase branch. A pharmacist approves it.

By Sumanth Ghanta and Thomas Roach · 10 min read

 

TL;DR: The U.S. still has more than 200 active drug shortages, and each one forces hospitals to change how they order, dispense, and dose a drug. That change is where patients get hurt. Most teams still work it out in spreadsheets or in test systems that are weeks old. This post shows how we give an AI agent its own disposable copy of production, a Lakebase branch created in under a second, so it can run the whole substitution against real data and real rules. A pharmacist approves the result before any changes are made in production.

sghantadbx_0-1792967860865.png

 

Shortages are now part of the daily job

When Hurricane Helene flooded Baxter's North Cove plant in September 2024, U.S. hospitals lost access to roughly 60% of their IV solutions. Within two weeks, more than 86% of providers surveyed by Premier were short of IV fluids.[1] 

Helene made the news. Most shortages don't. Active U.S. shortages peaked at 323 in early 2024, the most since tracking began in 2001, and were still at 227 in mid-2026.[2]  The average one has lasted more than four years.[3]  Managing them costs U.S. hospitals about 20.2 million staff-hours and $894 million annually.[4]  The root causes, mostly thin margins on cheap generics, will take years of policy work to fix. [5] 

Each shortage raises the same questions. Is there an alternative? Which patients are affected? What does it cost? Is there enough of the substitute? Does the formulary need to change? Who needs to know? Most hospitals still answer them with spreadsheets and manual tracking: 69.7% of pharmacy professionals in a 2026 survey named those as their main tools.[6]  And it's constant. In a national survey, more than two-thirds of health-system pharmacists had dealt with over 50 shortages in a year.[7] 

 

The dangerous part is the fix

The shortage itself rarely hurts anyone, the fix can. In cases collected by ISMP, one hospital substituted methohexital for propofol, staff made a dilution error with the unfamiliar drug, and the patient died of an overdose. At another, the pharmacy mixed its own bupivacaine with epinephrine, added too much epinephrine, and two patients went into ventricular fibrillation.[8] 

Those are the worst cases, but the pattern is common. Two-thirds of reported shortage errors involve the wrong dose or concentration,9 and 43% of hospitals report medication errors tied to shortages.[4] 

That's because responding to a shortage means changing production systems: the formulary, order sets, smart-pump libraries, and dispensing cabinets, and then training staff.[10]  At one academic medical center, routine changes like these took up to 14 days, and 44 of the 50 shortages it studied needed them faster.[11] 

 

How the change gets tested today

Before a substitution goes live, someone has to work out who it affects, what it costs, and what it breaks. Here's how that tends to happen. The first three are what pharmacy teams do. The rest are what a data team reaches for when someone asks it to run a what-if analysis. The times are our rough estimates, not measurements.

 

Approach

Time to a tested answer

Where it falls short

Reports, chart review, and a spreadsheet

Hours to days, per shortage

Someone exports the patients on the drug, the inventory, and the prices, then works out the swap by hand. None of the system's rules apply, audits find errors in most spreadsheets,[12]  and patient data ends up in files on laptops. The numbers are out of date by the next morning.

Make the change under pressure

Hours to make, days or weeks to see the full impact

In an urgent shortage, pharmacists switch orders one at a time as they verify them, under an interchange protocol, and IT pushes order-set or formulary changes through an expedited path with only a few test scenarios. Both happen in the live system, on real patients' orders, so problems show up in production. Many of the substitution errors described above happen in exactly this setting.

EHR or pharmacy test environment

Days to weeks

Built for software releases, not same-day decisions. The data is often weeks old: across industries, 51% of organizations take a month or more to refresh test data.[13]  The patients are often test or de-identified records, so allergies, kidney function, and ages may not match your real patients. Other teams share it.

Full database copy

Hours to set up, for every copy

It works, but every copy stores all the data again and has to be secured like production. Copies pile up: 45% of organizations keep 3 to 10 non-production copies of each dataset, and 60% have had sensitive data breached or stolen from non-production environments.[14] 

Reporting database or read replica

Minutes

Fine for "how many patients are on Lisinopril?" It's read-only, so it can't run the change.

Production with a rollback

Minutes

Holds locks on live tables, and the transaction can't stay open while a pharmacist spends the afternoon reviewing results. One slip and it's real.

Scratch tables

An hour or two of engineering

Foreign keys and triggers don't come along, and the app's queries have to be rewritten. It's no longer the real system.

Ask the agent

Seconds

It can read the data, but it can't run the change, so everything after the first write is the model's guess.

Each of these works for the job it was designed for. The trouble starts when the question takes several steps.

A substitution plan is a chain. Set the new drug active in the formulary. Find the affected patients. Reallocate inventory to them. Then calculate cost and 90-day coverage. Each step reads what the step before it wrote. Our rule of thumb: if a later step needs to read what an earlier step wrote, you need a writable, private copy of production. Only one option in that table gives you that, and it takes hours. A Lakebase branch gives you the same thing in under a second. We'll get to it after a quick look at the architecture.

 

The architecture: early warning on the Lakehouse, decisions on Lakebase

Before an agent can test a fix, it needs to know which shortages to work on. Every morning, the pharmacy and supply-chain teams get a ranked list of drugs that might run out, and the reason for each one, and the riskiest ones go to the agent.

sghantadbx_1-1792967860865.png

The work is split between two systems. The Lakehouse holds the history: it takes in the feeds, joins them, and scores risk. Lakebase, the Postgres database on Databricks, runs the app day-to-day and gives the agent a safe copy of production to work in. Here are the six steps:

  1. Ingest public and internal signals with Lakeflow: the openFDA shortages API, wholesaler EDI, ERP inventory, EHR dispensing, and supplier notices.
  2. Unify them into a medallion architecture governed by Unity Catalog, with a single drug-item master keyed by NDC and RxNorm.
  3. Score every drug's shortage risk using a model that combines national status, local days on hand, fill-rate trends, and supplier concentration.
  4. Explain risk in plain language using AI Functions to pull structured facts out of unstructured supplier notices.
  5. Serve scores and recommendations to the app through Lakebase synced tables, and record every approval and action in Lakebase decision tables that stream back to the Lakehouse through CDF.
  6. Rehearse each response on a disposable Lakebase branch, where a pharmacist agent simulates the change against the real production state before anyone approves it.

The diagrams below zoom in on three of those steps.

sghantadbx_2-1792967860865.png

sghantadbx_3-1792967860866.png

sghantadbx_4-1792967860866.png

 

Testing the fix on a Lakebase branch

A Lakebase branch is a disposable copy of a Lakebase database, the managed Postgres on Databricks. Four things make it a good fit here:

  • It's ready in under a second, no matter how big the database is.
  • It starts with production's schema, data, and database roles, and stores only what changes.
  • It runs on its own compute, so the agent's queries and writes don't compete with production for CPU and memory. Creating a branch has no performance impact on production, and branch compute scales to zero when it's idle.[15] 
  • A branch with an expiration date is billed only for the data that changes on it.[15] 

We tried it end-to-end in Supply Intelligence, a Databricks App on Lakebase for a fictional eight-hospital network. All of its data is synthetic.

The test case: Lisinopril 10 mg goes on allocation. Switching every order to Losartan 50 mg looks simple, but it's a switch from an ACE inhibitor to an ARB, not a generic swap, and the right answer depends on the patient. Across 1,847 patients, the agent found six groups:

Group

Patients

Action

A

Standard hypertension conversion

Safe to substitute automatically

B

Reduced kidney function

Adjusted starting dose

C

History of angioedema

Stop: individual review

D

Under 6 years old

Stop: consider another drug class

E

Need potassium monitoring

Eligible, with updated monitoring

F

Heart failure or post-MI

25 mg start with titration

A simple unit-price swap across all patients overstates the monthly cost by about [$52,000; confirm in a live run]. The agent recalculates it by indication instead.

Working that out is exactly the chain from the table above: set Losartan active in the formulary, find the affected patients, reallocate inventory to them, then calculate cost and 90-day coverage. A read replica can't run it, a spreadsheet can't enforce the rules, and we wouldn't let an agent try it in production.

So each simulation gets its own disposable production branch, created in under a second with a two-hour TTL, so abandoned work cleans itself up.

The branch has the same schema, constraints, and triggers as production, so if a plan would break a rule in production, it breaks on the branch first. Every pharmacist and every agent run gets its own branch, so competing plans never collide. The pharmacist reviews the patient groups, the findings, and the corrected cost, then approves. Discarding the simulation drops the branch. The same pattern lets you branch a point-in-time snapshot to replay a past recall, or give every pull request its own branch in CI.

Three rules keep it safe:

  • Approving isn't applying. Approval freezes the plan, and only a separate apply step writes to production.
  • The agent never holds production write access. It works on its branch, and the production write path is part of the apply step.
  • We replay the plan, not the branch. Production may have changed while the simulation ran, so we apply a short, reviewed set of changes instead of copying the branch back. Lakebase branches don't merge anyway.

sghantadbx_5-1792967860866.png

 

Running it for real

Supply Intelligence is a reference implementation. Before you use the pattern on real patients, plan for these:

  • Store simulation sessions and approvals in a table, so they survive an app restart.
  • Scope the agent's credentials to simulation branches only.
  • Check at apply-time that production hasn't changed in a way that invalidates the plan.
  • Stay inside the project limits on branches and active computes. One branch per decision with a short TTL keeps you well clear of them.
  • Govern branches like production. A branch of a table with PHI still contains PHI, so the same classification, masking, and access controls apply.

 

What it's worth

In our demo environment, the simulation ran in under a minute, given the low data volume. This will probably take longer for complex substitutions, as the investigations/iterations, and MCP tool/API callouts grow.

  • A tested answer the same day. The agent runs the entire substitution on a branch in minutes to hours, instead of days of spreadsheet work and test-environment builds.
  • Less manual work. Shortage management takes 10+ staff-hours per week in most health systems.[16]  A single watchlist replaces hours of cross-checking FDA lists, portals, and spreadsheets.
  • Safer changes. A pharmacist approves a plan that has already run against real patients and real rules, and production changes only when they apply it.

 

Where to start

You don't need the whole pipeline to start. Pick one kind of decision, like a therapeutic interchange, and run it on a branch with synthetic or de-identified data, timing how long the branch and the simulation take. Then sync formulary, inventory, and census tables from the Lakehouse into Lakebase, add the agent, and put a pharmacist approval step in front of production. Once that works, add the early-warning scores so the agent takes the riskiest shortages first, and extend the pattern to purchase-order reallocation and recall response.

 

Wrapping up

No single hospital can fix drug shortages. That takes changes to generic drug economics, sourcing, and policy. What a hospital can control is how safely it responds. Today, the response gets worked out in spreadsheets and test systems that can't run the real change, and the mistakes show up at the bedside. A Lakebase branch lets an agent run the whole change against real data and real rules, in a copy nobody else touches, and a pharmacist still decides whether it goes live.

The Supply Intelligence app is on GitHub at sghanta-sf/supply-intelligence. It includes the Lakebase schema and synthetic data, the branch workflow, and the substitution agent. The Lakehouse pipeline and risk model from Steps 1 to 4 aren't in the repo yet.

If you're working on drug shortages where you are, tell us in the comments which signals have actually helped.

Thomas Roach is Lead Solutions Architect at Databricks, supporting Healthcare

Sumanth Ghanta is Sr. Solutions Architect at Databricks, supporting Healthcare

References

[1] Premier: >86% of providers experiencing IV fluid shortages; CDC HAN: Shortage of IV and peritoneal dialysis solutions

[2] ASHP drug shortage statistics (University of Utah Drug Information Service data)

[3] USP: Long-lasting drug shortages drive average duration higher

[4] Vizient: Drug shortages cost hospitals nearly $900M annually in labor

[5] FDA: Drug Shortages — Root Causes and Potential Solutions

[6] Bluesight: 2026 Hospital Pharmacy Operations Report (a vendor survey)

[7] Hantel et al., A National Survey of Health System Pharmacists, JAMA Internal Medicine (2019)

[8] ISMP: A shortage of everything except errors (2012)

[9] ISMP: Drug shortages survey results (2017)

[10] ASHP Guidelines on Managing Drug Product Shortages (AJHP, 2018)

[11] Informatics impact of drug shortages, ASHP Summer Meeting poster abstracts (2013)

[12] Panko: What we know about spreadsheet errors (spreadsheet audit studies)

[13] Redgate: 2025 State of the Database Landscape

[14] Perforce Delphix: 2025 State of Data Compliance and Security Report

[15] Databricks docs: Lakebase branches

[16] Premier: Supply chain resiliency survey

[17] Supply Intelligence app is on GitHub at sghanta-sf/supply-intelligence

 

 

2 REPLIES 2

Pramod_Emani
New Contributor II

Thanks for the detailed write-up. "Replay the plan, not the branch" is the idea that does the real work here: the branch becomes a rehearsal space, and the apply step becomes a short, reviewable diff instead of a promoted staging copy.

 

One question from a deployment angle: between the pharmacist's review and the apply step, new orders and inventory movements will land in production. Do you re-run the patient grouping at apply time and diff it against the approved plan, or abort if the source tables changed?

 

And the reminder that a branch of a PHI table is still PHI belongs in every Lakebase branching tutorial.

Hey  @Pramod_Emani 

That will entirely depend on the pharmacy/formulary department’s policies. However, we should assume the source tables in production will change. The branch is not the source of truth; it is the investigation and simulation environment.

It also depends on whether approval-to-apply is short-lived. If the window is short, the approved plan can be treated as valid against that snapshot. If it is longer, because branching is cheap/easy/fast, the straightforward path is to create a new branch from current production and re-run the same investigation. You can also reset the working copy from the parent. You can compare the two runs and, if they differ, seek a fresh approval. The first approval does not carry over to a new snapshot.

In short, the operational gate here is to confirm that patient cohort classes still match what was approved, and no new classes emerged. Not a headcount tally within a class the pharmacist already signed.

A parallel operational step can be negotiating with suppliers so the substitute can meet this demand.