This has happened in the past, and was prevalent in the late Middle Ages of Europe and the early Renaissance, when centralized autocracies were the theoretical mode of rule, but had limited ability to enforce their will on walled cities.
The Hanse, the walled cities of the United Provinces and the "Republican" Italian city states provide examples of this evolution. A strange example is London, England, where the monarch held court within a city that had its own charter, method of selecting municipal officers and even essentially its own army. Monarchs in England ignored the wishes of Londoners at their considerable peril.
The primary issue here is the cities had a large enough population to man the defences, walls and natural protection (the Dutch in the United Provinces could and did breach the dikes and flood the polders surrounding the cities in order to frustrate the Hapsburg armies sent to quell the rebellion), and were wealthy enough to be worth defending. The citizens also needed the ability to withstand prolonged sieges if necessary, and you will note that most of the examples are either port cities in their own rights, or near enough to a coast or river to transport food and supplies, and make the besieger's lot a miserable one.
In the modern age, examples like Hong Kong and Singapore come to mind, and these city states have many of the features their forebears in the Hanse or the United Provinces did. It is theoretically possible that in some future where the EU breaks up or nations are riven between nationalists and unassimilated immigrants, port cities like Rotterdam or Gdansk might revert to this status as well (North American cities like San Diego, Galveston or Montreal might undergo the same political evolution if circumstances change drastically, and you can write your own backstory for other cites in the world).
So, yes, cities can quite easily remain democratic even if they are embedded in a more autocratic nation state.