The number one seed and defending champion was pushed all the way by the surprise winner of the Japan Open, but broke in the ninth game of the deciding set before serving out to reach the last 16.
It is Federer's first competitive tournament in singles since he lost to John Millman in the US Open last 16 in early September.
Djokovic sees off Coric to close gap on Nadal
He will face Spain's Roberto Bautista Agut for a quarter-final spot as he continues his quest for a third title in Shanghai.
Juan Martin del Potro displayed his battling qualities to overcome Richard Gasquet.
The number three seed fought back on two occasions, winning four straight games from 3-5 down in the first set and then recovering from a 2-6 deficit in the second set tie-break on the way to a 7-5 7-6 (9/7) victory.
Del Potro will face Borna Coric in the next round. He beat the Croatian 6-4 6-3 6-1 in the US Open fourth round last month.
Fourth seed Alexander Zverev is also through after a 7-5 6-4 win over in-form Georgian Nikoloz Basilashvili. He will play Alex de Minaur in the last-16 after his 6-4 6-3 victory against Benoit Paire.
Wimbledon finalist Kevin Anderson cruised to victory against Mikhail Kukushkin, winning 6-3 6-2 in just 64 minutes and will play Stefanos Tsitsipas after the Greek saved three set points in the second-set tie-break en route to a 6-4 7-6 (10/8) win over Karen Khachanov.
Marco Cecchinato recovered from 1-4 down in a final-set tie-break to defeat Chung Hyeon 4-6 7-6 (7/5) 7-6 (7/5) in two hours and 35 minutes while British number one Kyle Edmund maintained his good recent form with a 6-3 6-4 win over Andreas Seppi to reach the third round in Shanghai for the first time.
Shanghai Masters Men's Singles Results
- 1-Roger Federer (SUI) beat Daniil Medvedev (RUS) 6-4 4-6 6-4
- Roberto Bautista Agut (SPA) beat Mackenzie McDonald (USA) 3-6 6-4 6-1
- Sam Querrey (USA) beat Taylor Fritz (USA) 6-3 6-7(4) 7-5
- 8-Kei Nishikori (JPN) beat Yibing Wu (CHN) 3-6 6-0 6-3
- 3-Juan Martin del Potro (ARG) beat Richard Gasquet (FRA) 7-5 7-6(7)
- 11-Kyle Edmund (GBR) beat Andreas Seppi (ITA) 6-3 6-4
- Alex De Minaur (AUS) beat Benoit Paire (FRA) 6-4 6-3
- 4-Alexander Zverev (GER) beat Nikoloz Basilashvili (GEO) 7-5 6-4
- Kevin Anderson (RSA) beat Mikhail Kukushkin (KAZ) 6-3 6-2
- 10-Stefanos Tsitsipas (GRE) beat Karen Khachanov (RUS) 6-4 7-6(8)
- 16-Marco Cecchinato (ITA) beat Hyeon Chung (KOR) 4-6 7-6(5)
Coric claims Federer scalp to reach Shanghai final
Zverev loses his rag during Shanghai Masters semi-final loss to Djokovic