The right-back prodded home at the end of a chaotic 17-minute period at a sodden Mendizorroza that saw the two sides share three second-half goals.
Madrid rose to the challenge and restored their advantage three minutes after the equaliser to go three points clear of Barcelona, who visit Atletico Madrid on Sunday.
Eden Hazard's ankle injury opened the door for Gareth Bale to make his first start since October 5 and the winger almost made an early contribution, his deflected header hitting the post in the 10th minute.
Eder Militao was involved in two Alaves penalty shouts either side of that chance, the first resulting in Aleix Vidal being booked for simulation when there appeared to be a slight trip.
The rain intensified after an error-strewn first half and, in the 52nd minute, Madrid raised their level.
Kroos curled an inviting free-kick into the box and Ramos glanced it beyond goalkeeper Pacheco for his fifth goal of the season in all competitions.
It took just 13 minutes for the centre-back to undo his good work.
Ramos raised a hand to Joselu's face in the box and Perez sent Alphonse Areola, chosen ahead of Thibaut Courtois, the wrong way from the resultant spot-kick.
Madrid were tasked with responding and Carvajal delivered the decisive goal in quick fashion, prodding home the winner at point-blank range after Pacheco blocked an Isco header on the line.
Alaves pressed hard for a second leveller but desperate goal-line interventions from Marcelo and Areola in the closing stages denied both Perez and Manu Garcia, before Federico Valverde missed a clear chance for a third in the dying seconds.