In single cells (green shade), stochastic activity of restriction-modification enzymes (R—red, M—blue) may inadvertently lead to full methylation of invading phage DNA in a process known as “phage escape” from the bacterial immunity, resulting in direct consequences at the ecological scale (blue shade). Also, stochastic activity of the same enzymes may lead to accidental cutting of bacterial DNA in a process known as “self-restriction,” resulting in lowered bacterial growth rate at the population level (red shade). Trade-offs between self-restriction and phage escape at the ecological scale in turn influence R and M enzyme activities in surviving cells, thereby optimally balancing the efficiency and cost of immunity.