Federer defeated Roberto Bautista Agut of Spain 6-3, 2-6, 6-4, a day after being taken the distance by Daniil Medvedev of Russia.
"I'm actually quite happy," Federer said. "Bautista really had to raise his level of play in that second set to stay with me. I mean, he really caught fire, I thought. I served, I think, 80 percent in that second set and got broken twice."
Novak Djokovic cruised through his second-round match, but Juan Martin del Potro had to retire after hurting his right knee in a fall.
Federer led Bautista Agut by a set and a service break when he became entangled in a fight that lasted until the second-to-last game of the third set.
Bautista Agut, a finalist here in 2016, finally offered Federer an opening to take control by surrendering his serve in the ninth game of the third set.
Federer will play eighth-seeded Kei Nishikori, a finalist in Tokyo last week, in the quarterfinals. Nishikori ousted Sam Querrey 7-6 (7), 6-4 on Thursday.
Third-seeded Del Potro, who has been playing with a cold throughout the week, was playing Borna Coric when he fell near the end of the first set. Del Potro had the knee wrapped but called it quits after losing the first set 7-5.
Djokovic earned partial revenge when he beat Marco Cecchinato 6-4, 6-0. The only other time the second-seeded Djokovic played Cecchinato was in the French Open quarterfinals, where the Italian upset him in four sets.
A Masters event is a level below a Grand Slam, but Djokovic was rapt to crush Cecchinato.
"I was making him play always an extra shot," Djokovic said. "I was aggressive when I needed to be. The second set was perfect, really."
Since Djokovic lost that French Open match to Cecchinato, he's won 28 of his 30 matches. The Serb is on a 15-match winning streak, which includes title runs at Cincinnati and the U.S. Open. He's bidding to win a record fourth Shanghai title this week.
He will take on seventh-seeded Kevin Anderson of South Africa, whom he leads 6-1 on head-to-head. Djokovic defeated Anderson in straight sets in the Wimbledon final in July.
Anderson ousted 10th-seeded Stefanos Tsitsipas of Greece 6-4, 7-6 (1).
Fourth-seeded Alexander Zverev of Germany also advanced to the quarterfinals by pasting Alex de Minaur of Australia 6-1, 6-4.
Zverev will play Kyle Edmund after the Briton defeated Nicolas Jarry of Chile 7-6 (5), 6-3.
More AP tennis: https://apnews.com/tag/apf-Tennis and https://twitter.com/AP_Sports
Copyright 2019 The Associated Press. All rights reserved. This material may not be published, broadcast, rewritten or redistributed.