The documented history of Madrid dates to the 9th century, even though the area has been inhabited since the Stone Age. The primitive nucleus of Madrid, a walled military outpost in the left bank of the Manzanares, dates back to the second half of the 9th century, during the rule of the Emirate of Córdoba. Conquered by Christians in 1083 or 1085, Madrid consolidated in the Late Middle Ages as a middle to upper-middle rank town of the Crown of Castile. The development of Madrid as administrative centre began when the court of the Hispanic Monarchy was settled in the town in 1561.

Fortress and town

The primitive urban nucleus of Madrid (Majriṭ) was founded in the late 9th century (from 852 to 886) as a citadel erected on behalf of Muhammad I, the Cordobese emir, on the relatively steep left bank of the Manzanares. Originally it was largely a military outpost for the quartering of troops. Similarly to other fortresses north of the Tagus, Madrid made it difficult to muster reinforcements from the Asturian kingdom to the unruly inhabitants of Toledo, prone to rebellion against the Umayyad rule. Extending across roughly 8 ha, Muslim Madrid consisted of the alcázar and the wider walled citadel (al-Mudayna) with the addition of some housing outside the walls. Up until the proclamation of the Caliphate, local power was exerted by the Banū Sālim. By the late 10th century, Majriṭ was an important borderland military stronghold territory with great strategic value, owing to its proximity to Toledo. The most generous estimates for the 10th century tentatively and intuitively put the number of inhabitants of the 9 ha settlement at 2,000. The model of repopulation is likely to have been by the Limitanei, characteristic of the borderlands.

The settlement is mentioned in the work of the 10th-century Cordobese chronicler Ahmad ibn Muhammad al-Razi, with the latter locating the Castle of Madrid within the district of Guadalajara. After the Christian conquest, in the first half of the 12th century Al-Idrisi described Madrid as a "small city and solid fortress, well populated. In the age of Islam, it had a small mosque where the khuṭbah was always delivered," and placed it in the province of the sierra, "al-Sārrāt". It was ascribed by most post-Christian conquest Muslim commentators, including Ibn Sa'id al-Maghribi, to Toledo. This may tentatively suggest that the settlement, part of the cora of Guadalajara according to al-Razi, could have been transferred to Toledo following the Fitna of al-Andalus.

The city passed to Christian control in the context of the conquest of Toledo; historiography debates whether if the event took place in 1083, before the conquest of Toledo, in the wake of negotiations between Alfonso VI and al-Qadir, or afterwards, as a direct consequence of the seizure of Toledo in 1085.

