Almost exactly 1,000 days before Mr. de Blasio won the Democratic nomination for a second term, he stepped into a Brooklyn hospital and knew he had a problem. Two New York police officers had just been killed — assassinated, really — at point-blank range. Mr. de Blasio had come, as mayors do, to pay his respects. But as he and his entourage squeezed into the hospital’s corridors, something was off. Many of the men and women in blue standing in solidarity with the fallen were facing the wall, their backs to the mayor in protest.

More would turn away from Mr. de Blasio at the officers’ funerals. The head of the police union would say there was “blood on the hands” at City Hall and blame the mayor for racially charged rhetoric on policing, in particular, saying he had told his son Dante, who is half-black, to “take special care” when encountering police. Union leaders said it made cops out to be the bad guys. Now two officers, Rafael Ramos and Wenjian Liu, were dead.

It amounted to a political tinderbox for a rookie mayor whom few had expected to win in 2013, when Mr. de Blasio vaulted past a crowded field in a crazy race marked by Anthony Weiner’s implosion and Christine Quinn’s collapse. In his first year, Mr. de Blasio was facing not only a political crisis but also a genuine security situation months after violence had engulfed Ferguson, Mo.

Throughout December of 2014, the mayor and his team huddled deep into the night at Gracie Mansion to come up with a way to defuse the situation. Efforts included enlisting the help of Cardinal Timothy M. Dolan, who held mass at St. Patrick’s Cathedral the morning after the mayor’s hospital visit, and urged calm in “a city tempted by tension and division.” In a symbolic but unscripted moment, Cardinal Dolan emerged from the church arm in arm with the mayor’s wife, Chirlane McCray, who is African-American.

In the end, riots did not break out, and Mr. de Blasio’s stewardship through a racially fraught situation solidified his standing among his most important constituency, African-American voters, according to his political advisers.