惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Cisco Talos Blog
Cisco Talos Blog
Help Net Security
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
AWS News Blog
AWS News Blog
The Last Watchdog
The Last Watchdog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog
A
About on SuperTechFans
The Hacker News
The Hacker News
B
Blog RSS Feed
Simon Willison's Weblog
Simon Willison's Weblog
宝玉的分享
宝玉的分享
小众软件
小众软件
博客园_首页
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
Attack and Defense Labs
Attack and Defense Labs
G
GRAHAM CLULEY
A
Arctic Wolf
H
Hacker News: Front Page
博客园 - 叶小钗
PCI Perspectives
PCI Perspectives
W
WeLiveSecurity
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
N
News | PayPal Newsroom
Martin Fowler
Martin Fowler
N
Netflix TechBlog - Medium
Cloudbric
Cloudbric
NISL@THU
NISL@THU
H
Help Net Security
C
CERT Recently Published Vulnerability Notes
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Project Zero
Project Zero
The Register - Security
The Register - Security
S
Secure Thoughts
Vercel News
Vercel News
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 最新话题
Recent Announcements
Recent Announcements
L
Lohrmann on Cybersecurity
T
The Exploit Database - CXSecurity.com
Hacker News - Newest:
Hacker News - Newest: "LLM"
O
OpenAI News
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Healthcare RCM Analytics API with FastAPI and PostgreSQL
luis8choa · 2026-05-19 · via DEV Community

Introduction

I'm a biomedical engineer who ended up doing data analysis for a Revenue Cycle Management company in the U.S. — and honestly, I wouldn't change it. There's something fascinating about the intersection of healthcare operations and data.

But after two years on the floor, one thing became painfully obvious: the people actually resolving claims — billers, coders, AR agents — are flying blind. We're working with spreadsheets, static reports that are already two days old, and gut feeling. When you're processing 60,000+ claims a month, gut feeling doesn't scale.

The bottlenecks are always the same: which payer is denying the most claims right now? Which claims have been sitting unpaid for 90+ days and are probably never going to be resolved? Who on the team has a 40% error rate that nobody has flagged yet?

This information exists. It's sitting in the database. Nobody built the tool to surface it.

So I did. This is the story of building a REST API that gives RCM teams real-time access to the KPIs that actually matter — denial rates, AR days, aging buckets, and staff productivity — using FastAPI and PostgreSQL.


Section 1: What is Revenue Cycle Management?

If you're not in healthcare, RCM might sound abstract. Let me make it concrete.

Every time a patient sees a doctor, the provider needs to get paid. That payment doesn't come directly from the patient in most cases — it comes from an insurance company (called a payer). The process of getting that money from the payer is Revenue Cycle Management.

The claim cycle looks like this:

Medical service rendered
        ↓
Medical coding (CPT codes assigned to each procedure)
        ↓
Claim submitted to payer
        ↓
Payer reviews the claim
        ↓
Paid / Denied / Pending / Appealed

Enter fullscreen mode Exit fullscreen mode

Two numbers tell you almost everything about the health of this cycle:

Denial Rate — the percentage of claims a payer rejects. A high denial rate with a specific payer usually signals a billing accuracy problem, a credentialing issue, or a payer policy change nobody caught. If BlueCross is denying 35% of your claims and Aetna is only denying 8%, that's where your team should be focused.

AR Days — how many days on average it takes from claim submission to payment. The industry benchmark is 40 days. Above that, cash flow starts to suffer. Above 90 days, you're probably not getting paid at all.

The problem isn't that this data doesn't exist — it does. The problem is that when you're managing 60,000+ claims, nobody has a clean, real-time view of it. Directors and managers are making staffing and process decisions based on reports that are already outdated.

That's the gap this API fills.


Section 2: Architecture Decisions

When I started thinking about how to build this, I had three requirements: it had to be fast to query, easy for other developers to understand and extend, and it had to separate the business logic cleanly from the HTTP layer.

Why FastAPI over Flask or Django

FastAPI generates interactive API documentation automatically from your code. For a tool that other analysts or developers might consume, that matters enormously — the /docs endpoint gives you a working Swagger UI with zero extra configuration. Flask would have required a separate library for that. Django would have been overkill for an API-only project.

FastAPI also validates request and response data automatically using Python type hints, which catches entire categories of bugs before they reach production.

The Service Layer Pattern

The most important architectural decision was separating business logic into a services/ layer completely independent from the HTTP routing layer.

