The world number three claimed the first set in a tie-break, but the Ukrainian levelled the match through another breaker in the second.
The duo remained well matched in the third, but Stakhovsky managed to claim the first break point of the contest to take a 6-5 lead before holding serve to seal the set.
The 27-year-old secured an early break in the fourth as he looked to finish the match, but the reigning champion was able to take his first break of the encounter to get the set back on serve.
In the fourth-set tie-break, Stakhovsky edged ahead early on, eventually bringing up two match points.
Federer saved the first but his backhand crept wide while he was trying to defend the second, handing the Ukrainian the win.
Stakhovsky will face Austria's Jurgen Melzer in the third round.