Iker Casillas handed the hosts the opener with a horrible error which Randall Brenes coolly took advantage of and Joel Campbell added a second 10 minutes later to give Costa Rica a stunning 2-0 half-time lead.
The world champions improved greatly after the break, but took until the 82nd minute to get back into the game when substitute David Silva combined with Andres Iniesta to fire home.
And as the game entered stoppage time David Villa stooped to head home his 51st international goal and save the visitors' blushes.
Vicente Del Bosque had made four changes from the side that lost 1-0 to England at Wembley on Saturday.
Nacho Monreal was given his chance to stake a claim at left-back in place of Jordi Alba, whilst Carles Puyol, Juan Mata and Cesc Fabregas replaced Gerard Pique, Sergio Busquets and Silva.
However despite still fielding a strong side Del Bosque saw his side put in a disjointed display in the first half.
The visitors could not get their traditional passing game going on a pitch that cut up very badly in soaking wet conditions, and were made on the half-hour mark as Casillas stumbled with the ball at his feet inside the area and presented it perfectly for Brenes, who calmly lobbed the ball over Puyol and into the net.
Keylor Navas then denied Fabregas brilliantly from close range on two occasions before the hosts amazingly doubled their advantage when Campbell curled a wonderful shot beyond Casillas from the edge of the area.
Spain were much better after the break and Villa was unlucky not to bring his side back into the game on three occasions as Navas made another fine save from the Barcelona striker's free-kick before he struck the post and shot narrowly wide when clean through.
The visitors did eventually get on the scoresheet when Silva sent Iniesta free down the left and he cut the ball back for the Manchester City man to fire low across Navas into the bottom corner.
Villa then completed the comeback in stoppage time as he nodded in Santi Cazorla's free-kick at the near post.