A long-standing problem in the study of space and astrophysical plasmas is to explain the production of energetic electrons as magnetic fields 'reconnect' and release energy. In the Earth's magnetosphere, electron energies reach hundreds of thousands of electron volts (refs 1–3), whereas the typical electron energies associated with large-scale reconnection-driven flows are just a few electron volts. Recent observations further suggest that these energetic particles are produced in the region where the magnetic field reconnects4. In solar flares, upwards of 50 per cent of the energy released can appear as energetic electrons5, 6. Here we show that electrons gain kinetic energy by reflecting from the ends of the contracting 'magnetic islands' that form as reconnection proceeds. The mechanism is analogous to the increase of energy of a ball reflecting between two converging walls—the ball gains energy with each bounce. The repetitive interaction of electrons with many islands allows large numbers to be efficiently accelerated to high energy. The back pressure of the energetic electrons throttles reconnection so that the electron energy gain is a large fraction of the released magnetic energy. The resultant energy spectra of electrons take the form of power laws with spectral indices that match the magnetospheric observations.