The 20-time grand slam champion appeared set for a shock loss in Melbourne, battling a leg injury from the third set onwards on Rod Laver Arena.
Instead, he delivered a spectacular comeback, reaching the semi-finals with a 6-3 2-6 2-6 7-6 (10-8) 6-3 victory that was special even by his standards across three hours, 31 minutes.
Federer saved seven match points in the fourth set, including coming from 6-3 down in the tie-break, having needed a medical timeout.
The 38 year-old moved into his 46th grand slam semi-final and became the oldest man to get into the last four at the Australian Open since Ken Rosewall in 1977.
After squandering five early break point chances, Federer took his sixth when Sandgren sent a backhand long in the sixth game.
While Federer closed out the opener, a flurry of errors saw him give up a break and fall 3-0 behind to begin the second.
Federer committed 15 unforced errors in the second set – eight from the backhand side – as Sandgren levelled the match.
The Swiss great's struggles continued into the third, broken in the second game when he sent a tame forehand into the net.
Sandgren came from 0-40 down in the third game of the set, during which a frustrated Federer was given an audible obscenity warning before receiving treatment off the court.
Struggling physically, Federer tried to hang in there before giving up the set with a backhand into the net.
Mixing his game up, Federer fought hard against a seemingly undistracted Sandgren in the fourth set before saving three match points in the 10th game as the American faltered.
Sandgren put two match point opportunities into the net and sent another wide before saving a break point to take a 6-5 lead.
In an extraordinary tie-break, Federer came from 6-3 down and saved four more match points to force a decider as the Rod Laver Arena crowd erupted.
Federer had his right hamstring treated before the fifth set and he appeared far more mobile as he took control of the contest.
A break for 4-2 set him up and he had no trouble closing it out, an unreturnable serve wrapping up the amazing comeback.
Roger Federer  bt Tennys Sandgren 6-3 2-6 2-6 7-6 (10-8) 6-3
Federer – 44/56
Sandgren – 73/53
Federer – 5/3
Sandgren – 27/5
BREAK POINTS WON
Federer – 2/13
Sandgren – 4/14
FIRST SERVE PERCENTAGE
Federer – 65
Sandgren – 65
PERCENTAGE OF POINTS WON ON FIRST/SECOND SERVE
Federer – 71/53
Sandgren – 79/45
Federer – 160
Sandgren – 161