Thermochemical surface treatments of steels, such as carburizing and carbonitriding are used to improve mechanical properties, especially resistance to fatigue. Carbonitriding can achieve excellent properties, but the origins remain to be understood, as it has been less studied than carburizing. Fundamental understanding has to be established regarding the formation of microstructures and internal stresses as well as their couplings, during the cooling which follows the enrichment treatment.For this purpose, an original experimental method is introduced to follow in situ by High-Energy X-Ray Diffraction the phase transformation kinetics as well as the evolutions of the internal stresses during cooling, inside laboratory scale, 3 mm-thick samples with C and/or N composition gradients. The usual trends are confirmed regarding carburizing: the carbon-enriched case is the last to transform and the surface ends up with compression residual stresses. Conversely, for carbonitriding, unusual evolutions of microstructure and internal stresses are observed. The presence of nitrogen reduces the hardenability in the enriched case. This modifies the chronology of the phase transformations and this leads to tensile residual stresses at the surface.A coupled thermal, mechanical and metallurgical model predicting the phase transformation kinetics and the evolutions of internal stresses is set up. It achieves quantitative predictions and it shows that, in the studied cases, the phase transformation plasticity strains are the main origin of the residual stresses.