The aim of this paper was to design optimal strategies using nonlinear dynamic programming to guarantee the required level of liquidity in pay‐as‐you‐go pension systems through changes in the key variables of the system, such as the contribution rate, retirement age and/or indexation of pensions. These strategies, also known as automatic balancing mechanisms (ABMs), calculate the optimal path of these variables over time, managing fluctuations in longevity, fertility rates, salary growth or any other kind of uncertainty faced by the pension scheme without repeated legislative intervention. A numerical application of our model, which uses the projection of the population structure of two representative countries, illustrates the main findings of the paper. Copyright © 2015 John Wiley & Sons, Ltd.