The immune system is several systems. One of my favorite parts is the Thymus.
It's literally setup like a gauntlet. New immune cells from marrow come through the Thymus and are tested. They need to pass through and attack foreign cells then pass through and _not_ attack host cells. They are essentially tagged and filtered by this process.
Most cells are let go into the body, some cells are reserved as self regulatory cells, and the others that do not pass are destroyed.
It's a literal quality control and selection machine for your immune system.