Flat-slab subduction occurs when the descending plate becomes horizontal at some depth before resuming its descent into the mantle. It is often proposed as a mechanism for the uplifting of deep crustal rocks ('thick-skinned' deformation) far from plate boundaries, and for causing unusual patterns of volcanism, as far back as the Proterozoic eon. For example, the formation of the expansive Rocky Mountains and the subsequent voluminous volcanism across much of the western USA has been attributed to a broad region of flat-slab subduction beneath North America that occurred during the Laramide orogeny (80-55 million years ago). Here we study the largest modern flat slab, located in Peru, to better understand the processes controlling the formation and extent of flat slabs. We present new data that indicate that the subducting Nazca Ridge is necessary for the development and continued support of the horizontal plate at a depth of about 90 kilometres. By combining constraints from Rayleigh wave phase velocities with improved earthquake locations, we find that the flat slab is shallowest along the ridge, while to the northwest of the ridge, the slab is sagging, tearing, and re-initiating normal subduction. On the basis of our observations, we propose a conceptual model for the temporal evolution of the Peruvian flat slab in which the flat slab forms because of the combined effects of trench retreat along the Peruvian plate boundary, suction, and ridge subduction. We find that while the ridge is necessary but not sufficient for the formation of the flat slab, its removal is sufficient for the flat slab to fail. This provides new constraints on our understanding of the processes controlling the beginning and end of the Laramide orogeny and other putative episodes of flat-slab subduction.