Optimal defense against gut nematodes