Golovkin won most of the early rounds but then got hammered a few times with Alvarez's uppercuts and right hands.
The 35-year-old Golovkin, making his Las Vegas debut, kept hold of the World Boxing Council, World Boxing Association and International Boxing Federation belts in front of a crowd of 22,358 at the T-Mobile Arena.
Judge Dave Moretti scored the tense battle 114-114. Dan Trella saw it 115-113 for Golovkin but Adalaide Byrd had it one-sided, 118-110, for Alvarez.
Byrd's lopsided score didn't reflect the explosive drama of a bout in which Golovkin moved forward aggressively while Alvarez was the counter-puncher with fast hands.
"This was a real drama show," Golovkin said. "I want to thank all my fans for supporting me.
"Of course I want the rematch. This was a real fight."
Asked if he thought he won, Golovkin said, "Look I still have the belts and I am still the champion."
The baby-faced champion with the steel jaw is considered one of the fittest athletes in boxing, but Alvarez was also well-prepared for a fight which both needed to validate their places in history.
Golovkin won most of the early rounds but then got hammered a few times with Alvarez's uppercuts and right hands and seemed to be the more tired of the two near the end.
Golovkin established himself early with his stinging jab, all the while effectively cutting off the ring. There was no feeling-out process in this one as both fighters came to fight from the opening bell and tried to land big punches early.
Golovkin said he expected Alvarez's game plan to include a few surprises and the former two-time champion Alvarez didn't disappoint.
In the fourth round Alvarez tried to press the attack, but he paid for it as Golovkin got the better of those exchanges.
The 27-year-old Alvarez's best round was the 10th, when he stunned Golovkin with a vicious right hand to the head. Alvarez tried to finish him off but Golovkin survived and once he shook off the cobwebs the two continued their brawl on the ropes and in the centre of the ring.
By the time it reached the 12th round, both boxers looked exhausted. Alvarez charged out of his corner looking for the knockout and Golovkin finished the round with a wild flurry of lefts and rights.
Alvarez moved to 49-1-2 with 34 knockouts and Golovkin remained undefeated at 37-0-1 with 33 knockouts after a fight that was two years in the making.
Boxing fans will be hoping the contest is the launching point of an extended rivalry like those of Manny Pacquiao and Juan Manuel Marquez, Erik Morales and Marco Antonio Barrera and Micky Ward and Arturo Gatti.