Faf du Plessis scored a career-best 185 innings to help South Africa edge past Sri Lanka by 40 runs in the fourth one-day international against South Africa at Newlands.
Du Plessis's scintillating 185 run-knock fell only three short of the South African ODI record, as South Africa piled up 367 for five.
It seemed as though Sri Lanka, who had been outplayed in the first three matches, would be on the end of another crushing defeat.
But Sri Lankan captain Tharanga hit a magnificent 119 off 90 balls and led his team's most spirited showing of the series. They were in with a chance of winning until a late slide in which they lost their last six wickets for 20 runs in 4.3 overs to be bowled out for 327.
"Faf played an exceptional knock," said South African captain AB de Villiers. "Tharanga also played a fantastic knock but there wasn't a lot of panic. I felt comfortable with the variety we had in our bowling."
Tharanga and fellow left-hander Niroshan Dickwella thrashed 100 runs in the first 10 overs on the way to a first-wicket partnership of 139 off 98 balls before Dickwella was caught on the midwicket boundary off Dwaine Pretorius for 58 off 47 deliveries.
Kusal Mendis (29) helped Tharanga add 64 for the second wicket as Sri Lanka stayed comfortably ahead of the required run rate until Wayne Parnell dismissed both batsmen. Tharanga, who was caught at backward point, hit 11 fours and seven sixes and left the field to a standing ovation.
"We needed to get a good start and it was a much better batting performance," said Tharanga. "Unfortunately we lost too many wickets later."
South Africa took full advantage of good batting conditions winning the toss.
Du Plessis made his runs off 141 balls and hit 16 fours and three sixes. He was caught at long-on off the first ball of the last over trying to clear the boundary with a hit which would have taken him past Gary Kirsten's long-standing South African best of 188 not out, made against the United Arab Emirates during the 1996 World Cup in Rawalpindi.
Du Plessis shared century partnerships with Quinton de Kock (55) and De Villiers (64).
"When you're feeling in good touch you've got to score big runs. That's my job," said Du Plessis, who said the partnerships with De Kock and De Villiers were crucial. "Quinny was striking the ball nicely and that took the pressure off me, then AB was brilliant running between the wickets."