What do you mean but "Not always, but frequently."?
Are there some circumstances that determine it or it is purely random?
The circumstances I just described.
When you are fighting a realm's troops within their territory, you can predict whether or not you will face them as defenders by scouting the region to see if they are rallying. Of course, they could rally between when you scout and turn change.
It's not random at all, it just depends on the actions of the other realm's players.