The Spain international, a long-time reported target of the Champions League winners, saved spot-kicks from Mateo Kovacic and Oscar before Casemiro hit the crossbar with his shoot-out kick - having scored from 12 yards in normal time - to hand United victory.
United took the lead shortly before half-time thanks to a sensational piece of play from Anthony Martial, the forward jinking away from Dani Carvajal, Luka Modric and Lucas Vazquez to give Jesse Lingard the simplest of finishes at the back post.
Casemiro levelled from the penalty spot after Victor Lindelof could only stop a rampaging Theo Hernandez by crashing into him before the Brazilian missed the decisive penalty in a poor shoot-out.
United remain unbeaten in the four matches they have played on their tour of the United States after holding off Madrid in searing temperatures, while the first pre-season match for Zinedine Zidane's men ended in defeat.
The clubs will soon clash again as Madrid face United in the UEFA Super Cup in Skopje next month.
Lingard was one of two players retained from the United team that beat Manchester City 2-0 on Thursday and he had the first attempt with a shot Keylor Navas had to beat away.
In the stifling Santa Clara heat, the game was played at little more than walking pace, and Lingard bent a 20-yard effort narrowly wide after 40 minutes with Navas well beaten as both teams continued to struggle for attacking momentum at Levi's Stadium.
But in the first minute of stoppage time, a moment of Martial magic provided the opener.
Brilliant skill from the Frenchman saw him cut inside off the left and evade three Madrid defenders before pulling back a precise low cross that Lingard tapped in from close range.
Zidane changed his entire XI at the interval while Mourinho made eight substitutions including introducing Romelu Lukaku and Paul Pogba, with Ander Herrera forced off through injury after just five minutes of the second half.
Madrid were handed a glorious chance to level the scores after 68 minutes when a dreadful Lindelof challenge on Hernandez resulted in a penalty.
Casemiro stepped up to smash the spot-kick past De Gea and more penalties were required to find a winner with neither side making a breakthrough after Marouane Fellaini wasted a golden chance with seven minutes to play.
Martial blazed the first kick well over the crossbar before De Gea saved from Kovacic and Kiko Casilla denied Scott McTominay.
De Gea's save from Oscar allowed Henrikh Mkhitaryan to nudge United ahead but Madrid responded through Luismi Quezado before Lindelof hit his kick straight at Casilla and Hernandez scuffed wide.
Daley Blind converted his kick to pile the pressure on Casemiro, with the Brazilian thudding his effort against the bar to continue United's fine run in pre-season.