It's a mix, and the balance differs by country. Pure random selection exists, but modern customs services lean heavily on risk profiling. Passenger data is analyzed before you land: your flight origin, routing, travel history, how the ticket was bought, and whether you've had violations before. Flights from regions associated with narcotics, gold smuggling, counterfeits, or agricultural pests get more attention across the board.
On the floor, officers add human judgment, looking at luggage quantity versus trip length, visible nervousness, and how people answer simple questions. Detector dogs and baggage x-rays add another layer that's essentially item-driven rather than person-driven.
Officially, most countries say they don't target nationality as such, though in practice route-based profiling can feel like it. From a traveler's perspective the takeaway is the same either way: you can't predict selection, so travel as if you'll be checked. Honest declarations and organized luggage make even a targeted inspection a five-minute event.