A prescription is a health-care program implemented by a physician or other qualified practitioner in the form of instructions that govern the plan of care for an individual patient. Although the algorithmic nature of prescriptions is axiomatic, this insight has not been applied systematically to medication safety. We used software design principles and debugging methods to create a "Patient-oriented Prescription for Analgesia" (POPA), assessed the rate and extent of adoption of POPA by physicians, and conducted a statistical process control clinical trial and a subsidiary cohort analysis to evaluate whether POPA would reduce the rate of severe and fatal opioid-associated adverse drug events (ADEs). We conducted the study in a population of 153,260 hospitalized adults, 50,576 (33%) of whom received parenteral opioids. Hospitalwide, the use of POPA increased to 62% of opioid prescriptions (diffusion half-life = 98 days), while opioid-associated severe/fatal ADEs fell from an initial peak of seven per month to zero per month during the final 6 months (P < 0.0016) of the study. In the nested orthopedics subcohort, the use of POPA increased the practice of recording pain scores (94% vs. 72%, P < 0.00001) and the use of adjuvant analgesics (95% vs. 40%, P < 0.00001) and resulted in fewer opioid-associated severe ADEs than routine patient-controlled analgesia (PCA) (0% vs. 2.7%, number needed to treat (NNT) = 35, P < 0.015). The widespread diffusion of POPA was associated with a substantial hospitalwide decline in opioid-associated severe/fatal ADEs.