Barca took a seventh-minute lead at Real's Bernabeu stadium through Andres Iniesta before a Karim Benzema double and Messi's first of the night made it 2-2 at the break.
Cristiano Ronaldo put Real ahead from the penalty spot 10 minutes after half-time after he was tripped by Dani Alves and the match turned when home captain Sergio Ramos was sent off for tripping Neymar when he was through on goal in the 63rd.
Messi clipped home the resulting penalty to level at 3-3 and struck the winner from the spot six minutes from time after Iniesta was felled in the area.
With nine games left, Real have 70 points, level with city neighbours Atletico Madrid, who won 2-0 at bottom side Real Betis in the earlier kickoff, and one ahead of third-placed Barca.
Image: Barcelona's Lionel Messi (left) and Neymar (right) celebrate a goal as Real Madrid's Cristiano Ronaldo (second left) and Angel Di Maria (second right) walk back during La Liga's second ''Clasico'' match of the season at Santiago Bernabeu stadium in Madrid.
Photograph: Paul Hanna/Reuters
Barca's Pique back in time for Sunday's 'Clasico'
Real Madrid v Barcelona: The ' El Clasico' in numbers
El Clasico: World's Best vs World's Richest...
Sports Shorts: Bhupathi-Anderson knocked out of Miami Open
La Liga: Messi becomes highest goal-scorer for Barca