The mosque was reconsecrated as the church of the Virgin of Almudena (, the garrison's granary). The society in the 11th and 12th centuries was structured around knight-villeins as a leading class in the local public, social and economic life. The town had a Muslim and mozarabic preexisting population (a number of the former would remain in the town after the conquest while the later community would remain very large throughout the high Middle Ages before merging with the new settlers). The town was further repopulated by settlers with a dominant Castilian-Leonese extraction. Frank settlers were a minority but influential community. The Jewish community was probably smaller in number than the mudéjar one, standing out as physicians up until their expulsion. By the end of the Middle Ages, the best-positioned members of the mudéjar community were the alarifes ('master builders'), who were tasked with public works (including the management of the viajes de agua), and had a leading role in the urbanism of the town in the 15th century.

Since the mid-13th century and up to the late 14th century, the concejo of Madrid vied for the control of the Real de Manzanares territory against the concejo of Segovia, a powerful town north of the Sierra de Guadarrama mountain range, characterised by its repopulating prowess and its husbandry-based economy, contrasted by the agricultural and less competent in repopulation town of Madrid. After the decline of Sepúlveda, another concejo north of the mountain range, Segovia had become a major actor south of the Guadarrama mountains, expanding across the Lozoya and Manzanares rivers to the north of Madrid and along the Guadarrama river course to its west.

The society of Madrid before the 15th century was an agriculture-based one (prevailing over livestock), featuring a noteworthy number of irrigated crops. Two important industries were those of the manufacturing of building materials and leather.

John I of Castile gifted Leo V of Armenia the lordship of Madrid together with those of Villa Real and Andújar in 1383. The Madrilenian concejo made sure that the privilege of lordship did not become hereditary, also presumably receiving a non-sale privilege guaranteeing never again to be handed over by the Crown to a lord.

Later, Henry III of Castile (1379–1406) rebuilt the town after it was destroyed by fire, and he founded El Pardo just outside its walls.

During the 15th century, the town became one of the preferred locations of the monarchs of the Trastámara dynasty, namely John II of Castile and Henry IV of Castile (Madrid was the town in which the latter spent more time and eventually died). Among the appeals the town offered, aside from the abundant game in the surroundings, the strategic location and the closed link between the existing religious sites and the monarchy, the imposing alcázar frequently provided a safe for the Royal Treasure. The town briefly hosted a medieval mint, manufacturing coins from 1467 to 1471. Madrid would also become a frequent seat of the court during the reign of the Catholic Monarchs, spending reportedly more than 1000 days in the town, including a 8-month long uninterrupted spell.

By the end of the Middle Ages, Madrid was placed as middle to upper-middle rank town of the Castilian urban network in terms of population. The town also enjoyed a vote at the Cortes of Castile (one out of 18) and housed many hermitages and hospitals.

Facing the 1492 decree of expulsion, few local Jews opted for leaving, with most preferring to convert instead, remaining as a non-fully assimilated converso community, subject to rejection by Old Christians. Likewise, adoption of Christianism by the mudéjar community facing the 1502 pragmatic law of forced conversion was also widespread. Seeking to protect its economic interests, the council actively promoted assimilation in the latter case by awarding tax and economic benefits, and gifts.

The 1520–21 Revolt of the Comuneros succeeded in Madrid, as, following contacts with the neighbouring city of Toledo, the comunero rebels deposed the corregidor, named Antonio de Astudillo, by 17 June 1520. Juan Zapata and Pedro de Montemayor found themselves among the most uncompromising supporters of the comunero cause in Madrid, with the former becoming the captain of the local militias while the later was captured by royalists and executed by late 1520. The end of revolt came through a negotiation, though, and another two of the leading figures of the uprising (the Bachelor Castillo and Juan Negrete) went unpunished.

Capital of the empire

Philip II (1527–1598), moved the court to Madrid in 1561. Although he made no official declaration, the seat of the court became the de facto capital. Unlikely to have more than 20,000 inhabitants by the time, the city grew approaching the 100,000 mark by the end of the 16th century. The population plummeted (reportedly reduced to a half) during the 5-year period the capital was set in Valladolid (1601–1606), with estimations of roughly 50–60,000 people leaving the city. The move (often framed in modern usage as a case of real estate speculation) was promoted by the valido of Philip III, Duke of Lerma, who had previously acquired many properties in Valladolid. Madrid undertook a mammoth cultural and economic crisis and the decimation of the price of housing ensued. Lerma acquired then cheap real estate in Madrid, and suggested the King to move back the capital to Madrid. The king finally accepted the additional ducats offered by the town of Madrid in order to help financing the move of the royal court back to Madrid.

During the 17th century, Madrid had an estate-based society. The nobility, a quantitatively large group, swarmed around the royal court. The ecclesial hierarchy, featuring a nobiliary extraction, shared with the nobility the echelon of the Madrilenian society. The lower clergy, featuring a humble extraction, usually had a rural background, although clerics regular often required certifications of limpieza de sangre if not hidalguía. There were plenty of civil servants, who enjoyed considerable social prestige. There was a comparatively small number of craftsmen, traders and goldsmiths. Domestic staff was also common with servants such as pages, squires, butlers and also slaves (owned as symbol of social status). And lastly at the lowest end, there were homeless people, unemployed immigrants, and discharged soldiers and deserters.

During the 17th century, Madrid grew rapidly. The royal court attracted many of Spain's leading artists and writers to Madrid, including Cervantes, Lope de Vega, and Velázquez during the so-called cultural Siglo de Oro.

By the end of the Ancient Regime, Madrid hosted a slave population, tentatively estimated to range from 6,000 to 15,000 out of total population larger than 150,000. Unlike the case of other Spanish cities, during the 18th century the slave population in Madrid was unbalanced in favour of males over females.

In 1739 Philip V began constructing new palaces, including the Palacio Real de Madrid. Under Charles III (1716–1788) that Madrid became a truly modern city. Charles III, who cleaned up the city and its government, became one of the most popular kings to rule Madrid, and the saying "the best mayor, the king" became widespread. Besides completing the Palacio Real, Charles III is responsible for many of Madrid's finest buildings and monuments, including the Prado and the Puerta de Alcalá.

Amid one of the worst subsistence crises of the Bourbon monarchy, the installation of news lanterns for the developing street lighting system—part of the new modernization policies of the Marquis of Esquilache, the new Sicilian minister—led to an increase on oil prices. This added to an increasing tax burden imposed on a populace already at the brink of famine. In this context, following the enforcing of a ban of the traditional Spanish dress (long cape and a wide-brimmed hat) in order to facilitate the identification of criminal suspects, massive riots erupted in March 1766 in Madrid, the so-called "Mutiny of Esquilache".

During the second half of the 18th century, the increasing number of carriages brought a collateral increment of pedestrian accidents, forcing the authorities to take measures against traffic, limiting the number of animals per carriage (in order to reduce speed) and eventually decreeing the full ban of carriages in the city (1787).

On 27 October 1807, Charles IV and Napoleon signed the Treaty of Fontainebleau, which allowed French troops passage through Spanish territory to join Spanish troops and invade Portugal, which had refused to obey the order for an international blockade against England. In February 1808, Napoleon used the excuse that the blockade against England was not being respected at Portuguese ports to send a powerful army under his brother-in-law, General Joachim Murat. Contrary to the treaty, French troops entered via Catalonia, occupying the plazas along the way. Thus, throughout February and March 1808, cities such as Barcelona and Pamplona remained under French rule.