The 37-year-old Swiss top seed faces Spain’s unseeded Roberto Bautista Agut on Thursday in the last 16.
The 20-time Grand Slam champion initially wasted little time stamping his mark on the tournament, breaking the 22nd-ranked Medvedev in the first game.
But Medvedev, fresh from winning the Japan Open, broke back and enjoyed even more luck on Federer’s service in the second set.
Federer’s large cheering squad – decked out in matching red T-shirts – looked on in disbelief as Medvedev grabbed the second set.
The 22-year-old then put the Swiss under immediate pressure on his serve in the deciding set, only for an uncharacteristically flustered Federer to hold.
In what was the first meeting between the pair, Federer broke in the ninth game to finally destroy Medvedev’s resolve in just under two hours.
With the exception of injured world number one Rafael Nadal, Federer’s chief rivals are all still in the mix.
Juan Martin del Potro and Alexander Zverev both defied illness to join Federer and Novak Djokovic in the next round.
Del Potro, the third seed, said that he is suffering from a virus and reviewing his health “hour by hour”, after labouring past France’s Richard Gasquet.
The Argentine lost Sunday’s final of the China Open in Beijing to unseeded Nikoloz Basilashvili and afterwards revealed that he had been unwell.
Three days on and the 30-year-old continues to be under the weather, but just about did enough to see off Gasquet 7-5, 7-6 (9/7).
Between coughs at his post-match press conference, Del Potro said: “It wasn’t easy to play for me today, I did what I can. I didn’t run too much.
“But I’m going like hour by hour and see how I’m feeling,” added Del Potro, who plays 13th seed Borna Coric of Croatia next in Shanghai.
“I got lucky that I won, but tomorrow will be a different day.
“If I have a good night today and I have a good recovery tomorrow morning, maybe I will feel a little bit better for tomorrow night and play better than today.”
The 21-year-old Zverev fought off a cold — he has had a sore throat and blocked nose for a few days — and the raw power of Basilashvili, winning 7-5, 6-4.
The fourth seed will play Australia’s world-ranked 33 Alex de Minaur.
Zverev said that Basilashvili, who is up to a career-high ranking of 23, “knows how to play, definitely”.
“Probably the hardest-hitting player I have ever played against,” said Zverev.
Number two seed Djokovic nailed his place in the last 16 on Tuesday with a convincing victory over Jeremy Chardy.
The Serb, who is in sparkling form having won Wimbledon and the US Open this summer, plays the 16th seed Marco Cecchinato of Italy on Thursday.