Conservative businessman Matt Bevin won the Kentucky gubernatorial race on Tuesday night, handing the Republican Party its 31st governorship in a state that has elected Democrats to that office all but once since the presidency of Lyndon B. Johnson.

Bevin’s victory comes as a surprise after pre-election polls showed Kentucky Attorney General Jack Conway, the Democratic candidate, holding a slight to substantial lead. Instead, Bevin won the race by a margin of 52 to 44 percent, with 99 percent of precincts reporting. Bevin also ran a sometimes-troubled campaign marked by friction with the state and national GOP establishment, as my colleague Russell Berman reported last month.

Things were looking rosy for Republicans in Kentucky. And then came Matt Bevin. Again. The Tea Party outsider had tried to oust McConnell in a primary challenge, and had been routed. But a year later, he squeaked out a victory (by 83 votes!) in the GOP gubernatorial primary over the party’s preferred candidate, James Comer. Republicans—McConnell included—reluctantly embraced their unlikely standard-bearer, but Bevin’s path to the governor’s office has not been smooth. Conway has vastly outspent Bevin on television, and the Democrat has maintained a small but sturdy lead in the polls. Republicans have been frustrated both by Bevin’s frequent missteps and by the manufacturing executive’s hesitance to put much of his own money into his campaign. Late last month, the Republican Governors Association pulled its TV ads for Bevin, sending a signal it believed the race was lost. Bevin responded by putting up a million dollars worth of commercials on his own, and on Tuesday morning, the RGA announced it was going back on the air for the last two weeks of the race. “We decided to go back in because we’ve been doing the polling, and the polling shows the race very winnable,” RGA spokesman Jon Thompson told me.

Bevin fought back hard by emphasizing his outsider credentials—an easy argument to make after his high-profile scuffles within his own party—and praising Donald Trump, whose anti-establishment campaign upended the GOP presidential contest. He also rallied to the defense of Kim Davis, the Rowan County, Kentucky, clerk who was briefly jailed this summer for defying a federal court order to enforce the U.S. Supreme Court ruling that legalized same-sex marriage nationwide.

Some Democrats, surprised by Bevin’s come-from-behind win, blamed the fierce anti-establishment mood that suffuses the current political landscape for their defeat. “Attorney General Jack Conway ran a strong campaign focused on the issues that matter to Kentuckians: good schools, good-paying jobs, and economic opportunity,” said Elisabeth Pearson, the executive director Democratic Governors Association, in a statement after the loss. “Unfortunately, he ran into the unexpected headwinds of Trump-mania, losing to an outsider candidate in the Year of the Outsider.”