Barca, whose win put them top because of a better head-to-head record, have five games left, Real have six to play.
Casemiro scored first for the hosts before Messi and Ivan Rakitic put Barcelona in front and Sergio Ramos was shown a red card for a wild lunge.
Substitute James Rodriguez thought he had earned Madrid a point late on.
But Messi, who scored his first with a superb jinking run and finish, fired in from the edge of the area to win it for Barcelona.
Both Messi and Cristiano Ronaldo had earlier missed good opportunities to give their sides the lead, with the Argentina international poking wide of an open goal before the break and the Real Madrid forward slicing over in the second half.
Real – who have a game in hand on Barcelona – also felt they should have had a penalty when Ronaldo was clipped by Samuel Umtiti after only two minutes.
- Analysis: 500 up Messi proves he’s still the best
- Quotes: Enrique hails ‘gargantuan’ Barcelona win
- Relive Real Madrid v Barcelona
Barca crisis averted?
Reaching the Champions League quarter-finals and competing to win La Liga would hardly constitute a crisis for most clubs, but this is Barcelona.
Trophies are often the minimum requirement for those in charge at Camp Nou. Fans expect to see their side win in style and have questioned the merits of boss Luis Enrique, who is to leave at the end of the season.
The travelling Catalan contingent could not complain about Sunday’s heroics, however, as they were treated to two fine finishes from Messi that were complemented by an equally composed Rakitic strike from the edge of the area.
Any crisis talks can be postponed while this side continues to boast Messi in its ranks, with the little magician showing he still has the ability to carry the Blaugrana against the world’s best teams.
A genius with the football at his feet, Messi continued to be the creative spark for Barcelona even after Casemiro – lucky not to be sent off himself – had twice scythed the forward down and an innocuous Marcelo elbow left the Argentine with a bloodied mouth.
His reward, as well as outshining Real Madrid counterpart Ronaldo in this Clasico, was to further ingrain his name into Barcelona folklore.
Still Madrid’s title to lose
Real Madrid have won the Champions League in two of the past three seasons, but have been less successful domestically – they are without a La Liga title since 2012, with Barcelona taking the trophy three times and Atletico Madrid once since then.
Down to 10 men after Ramos’ sending off and having pulled level with five minutes to spare, Zinedine Zidane’s outfit looked intent on a winner that would have effectively put the title beyond Barcelona.
That left the space for the visitors to break away and score themselves. Tactical naivety from Zidane? Perhaps, but with a game in hand, La Liga still looks Real’s to lose.
It had started promisingly for the hosts, with Casemiro the unlikely early hero when he poked home after Ramos hit the post. However, when Gareth Bale limped off with an ankle problem, the momentum swung in Barcelona’s favour.
Has the momentum in the title race also shifted away from Los Merengues?
If Zidane’s side, who remain on course to become the first team to secure back-to-back Champions Leagues, can win their remaining six games in La Liga, the Frenchman will end Madrid’s five-year wait for the domestic title.
Keepers come out on top… almost
Even with Brazil international Neymar suspended for Barcelona and Bale going off injured in the first half for Madrid, both sides boasted a plethora of attacking talent at the Bernabeu.
But it was the goalkeepers who looked, for a long time, to have come out on top as Marc-Andre ter Stegen and Keylor Navas made a series of fine saves to keep the score down.
Barcelona’s Ter Stegen was equal to efforts from Ronaldo and Karim Benzema in the first half, before Paco Alcacer, Gerard Pique and Luis Suarez were all denied by Navas after the break.
Ter Stegen made 12 saves in total, the most by a Barcelona keeper in La Liga since the 2003-04 season, but had little chance with either Casemiro’s opener or Rodriguez’s late leveller.
Eventually Barcelona’s class in attack also shone through, La Liga’s top goalscorer Messi leaving Navas well beaten with the winner.
Man of the match – Lionel Messi (Barcelona)
La Liga title ‘will be tight until the end’
Barcelona boss Luis Enrique: “We are first now but Madrid have an extra game. It will be tight until the end. We got the result we came here for.
“This is a season that weighs on us like five. So many things have happened, good things, not so good things, things I’ve already forgotten.
“The 2-2 goal was a terrible blow but players were able to come back in the last breath – the happy ending that we all wanted at Barcelona.”
Real Madrid coach Zinedine Zidane: “Nothing changes now. Maybe after today the league will be more open. But we still depend on ourselves.”
Both sides are back in La Liga action on Wednesday, as Barcelona host Osasuna and Real Madrid visit Deportivo La Coruna.