Several results indicate that the atmospheric temperature of the ultra-hot Jupiter KELT-9b in the main line formation region is a few thousand degrees higher than predicted by self-consistent models. We test whether non-local thermodynamic equilibrium (NLTE) effects are responsible for the presumably higher temperature. We employ the Cloudy NLTE radiative transfer code to self-consistently compute the upper atmospheric temperature-pressure (TP) profile of KELT-9b, assuming solar metallicity. The Cloudy NLTE TP profile is $approx$2000 K hotter than that obtained with previous models assuming local thermodynamic equilibrium (LTE). In particular, in the 1-10$^{-7}$ bar range the temperature increases from $approx$4000 K to $approx$8500 K, remaining roughly constant at lower pressures. We find that the high temperature in the upper atmosphere of KELT-9b is driven principally by NLTE effects modifying the Fe and Mg level populations, which strongly influence the atmospheric thermal balance. We employ Cloudy to compute LTE and NLTE synthetic transmission spectra on the basis of the TP profiles computed in LTE and NLTE, respectively, finding that the NLTE model generally produces stronger absorption lines than the LTE model (up to 30%), which is largest in the ultraviolet. We compare the NLTE synthetic transmission spectrum with the observed H$alpha$ and H$beta$ line profiles obtaining an excellent match, thus supporting our results. The NLTE synthetic transmission spectrum can be used to guide future observations aiming at detecting features in the planets transmission spectrum. Metals, such as Mg and Fe, and NLTE effects shape the upper atmospheric temperature structure of KELT-9b and thus affect the mass-loss rates derived from it. Finally, our results call for checking whether this is the case also of cooler planets.