Messi had broken a three-year goalless drought against Madrid to cancel out Casemiro's opener for Madrid in the first-half.
Ivan Rakitic's stunning strike and a red card for Madrid captain Sergio Ramos for chopping down Messi 13 minutes from time put Barca on course for victory before James Rodriguez came off the bench to level four minutes from time.
However, fittingly, Messi had the final say with a brilliant finish deep into stoppage time to lift Barcelona's hopes of a third straight La Liga title.
Cristiano Ronaldo had strong appeals for a penalty waived away inside two minutes after he appeared to have been clipped by Samuel Umtiti.
More From This Section
Barca grew slowly into the game and had their first big chance when Luis Suarez dragged wide Jordi Alba's fine cut- back from the edge of the box 11 minutes in.
Shortly after Messi was left floored and bloodied after being caught by a stray elbow from Marcelo.
The Argentine was still down by Ronaldo drilled another fine effort towards goal that Marc-Andre ter Stegen did well to parry to safety.
The lead lasted just five minutes, though, as with a handkerchief still mopping the blood from his cheek, Messi danced past Dani Carvajal and Nacho to fire home his first goal against Madrid for three years.
Ter Stegen was called into action again to prevent Real immediately retaking the lead as he flew to his left to save from Luka Modric's long-range effort.
Madrid were rampant at the start of the second period, but were met with a wall of resistence in Ter Stegen.
The German dived low to his left to turn international teammate Toni Kroos's effort behind before diverting Karim Benzema's goalbound header to safety with his outstretched foot.
However, Keylor Navas was also busy at the other end as he came to Madrid's rescue on three occasions.
Firstly, he got a foot to Paco Alcacer's prodded effort before pulling off acrobatic saves to deny Gerard Pique and Suarez.
There was nothing Navas could do to deny Barca 17 minutes from time when Rakitic took aim from 25 yards and drilled into the top corner.
The match seemed to have swung decisively in Barca's favour four minutes later when Ramos scythed down Messi to be shown the 22nd red card of his career.
However, even with 10 men, Madrid rallied and levelled when substitute James Rodriguez swept home Marcelo's cross four minutes from time.