Abstract Parasite mediated selection may result in arms races between host defence and parasite virulence. In particular, simultaneous infections from multiple parasite species should cause diversification (i.e. balancing selection) in resistance genes both at the population and the individual level. Here, we tested these ideas in highly polymorphic major histocompatibility complex (MHC) genes from three-spined sticklebacks (Gasterosteus aculeatus L.). In eight natural populations, parasite diversity (15 different species), and MHC class IIB diversity varied strongly between habitat types (lakes vs. rivers vs. estuaries) with lowest values in rivers. Partial correlation analysis revealed an influence of parasite diversity on MHC class IIB variation whereas general genetic diversity assessed at seven microsatellite loci was not significantly correlated with parasite diversity. Within individual fish, intermediate, rather than maximal allele numbers were associated with minimal parasite load, supporting theoretical models of self-reactive T-cell elimination. The optimal individual diversity matched those values female fish try to achieve in their offspring by mate choice. We thus present correlative evidence supporting the ‘allele counting’ strategy for optimizing the immunocompetence in stickleback offspring.