Michael Phelps brought the curtain down on one of sport's most storied careers with a dynamite relay swim to give himself 23rd Olympic gold medals and declared it a perfect finale.

The American, far and away the most decorated athlete in Olympic history, finished with five golds and a silver in Rio after signing off in dramatic style, coming to the rescue in Saturday's 4x100m medley final.

Source: AFP

Turning back the clock in his fifth and final Games, Phelps produced a blistering third leg of butterfly to restore his team's lead and tee up victory after Britain's Adam Peaty had threatened to gatecrash his party.

"Getting off the bus and walking to the pool tonight, I pretty much felt myself starting to crack," confessed Phelps, who bows out with 28 Olympic medals overall.

"Last warm-up, last time putting on a suit, last time walking out in front of people, representing my country -- it's insane, a lot better than it was four years ago," added the 31-year-old, who retired after the 2012 London Games before returning for one last hurrah.

"This is how I wanted to finish my career. I've lived a dream come true. Being able to cap it off with these Games is just the perfect way to finish."

The hullabaloo over the Phelps's farewell overshadowed the achievement of the women's 4x100m medley relayers as they captured their country's 1,000 Olympic medal, according to the US Olympic committee, dating back to 1896 when James Connolly won triple jump gold.

Even that statistic seemed to pale against the irrepressible Phelps -- and likewise Ryan Murphy's leadoff backstroke leg, which set a new 100m world record of 51.85.

"No matter what country you swim for you're indebted to Michael Phelps," said Murphy after winning his third Rio gold. "He's opened a lot of doors for all of us. It was awesome to be in that race with him."

Nathan Adrian brought the Americans home to preserve their unbeaten Olympic record in the event and give them a 16th swimming gold from 32 events for the week, matching their haul in London four years ago.

An Olympic record time of 3:27.95 was lost in the emotion after the race as Phelps tearfully saluted the crowd while his beauty queen fiancee Nicole Johnson looked on sobbing as she cradled baby son Boomer.