Federer won the first set but Sandgren rallied to bag the next two against the error-prone Swiss, who received a code violation warning for obscene language and took a lengthy medical timeout during the third set on Tuesday.
The 38-year-old's movement seemed restricted but the 20-times Grand Slam winner and six-time champion at Melbourne Park carried on.
He saved seven match points in the fourth set before winning the tiebreaker to force a decider.
Federer, who got involved in a lengthy argument with Serbian chair umpire Marijana Veljovic during an ill-tempered third set, converted his first match point and will meet either Milos Raonic or Novak Djokovic for a place in Sunday's final.
Â