Karim Benzema’s lovely backheel in the 14th minute placed the champions in command at a soggy Alfredo di Stefano stadium, and a deflected Toni Kroos free kick doubled their lead in the 28th.
Oscar Mingueza equalised for Barcelona on the hour mark, and the defender almost equalised again later on, although the Catalans had a massive penalty appeal turned down after Martin Braithwaite collapsed after a challenge by Ferland Mendy.
Real Madrid midfielder Casemiro was sent off in stoppage time after receiving two yellow cards in a minute, while Barcelona substitute Ilaix Moriba struck the crossbar in the fourth minute of extra time.
The hosts survived the nail-biting end to round off an incredible week that began with a 3-1 victory over Liverpool in the first leg of the Champions League quarter-finals on Tuesday.
Zinedine Zidane’s side climbed to the top of the table after joining Atletico Madrid on 66 points, while Atletico will retake first place when they visit Real Betis on Sunday. On 65 points, Barcelona fell to third place.