Bacterial populations whose growth depends on the cooperative production of public goods are usually threatened by the rise of cheaters that do not contribute but just consume the common resource. Minimizing cheater invasions appears then as a necessary mechanism to maintain these populations. However, that invasions result instead in the persistence of cooperation is a prospect that has yet remained largely unexplored. Here, we show that the demographic collapse induced by cheaters in the population can actually contribute to the rescue of cooperation, in a clear illustration of how ecology and evolution can influence each other. The effect is made possible by the interplay between spatial constraints and the essentiality of the shared resource. We validate this result by carefully combining theory and experiments, with the engineering of a synthetic bacterial community in which the public compound allows survival to a lethal stress. The characterization of the experimental system identifies additional factors that can matter, like the impact of the lag phase on the tolerance to stress, or the appearance of spontaneous mutants. Our work explains the unanticipated dynamics that eco-evolutionary feedbacks can generate in microbial communities, feedbacks that reveal fundamental for the adaptive change of ecosystems at all scales.