The Swiss top seed, playing his first tournament since his shock second-round exit at Wimbledon, dug deep to claim the third set for a 7-6 (7/4), 3-6, 7-5 quarter-final victory.
Mayer, 45th in the world compared to Federer’s fifth ranking, fired down six aces, three times more than the Swiss star, but Federer was strong where it counted, saving three of the five break points he faced in the third set.
“It was extremely difficult,” said Federer.
“I started really well. I thought we were both hitting the ball well in the first set and not giving each other that many chances. It went down to the wire.
“I’m happy I played a good tie-break. I should have been up early with a break in the second set; he got me there. It was a bit of a rollercoaster till the very end of the match. Just had to tough it out.
“The conditions were cold and heavy, the clay was heavy. So, it was different than we had expected at the beginning of the day when we thought we would play at 5.15pm. I have to say that I really enjoyed the match. It was a tough match and Florian fought hard.”
Federer has a 32-4 event record in Hamburg, where he won the title in 2002, 2004-05 and 2007, then finished runner-up in 2008 to Rafael Nadal.
The Swiss star will now face Argentinian qualifier Federico Delbonis in Saturday’s semi-finals.
German second-seed Tommy Haas made a quarter-final exit when he lost in straight sets, 6-2, 6-4, to Italian 12th-seed Fabio Fognini, who claimed his first ATP tournament win at Stuttgart last week.
Fognini, who had also beaten Haas in the last-eight at Stuttgart, will play third-seed Spaniard Nicolas Almagro, who beat fifth-seed Juan Monaco of Argentina 4-6, 6-0, 6-3 in just under two hours.