“There is a perfect constellation of political forces in San Francisco that will support a bold, progressive district attorney,” said Anne Irwin, a former public defender in the city who is now the director of Smart Justice California, an advocacy group that has endorsed Mr. Boudin and his main opponent, Suzy Loftus.

It is not as though the city has been a bastion of tough-on-crime policies. The current top prosecutor, George Gascón, has taken steps to divert young adults from prison, and San Francisco was the first city to clear old marijuana convictions. One study concluded that if the United States “could match San Francisco’s rates” then “mass incarceration would be eliminated.”

In a measure of the city’s liberal politics, all of the four candidates in the district attorney race are, in one way or another, arguing for reducing incarceration even more.

Ms. Loftus, a former prosecutor and the former president of the Police Commission, an oversight board, is also running on a platform of overhauling the justice system.

Rhetorically, there is little daylight between Mr. Boudin and Ms. Loftus. But the city’s establishment has lined up behind Ms. Loftus, including Gov. Gavin Newsom, Mayor London Breed, Senator Dianne Feinstein and Senator Kamala Harris, a Democrat who is running for president and whose own record as San Francisco’s district attorney is being attacked from the left.

Mr. Boudin, on the other hand, is racking up endorsements from grass-roots liberal groups in the city, and has emerged as a darling among national activists, who see him as the candidate most willing to tear down the system. He has attracted support from prominent criminal justice system critics like Shaun King, who founded the influential Real Justice PAC and has over a million followers on Twitter, and Larry Krasner, the lawyer who made a career with civil rights suits against the police and then became the top prosecutor in Philadelphia.