Spain were heading out of the World Cup for three minutes before Kai Havertz became a nation's unlikeliest hero.
At 2-1 down to a Japan side who staged a remarkable second half fightback, Spain slipped below both the Japanese and Costa Rica in Group E and looked to be heading for the exit when the Costa Ricans took a 2-1 lead against Germany.
However, German substitute Havertz then struck twice to turn the tables and drop Costa Rica down to the bottom of the table.
Niclas Fullkrug then struck his second of the tournament to make it 4-2 to Germany, but for them the victory was in vain as they remain behind Spain on goal difference.
The Spanish could have done Germany a similar favour had they equalised against Japan, but the Samurai Blue held on for a remarkable win and finish top of the group.
Spain let their standards slip in the second period and allowed Japan to come back into the game, although their recovery was not without controversy.
After substitute Ritsu Doan's effort from distance passed through a weak attempt at a save from Unai Simon to spark the Japan fans into life, they then remarkably took the lead five minutes later.
Doan's fellow substitute Kaoru Mitoma looked to have failed to keep the ball in play when he stretched at the far post, and celebrations were cut short after Ao Tanaka turned his cross home.
The first replay on the big screen suggested that the ball was indeed out of play, only for a lengthy VAR intervention and the goal to eventually be awarded to Japan, although replays weren't conclusive that the ball was indeed in.
Spain were stunned, with all the poise they demonstrated in the first half completely evaporated.
The Spanish had been dominant, with their four young stars Pedri, Gavi, Nico Williams and Alejandro Balde to the fore.
Williams is the grand old man of the group given that he turned 20 all the way back in the summer, but you can bet that the old timer would be able to beat them all a foot race.
One incredible burst of speed down the right almost turned a bad pass into a good one, not that there were many bad ones at all in a first half which ended with Spain hogging 83 per cent of the possession, with so much of that going through Pedri and Gavi in the middle.
The pair take such responsibility for ones so young, something which gives Sergio Busquets - the real grand old man of the team - a licence to drop back and keep the centre-backs company. It's probably also why Enrique plays Rodri back there.
It was a couple of old hands who combined for Spain's goal, with Cesar Azpilicueta crossing for Alvaro Morata's header, and that point it looked as though they would run away with it.
However Japan had other ideas, and that set up a frantic second half when minds were on the Germany game just as much as this clash.
In the end Spain survive, but only just.