Military history of Ray, Iran

This article concerns the city of Ray, Iran (near Shahr-e-Rey) as a military objective, not the large territory of which it was once capital ("Ragau" in the Apocryphal Book of Judith). Ray, in an area of fertile lowland between the Zagros Mountains, the Elburz Mountains, and the great Dasht-e Kavir desert, commanded vital routes across and around the mountains, and was a key to power over the whole of Persia (Iran). The vast majority of ancient Persian literature has been lost, so little is known about the history of Ray before the arrival of Islam in the 7th century CE (although it is worth noting here that it was one of the great centres of the Zoroastrian religion).

Seleucids and Sassanids
Alexander the Great passed through Ray (then called Rhagae) in pursuit of Darayavahush (Darius) III, last of the Achaemenid dynasty of Persia, resting his exhausted troops there for five days when he heard that his quarry had already reached the Caspian Gates pass (the much later historical epic, Shah-nameh, suggests that the garrison at Ray elected to join Alexander, and aided his conquest of Persia). After the great conqueror's untimely death, Seleucus, a successful officer in his army, initially settled in Babylon as his share of the empire, embarked on a nine-year campaign of conquest in 311 BCE, ultimately acquiring most of Persia. He followed Alexander's policy of establishing Greek cities at key strategic points, and among these was Europos, a replacement for the old Rhagae (much needed because there was an earthquake around 300 BCE).

Around 250 BCE, during the reign of the third Seleucid emperor, Arsak (Arsaces) killed the viceroy of Parthia and temporarily set up headquarters at Ray (Rhages), founding the Arsacid dynasty. He was unable to hold the city, but his family remained in control of the territory further east. A later Arsacid ruler of Parthia, Phraates I subdued the Mardi people of the Elburz Mountains, nominally subjects of the Seleucids, shortly after his accession in 181 BCE. According to Strabo's Geography, he settled them at Charax, a fort between Ray (Rhagae) and the Caspian Gates pass, the main communication route with the east. Phraates' successor Mithridates I then expanded Parthia, his conquests including Ray. The town seems to have suffered, and he had it "refounded" around 148 BCE with the name Arsacia.

