AI-powered anomaly detection to stop counterfeit drugs and prescription fraud in real time
Case Study2026

AI-powered anomaly detection to stop counterfeit drugs and prescription fraud in real time

PythonTypeScriptRabbitMQPostgreSQLRedisAzure OpenAILangGraphHL7 FHIREPCISGS1 SGTINAWS

About The Project

From paper trails and reactive recalls to an AI sentinel watching every handoff. Pharmaceutical distributors operating across countries face an escalating dual crisis: counterfeit drugs infiltrating their distribution network at the last customs handoff, and prescription anomalies, duplicate dispensing, forged e-Rx records, and duplicate dispensing of controlled substances flagged by the platform's internal clinical safety thresholds going undetected until monthly audits. With the FDA's phased DSCSA enforcement window running from May 2025 through November 2026 depending on entity type, the client faced an imminent, staggered set of compliance deadlines and needed a system that would be audit-ready before each one triggered.

We built a web-based platform that placed an AI reasoning agent, powered by Azure OpenAI and orchestrated with LangGraph, at every critical handoff point in the supply chain. The agent cross-references serialisation records, EPCIS events, and prescription histories in real time, flags anomalies within seconds, and writes every decision to an immutable audit ledger. Manual audits dropped from monthly to on-demand. Counterfeit interception moved from post-recall to point-of-entry.

AI-powered anomaly detection to stop counterfeit drugs and prescription fraud in real time supporting graphic

System Architecture

System Architecture diagram

Key Challenges

Safety & fraud

Counterfeit drugs entering at the distributor handoff- undetected until recalls. The client's warehouse received 1,200 to 3,000 individual batch scans per day. Their legacy WMS checked only format validity of the GS1 barcode, not whether the serial number had already been dispensed elsewhere, cloned, or was missing from the manufacturer's ledger. Counterfeit batches with syntactically valid but semantically fraudulent serial numbers were passing through. The average detection lag was 47 days after distribution to pharmacies.

Prescription control

Duplicate dispensing of controlled substances flagged against platform-defined clinical safety thresholds. The HL7 FHIR e-Rx system issued prescriptions from three hospital EHRs. There was no cross-system deduplication: the same MedicationRequest bundle could be dispensed at two pharmacies in different cities for the same patient on the same day. For controlled substances like tramadol, benzodiazepines; this was both a clinical risk and a violation of the distributor's own safety protocols. While CDSCO Schedule H1 mandates a Register of Sale for these drugs and requires three-year record retention, it does not define a national per-patient monthly quota. The platform implemented configurable clinical thresholds to fill this gap proactively. The fraud was invisible because each pharmacy's system was a silo.

Regulatory compliance

Three jurisdictions, three audit formats, no shared traceability record. Operating across India, UAE, and an EU export channel meant three different compliance regimes: CDSCO Schedule H1, UAE MOHAP traceability mandates, and EU FMD Article 54a verification. Each regulator expected a different report format, different event granularity, and different response SLAs for deviation reports. The team was manually reformatting PostgreSQL exports into Word documents for each quarterly audit, a process that took 3 to 5 staff-days per cycle and introduced transcription errors.

Our Solution

Compliance across borders

Three jurisdictions, three audit formats, no shared traceability record. Operating across India, UAE, and an EU export channel meant three different compliance regimes: CDSCO Schedule H1, UAE MOHAP traceability mandates, and EU FMD Article 54a verification. Each regulator expected a different report format, different event granularity, and different response SLAs for deviation reports. The team was manually reformatting PostgreSQL exports into Word documents for each quarterly audit, a process that took 3 to 5 staff-days per cycle and introduced transcription errors.

AI serial number sentinel

Every inbound batch scan triggers a Python worker that publishes a scan.received event to RabbitMQ. The LangGraph agent pulls the GS1 SGTIN from the event, queries PostgreSQL for the full chain-of-custody history, checks Redis for recent scan activity (clone detection: same serial scanned at two locations within 24 hrs), and first runs a deterministic Python rule engine to validate geographic and temporal plausibility- checking whether the shipment could physically traverse the distance between scan locations in the elapsed time. Only when this check is inconclusive due to ambiguous custody documentation, multi-hop routing, or missing intermediate scan events does the system invoke the Azure OpenAI reasoning model to evaluate broader contextual plausibility. Upon detecting an anomaly, the agent sets a QUARANTINE flag in the WMS via REST, posts a RabbitMQ alert.counterfeit event, and auto-drafts the appropriate deviation report for the batch's destination jurisdiction: a DSCSA §582 deviation notice for US-destined batches, a CDSCO Form 26 deviation report for India, an EU FMD Article 20 competent authority notification for EU-bound batches, and a MOHAP/Tatmeen incident report for UAE.

Cross-silo e-rx deduplication engine

A TypeScript service subscribes to rx.dispense.requested events from the three hospital FHIR endpoints within the client's contracted network, each connected under a formal data-sharing agreement. This federated model operates within a defined partner network; it does not claim full national interoperability across India's broader EHR ecosystem, which remains under development via the NDHM/ABHA infrastructure. Before authorising a dispense, it materialises a patient-level prescription state in Redis (TTL: 30 days). The 30-day Redis TTL serves the active deduplication window only. All dispense events are simultaneously written to PostgreSQL as the durable audit record, satisfying the CDSCO Schedule H1 three-year record retention requirement. Keyed on patient ABHA ID (Ayushman Bharat Health Account) in India, Emirates ID in the UAE, and national health number in the EU channel with a configurable identity scheme per jurisdiction combined with ATC drug code and prescriber ID. The LangGraph agent evaluates: Is this the same bundle? Is the inter-dispense interval clinically plausible? Has the patient's dispense frequency exceeded the platform's configured clinical safety threshold for this drug class this month? Decisions: approve, hold, flag - are written back to the FHIR server as a "MedicationDispense" status and to the PostgreSQL audit ledger atomically.

Multi-jurisdiction regulatory report generator

A Python APScheduler job runs nightly, querying the immutable audit ledger for events requiring regulatory reporting. The LangGraph agent classifies each event by jurisdiction (CDSCO / MOHAP / EU FMD) using the batch's country-of-destination field, then prompts Azure OpenAI to generate the jurisdiction-specific report in the correct format (CDSCO XML, UAE MOHAP submission via the Tatmeen traceability platform API, EU EMVS API call). Reports are reviewed in a React.js dashboard before one-click submission.

Supply chain intelligence dashboard

A React.js + TypeScript frontend gives warehouse managers, compliance officers, and regulators (read-only, scoped by jurisdiction) a live view of the AI agent's decision log, quarantine queue, batch heatmap by risk score, and prescription anomaly feed. The dashboard is deployed as a Docker container on AWS with role-based access, a pharmacy sees only their dispense history; a CDSCO auditor sees all India-destined events, nothing else.

The Result

94% Faster anomaly detection

Mean time from counterfeit batch entry to quarantine dropped from 47 days to under 3 hours

100% pre-deadline compliance rate

Zero non-compliant batches passed inspection after launch. First clean internal audit in client history, completed ahead of the client's applicable DSCSA phased deadline

213 Duplicate Rx blocked in 60 days

Cross-silo deduplication engine blocked 213 duplicate controlled substance dispenses in the first two months, enforcing platform-configured clinical safety thresholds across the contracted pharmacy network.

97% audit report time reduced

Regulatory report generation fell from 3 to 5 staff-days per cycle to 20 minutes of review + one-click submit.

Need a similar solution?

Talk with our team about your project goals and timeline.

Contact Us