Immune system process that functions in the calibrated response of an organism to a potential internal or invasive threat.