Federer is playing his first tournament since losing in the second round of Wimbledon.
A four-time champion on the clay courts of Hamburg, Federer needed 2 hours to overtake Mayer. Federer was down 5-1 in the second set, won the next two games but then faltered again. He double-faulted and had two straight forehand errors to give up the set.
In the third, Federer broke serve twice, only to see the German re-break both times. But with the match on the line, the Swiss former No. 1 raised his game. He broke serve for a 6-5 lead and served out the match at love, hitting a service winner on match point.
He'll play Argentine qualifier Federico Delbonis, who upset 14th-seeded Fernando Verdasco of Spain 6-7 (5), 7-6 (8), 6-4 to make the semifinals of a tournament for the second time in his career.
Fognini prevailed 6-2, 6-4 over the second-seeded home favorite. The 12th-seeded Italian is looking for his second straight title after winning his first tournament in Stuttgart, where he beat Haas in the quarterfinals.
The fifth-seeded Monaco beat Almagro in the Hamburg semifinals last year. Almagro was runner-up in Hamburg two years ago, while Monaco beat Haas for the title last year.
Delbonis' previous semifinal appearance was two years ago in Stuttgart.
After fending off a pair of match points in the second set, Delbonis failed to serve out the match at 5-3. He then wasted two match points on Verdasco's serve before the Spaniard double-faulted on the third.