The aim of this paper is to design an automatic balancing mechanism to restore the sustainability of a pay-as-you-go (PAYG) pension system based on changes in its main variables, such as the contribution rate, normal retirement age and indexation of pensions. Using nonlinear optimisation, this mechanism, identifies and applies an optimal path of these variables to a PAYG system in the long run and absorbs fluctuations in longevity, fertility rates, salary growth or any other events in a pension system.