Roger Federer was pushed all the way by Croatia's Marin Cilic before sealing his quarter-final spot at the Toronto Masters in Canada.
Having taken the first on a tie-break, Federer had several opportunities to wrap up a straight sets win but saw his opponent save six match points in the second before forcing a decider.
All six of the match points came at 4-5 on the Croat’s serve, but Federer was unable to push home his advantage and Cilic would go on to win a second breaker.
The third proved another tight affair, but the 17-time grand slam champion claimed the only break of the contest in the ninth game with a pinpoint forehand winner to secure a decisive advantage.
He then served out to complete a hard-fought 7-6 (7/5) 6-7 (3/7) 6-4 win in two hours and 40 minutes and was quick to pay tribute to his opponents afterwards.
"It was a thrilling match and I hope to keep it up tomorrow," said Federer. "I was unlucky with some shot selections on some of the match points and he hung in there.
"It was nice to win this one as I've had some tight losses this season. In the third set, his level didn't drop, I just had to keep going and try to create chances.
"I thought Marin played really well, especially for longer periods. I'm happy I was able to find a way tonight.
"It's nice winning those kind of matches, because I also lost a bunch in my career, especially this season I have lost some closer ones."
Federer will next face David Ferrer after the Spaniard overcame a slow start to beat another Croat, Ivan Dodig, 1-6 6-3 6-3.
Home hope Milos Raonic maintained his hopes of making it back-to-back titles after his win in Washington last week, although he too was taken to three sets.
Raonic won the opener against France's Julien Benneteau but then rather lost his way in the second - the Frenchman breaking his powerful serve twice – before reasserting himself in the decider to clinch a 6-3 4-6 6-4 win and a last-eight clash with Spain's Feliciano Lopez.