At the time of the Ksirodaka-lila (churning the cosmic “ocean of milk”) there was not yet any being named Rahu or Ketu. There was however an asura (“demon”) named Svarbhanu. When the amrita (“nectar of immortality”) was finally produced from the ocean, the devas (“gods”) managed to get it from the asuras by trickery via Mohini Avatar (an incarnation of the Supreme Godhead). Svarbhanu, however, was the most intelligent among the asuras, and was not convinced that things would be fair. Therefore he assumed the appearance of a deva and sat accross from Surya and Candra (gods of the Sun and Moon) as Mohini was distributing the amrta. Svarbhanu thought that if all the demigods drank they would overpower him, even if he too drank, so he wanted to drink first and kill everyone or steal all their nectar. But Surya and Candra saw his body language in moving to lift the cup of amrita in time that they could call out to Mohini and she could decapitate Svarbhanu with her discus before he could swallow the nectar.
However two conditions arose: 1) the amrita of immortality touched the lips of Svarbhanu, 2) the purifying discus of Vishnu touched his body as well. Therefore neither the head of Svarbhanu nor the decapitated trunk was able or fit to be killed and done away with. Therefore Mohini had them cast to opposite ends of the sky – as far as possible apart from one another and never able to move closer. We came to call the head Rahu and the trunk Ketu. Both of them were entrusted with demigod-like positions by Mohini / Vishnu: invested with power to be among the planetary gods – who now with their addition came to number nine.
Svarbhanu, however, at least apparently seems to retain his hatred of Surya (the Sun) and Candra (the Moon), thus the two opposite locations in the sky that his head (Rahu) and body (Ketu) occupy affect our astronomical reality as the point in the ecliptic path where solar and lunar eclipses take place. It is as if Rahu and Ketu have their revenge during an eclipse.
– Vic Dicara
The accounts are told in several very old Indian books called Puran, including the Bhagavata Purana