The FSB security service said in a statement quoted by Russian agencies that the raid was part of an operation to detain "wanted persons accused of participating in illegal armed groups in the North Caucasus".
"Criminals were destroyed by return fire when they attempted to resist," the FSB said, without specifying how many suspects were killed.
Local online newspaper Fontanka.Ru reported that two alleged militants were killed and three arrested.
TV footage showed heavily-armed men in balaclavas cordoning off the multistorey apartment block on the outskirts of the northwestern city famed for its tsarist-era palaces.
More From This Section
Special operations against suspected Islamists are frequent in Russia's North Caucasus region but have been rare in Moscow and Saint Petersburg in recent years.
Russia has battled a simmering insurgency in the Caucasus ever since fighting two brutal separatist conflicts with Chechnya.
Many Islamists have left for Syria and there has been little violence linked to the North Caucasus spilling out of the region in recent years, with the last such attacks in the southern city of Volgograd in 2013.