The familiar story that the Jade Emperor held a race and that the rat won by riding on the ox's back and jumping off at the finish is a folk tale, widely told and much loved, but it is a later explanation of an order that already existed rather than its cause. What the twelve-year cycle rests on historically is the branch system, and its correlation with animals is attested in the Qin-period bamboo manuscripts from Shuihudi, dating to the third century BCE, in a day-book that gives animals for the branches in an order close but not identical to the modern one.
The twelve-year length itself matches the sidereal period of Jupiter, about 11.86 years, which Chinese astronomy tracked as the Year Star, Suixing, and this is generally taken as the origin of a twelve-part division of the years. The system is shared, with local variation in the animals, across China, Korea, Japan, Vietnam, Mongolia, Tibet and Thailand.
Sources Chinese Mythology: An IntroductionAnne Birrell with Chinese Mathematical Astrology: Reaching Out to the StarsHo Peng Yoke