The 20-time Grand Slam champion emerged victorious over his opponent over four sets but he was far from his best.
In an astonishing scoreline, Federer secured a 7-6 (7-5) 6-7 (3-7) 7-6 (7-4) 7-5 victory on a deserted Court Philippe Chatrier.
The world No 59 pushed Federer to the brink, in what would have been his earliest exit in Paris since 2004.
But the Swiss can only have himself to blame after making 63 unforced errors – though there were some vintage Federer shots.
The clash ended at 12.43am local time and he has admitted he could quit Roland Garros to save energy for Wimbledon this year.
The 39-year-old underwent double knee surgery last year and is in his third open since his operations in a remarkable test of his physically.
Federer is through to the last 16 – extending his own record of 68 times in a Grand Slam – where he will face ninth seed Matteo Berrettini.
But Wimbledon has always been the tournament he has had his sights set on and the tennis legend has admitted he could pull out of the French Open to conserve energy.
“These are all stepping stones to something that is really important to me. It is the season, and it is the comeback. I need matches like these,” Federer said.
“We go through these matches, we analyse them highly and look on what’s next and will do the same tonight and tomorrow.
“Because I need to decide if I keep on playing or not or is it not too much risk at this moment to keep on pushing, or is this just a perfect way to just take a rest?
“Because I don’t have the week in between here and Halle [the grass-court tournament] like normal to see what’s best now, if you count back from Wimbledon and so forth.
“It’s just a lot going on, but having a match like this, knowing I could have probably played a fifth set but not knowing how I will wake up tomorrow is interesting, to say the least.”