Broad questions
There were merchant republics, how come these city states could hold off being taken over by large empires?
I do realize their power could be large in some examples like Venice, but then the question is why these did not expand by land if they did wield so much military power.
How did the power play look specifically if it was the case of the kingdoms rather having these city states independent? Sounds like good political intrigues lasting hundreds of years.
Geography
Having natural borders, such as mountains or major rivers is a big plus. It restricts the movement of enemy armies and creates natural choke points.
Great power rivalries
With being a large kingdom comes a large number of adversaries - small kingdoms can form alliances with the rivals of the great power that threatens them.
The Offensive - Defensive balance
It is a lot easier to defend than attack, the defender enjoys the advantage of choosing the battlefield or even if there be a battle at all.
Political stability
Middle age kingdoms were incredibly unstable, especially around successions. Often it is enough as a defender to await such a circumstance where the larger kingdom is now too focused on internal affairs to be able to commit resources.
This is to some extend true today, look at Vietnam, Afghanistan (both NATO and the Soviets).
Hi there. You might be interested in this answer of mine examining the mechanics of medieval military occupations; you'll see that more often than not, only with difficulty do even the largest states find the right opportunity for territorial expansion. I also wrote this other answer acknowledging the vulnerabilities of Italian maritime republics. Although popular notions of history, perhaps aided by popular media, make us thing that history is a succession of wars and conquests, the reality is much more nuanced.