Little is known about events around Ray over the next several hundred years (except that in 459 CE Peroz, son of Sassanid emperor Yazdegerd II, with allies from the Khorasan area, fought at Ray against his brother- who had succeeded their father as emperor Hormizd III- and thus became emperor Peroz I. Over a century later, the usurper Bahram Chobin was based in the city, though the military action in his brief period as ruler (590-591 CE) seems to have taken place elsewhere- the same may be said for his effective successor Bistam, who minted coins in the city. Thus it would be wrong to assume that the following catalogue of events represents an abrupt change in the military history of Ray; the Islamic sources are simply very rich (which is also why Hijri dates are given alongside the CE dates from here on).

Muslim conquest, 7th century CE
In 19 H (640 CE) the forces of the second Islamic Caliph, 'Umar overran the key cities of Mesopotamia, forcing the Sassanid emperor, Yazdegird III, to withdraw across the Zagros Mountains to the Iranian heartland. He set up a new headquarters at Ray, called for aid from his nobles, and counter-attacked, but without much success. About 21 H (642 CE) the Caliph's forces began a new phase of their attacks by seizing a key pass over the mountains in the battle of Nihawand (now Nahavand). A Muslim army, led by Nu'aim ibn Muqarrin, descended (about 22 H/ 643 CE) from the uplands to the central plain of Iran. Yazdegird had moved on, leaving Ray in the hands of local governor Siyavakhsh, son of Mihran, son of Bahram Chobin. Allying himself with his neighbours further east (in Damavand, Tabaristan etc.) on the grounds that if Ray fell, they would be next, Siyavakhsh put up a strong defence, but after about a week he was, according to al-Tabari, betrayed by one of the city's aristocrats, Al-Zinabi Abu al-Farrukhan (perhaps due to political rivalry, perhaps because he had led a force from Ray to help battle the invaders at Waj Rudh, on the road from Hamadan, and had seen at first-hand the consequences of resisting the Muslims ). While the armies engaged in a night battle at the foot of the mountain just outside Ray, he led some of Nu'aim's cavalry by a little-known route into the city (an alternative version has the Muslims discovering the way into the city for themselves ), from whence they emerged to attack the defenders' rear, causing great slaughter. To set an example, Nu'aim ordered the destruction of the Old Town ("al-Atiqah", perhaps the aristocratic quarter of Ray; it was rebuilt by Farrukhan, whom he appointed as governor). Damavand and other territories to the east swiftly capitulated.

There were rebellions both in Hamadan and Ray shortly after the death of caliph 'Umar in 24 H (644-5 CE). The new Caliph, 'Uthman, placed Sa`d ibn Abi Waqqas (original leader of the Muslim campaign in Mesopotamia) in charge of Iraq, which then included the area known as Iraq Adjami (Iranian Iraq), stretching across the Zagros Mountains to Ray and beyond- also sometimes referred to as the Jibal. Sa'd sent 'Ala ibn Wahabin to make an example of Hamadan; the people of Ray, still dominated by feuding, self-interested aristocrats, soon abandoned their behaviour and started paying their taxes in 25 H (646 CE). Still the spirit of rebellion and dissension remained in Ray, so later in the Caliphate of 'Uthman, when Iraq was governed by Abu Musa al-Ashari- probably about 34 H (655 CE)- Qarazah ibn Ka'b Ansari had to be sent to impose peace.

Dynasties and ideologies, 8th century CE
In the declining years of the Umayyad dynasty, the Caliphate came close to collapse. In 122 H (740 CE) the Shi'ite Muslim Zayd ibn 'Ali had attempted unsuccessfully to take over as Caliph, and in 127 H (744 CE) the Shi'ites backed another claimant, Abdallah ibn Mu'awiyah. Failing to gain a victory in Mesopotamia, he crossed the Zagros Mountains, and by the end of 128 H (745 CE) most of western Iran, including Ray, had submitted to him. He was defeated a few months later, but the spirit of unrest remained. A year or two later, a revolt of Iranian Jews took place, led by Abu ‘Isa Isaac ibn Jacob al-Isfahani, (known as Abu Isa, or Obadiah) who claimed to be a messiah and proposed to lead his people back to Judea. He and his followers travelled from town to town gathering increasing support while fending off Muslim troops. However, when he brought his force to Ray, apparently about 131 H (748 CE), he met an army led by al-Mansur, who would later become the second 'Abbasid caliph, and was defeated with considerable bloodshed. He is believed to have been killed in the battle- but some of his followers thought otherwise, saying that he escaped and hid in a nearby mountain cave, and the Isawiya sect lasted at least two centuries more.

In the campaign which finally achieved the ascendancy of the 'Abbasid dynasty over the Umayyads, history vaguely repeated itself. Like the Sassanid emperor Yazdgird III, the leader of Arab forces in Iran, Nasr ibn Sayyar, went to Ray in the belief that there he would be able to obtain troops to challenge the 'Abbasids, who were pursuing him across the country. Meeting little success, he moved on to Saveh just before the pursuers reached Ray- but during his short stay in the city he had become ill, and he died in the autumn of 131 H (748 CE) soon after reaching Saveh.

In the years immediately after the 'Abbasid dynasty took over the caliphate, there was more unrest. In 137 H (754-5 CE) a Zoroastrian supporter named Sunbadh, one of the first Khurramis (supporters of the late Abu Muslim, who had brought the 'Abbasids to power, only to be killed by the second 'Abbasid Caliph) took his tens of thousands of followers to Ray. There he opened the storehouses Abu Muslim had left when he went on the journey that ended with his assassination, and claimed the treasure within, before setting off towards Hamadan with thousands more supporters. The Khurrami cause did not die with the bloody defeat of Sunbadh's army a few weeks later, and in 162 H (778-9 CE) more supporters of Abu Muslim allied at Djurdjan (Gorgan) with a sect known as the Muhammira, or "wearers of red", under the nominal leadership of one of Abu Muslim's sons or grandsons, Abu'l Gharra (but organised by 'Abd al-Qahhar). They marched to Ray, but there they met, and were crushed by, an army sent by Caliph al-Mahdi, led by 'Umar ibn 'Ala, governor of Tabaristan.

Between those two Khurrami insurrections, in 141 H (758-9 CE) there was another illustration of the strategic importance of Ray, when the governor of Khorasan rebelled against the Caliph al-Mansur, who sent his son Muhammad (later Caliph al-Mahdi) to restore control, using Ray as a base. In the event, the governor was defeated by some of his own subjects, but Muhammad ruled the eastern territories from Ray until 152 H (768-9 CE), and redeveloped the city under the name of Muhammadiya, with improved defences and military facilities (creating a new suburb, Mahdi-abadah, to resettle those whose homes were demolished in the process). His son, the great Harun al-Rashid, born and raised in Ray, made similar use of the fortified town, for example in 189 H (805 CE) when he heard that another rebellion was brewing in Khorasan. While in Ray, he took the opportunity to torture the local governor, Ishaq ibn al-Abbas al-Farsi to try and make him reveal the whereabouts of his niece's husband, the troublesome Isma'ili Imam, Muhammad ibn Ismail. Ishaq died as a result of his treatment.

Tahirids and Zaydis, 9th century CE
In 195 H (811 CE), Ray stood at the frontier of the territories of Harun's sons, Caliph Muhammad ibn Harun al-Amin and governor Abu Jafar al-Ma'mun ibn Harun. Their advisors had goaded them into war, and when al-Amin's forces, led by former Ray governor 'Ali ibn 'Isa ibn Mahan, marched over the Zagros Mountains from Baghdad, a much smaller, but mobile and well-led defence force, under Tahir ibn al-Husayn, awaited them at Ray. Tahir decided to risk meeting the invaders out on the plain, where his cavalry could be most effective, so the Battle of Rayy, brilliantly successful prelude to his counter-invasion of Iraq, actually took place about a day's march from the city. When al-Mam'un was thus established as Caliph, Tahir was rewarded with his old governorship of the eastern territories, which continued in the family for decades as a hereditary post.

In 250 H (864 CE) the people of western Tabaristan had had enough of the growing arrogance and corruption of the Tahirids, and appealed to al-Hasan ibn Zayd of the Alavid dynasty, a leader of the Zaydi Shi'ites, who lived in Ray. He agreed to help, and was soon acknowledged as lord of Tabaristan, with the backing of nearly all the other peoples of the Elburz Mountains, including the Daylamites. An Alavid, Muhammad ibn Ja'far ibn al-Hasan, expelled the Tahirid governor of Ray in the winter of 250 H (865 CE), but Muhammad ibn Tahir sent a force from Khorasan, led by Muhammad ibn Mikal, which soon retook the city and captured Muhammad ibn Ja'far. In the same period of counter-attack, al-Hasan himself was forced to withdraw to Daylam, but quickly regained his position with the Daylamites' help. The Daylamite general Wajin recaptured Ray, and installed Ahmad ibn 'Isa ibn 'Ali as governor. In 252 H (866 CE), we learn of Ahmad recapturing Ray from the Tahirid governor 'Abd Allah ibn 'Aziz with the help of the Daylamite prince Justan ibn Wahsudan, so presumably he was expelled at some point. Abd Allah later turned the tables and captured Ahmad, but was himself subsequently taken prisoner by al-Qasim ibn 'Ali ibn al-Hasan for the Alavids. In 253 H (867 CE) Musa ibn Bugha al-Kabir was appointed by the Caliph as governor of Jibal, with a mandate to recover Ray from the Alavids. This he did, but in the summer of 255 H (869 CE) he had to go to the Caliph's capital at Samarra, and apparently left 'Abd al-'Aziz ibn Abi Dulaf in charge at Ray. "Apparently", because all we know about 'Abd al-'Aziz' tenure is that when al-Qasim arrived at the city gate a year or so later, sent by al-Hasan, it was 'Abd al-'Aziz who officially invited him and his troops in. Musa rushed back from Samarra as soon as he heard the news, in late summer 256 H (870 CE) and soon ousted the Alavids. They reportedly took over again for a short while in 258 H (872 CE), and the whole region was becoming so troublesome that in 259 H (874 CE) Musa resigned his governorship. About this time, incidentally, Khalaf al-Hallaj was sent to spread the message of Isma'ili Shi'ite Islam across the plain of Iran, as the first da'i of Jibal, based near (later in) Ray.

Musa's appointee as governor at Ray, al-Salani, died in 262 H (late 875 CE), and for political reasons, the Caliph appointed as his replacement the Iranian ex-bandit Ya'qub-i Laith Saffari, who in 259 H (873 CE) had destroyed Tahirid power in Khorasan. Ya'qub, first of what would become the Saffarid dynasty, had coins minted at Ray within months of taking office (though his capital was further east, at Zaranj). Ya'qub died in 265 H (879 CE) and was succeeded by his brother Amr-i Laith Saffari. In 270 H (884 CE) al-Hasan died, and the following year, the governor of Qazwin, Adgu-tegin, seized Ray, which apparently had been taken over by al-Hasan's Alavid supporters. About the same time, precisely because the threat from rebels was diminishing, the Caliph turned against 'Amr, favouring instead Ahmad ibn 'Abd al-'Aziz ibn Abi Dulaf, governor of Isfahan (and son of the former negligent Ray governor). While Ahmad harried 'Amr in the west, a Tahirid supporter, Rafi' ibn Harthama, was attacking his possessions in the east, in alliance with the rival Samanid dynasty. Moving steadily westward, in 275 H (888-9 CE) Rafi' defeated al-Hasan's brother and heir Muhammad ibn Zayd, then he captured Ray in 276 H (889 CE), and made it his headquarters.

A new Caliph, al-Mu'tadid, brought a new policy in 279 H (892 CE)- he saw Rafi' as a greater threat than 'Amr, so he sent Ahmad to eject him from Ray. This was achieved with ease, in a battle near the city on 23 Dhu al-Qadah (14 February 893 CE)- though it would be another three years before Rafi's career was finally ended, by 'Amr. Meanwhile, the Caliph's son, al-Muktafi was temporarily installed as governor of Ray. The Caliph ingeniously rewarded 'Amr's success against Rafi' in 283 H (896 CE) with a grant of the governorship of Ray plus large territories to the east. In order to claim his reward, 'Amr had only to persuade the incumbent Samanid governor of the eastern territories, Isma'il ibn Ahmad ibn Asad, to leave. The first army he sent failed, so he decided to take charge of an invasion in person, resulting in his capture and humiliation in 287 H (900 CE). Isma'il was rewarded by having his own territory expanded to include the other lands that would have been 'Amr's, including Ray. Also in that year, the Samanids gained control of Tabaristan.

Samanids, early 10th century CE
Although Isma'il does not seem to have been much concerned with his obligation to send annual tribute to Baghdad, he did devote considerable resources to the defence of his expanded quasi-kingdom. Still, Ray was very much on the fringe of his territory, and tended to be overlooked in commercial policies designed to benefit his heartland in Khwarazm, 1,000 km to the north-east. Furthermore, in 289 H (902 CE), Muhammad ibn Harun, whom Isma'il had appointed governor of Tabaristan, rebelled and declared his support for Shi'ism. The city's inhabitants therefore invited him to come and rid them of their unpopular governor Ukratmush al-Turki, which he did, defeating and killing Ukratmush that summer. Isma'il hastened to regain control, and a few months later he routed Muhammad's forces just outside the city. Muhammad fled to Daylam, but his forces were scattered. Meanwhile, a newly appointed vizier in Baghdad, 'Abbas ibn Hasan, began trying to take advantage of the unrest to bring Isma'il under tighter control, but the very efficient Samanid armed forces did not permit the unrest to turn into an effective rebellion.

Isma'il, who died in 295 H (907 CE), was not the only efficient and troublesome warlord in the Caliphate. Yusuf Ibn Abi'l-Saj, who had pushed his nephew aside to succeed his brother Muhammad as governor of Armenia and Azerbaijan, had a most uneasy relationship with the authorities in Baghdad. In 304 H (916-7 CE), he expanded his territory by invading Ray, then sent a letter to Baghdad claiming that the previous vizier had made him governor of the province (at this time two rivals, 'Ali ibn al-Furat- an ally of Yusuf- and 'Ali ibn 'Isa were effectively taking turns to eject each other from the vizierate every few years). A few months later the caliph sent an army, led by Khaqan al-Muflihi, to remove Yusuf's governor from Ray. Yusuf took his army back to Ray and defeated Khaqan's force, but after another few months, hearing of the approach of a stronger army, led by the very competent general Mu'nis al-Khadim, Yusuf withdrew to Ardabil, which he could defend more effectively. The move worked, and in 306 H (918 CE) he defeated Mu'nis, but the following year the general returned, and captured the rebel, who was imprisoned in Baghdad. Furthermore, when Yusuf left Ray in 306 H, the Daylamite 'Ali ibn Wahsudan took his chance and moved in. 'Ali's triumph was short-lived, however, because he had recently murdered his brother Justan (by then ruling Daylam as Justan III). Justan's son-in-law Muhammad ibn Musafir had since then been waiting for a chance of revenge, and in 307 H (919 CE) he killed 'Ali.

One of Yusuf's senior officers, Subuk, remained free and loyal. He gained control of Azerbaijan, then defeated an army sent to remove him, and became officially recognised as governor there. Outlying territories such as Ray were more of a problem, and by early 309 H (921 CE) the city was conquered by another Daylamite prince, Layli of Ishkawet (thanks to treason by Mu'nis' local deputy, Akh Su'luk). His rule lasted only months before the Samanid vizier Bal'ami delivered his head to the Caliph. In 310 H (922 CE) Subuk died; Yusuf was released, and made governor of Azerbaijan, plus Ray, Qazwin etc. Ahmad ibn 'Ali, the existing governor at Ray (another Daylamite, and a convert to Isma'ili Islam) objected to this arbitrary decision, and rebelled against the Caliph, so in 311 H (924 CE), Yusuf defeated and killed him, then put Muflih, one of his former slaves, in control of the city before moving on to Hamadan. Soon afterwards, the people of Ray expelled Muflih, who was replaced by a Samanid governor, and in 313 H (925 CE) Yusuf returned, to instal another of his deputies (the last time he would intervene in the city, as he was captured near Kufa and killed a couple of years later).

In 314 H (926 CE), at the request of Caliph al-Muqtadir, the Samanid leader Nasr ibn Ahmad ibn Ismail mounted an expedition to dislodge Fatik, the freedman then governing Ray on behalf of Yusuf ibn Ali 'I-Sadj. He captured the city in Djumada II (August–September) and returned to Bukhara a couple of months later, once stability had been assured. In 316 H (928 CE), the Da'i Saiyid Abu Muhammad Hasan ibn Kasim (deposed former ruler of Tabaristan) and Abu Mansur Makan ibn Kaki (former governor of Djurdjan) set out on a campaign of conquest, so in early Sha'ban (late September) Muhammad ibn Sa'luk, the governor appointed to Ray by Nasr ibn Ahmad, effectively invited them to take control of Ray, pleading illness, and retired to Khorasan. The effortless conquerors discovered too late that Asfar ibn Shirawaihi, the man whose rebellion had ended Makan's governorship, had returned from Khorasan and conquered both Djurdjan and Tabaristan. The Da'i tried to depose him, but was defeated, and killed by Asfar's lieutenant Mardawidj ibn Ziyar on 24 Ramadan, 316 H (11 November 928 CE). Asfar then marched his army to Ray and defeated Makan, who withdrew in haste. About 318 H (930 CE), Asfar sent Mardawidj ibn Ziyar to command a force against Muhammad ibn Musafir in Daylam, but instead of fighting they teamed up against Asfar, who fled, but was caught and killed the following year. Makan ibn Kaki prevented Mardawidj from taking over any of Asfar's territories except Ray, but he did gain the service of three of Makan's ablest officers, the Daylamite brothers 'Ali, Hasan and Ahmad ibn Buya.

Mardawidj, who seems to have had delusions of grandeur, allegedly including plans to capture Baghdad, was murdered by disaffected Turkic members of his own staff, in Safar 323 H (January 935 CE) at Isfahan while celebrating a Zoroastrian festival, and was succeeded at Ray by his brother Vushmgir, to whom Makan had to flee in 329 H (940 CE) after being defeated by the army of Khorasan. Their combined force met the Khorasani army, commanded by Abu 'Ali Ahmad ibn Muhtaj, governor of Khorasan, at Ishakabad on the Damghan road near Ray, on 21 Rabi' l (25 December)- Makan was killed by an arrow shot to the head. Abu 'Ali returned to Khorasan after a while, allowing Vushmgir to return to Ray, but after the death of their overlord Nasr ibn Ahmad in 331 H (943 CE), Hasan ibn Buya seized the opportunity to drive him out again. The next Samanid overlord, Nasr's son Abu Muhammad Nuh ibn Nasr ibn Ahmad, swiftly sent Abu 'Ali and his army back to Ray, but on the long march, some of them deserted, and when he met Hasan's force, 3 farsakhs [circa 18 km] outside Ray, most of the Kurdish soldiers in his army switched sides. He escaped back to Nishapur, but Nuh ordered him to try again, so in Djumada 333 H (January -February 945 CE), Abu 'Ali advanced against Ray again. On this occasion Hasan chose to withdraw, so Abu 'Ali captured the town and surrounding region in Ramadan (April–May). Hasan's older brother 'Ali sent him back and somehow (possibly by diplomacy) he regained the lost territory. Meanwhile, Hasan's other brother Ahmad was in a position to take control of Baghdad itself, so the Caliph, with whom the brothers had always maintained friendly relations, accepted the reality of the situation and gave them official status and power, with the new honorary names "'Imad al-Daula", "Rukn al-Daula" and "Mu'izz al-Daula". Ray became the capital for Hasan/Rukn's territory.

Buyids, late 10th and early 11th centuries CE
About the same time, Muhammad ibn Musafir's son, Marzuban ibn Muhammad, seized power in Azerbaijan. In 337 H (948 CE), following an alleged diplomatic insult, he attempted to capture Ray, but Rukn al-Daula managed to stall long enough to get reinforcements from his brothers, then defeated and captured Marzuban at Qazwin, going on to seize some of his territory in Azerbaijan. Shortly afterwards, 'Imad al-Daula died, having named Rukn's son Fana Khusrau as his heir. The new amir (henceforth to be known as 'Adud al-Daula) had only just entered his teens, so Rukn acted as his regent. This involved spending several months in 'Imad's capital, Shiraz, and inevitably, while Rukn was away, Abu 'Ali once again brought an army from Khorasan and seized Ray in 338 H (949 CE). To attempt to defend this position if Rukn brought the combined armies of the two states he was ruling would have been foolish, so the Samanid general allowed him to return peacefully, subject to payment of tribute, and renouncement of the territory he had captured in Azerbaijan (sadly for Abu 'Ali, such diplomacy was not popular in Khorasan, and he was deposed, dying in exile at Ray).

Throughout all this time, Rukn had new problems with old enemies. Abu 'Ali besieged Ray unsuccessfully, and made peace in 342 H (953 CE), but he was soon followed by the Ziyarid Vushmgir (sometimes ruler of Tabaristan and/or Djurdjan) who was allied with the Samanids. In 344 H (955 CE) he too signed a peace treaty, but by 347 H (958 CE, shortly after a major earthquake had struck the region around Ray and Qazwin) hostilities had resumed, and Vushmgir briefly took control of Ray- following which Rukn briefly took control of Djurdjan, etc. In 356 H (967 CE), while preparing for another joint campaign with his Samanid allies against Rukn, Vushmgir was killed by a boar during a hunt, and his eldest son, Bisutun made a successful alliance with Rukn against a younger son, Qabus, who was the Samanids' choice. Rukn attempted to devise a working arrangement to keep his own sons happy after his death, which occurred in 366 H (976 CE). Unfortunately, the second son 'Ali (Fakhr al-Daula), who inherited Ray, never fully accepted 'Adud al-Daula as his superior, so in 369 H (980 CE), at 'Adud's request, the younger brother Buya (Mu'ayyid al-Daula) invaded, and drove him (with his ally Qabus) to Khorasan. When 'Adud died in 372 H (983 CE), Fakhr and Qabus returned to Djurdjan, with Samanid allies from Khorasan who helped to defeat and kill Mu'ayyid shortly afterwards, in 373 H (984 CE).

After Fakhr's death in 387 H (997 CE), power passed to his infant sons, whose mother Saiyida acted as regent. Nine-year-old Abu Taleb Rostam (honorific name Majd al-Daula) inherited Ray, while his younger brother Abu Taher (Shams al-Daula) had Hamadan. Following the seizure of Khorasan in 388-9 H (999 CE) by the Ghaznavids- Turkic warriors from further east- the exiled Samanid Isma'il ibn Nuh al-Muntasir attempted to capture Ray in 390 H (1000 CE), but failed. By 397 H (1007 CE), the young adult Majd was becoming frustrated by his mother's dominance, and arranged with his vizier to take control. She escaped and sought help from the Kurdish leader Abu Najm ibn Hasanuya. Allying themselves with Shams, they besieged Ray and eventually imprisoned Majd in the hilltop fortress of Tabarak, adjoining the city. After a year, during which Shams was nominal ruler both of Hamadan and Ray, Majd was allowed to return to purely nominal power, and a life of luxury. As his mother grew older, Shams waited for the ideal moment to take Ray back, striking successfully in 405 H (1014-15 CE). Both Saiyida and Majd escaped, and Shams' troops refused to pursue them, so they were soon able to return and drive him back to Hamadan. Saiyida was also uncomfortably aware that the Ghaznavids, by now well established in Khorasan, had thoughts of westward expansion, and she engaged in a subtle diplomatic standoff with the Ghaznavid Sultan (i.e. emperor, only nominally loyal to the Caliph) Mahmud ibn Sabuktegin- honorific name Yamin al-Daula- who temporarily chose to direct his conquering zeal south-eastwards instead. Some rulers were less perceptive than Mahmud, such as ibn Fulad, probably another Daylamite, who began incursions into the province of Ray about 407 H (1016 CE). With help from Tabaristan, Saiyida managed to keep him at bay, but he too sought help in Tabaristan, and received 2,000 troops from the Ziyarid regional overlord Manuchihr. Ray was besieged, and Saiyida (or, nominally, Majd al-Daula) was forced to give ibn Fulad the governorship of Isfahan. Ibn Fulad disappears from the historical record after this, so it is likely that the incumbent governor of Isfahan made an effective objection after the fashion of the time.

When Saiyida died in 419 H (1028 CE) Majd, having been kept for so long in enforced idleness, away from the real workings of government, was hopelessly out of his depth. Many of his troops were Daylamites, but he was generations removed from his family's origins in the same area, and culturally far apart from them, so they refused to acknowledge him as their master, and ran riot through the city. Hamadan had been conquered by Daylamites shortly after Shams' death a few years previously, so in desperation Majd turned for help to Sultan Mahmud. Knowing that his opportunity had arrived, Mahmud sent 8,000 cavalry to restore order- and to capture Majd. Mahmud also moved towards Ray himself, temporarily taking control of Djurdjan, which might otherwise have attempted its own coup in Ray. When Mahmud's general 'Ali approached the city in Rabi II 420 H (May 1029 CE), Majd came out in person to greet him, with a small honour guard of some 100 soldiers. He was politely detained, while 'Ali's force took over the city. An express message was sent to Sultan Mahmud, and he arrived about three weeks later (26 May) to be greeted by the sight of a vast hoard of treasure captured by 'Ali's men. He gently suggested to Majd that he should have paid more attention to the role of the King in chess, before sending him into exile, with his heir Abu Dulaf.

Ghaznavids and Oghuz, mid 11th century CE
Previously, the various military actions in the vicinity had meant relatively little to the people of Ray, because each successive ruler had an interest in keeping the city's commercial life running as smoothly as possible, and levying taxes. Sultan Mahmud, however, had an additional motivation. He was an ardent Sunni Muslim, and Ray was a city where Sunnis were a minority. Now Mahmud's troops set about rectifying this by direct reduction of the numbers of supporters of other branches of Islam. Some were taken off to Khorasan, others fled or were driven into exile, and many were stoned to death within the city, bodies being hung from trees lining the streets. Religious texts contrary to Sunni belief were burned, more acceptable books were taken to Mahmud's capital, Ghazni, which he had for decades been transforming into a city of culture. There too Mahmud soon returned, leaving his son Mas'ud in charge at Ray, with orders to extend his territory as far as possible. Mas'ud did so, capturing key centres such as Isfahan, but eleven months after the triumph at Ray, his father died, and Mas'ud had to hurry to Ghazni himself, to stake his claim to the Sultanate. When the deposed governor of Isfahan, Majd's cousin Muhammad ibn Rustam Dushmanziyar ('Ala' al-Daula; also familiarly known as Ibn Kakuya) heard that Mas'ud had left the area, he moved rapidly to recapture, not just Isfahan, but other towns including Ray during 421-22 H (1030-31 CE). Unfortunately for him, Mas'ud had few problems deposing and crippling his twin brother Muhammad to win the Sultanate, and soon sent his general Tash Farrash to teach the rebel a lesson. Once again, the citizens of Ray were subjected to atrocities- but 'Ala' himself evaded the Ghaznavid troops, and was eventually allowed to remain in power at Isfahan.

Some years previously, Mahmud had attempted to control a population of Turkic Oghuz nomads which had been causing havoc in Khorasan, by holding their leader, Arslan ibn Seljuq, as a hostage and dispersing them over a wide area, apparently hoping that in small groups they could be controlled by his local governors. This failed, and groups of Oghuz moved westward, some settling in Azerbaijan. Others spent some time along the southern shore of the Caspian Sea, and in 420 H (1029 CE) some of them, led by one Yaghmur, waited until Mahmud's main army left newly conquered Ray, and paid the city a visit. Remarkably, Mas'ud chose not to oppose them, but to employ them in Khorasan. During the campaign against 'Ala' al-Daula, in 424 H (1033 CE), Tash Farrash learned, at Nishapur, that the Oghuz in Khorasan had not abandoned their old plundering ways, and as punishment he executed many, including Yaghmur and over fifty other leaders. Later, with Tash Farrash busy at Isfahan, and Mas'ud dealing with a rebellion in India, the survivors of these Oghuz headed for Ray. They claimed that their true destination was Azerbaijan, where their cousins were still living in peace, but for the populations of all the communities they passed through and plundered, that made no difference, and the area round Ray itself was particularly wealthy. About 426 H (1035 CE) Tash assembled an expeditionary force including 3,000 cavalry, and even a few elephants, to drive the Oghuz away once more, but when his force, with all its supplies, was still some distance from their encampment near Ray, the Oghuz warriors, taking only their weapons and light rations, moved out to attack. Although the sheer strength of Tash's force gave him an advantage, it consisted of several different contingents, and when the Oghuz captured the leader of the Kurdish troops, he offered to remove his troops from the battle if they would spare his life. This done, the advantage was with the Oghuz, who, by sheer weight of numbers, were even able to cut down the elephants, including the one Tash Farrash was riding. He and most of his officers were killed, and his army routed; then, with the additional resources gained from the victory, the Oghuz troops attacked Ray itself. The governor, Abu Sahl al-Hamduni, recognising that his forces were outnumbered, took them into the fortress of Tabarak, but instead of settling down to a siege, the Oghuz ignored him, and rampaged through the city. Abu Sahl brought his troops out to fight again, and captured two of the most important Oghuz leaders, which was enough to bring about a truce. It was agreed that the Oghuz should pay some compensation and leave Ray, which they did, in 427 H (1035-6 CE), only to observe an army approaching from Djurdjan. This they ambushed, capturing the commander and some 2,000 of his men.

'Ala' al-Daula, forced out of Isfahan again by the forces of the late Tash Farrash, soon learned that Ray was almost defenceless, and paid a friendly visit to the city, offering protection if Abu Sahl would pay him. When the governor refused, 'Ala' sent a message to the Oghuz, who were still not hurrying on the journey to Azerbaijan, offering land near Ray if they would help him against Abu Sahl. Some 1,500 of them did so- not because of 'Ala's offer, but because of an even better offer from one of his officers, who wanted to use them to depose 'Ala'. Learning of this plot soon after his combined forces had persuaded Abu Sahl to submit in Jumada I 429 H (February–March 1038 CE), 'Ala' had the officer imprisoned at Tabarak, so the Oghuz went on the rampage again. While 'Ala' set about dealing with the new problem and taking control of Ray, the arrival of the new Oghuz in Azerbaijan completely upset the tolerably successful balance which had been struck with the earlier immigrants. Vicious Oghuz raiding, affecting both the dominant population group and the Kurdish minority, led to an alliance between Wahsudan, the Rawadid ruler of Azerbaijan, and the Kurdish leader Abu'l-Hayja ibn Rabib al-Daula. Outnumbered, many of the Oghuz fled once more, and at the end of 429 H (1038 CE) a large group came to Ray, where they allied with Fana-Khusrau, son of Majd al-Daula, and Kam-Rava, Daylamite ruler of Saveh, to besiege the city. 'Ala' abandoned Ray to its fate, followed by many well-informed citizens, and the Oghuz once again began looting. They also killed many of the men and enslaved many women, leaving Ray almost deserted.

Seljuqs, mid to late 11th century CE
To the south-east of the Aral Sea was the homeland of the Oghuz, many of whom still lived there, as relatively well-behaved Sunni subjects of the Sultan. After the death in 425 H (1034 CE) of the local ruler 'Ali-Tegin, who had protected them, a surprising chain of events made some of them rulers of Khorasan and Khwarazm within a few years. Under the leadership of Arslan ibn Seljuq's nephew Tughril-beg (who had been crowned as Sultan) and his half-brother Ibrahim Yinal, many of them moved on westwards. In 433 H (1041-2 CE) Ibrahim arrived at Ray, and began driving away the Oghuz who were already there, by now known as the "Iraqi Turkmen". The following year, Tughril arrived, and decided to make Ray the capital of his territory, sending Ibrahim off to fight the Kurds. Fana-Khusrau ibn Majd al-Daula was allowed to remain in residence at Tabarak, where he had prudently retreated when Ibrahim's force arrived.

The city was a wreck, with perhaps as few as 3,000 inhabitants, so Sultan Tughril ordered a massive reconstruction programme, before moving on westward to expand his empire. For years, Ray remained peaceful, and regained its prosperity, but in 451 H (1059 CE), following the death of his brother Da'ud (Chaghri-beg) who had remained in the east as ruler of Khorasan, Tughril received reports of strange movements by Ibrahim Yinal's army, which appeared to be heading for Ray. Suspecting an attempted coup, Tughril allied himself with Da'ud's sons, and raced to intercept his half-brother. Ibrahim was captured near the city, and on 9 Jumada II 451 (23 July 1059 CE) was given an honourable death by strangulation. The childless Tughril later married one of Da'ud's wives, and installed her son Sulayman at Ray as his successor, but when he died shortly afterwards, in Ramadan 455 H (September 1063 CE), Da'ud's other son Abu Shuja Alp-Arslan Muhammad, who had succeeded his father in Khorasan, had his own ideas. To complicate matters, there was also a member of Tughril's generation still active, Qutlumush ibn Arslan Isra'il, who invoked the Turkic tradition that the most senior male member of the family should succeed to power. Aware of Qutlumush's intentions, Alp-Arslan moved his army from Khorasan towards Ray even before Tughril's death. Even so, Qutlumush arrived first, with Turkmen troops who had been based in the nearby Elburz Mountains, and besieged the city, plundering the surrounding area for supplies. Hearing of Alp-Arslan's approach, Sulayman's officers, including ultimately his vizier, decided to offer him the Sultanate if he defeated Qutlumush, and relegate Sulayman to heir-apparent. In Dhu'l Hijjah 456 H (December 1063 CE) Alp-Arslan's forces achieved their goal, despite the flooding of a salt-marsh to hinder their approach, and the fleeing Qutlumush was killed, allegedly in a fall from his horse. Alp-Arslan was acknowledged as Sultan, and for two generations, Ray continued in peace.

In 485 H (1092 CE) the prosperity of the Seljuq empire was severely disturbed by the assassination of the brilliant vizier Nizam al-Mulk, followed very soon afterwards by that of his master, Alp-Arslan's son, Sultan Malik Shah. Once again there was a scramble for power, led by Malik-Shah's widow, Turkan Khatun, who concealed his death until she had obtained agreement that he should be succeeded by their young son Mahmud. She had Malik-Shah's eldest son Berk-Yaruq imprisoned during this time, but when the Sultan's death was announced, supporters of Nizam al-Mulk freed him, and he was proclaimed Sultan at Ray, before following and defeating Turkan Khatun's forces (January 1093 CE), after which he allowed her and Mahmud to rule over southern Iran. For months Berk-Yaruq fought other contenders in different parts of his new empire, until his uncle Tutush, ruler of Damascus, raised a new army and invaded Iraq. Conveniently for Berk-Yaruq, Turkan Khatun died in Ramadan 487 (September–October 1094 CE) followed shortly afterwards by young Mahmud, and their troops agreed to support him. The armies of Tutush and Berk-Yaruq met outside Ray on 17 Safar 488 (26 February 1095 CE), but most of Tutush's allies deserted him before battle commenced, and he was killed by a ghulam (soldier-slave) of a former ally, Aq-Sonqur, whom he had executed a few months earlier for attempting to abandon the campaign of conquest.

In 491 H (1098 CE) the amir Öner, a former governor of Fars who had been demoted after failing to quell a Kurdish rebellion, was persuaded to rebel, by Berk-Yaruq's dismissed ex-vizier, Mu'ayyad al-Mulk 'Ubayd Allah- a major reason being the suspicion that Berk-Yaruq's closest advisor, Majd al-Mulk, a known Shi'ite sympathiser and outward opponent of violence, was behind a series of assassinations of amirs. The following year, Öner set out from Isfahan towards Ray with an army of 10,000 but he was assassinated near Saveh by one of his Turkman ghulams (who was allegedly a member of the Batini Isma'ili sect), and the rebellion fell apart. Now other amirs banded together and demanded that Majd be handed over to them. Initially, Berk-Yaruq resisted, but the armed forces were on the amirs' side. Mu'ayyad went to the Sultan's half-brother, prince Muhammad, and suggested that if he sought power this would be a good moment to take it. Muhammad took this advice, proclaimed himself sultan, and appointed Mu'ayyad as his vizier. Shortly afterwards, Majd was killed, either by the amirs or by disaffected soldiers, and Berk-Yaruq was abandoned. Muhammad met with his new allies at Khurraqan, and marched towards Ray. With the small forces that remained to him, Berk-Yaruq got there faster, and was joined by amir Yinal ibn Anushtakin al-Husami and 'Izz al-Mulk Mansur ibn Nizam al-Mulk, with their forces. Still not strong enough to confront Muhammad, Berk-Yaruq left Ray to gather more allies, but his mother Zubaida Khatun remained behind, and when Muhammad's army reached the city in late summer 493 H (1099 CE), they found her there. Mu'ayyad imprisoned her in the citadel, demanded money from her, and then, against the advice of his councillors, had her strangled. In the autumn of 494 H (1100 CE) Berk-Yaruq defeated Muhammad between Ray and Hamadan, and personally executed Mu'ayyad, but the war continued, including a curious, almost bloodless battle at Ray in Jumada I 495 H (February–March 1102 CE) which scattered Muhammad's 10,000 cavalry. However, when Berk-Yaruq died of tuberculosis in Rabi II 498 H (December 1104 CE), his son was only four years old, so Muhammad swiftly took over from the little Sultan Malik Shah II.

Last days of the Seljuqs, late 12th century
The rivalry after the death of Malik-Shah I had split the Sultanate, effectively creating buffer states on all sides of Ray. Nevertheless, when the Jewish traveller Rabbi Benjamin of Tudela visited the region around 1169 CE, he was told that some 15 years earlier an Oghuz tribe called the Khofar-al-Turak had allied themselves with some of the lost tribes of Israel, who lived among the mountains near Nishapur, to invade the heartland of Iran, capturing and looting the city of Ray. This would refer to the Oghuz incursions of 548 H (1153-4 CE) from their settlements east of Khorasan, which led to their defeat of Sultan Ahmed Sanjar, although other records of these events do not specifically mention Ray. There were other threats to the city at this period, though. Ildegiz, atabeg of Azerbaijan, was determined to oust the amir of Ray, Inanj Sonqur, who had challenged his attempt to install his stepson Arslan-Shah (Arslan ibn Toghril, grandson of Muhammad) as Sultan of Iran. In 555 H (1160 CE) he succeeded, and Inanj withdrew to Bisotun. Inanj did not give up, and in 562 H (1166-7 CE) he sought help from the Khwarazm Shah, Il-Arslan. This alliance succeeded in recapturing Ray from the atabeg's garrison, but the Khwarazmians caused much damage in nearby Abhar and Qazwin before they returned home. Ildegiz arranged for Inanj to be killed, and put his son and heir Muhammad ibn Ildigiz Jahan Pahlawan (husband of Inanj's daughter Inanj-Khatun) in charge at Ray. After his father's death in 568 H (1172-3 CE), Pahlawan, as atabeg, was also the power behind the Sultan's throne, and became the key to stability when Arslan-Shah was assassinated in 571 H (1176 CE), leaving a son and heir, Toghril III, just seven years old.

At this time, Saladin was enjoying considerable success, conquering large areas of Syria and Egypt. Saladin attempted to capture the city of Mosul, in 578 H (1182 CE). Fearing that if Mosul fell, his territory would be next, Pahlawan allied himself with the ruler there, and when Saladin returned in 581 H (1185 CE) marched his army to challenge him. In the end Saladin's efforts were resisted without him, for Pahlawan succumbed to dysentery, and died late in 581 H or early in 582 H (1186 CE). The Iranian territory was inherited by his son Qutlugh Inanj, but the office of atabeg went by seniority to his brother Qizil Arslan, who treated the young adult Sultan Toghril as a puppet, while favouring another of Pahlawan's sons, Abu Bakr.

This succession was the occasion for major civil disturbances, notably in Isfahan, where Shafis and Hanafis (both branches of Sunni Islam) fought each other, and in Ray, where the Shafis and Hanafis allied themselves against the Shi'ites (who despite earlier attempts to eradicate them, still represented about half the Muslim population of the city). Many years later, in 617 H (1220 CE), the geographer Yaqut al-Hamawi came to Ray, looking for somewhere to settle following the Mongol conquest of the eastern city where he had been living. Ray was then, without any help from the Mongols, mostly in ruins, and he was told that after driving away the Shi'ites, the Shafis had turned on the Hanafis, and expelled most of them too. Yaqut also reported on the curious design of the city, where the streets were very narrow and labyrinthine, and some people even lived in caves, for more effective defence in house-to-house fighting. However, as the next few paragraphs demonstrate, he was not told anything like the whole truth about the decline of Ray, and in reality the disturbances of 582 H may have had little to do with it.

Sadly, young Toghril's attempts to assert himself, while militarily quite successful, were diplomatically disastrous, and in 586 H (1190 CE) he was forced to surrender to Qizil Arslan, who imprisoned him and his young son in Azerbaijan, then set himself up as Sultan. A year or so later, Qizil Arslan was poisoned (allegedly by Inanj Khatun), and Toghril was eventually released. Gathering an army in the spring of 588 H (1192 CE), he hastened to oppose Qutlugh Inanj, and soon defeated him. Qutlugh took a huge gamble, and headed for Ray, while sending a message calling for help from the Khwarazm Shah, Tekish (some sources claim that a message was sent by the Caliph, al-Nasir, whom Toghril had threatened before his imprisonment; others claim that Tekish decided to make the expedition when he heard of Qizil Arslan's death, hoping to profit from the inevitable succession dispute). The Khwarazm Shah set off westwards, early in the summer of 588 H, but by the time his army arrived at Ray, Qutlugh Inanj had decided he definitely did not want their help; worse, after capturing the Tabarak fort and beginning negotiations with the two Iranian armies, he learned that his brother, the ruler of Khorasan, was preparing to seize power back in Khwarazm. To salvage something from the situation, before hurrying home, Tekish engineered a three-way power split in which Ray was to be a centre of Khwarazmian influence in Iran. At the suggestion of Inanj Khatun, Tekish's son Yunus Khan married Toghril's daughter. The Sultan himself married Inanj Khatun, and took her to Hamadan in Ramadan (September–October)- only to have her strangled some time later, on hearing that she was planning to poison him.

Once Tekish was well on his way back to Khwarazm, the disputes resumed. Qutlugh Inanj toured Azerbaijan, trying to build forces for another attack on Toghril, but Abu Bakr, who had succeeded to Qizil Arslan's title and territory there, drove him out. In Muharram 589 H (January–February 1193 CE), Tekish's forces attacked and defeated one of Toghril's eastern allies, so the Sultan used this treaty violation as justification for besieging the Khwarazmian garrison in the Tabarak fort at Ray, eventually gaining entry and killing most of them, following which, in Sha'ban (August) he had the fort destroyed. Nearby, in rural Khvar-i Ray, Toghril won a battle against Khwarazmian raiders, capturing five of their leaders, then he returned to Hamadan. A few weeks later, Qutlugh Inanj returned to Ray, having made an alliance with Muzaffar al-Din of Qazwin. Asked by his new governor at Ray for reinforcements, the Sultan sent 4,000 horsemen from Hamadan, forcing Qutlugh to abandon his siege and escape towards Damghan. He was pursued, but escaped and contacted the Khwarazmians. Tekish's brother had conveniently died, and when the Khwarazm Shah heard of the fate of his garrison at Tabarak (receiving also, about the same time, a direct invitation from the Caliph to take over Toghril's territory) he sent 7,000 horsemen, who joined up with Qutlugh and began advancing on Toghril's smaller army. The Sultan retreated to Ray, and on 4 Muharram, 590 H (30 December 1193 CE) he made a desperate stand at the gate of the city. Unexpectedly, he won.

It was inevitable that Tekish would try to regain Ray, so Sultan Toghril III did not return to Hamadan. As he and his army waited at Ray, it became apparent that he had a fondness for alcohol. Some of his amirs lost respect for their commander, and the Khwarazm Shah began receiving messages of support as he approached. When the great Khwarazmian army arrived, on the last day of Rabi' I, 590 H (25 March 1194 CE), Toghril found he could not trust his amirs, so he rode out of the city gate accompanied only by those who were willing to support him in the most honourable course of action, and the little force charged the Khwarazmian advance guard. Toghril's body was later hung up in the main bazaar of Ray, but his head was sent to the Caliph at Baghdad.

Warlord anarchy, circa 1200 CE
Tekish, allied with troops sent by the Caliph, went on to take Hamadan, and was nominated as Sultan, following which he appointed Qutlugh Inanj as nominal governor of the region, but gave the real power to his own sons Yunus Khan and Muhammad Khan, and awarded land to his amirs. Neither Qutlugh, nor the Caliph's vizier, Mu'ayyid al-Din ibn al-Qassab, was happy with this, and once Tekish had left for Khorasan, early in 591 H (autumn 1194 CE) Qutlugh marched an army towards Hamadan. Yunus' general Miyajuq brought a force out from Ray and defeated him, but over the winter, Qutlugh joined forces with Mu'ayyid, and they returned to drive Yunus and Miyajuq back from Hamadan to Ray, which they then attacked. The Khwarazmians abandoned the city and headed east towards Djurdjan, at which point Qutlugh betrayed Mu'ayyid by leading his own force into Ray and taking possession (and allowing his troops to take possession of anything movable). Mu'ayyid therefore laid siege to the city, and when the defences were breached, Qutlugh was forced to withdraw. The vizier also let his victorious troops take what they wanted from Ray, before taking them in pursuit of his former ally.

Failing to capture Qutlugh, Mu'ayyid attempted instead to drive all the remaining Khwarazmians out of western Iran, but late in 592 H (July 1196 CE) he fell ill and died, shortly before the Khwarazm Shah returned with his main army. Tekish therefore sent Miyajuq to reconquer Hamadan, while he captured Ray. A couple of months earlier, Muhammad Khan and Miyajuq, with help from Yunus Khan's wife (daughter of the late Sultan Toghril) had arranged an ambush in which Qutlugh was beheaded. The power vacuum in the anti-Khwarazmian forces was quickly filled by a mamluk (soldier-slave) named Nur al-Din Kukya, who seized Hamadan as soon as Tekish was safely on his way back eastwards, then formed an alliance with other mamluks and displaced Iranian amirs, which went on to take Ray, where Miyajuq's treasury was seized, and his supporters killed. Hearing of this, Miyajuq assembled a large force, so Kukya and his allies fled the city as the Khwarazmians approached in 593 H (1197 CE). In the spring of 594 H (1198 CE) Tekish returned, and appointed Miyajuq as his deputy with full responsibility for western Iran (Iraq Adjami). After the Khwarazm Shah had left again, Miyajuq and his troops began pillaging the whole region, so Abu Bakr of Azerbaijan and Ay Aba (an honourable mamluk who had given up supporting Qutlugh when it became apparent how much damage the wars were doing) formed an alliance to bring him under control. They defeated him that autumn, and Abu Bakr's troops settled at Ray for the winter, but then he received word that the Khwarazm Shah was returning, so he hurried back to Azerbaijan, giving Miyajuq's army the opportunity to re-enter the city and continue pillaging. On hearing in 595 H that Tekish was indeed returning, and intended to punish him, he left rapidly (he was later caught and punished).

Once Miyajuq had fled Ray, Kukya returned there. Although Abu Bakr was his father -in-law, he ignored all attempts to control him, which Abu Bakr could not easily back up with force, because he had to devote most of his resources to fighting Crusaders on his western borders. Perceiving this as weakness, many of Abu Bakr's eastern supporters switched their allegiance to Kukya. Tekish could probably have controlled him, but in Ramadan 596 H (June 1200) the Khwarazm Shah died, and was succeeded by Muhammad Khan (who took the honorific name 'Ala' al-Din). Among the first to hear of this were the Ghurid leaders then in power at Ghazni, the brothers Ghiyath al-Din Muhammad ibn Sam and Mu'izz al-Din Muhammad ibn Sam, and within weeks they had moved their armies westwards into Khorasan. Once they had captured Nishapur, Mu'izz al-Din was sent on an expedition towards Ray, but he let his troops get out of control and got little further than Djurdjan, earning criticism from Ghiyath al-Din which led to the only reported quarrel between the brothers. Meanwhile, when the news of Tekish's death reached the Iranian Iraqis, they killed every Khwarazmian they could find.

Another mamluk, Nur al-Din Gokche, took control of Ray (possibly without violence), and eventually the whole of north-western Iran, but in 600H (1203-4 CE) he was defeated by yet another mamluk, Shams al-Din Ai-Toghmish, and killed. In the same year Kukya was defeated in battle by one of his former mamluk associates, Aydughmish, and killed. Shams formed an alliance with Abu Bakr which brought peace to the region for several years, but in 608 H (1211-12 CE) he was ousted by the power-hungry Mengli, against whom the Caliph eventually formed a successful grand alliance, in 612 H (1215–16). Another mamluk, Saif al-Din Ighlamish, was appointed as governor in north-western Iran, then in 614 H (1217 CE) the Khwarazm Shah 'Ala' al-Din Muhammad, having gained some stability in Khwarazm and Khorasan, brought his army west to claim the Sultanate which had been granted to his father. Ighlamish decided to recognise the claim, but was soon assassinated. Learning of this power vacuum, Sa'd ibn Zangi, the atabeg of Fars, brought his army north to seize power in Ray. He seems to have learned of the assassination, but not of the presence of 'Ala' al-Din's large Khwarazmian army in the vicinity, and he was defeated and captured (sources are divided on whether he actually got into the city at all, or was stopped en route). In return for tribute payments and other forfeitures, he was freed and treated as an ally.

Less than three years later, early in 617 H (1220 CE) the refugee geographer Yaqut al-Hamawi passed through the semi-ruined city. It was explained to him that, a short distance to the north, there was a large village or market-town, consisting largely of underground dwellings, "with rebellious inhabitants. They not only disregard their governors, but are in constant clashes amongst themselves, to the extent that the inhabitants of its twelve quarters cannot visit one another" (he also implied that one reason for the luxuriant horticulture around the village was that grazing animals were likely to be stolen). Most of the population of Ray had not gone far; they had merely left the fortifications to the warriors, and settled in the strategically insignificant village, Tehran.

The Mongols and after, 1220 CE onward
Also fleeing the Mongols (otherwise known as the Tatars) was the Khwarazm Shah, whose lack of diplomacy had arguably brought the invaders west in the first place. Unfortunately, 'Ala' al-Din Muhammad also headed for Ray, and two divisions of the great horde were sent after him, commanded by the very capable generals Subedei and Jebe. The two pursuing forces took different routes across Iran, plundering and slaughtering, before meeting up at Ray in the autumn. No attempt was made to defend the city on this occasion, and its occupants were treated relatively well as a result. Still, as the Mongols pressed on towards 'Ala's apparent next destination, Hamadan, they were preceded by rumours that in the province around Ray, some 700,000 people had died, including the entire population of the city of Qom. The Khwarazm Shah had headed north-west, and some sources indicate that the pursuing Mongols passed close to Ray again in mid-winter, where they were engaged in a battle which they easily and bloodily won.

'Ala' al-Din died of natural causes a few weeks later, hiding on an island in the Caspian Sea. He was succeeded by his son Jalal al-Din Mingburnu, who had managed to evade the Mongols and hid for three years in India. During that time, though, another son, Ghiyath al-Din (not to be confused with the earlier Ghurid leader) also managed to survive, and to acquire an army, which he used to conquer much of Iranian Iraq. In 621 H (1224 CE), Jalal al-Din left India and headed for Iran to confront his brother. By a high-speed march from Isfahan, he managed to catch his brother by surprise, just outside Ray. When most of Ghiyath's officers declared their support for Jalal, the issue was decided without a battle. According to Ibn al-Athir's history, the Mongols also returned to Ray in this year, but other sources do not seem to support this. What can be said with more certainty is that before 617 H, Ray (and presumably Tehran) was a major centre for the manufacture of beautiful lustre-ware pottery, but after the Mongols passed through, the industry moved to other cities such as Kashan.

Still, life went on. And it seems that, although almost the entire civilian population had left, Ray continued to have military significance. In a battle near the city in Safar 683 H (May 1284 CE) the Buddhist prince Arghun attempted to defeat his Muslim uncle Tegüder, who had deftly seized power as viceroy (Il-Khan) of the western part of Kublai Khan's vast empire, after the premature death of Arghun's Buddhist/ Christian father Abaqa Khan (apparently caused by something he drank). The attempt failed, but Arghun soon acquired a new ally, and by August Tegüder was dead. Arghun's son Mahmud Ghazan, who succeeded to the Ilkhanate in 694 H (1295 CE), after converting from vague Buddhist/ Christian/ Shamanist belief to tolerant Sunni Islam, had the fort of Tabarak rebuilt, and according to some sources attempted to revive the city itself, but nothing seems to have come of this effort. In 727 H (1327 CE), a new Il-Khan, Arghun's grandson Abu Sa'id, issued orders for the execution of the amir Chupan, formerly the most powerful man in his government, but the latter, alerted by the earlier execution of his son, gathered his forces and marched west from Khorasan to take control of Ray. On the way, at Semnan (between Damghan and Ray) he asked Shaikh 'Ala' al-Daula to mediate, but Abu Sa'id refused this help, so Chupan fled east to Herat instead.

A later amir, Wali of Mazandaran (Tabaristan) first attempted to conquer the district of Ray in 772 H (1370 CE), but was defeated by Uwais, a leader of the Mongol Djalayirid tribe. Encouraged by the Shah Shudja, of the Arabic Muzaffarid dynasty in Khorasan, Wali tried again two years later, and captured both Ray and Saveh. As his power grew over the next few years, he attracted the attention of great amir Timur (Tamerlane), Turkic Mongol warrior and devout Muslim, who fought several campaigns to subdue him. Timur conquered the key city of Astarabad (Djurdjan) in 786 H (1384 CE), and he was able to capture Ray without striking a blow, because Wali had fled.

The Spanish diplomat Ruy Gonzalez de Clavijo found, when he passed through on a mission to the East in 1404 CE, that the walled city had no civilian inhabitants, while Tehran, still unfortified, had grown to the size of a city. Nonetheless, Ray's fortifications may have retained some military significance. In the first half of the 15th century CE, Timur's son Mirza Shahrukh had to bring his army through Ray on several occasions, particularly in his attempts to control the Qara-Qoyunlu ("Black Sheep"), Turkmen people who had gained control of Azerbaijan and Iraq. In 810 H (1408 CE) the Qara-Qoyunlu had defeated and killed Shahrukh's brother Miranshah in Azerbaijan, and his response was to bring 200,000 horsesmen to Ray to prevent them from overrunning the area. On a later visit to Ray, in 839 H (1435-6 CE), Shahrukh finally brought some stability to the area, by recruiting Jahan Shah, one of the sons of the great former Qara-Qoyunlu leader Qara Yusuf, to govern Azerbaijan and oust his older brother Qara Iskander. Shahrukh's death from natural causes, in 850 H (1447 CE), occurred near Ray, on an expedition against one of his own grandsons, Muhammad ibn Baysunghur, the local governor, who was attempting to expand his territory in anticipation of the old man's demise.

Muhammad soon had other matters to worry about, as Jahan Shah had expansion plans of his own. By 853 H (1453 CE) the heirs of Timur had effectively been driven out of western Iran, holding only Kerman and Arbaquh, between Shiraz and Isfahan. They knew that capturing Ray would give them a significant strategic advantage over key communication routes from Azerbaijan, but their attempts came to nothing. After that, the ancient city gradually faded into insignificance. Attacks on Iran from the great plains of eastern Asia still occurred, and in 939 H (1533 CE) Uzbek raiders penetrated as far as Ray. Twenty years later, ramparts were constructed around Tehran, and Ray finally ceased to be a military objective.