Defending Shanghai Masters champion Roger Federer avoided a third-round upset against Roberto Bautista Agut as he came through in three sets to clinch a quarter-final meeting with Kei Nishikori.

The Swiss, whose ranking as number two in the world is under threat this week, was broken three times in the second set to force a decider but eventually prevailed 6-3 2-6 6-4.

Bautista Agut had never even taken a set off Federer in their previous seven meetings but forced a decider only to be crucially broken at 4-4, and the Swiss served out to love to clinch the win.

Federer will now meet Nishikori, who he has not lost to since 2014, for the first time since the 2017 Australian Open.

There were signs this was not going to be a straightforward evening for Federer early in the first set when Bautista Agut had a break point in the Swiss' second service game.

He could not capitalise, though, and Federer soon gained a 3-1 lead en route to taking the opener.

Federer won an 11-minute game at the start of the second set to break Bautista Agut again before the Spaniard instantly roared back and reeled off four games in a row.

Bautista Agut then forced a decider by breaking Federer for a third time, successfully winning a challenge to bring up set point, which he took when his opponent netted a backhand.

The third set remained on serve until, at 4-4, Federer claimed his first break since the start of the second set, and he capitalised to secure another hard-fought win having also beaten Daniil Medvedev in three sets on Wednesday.

"It was a very tough match, I thought it was a really high level," Federer said afterwards.

"They're tough conditions – the ball stays super low, it's fast, it's cooler.

"If you want to make the winner you have to take a lot of risks, it seems like. If you find a great groove, it's hard to go through the opponent."