This time, the polls weren’t wrong. For months, as Sadiq Khan maintained his lead over Zac Goldsmith, the Labour candidate’s team were haunted by memories of the 2015 general election. The Conservatives’ unforeseen majority meant victory was never assumed. Labour MPs feared that low turnout or a “Bradley effect”, with voters shunning a Muslim candidate in the privacy of the polling booth, would destroy Khan's hopes.

But his victory was just as comfortable as forecasts suggested. In the final round of voting, Khan beat Goldsmith by 57-43, the second largest margin since the mayoralty was established in 2000 (the year Ken Livingstone defeated Steve Norris by 58-42). With more than 1.3m votes, Khan achieved the biggest personal mandate of any politician in UK history.

It is hard to recall that his triumph was never initially regarded as inevitable. London is a Labour city but one that has twice elected a Conservative. Many predicted that Zac Goldsmith - telegenic, green, liberal, independent-minded - would emulate Boris Johnson’s achievements. Yet the Tory candidate was not merely beaten but thrashed. After a cynical campaign that painted Khan as the friend of Islamist extremists, he suffered the worst fate for a politician: losing with dishonour.

As the Labour candidate, Khan (who I recently profiled) began with a default advantage. In recent elections, Londoners have voted for his party in ever greater numbers (44 per cent in 2015). But Khan’s victory cannot be attributed to partisan loyalties alone. As even the pro-Goldsmith Evening Standard conceded in its final editorial: “[He] fought the stronger and more combative campaign”.

For Khan’s team, Miliband’s fate was not just a lesson in the fallibility of polling. It was a lesson in what not to do. From the outset, they vowed to avoid the errors that dogged that campaign.

Khan’s strategists cited four insights as central to his success. The first was that “personality matters more than policy”. Having seen Miliband defined by his opponents (“weak”, “weird”, “treacherous”), Khan’s team “set out hard and fast to paint a picture of who he was”. His election leaflets rooted his policies in his personal story: “the bus driver’s son who’ll make commuting more affordable”, “the council estate boy who’ll fix the Tory housing crisis” and “the British Muslim who’ll take on the extremists”. By the end of the campaign, journalists groaned at the mention of his bus driver father: a sure sign of success. As victorious campaigns testify, the best messaging is simple and repetitive. “The bus driver’s son” was Khan’s equivalent of the Tories’ “long-term economic plan”. By contrast, Goldsmith failed to define himself personally, allowing Labour to paint the billionaire’s son as posh and aloof.

The second insight was that policy should be announced early - and then endlessly reannounced. All of Khan’s signature pledges - the fares freeze, “first dibs” on new homes, the “London living rent” - were made by January. Having left the blocks early, Khan opened up a double-digit lead. From this point onwards, Goldsmith never looked competitive. Unlike Khan, he delayed major announcements until the closing stages of the campaign. It was on the final day that the lifelong environmentalist pledged in the Evening Standard to be “the greenest mayor ever” - a pitch made all too rarely before.

The third insight was that winning campaigns don’t adopt a “35 per cent strategy” - shorthand for Miliband’s narrow focus on Labour’s core vote and former Liberal Democrats. “We decided that we were literally going to compete for every vote,” a strategist said. In contrast to Ken Livingstone, who sought victory through a rainbow coalition of left-wingers, Khan spent more time in Tory-leaning outer London than the city’s inner half. He engaged positively with all media titles, including the Sun, the Daily Mail and City AM, and avoiding picking unnecessary fights.

Having run to Tessa Jowell’s left in Labour’s selection contest (trading on his opposition to the Iraq war, the welfare reform bill and his nomination of Jeremy Corbyn), he swiftly made a centrist pitch to the electorate at large. He would, he repeatedly declared, be “the most pro-business mayor ever”. Milibandite policies such as the 50p tax rate and the “mansion tax” were disowned. In a defining interview with the Mail on Sunday a week after his selection, Khan ruthlessly distanced himself from Corbyn, condemning his failure to sing the national anthem and presciently warning of Labour’s “anti-Jewish” image. He went on to make just two public appearances with his party's leader and was listed in the “hostile” group of MPs.

