From within his presidential palace, President Nicolás Maduro regularly commandeers the airwaves, delivering speeches intended to project stability to his crumbling nation. But as the Venezuelan state disintegrates under the weight of Mr. Maduro’s corrupt leadership and American sanctions, his government is losing control of segments of the country, even within his stronghold: the capital, Caracas.

Nowhere is his weakening grip on territory more evident than in Cota 905, a shantytown that clings to a steep mountainside overlooking the gilded halls from which Mr. Maduro addresses the nation.

In the maze of shacks that make up Cota 905 and the adjoining communities of El Cementerio and La Vega, home to about 300,000 people, the capital’s largest gang has moved into the power vacuum left by an unraveling nation: It delivers food to the needy. It helps pay for medicine and funerals, equips sports teams and sponsors music concerts. On national holidays, it hands out toys and puts up bouncy castles for children.

The territory the gang controls is off limits to law enforcement. And, a local police commander said, with access to grenade launchers, drones and high-speed motorbikes, the gangsters are better armed, and better paid, than most of Venezuela’s security forces.

They deliver a brutal brand of justice: Thieves caught in the areas they control are shot in the hand. Domestic abusers get one warning; repeat offenders are shot, residents said. And gang members who try to leave the underworld are hunted down as traitors.

But many who live under their control say the gangsters’ rule is better than the lawlessness and violence that reigned before they took over. Residents said they had no hope of any help coming from the government.

“The majority of us prefer to live like this,” said Belkys, a Cota resident who asked to be identified only by her first name, as she was afraid of retribution from the gang. “We don’t see a real solution.”

Hunkered down in his fortified Caracas residences, Mr. Maduro crushed the oppositionpurged the security forces of dissent and enriched his cronies in an effort to eliminate challenges to his authoritarian rule.

In remote areas, swathes of national territory fell to criminals and insurgents. But gang control of Cota 905 and the surrounding shantytowns, which lie just two miles from the presidential palace, is evidence that his government is losing its grip even on the center of the capital.

Across the city, other armed groups have also asserted territorial control over working-class neighborhoods.