A much-changed Madrid side snatched victory at El Molinon thanks to Isco's two goals, which included a 90th-minute winner, to stretch their lead over Barcelona before the Catalans closed the gap back down to three points at the Nou Camp.
Messi scored twice and set up a third for Paco Alcacer as Barcelona saw off their Basque opponents, who pressed them until the end of a nervy encounter.
The win, however, kept the Catalans within touching distance of Los Blancos, having played one match more, ahead of next Sunday’s Clasico.
Despite their recent jitters, he is confident that his side can do well in the reverse leg against the Italians and against Madrid in next weekend's crucial title showdown if they perform to their very best.
“We have to be marvellous and perfect,” he said. “The players need confidence to be at their best and that’s what I’m trying to do as the coach.
Messi put Barcelona ahead with a low drive and doubled the lead with a tap-in after Luis Suarez’s shot was saved, but Sociedad hit back when Inigo Martinez’s lashed effort bounced off Samuel Umtiti into the Barcelona net.
Alcacer extended the Catalans’ advantage before Xabi Prieto reduced the deficit to 3-2 just before halftime, while the second half stayed goalless despite intense pressure from the visitors.
Sporting opened the scoring in the 14th minute when Mikel Vesga scooped a pass over Madrid's defence which Duje Cop slammed home, and then Isco equalised three minutes later with a brilliant individual goal.
Vesga looped a header over Kiko Casilla to put the hosts back in front after halftime, but Alvaro Morata equalised with a headed goal of his own, before Isco's late winner.
The Spain international said that fighting until the very end and snatching late victories are part of the club's fabric.
Atletico Madrid missed two late penalties but still thrashed bottom of the table Osasuna 3-0 at home with a brace from Yannick Carrasco to stay third in the table.
In the battle to avoid the drop, Deportivo La Coruna beat Malaga 2-0 to move nine points clear of the relegation zone, with Sporting Gijon still 18th, on 22 points.