“I am very sorry for my actions,” he said. “When we sold the drugs, we never intended for anyone to lose their life.”

In announcing her sentence, Judge Ronnie Abrams acknowledged that it could have been any of the other three men charged along with Mr. Cartagena who handed Mr. Williams the fatal drugs. However, she said, Mr. Cartagena knew the heroin was laced with fentanyl when he sold it, while Mr. Williams was unaware.

The harm from that sale was “very clear and very tragic,” she said.

The length of the sentence, she added, is intended to serve as a deterrent to both Mr. Cartagena, who has been convicted of drug charges in the past, and to others who sell fentanyl, which has led to many deaths across the country in recent years.

“It’s got to stop,” she said.

Mr. Cartagena, who is also known as “Green Eyes,” was first introduced to heroin when he was about 13 years old and living in Puerto Rico, where he grew up, his lawyer, Sean M. Maher, said in court. He was struggling with school and spending more and more time on the streets in order to avoid a tumultuous and violent family life, Mr. Maher said.