Karim Benzema scored a last-gasp winner to secure victory and spare Real Madrid's blushes against La Liga bottom club Huesca.
After falling behind early on, Zinedine Zidane's side thought they had turned things around through Isco and Dani Ceballos - only for the lowly visitors to hit back.
But Benzema settled the game with a stunning 89th-minute strike as Madrid won 3-2 in front of a sparse Bernabeu crowd.
Huesca, with only five league wins all season, hit the front with just three minutes on the clock as Watford loanee Cucho Hernandez stroked home the opener.
He then passed up a superb chance to stun Madrid further still as he headed over when well-placed.
Benzema missed a good opportunity to level from close-range before wasting another chance by shooting straight at Huesca goalkeeper Roberto Santamaria.
Luca Zidane, son of manager Zinedine, was making his first appearance of the season and was almost beaten by a Moi Gomez effort which flew narrowly wide.
Isco, out of favour under former boss Santiago Solari, equalised for the hosts as he finished into an open goal after Benzema's parried shot was rolled into his path by Brahim Diaz.
Not to be overawed, Huesca should have restored their lead soon after but Ezequiel Avila blazed over when in a good position.
Gareth Bale played a big part in the goal which put Madrid in front, sending in a perfect cross with the outside of his foot for Benzema to head back across goal where Ceballos converted.
Although his wonderful ball had led to Ceballos' goal, Bale was guilty of missing a fine chance to wrap up the points as he stretched out to reach Alvaro Odriozola's cross only to send his effort over the top.
Moments later and the visitors took their chance to level, Xabier Etxeita powering a header past Zidane to equalise.
But, as the game progressed towards its conclusion, Huesca fell deeper and deeper and were made to pay as Marcelo played the ball to Benzema and the France striker curled home a superb winning goal.
Elsewhere, Valencia won 1-0 at Sevilla to leapfrog their rivals into sixth place and extend their unbeaten league run to 11 games.
Dani Parejo scored the game's only goal, tucking away a penalty after Jose Luis Gaya was brought down by Ever Banega.
Sunday's other three games were all drawn, Eibar coming from behind twice to secure a share of the spoils at Levante in a 2-2 draw.
Rayo Vallecano are five points from safety after they were pegged back by Real Betis to draw 1-1 in Madrid.
Valladolid moved two points clear of the bottom three - but it could have been better had they maintained the early lead they established at home to Real Sociedad.
Keko struck in the ninth minute but Sociedad stayed in the game and earned a point as Mikel Oyarzabal equalised 11 minutes from time.