The past few decades have generated growing recognition that the immune system makes an important contribution to cardiac development, composition and function. Immune cells infiltrate the heart at gestation and remain in the myocardium, where they participate in essential housekeeping functions throughout life. After myocardial infarction or in response to infection, large numbers of immune cells are recruited to the heart to remove dying tissue, scavenge pathogens and promote healing. Under some circumstances, immune cells can cause irreversible damage, contributing to heart failure. This Review focuses on the role of the immune system in the heart under both homeostatic and perturbed conditions.