Khedira has agreed a five-year deal and joins for an undisclosed fee.
The 23-year-old Germany international had spent his entire career with the Swabians, coming through the youth ranks from the age of eight to make his first-team debut in October 2006, the season in which Stuttgart last won the Bundesliga.
Khedira became a regular in Armin Veh's team that season and penned his first professional contract just after the winter break, a deal he extended in 2008 until 2011.
"Obviously you don't gladly let such a leading player and figure like Sami Khedira leave, but on the other hand, we could understand Sami's desire to continue his career with Real," explained Stuttgart's director of sport Fredi Bobic.
"We wish him lots of success with his new challenge in Madrid."