How much of its resources should an individual invest in a costly immune system? In this article, we apply an evolutionarily stable strategy analysis to an epidemic model to answer this question. On the one hand, an investment in immune function confers protection to infectious agents by reducing host susceptibility, pathogen virulence, or the length of the infectious period. On the other hand, an immune system is costly since it absorbs resources that otherwise might be invested in increasing the host's fertility or longevity. In addition, an active immune system may be able to clear pathogens efficiently but at the same time may result in immunopathology. By means of a reproductive value approach, we show how to compare the costs and benefits of an immune system systematically and how to derive the evolutionarily stable level of immune function. We then apply these methods to various plausible scenarios. The analysis reveals that the relationship between the life span of an organism and the optimal level of investment in immune function is less straightforward than one might expect. First, the prevalence of infection is reduced to the lowest possible level only under special circumstances. Second, members of a long-lived species do not necessarily have to invest more in immune function than those of a short-lived species. In fact, the opposite may be true. Third, the outcome of evolution can be contingent on the initial conditions. Depending on its initial investment strategy, a population may evolve to a state where very much or almost nothing is invested in a costly immune system.