The fourth insight was to anticipate and prepare for opponents’ attacks. Khan’s team knew that the Tories would play the “extremism” card - and pre-empted it. In a speech to the parliamentary press gallery on 19 November 2015 following the Paris attacks, he declared that Muslims had a “special role” to play in combating the threat “not because we are more responsible than others, as some have wrongly claimed, but because we can be more effective at tackling extremism than anyone else”. Khan spoke of how “too many British Muslims grow up without really knowing anyone from a different background”, warning that the political establishment had for too long “tolerated segregation” at the expense of “creating a common life”. The speech was well-received by the conservative press and enhanced Khan’s standing among the lobby.

As the Tories ramped up their attacks, the Labour candidate maintained his composure. “I’ve watched him go through this extremism row two or three times quite closely,” an MP told me. “He’s extraordinarily calm under that level of pressure. He draws on a well of inner stability that is really impressive. Tony Blair could obviously do it in spades but there are not that many senior politicians who can do it.”

Having established a commanding poll lead, Khan’s team were able to dismiss Goldsmith’s tactics as “desperate”. Again, the contrast with Miliband was marked. Confronted by the Tory charge that he would “do a deal” with the SNP, the Labour leader was slow to react. The fragility of his party’s polling position meant he struggled to deny there would be any arrangement. Miliband’s “weak” image meant voters readily believed that he would be held to ransom by the nationalists. By contrast, Khan’s positive media profile meant voters simply didn’t buy the “extremism” charge. Indeed, polling showed that he was more trusted than Goldsmith to tackle the terrorist threat.

After repeatedly distancing himself from Livingstone and seeking to rebuild fractured relations with the Jewish community, Khan was able to credibly condemn the former mayor’s incendiary remarks on Hitler and Zionism. The speed and conviction with which he called for his expulsion was typical of his efficient decision making.

The strength of Khan’s campaign reflected the qualtiy of his team. He recruited Patrick Hennessey, one of Westminster’s most respected spin doctors, as his communications director and employed his trusted and long-standing aides Jack Stenner (political director), Nick Bowes (head of policy) and Leah Krietzman (senior adviser). The close-knit team stood in contrast to Miliband’s, which was perpetually divided and lacked clear lines of authority.

Khan’s victory completes his remarkable personal journey from council home to City Hall and provides political consolation for Labour. As mayor, his administrative focus will be on delivering his signature pledges: the fares freeze, the 50 per cent affordable housing target and the London Living Rent. But strategists say he will also seek progress in four longer-term “legacy” areas: social integration, skills and further education, the night-time economy and air pollution. Andrew Adonis, the cerebral former cabinet minister, is likely to take on a transport role.

As the most senior elected Labour politician (with the third largest personal mandate of any in Europe), Khan will inevitably be touted as a future leader. But he will wisely maintain his distance from the party's Westminster warfare, resigning his Tooting seat. Unlike Boris Johnson, he will not treat the capital as a mere springboard to greater things.

Beyond London, as the first Muslim mayor of a major western city, Khan will be a figure of global significance. His election is a rebuke to extremists of all stripes, from Donald Trump to Abu Bakr Al-Baghdadi, who assert that religions cannot peacefully co-exist.

As the first Labour mayor since 2008, Khan stands as one of the winners of British politics. No one has ever prospered by betting against him. At the 2010 general election, he defended his Tooting seat from an aggressive and well-funded Conservative challenge. In the same year, he managed Miliband’s leadership campaign, masterminding the defeat of elder brother David. In the 2014 local elections, after he was rewarded with the post of shadow London minister, he achieved Labour’s best result in the capital since 1971. At last year’s general election, on an otherwise morose night, the party gained seven London seats, its strongest performance since 2001. In the mayoral selection contest, Khan beat the favourite, Tessa Jowell, by a landslide.

He has now won his greatest prize yet. If Miliband’s defeat was a lesson in failure, Khan's victory is an inspiring lesson in success.