Blog / MarkupRx
Matching 13 federal drug-pricing datasets without letting fuzzy matches win
TL;DR
It ingests 13 federal sources and resolves ~239,000 NDC products to RxNorm concepts. Most of the interesting problems were in the data, not the product.
Companion to What one pharmacy owner taught me that 2,400 cold emails couldn't. That post is about why MarkupRx never found users. This one is for people who asked how it worked.
MarkupRx compared what independent pharmacies were reimbursed for generic drugs against what the drugs cost them, using only public federal data, and drafted appeals for the losses. It ingests 13 federal sources and resolves ~239,000 NDC products to RxNorm concepts. Most of the interesting problems were in the data, not the product. Here are the ones worth writing down.
Thirteen feeds, one join key
The join key across almost every source is the NDC, the National Drug Code. It comes in three 10-digit shapes (4-4-2, 5-3-2, 5-4-1) that all normalize to one 11-digit form by padding a different segment with a zero. Get the padding wrong and you silently join the wrong drug. So normalization is strict: split on dashes, require exactly three segments, pad by segment length, and raise on anything else. A bad NDC is skipped and logged, never "fixed." Every row stores both the 10- and 11-digit forms, so nothing converts on the fly.
The sources fight back in smaller ways too:
- Moving URLs. CMS removed the NADAC API, so the file URL is built from the most recent Wednesday. The Federal Upper Limit file is found by probing a handful of plausible dates across six months.
- Shifting headers. The ASP pricing workbook prepends title rows, so the header row is detected by scanning for a cell containing "hcpcs". NADAC switched its headers from snake_case to Title Case at one point, so all headers get normalized first.
- Floats where IDs should be. The Excel reader returns NDCs from the ASP file as floats, so 50242006001 arrives as "50242006001.0" and fails every length check until it's cast back to an integer.
- A methodology change. CMS changed how NADAC is calculated in December 2024, so rows after that date carry a flag.
Ingestion has to survive re-runs and republished files without double-counting. Each source loads into a staging table, then promotes to the main table with INSERT ... ON CONFLICT DO UPDATE inside one transaction, against a unique key such as (ndc_code, as_of_date) for prices. Re-ingesting the same file updates rows in place.
Two syncs of the same source must never run at once, so there are three locks: a Redis SETNX with a four-hour TTL, a Postgres advisory lock, and a partial unique index on the run log, so only one run per source can be open at a time:
CREATE UNIQUE INDEX uix_sync_run_source_inflight
ON sync_run(source) WHERE completed_at IS NULL;
The database is the last line of defense if the other two locks fail.
Price history (~837,000 NADAC rows now) is range-partitioned by year on as_of_date, so time-range queries only touch the years they need.
Resolving a drug in six passes, with fuzzy matching that can never win
To compare prices across sources you need to know that two NDCs are the same drug, which means mapping each NDC to an RxNorm concept (an RxCUI). The project's instruction file for the agent says, in capitals, never use fuzzy text matching for drug names. A wrong match in a pricing appeal is worse than no match.
That's not quite what shipped, and the difference is the useful part. Resolution runs in passes, from most to least authoritative:
- Normalize the NDC (above). No fallback.
- openFDA's own RxCUI list for each product, at ingest. Confidence 1.0.
- RxNorm's monthly bulk file, mapping NDCs to concepts where the mapping isn't marked obsolete.
- RxNorm API, run backwards. Instead of asking "what concept is this NDC?" for ~228,000 unmatched NDCs, ask "which NDCs belong to this concept?" for ~32,000 concepts. That's about 7× fewer calls under a 20-requests-per-second limit, and every match is guaranteed to point at a real concept, because you started from one.
- RxNorm API forward, then an approximate-name match as a last resort, with confidence capped at 0.85.
- Orange Book chaining: application number → FDA product → NDC → concept, plus a trigram-similarity fallback.
So two fuzzy steps exist. The rule that makes them safe: every pass only fills rows that are still unmatched, every link records where it came from and how confident it is, and a fuzzy match can never overwrite an exact one. Unmatched rows stay NULL and are retried next run. The rule isn't really "no fuzzy matching." It's "fuzzy matching can never silently win."
Where it landed: 70.5% of ~239,000 NDC products resolve to a concept. About 30% of NDC products (70,530 of 239,278) still carry no RxNorm drug-concept link — they resolve to no canonical drug and are excluded from cross-source joins.
The unit-of-measure bug that made every loss figure wrong
The core math is simple: a claim is underwater when what the pharmacy was paid is less than NADAC (the national average acquisition cost) times the quantity dispensed. Two details make it honest. NADAC is taken as of the dispense date, not today's price. And for the public benchmark, reimbursement per unit comes from Medicaid utilization data (SDUD) for the same drug and quarter.
The bug: a materialized view of quarterly NADAC averages dropped the pricing_unit column. Some drugs are priced per mL, others per each. Once the unit was gone, the system compared a per-mL reimbursement against a per-each cost, and produced confident, precise, wrong loss figures.
The right fix would be converting mL to each. But no free per-NDC conversion table exists. So the fix is a refusal instead:
- Only compare drug-quarter cells where NADAC has exactly one pricing unit (
HAVING COUNT(DISTINCT pricing_unit) = 1). - Drop implausible spreads: a cost more than 10× the reimbursement, or a loss worse than $1,000 per fill.
- Anything that fails renders as N/A, never $0, because a $0 on an appeal letter reads as "no loss".
The bug was caught the way I'd want: failing regression tests were written first, and the guard was built to make them pass.
Evidence you can re-derive, not just store
An appeal is an argument with a payer that will look for holes. So the evidence behind each flagged claim is frozen at the moment the letter is generated: the NADAC price and its as-of date, the per-unit figures, the loss, which data source it came from (the pharmacy's own claims or the Medicaid benchmark), and one-way hashes of the claim references, never the raw values.
The PDF itself is never stored. It's regenerated from that frozen snapshot, deterministically, every time. The letter also has to say where its numbers came from: benchmark figures are labeled as Medicaid benchmark data, not pharmacy-specific claims.
For audits, an export bundle collects the regenerated PDFs, a manifest listing each file with its SHA-256, and a signature over that manifest. The manifest is canonical JSON (sorted keys, no whitespace) signed with an ECDSA P-256 key that lives only in AWS KMS. The public key is committed to the repo. Anyone can check it: re-render the PDFs, hash them, compare with the manifest, verify the signature. Nobody can quietly change the numbers after filing.
This is the same habit I picked up building bank reconciliation and GL reporting in a previous job: if a number can't be traced back to its source, nobody should trust it.
How the agent-written code was kept honest
Claude Code did most of the typing. I wrote specs, edge cases and reviews; the agent proposed changes. Some numbers from the repo:
- 2,641 commits from March to June 2026, essentially one author.
- ~2,660 tests, mostly integration tests against a real Postgres. The instruction file says it directly: mock-heavy tests miss protocol and infrastructure bugs. A full run takes about 17 minutes.
- ~56,800 lines of Python test code against ~55,600 lines of Python application code.
- Architecture tests that fail the build if layers import each other the wrong way (for example, the API layer importing the ingestion pipeline).
The surprise: the single hard CI gate isn't the test suite. It's a check that every frontend route is claimed by exactly one workflow document. The largest category of commits (about 1,230 of 2,641) is documentation. When an agent writes code fast, the thing that keeps drifting is the gap between what the code does and what anyone thinks it does, so that gap is what I gated on.
The instruction file also stated rules that the code later bent, like the fuzzy-matching rule above. Treat the instruction file as a set of claims to verify, not a description of the system.
I build payments and ledger software, most recently in card products. I'm open to contract work: [email protected].
Related reading