Federer, 36, had never lost in 16 previous meetings with the 35-year-old Ferrer, whom he first defeated 14 years ago.
Federer, 36, had never lost in 16 previous meetings with the 35-year-old Ferrer, whom he first defeated 14 years ago at the Vienna Indoor tournament.
But while Ferrer managed to take the opening set -- ending Federer's 32-set streak -- the Swiss ace raised his game to win 4-6, 6-4, 6-2.
"I actually feel really happy because I know I can play a lot better. David can play a lot better, too," Federer said. "We battled, both tried to find a way to win. You know, he had a good start, I had a better finish."
A strangely error-prone Federer was unable to generate his usual fluency early on, and quickly found himself giving away early breaks to trail 4-1 in the first set.
Nowhere was Federer's wayward perfformance better illustrated than in the seventh game, when he squandered three break points at 0-40 to allow Ferrer to take a 5-2 lead.
Federer held for 5-3 and looked to have clawed his way back into the set with a break of Ferrer's serve in the next game to make it 5-4.
But Federer was struggling again as he served to level the set, finding himself set point down. He saved the first with an ace but Ferrer made no mistake with his second set point, converting to take the opener 6-4.
Federer responded quickly in the second set, going a break up to lead 3-2 before holding for a 4-2 lead.
With Federer slowly improving his first serve, Ferrer was unable to carve out the break opportunities he had found in the first set.
The set went with serve as Federer levelled.
An early break in the decider put him in control as a weary Ferrer began to tire.
Some vintage play at the net helped put Federer 4-2 up with Ferrer seemingly unable to summon a response.
The decisive break came in the seventh game, with Ferrer netting a forehand return to leave Federer 5-2 up and serving for the match.
Federer promptly went in for the kill, attacking the net and opening up the court to clinch victory with a deft volley.
Federer will now play another Spaniard, Roberto Bautista Agut, in the quarter-finals. Bautista Agut defeated France's Gael Monfils in a gruelling slugfest, winning 4-6, 7-6 (7/5), 7-6 (7/2).
"I hope that this match gives me some better rhythm and confidence against Bautista Agut, who plays actually very similar to David," Federer said.