In 1992, the city had 1,641 deaths from AIDS. Last year, just 177 San Franciscans with H.I.V. died, and most of them actually succumbed to heart disease, cancer or other old-age ills, said Dr. Susan Buchbinder, the head of H.I.V. prevention research for the city health department.

By other measures, too, San Francisco is ahead. According to a 2012 estimate by the Centers for Disease Control and Prevention, only 39 percent of all infected Americans had seen an H.I.V. doctor, and only 30 percent were taking their pills consistently enough to be “virally suppressed,” meaning they were not infectious. By contrast, in San Francisco, 82 percent of residents with H.I.V. were in care, and 72 percent were suppressed. In Ward 86 — all of whose patients are uninsured or on public assistance — suppression has reached 84 percent.

Demographic Advantages

San Francisco has some natural advantages: wealth, political leaders who consistently back the fight — in part because the gay vote is so big — and a close-knit medical community in which many of the top officials in the fight against H.I.V. have studied together, trained each other and done research projects together through the University of California, San Francisco.

Because of the tech boom, City Hall’s budget grew from $5 billion to nearly $9 billion in 10 years. For patients not eligible for federal or state aid, the city has its own health insurance: Healthy San Francisco. And it has been able to counter every cut in federal AIDS funds.

“One of my first budget questions is always, ‘Are they cutting our Ryan White money again?’ ” Mayor Edwin M. Lee said in an interview, referring to the 1990 law that pays for AIDS drugs. “Since 2011, we’ve backfilled more than $20 million — with very little debate.”

Wealth also eases the burden in a harsher way: Soaring rents have driven out many poor residents. Two-thirds of San Francisco’s infected are white or Asian; nationally, 63 percent are black or Hispanic. Older, wealthier, openly gay white men are more likely to be insured and well-informed about risks than young black and Hispanic men, the epidemic’s fastest-growing subgroup.