The 19-time Grand Slam champion needs to win the Swiss Indoors this week to keep his chances alive of catching Rafael Nadal at the top of the rankings.
But for large periods of his quarter-final clash against Adrian Mannarino, Federer was staring down the barrel.
Mannarino won the opening set 6-4 to heap pressure on Federer in front of his hometown fans in Basel.
Federer came back to win the second before the Frenchman carved out two break points in the sixth game of the deciding set.
Federer saved the first but missed his first serve at 30-40 down. His second serve was out wide to the Mannarino forehand and he delivered a rocket of a reply.
It appeared to catch Federer flat-footed as he was left rooted to the spot as the ball made a beeline for the baseline.
But you don’t win 19 Grand Slams without having the ability to pull a rabbit out the hat when it matters.
Federer duly picked up the half volley with his backhand to send a sweet reply down the line that proved to be a clear winner.
The shot had the Centre Court supporters in Basel on their feet and sent Twitter bonkers.
One Federer fan gushed: “OMG! Shot of the season. Shot of the century.”
Another said: “Producing the goods when it really matters. Bravo Roger Federer.”
A fellow user added: “Doesn’t get much better than that. What a shot, what a player.”
Federer went on to hold service before wrapping up 4-6 6-1 6-3 win.
A tournament win this week will take the Swiss to within 1,460 points of Nadal ahead of the Paris Masters next week.