routers/claims.py             receives HTTP request, validates parameters
services/claims_service.py    contains the actual calculation logic

Enter fullscreen mode Exit fullscreen mode

This means two things in practice. First, the alert system can call get_denial_rate() directly from claims_service without making an internal HTTP request — it just calls the Python function. Second, testing the denial rate calculation doesn't require simulating an HTTP request — you call the function directly with a database session.

SQLAlchemy 2.0 with Pydantic v2

SQLAlchemy handles the relationship between Python objects and PostgreSQL tables. Pydantic handles the relationship between Python objects and JSON. They solve different problems and that's why you need both.

A SQLAlchemy model says: "this is how a claim is stored in the database — all columns, all relationships, including internal fields like hashed_password."

A Pydantic schema says: "this is what a claim looks like when it enters or leaves the API — only the fields the client should see."

The separation is what prevents accidentally exposing hashed_password in a response.


Section 3: The Denial Rate Calculation

This is the query I'm most proud of in the project — not because it's complex, but because it took me a while to realize it could be done in a single database round trip.

My first instinct was two separate queries:

# Query 1 — total claims per payer
total = db.query(Claim.payer, func.count(Claim.id)).group_by(Claim.payer).all()

# Query 2 — denied claims per payer
denied = db.query(Claim.payer, func.count(Claim.id))\
           .filter(Claim.status == "denied")\
           .group_by(Claim.payer).all()

Enter fullscreen mode Exit fullscreen mode

Two trips to the database. Two result sets to merge in Python. More code, more room for error.

The better approach uses a conditional SUM with CASE WHEN — a single query that counts everything at once:

results = db.query(
    Claim.payer,
    func.count(Claim.id).label("total"),
    func.sum(
        case((Claim.status == "denied", 1), else_=0)
    ).label("denied"),
).group_by(Claim.payer).all()

Enter fullscreen mode Exit fullscreen mode

The SQL this generates:

SELECT payer,
       COUNT(id) AS total,
       SUM(CASE WHEN status = 'denied' THEN 1 ELSE 0 END) AS denied
FROM claims
GROUP BY payer

Enter fullscreen mode Exit fullscreen mode

The CASE WHEN assigns 1 to every denied claim and 0 to everything else. SUM adds those up. One query, one database round trip, all the data you need.

The denial rate is then calculated in Python:

"rate": round((row.denied or 0) / row.total * 100, 2)

Enter fullscreen mode Exit fullscreen mode

The or 0 handles the edge case where SUM returns NULL for payers with zero denials — in SQL, summing an empty set returns NULL, not 0.


Section 4: Testing Strategy

Testing an API that talks to a database introduces a fundamental problem: you can't run tests against your production database, but you also can't test database logic without a database.

The solution has two parts.

SQLite for local tests

Instead of requiring a running PostgreSQL server to run tests, the test suite uses SQLite — a file-based database that needs no server. Each test creates all tables, runs, and drops everything:

@pytest.fixture(autouse=True)
def setup_db():
    Base.metadata.create_all(bind=engine_test)  # create tables
    yield                                         # run the test
    Base.metadata.drop_all(bind=engine_test)     # drop everything

Enter fullscreen mode Exit fullscreen mode

Every test starts with a completely clean database. No data contamination between tests.

FastAPI's dependency_overrides

The bridge between "my app talks to PostgreSQL" and "my tests talk to SQLite" is FastAPI's dependency override system:

app.dependency_overrides[get_db] = override_get_db

Enter fullscreen mode Exit fullscreen mode

This single line tells FastAPI: "whenever any endpoint asks for get_db, give it override_get_db instead." Every endpoint in the application — without modifying a single line of production code — now talks to SQLite during tests.

The 80% coverage threshold

The CI pipeline fails if test coverage drops below 80%. This isn't about achieving a number — it's about making coverage degradation visible. If someone adds a new service function and forgets to write tests for it, the pipeline catches it before the code reaches main.

The current coverage is 93%.


Conclusion

Two years working in RCM gave me a very specific frustration. Ten weeks of building gave me a very specific solution.

The most valuable part of this project wasn't any particular technical decision — it was having to translate operational problems into database queries and vice versa. That translation is hard to fake in an interview, and hard to build without having been on both sides of it.

The project is open source:
🔗 github.com/luis8choa/RCM-Analytics-API

What's next: a frontend dashboard to visualize the KPIs, and a production deploy so billing teams can actually use it.

If you work in healthcare operations and this resonates — or if you have feedback on the technical side — I'd genuinely like to hear from you.