Dramatic late strikes by Philippe Coutinho and Neymar gave Brazil their first win of the World Cup against Costa Rica in St Petersburg on Friday and broke Central American hearts by sending them out of the tournament.
The result leaves the five-times world champions with four points from two games after they drew 1-1 with Switzerland in their opening match, and they provisionally rise above Serbia to top Group E.
Serbia play Switzerland later on Friday.
The clock had ticked past 90 minutes when Marcelo crossed from the left and substitute Roberto Firmino headed the ball back across goal to Gabriel Jesus.
Jesus's first touch took the ball away from the defender and Coutinho raced in to poke past Keylor Navas from six metres out and claim his second goal of the tournament.
Neymar added the second with practically the last kick of the game, racing on to Jesus's square ball following a quick counter-attack as Costa Rica were forced to push for the equaliser.
The forward, who thought he had won a penalty in the 77th minute only for the referee to reverse the decision after consultation with the video assistant referee (VAR), was overcome by emotion on the whistle, covering his face as tears streamed down his cheeks.
For long periods Costa Rica's flat-back five kept Neymar on the periphery, with Johan Venegas and Cristian Gamboa both man-marking him out of the game as Brazil found it hard to carve out chances in the first half.
Marcelo's tame shot straight at Navas in the 41st minute was the first effort on target from either side before the break, and the team went into halftime with the boos and whistles of their own fans ringing in their ears.
Celso Borges spurned arguably the best chance of the first period for Costa Rica when he ran on to Gamboa's cut back but shot wide from eight metres out.
The result means Brazil have avoided the ignominy of equalling their longest winless run at the World Cup.