Energy savings in electric rail transport are important in order to increase energy efficiency and reduce its carbon footprint. This can be achieved by storing and using the energy generated during regenerative braking. The system described in this paper consists of a supercapacitor energy storage system (SC ESS), a bidirectional DC/DC converter, and an algorithm to control the energy flow. The proper design of the algorithm is critical for maximizing energy savings and stabilizing the power grid, and it affects the lifetime of the SC ESS. This paper presents an energy flow control algorithm based on Pontryagin’s minimum principle that balances maximum energy savings with maximum SC ESS lifetime. The algorithm also performs SC ESS recharging while the rail vehicle stops on inclines to reduce the impact of its next acceleration on the power grid. To validate the algorithm, offline simulations are performed using real tram speed measurements. The results are then verified with a real-time laboratory emulation setup with HIL simulation. The tram and power grid are emulated with LiFePO4 batteries, while the SC ESS is emulated with a supercapacitor. The proposed algorithm controls a three-phase converter that enables energy exchange between the batteries and the supercapacitor. The results show that the proposed algorithm is feasible in real time and that it can be used under real operating conditions.