Former secretary of state Hillary Clinton and Sen. Bernie Sanders (Vt.). (Right to left: Melina Mara/The Washington Post; Lucian Perkins for The Washington Post)

Hillary Clinton appeared to squeak past insurgent rival Sen. Bernie Sanders in Iowa’s presidential nominating vote, according to results Tuesday, redeeming a crushing loss here in 2008 but revealing the shortcomings of a candidate who once seemed invincible.

Results from Iowa’s Democratic Party, announcing 100 percent of the precincts counted, gave Clinton a whisker-thin margin: 49.8 percent to Sanders’s 49.6 percent — setting up what is likely to become a prolonged contest for the Democratic presidential nomination.

Under the state’s caucus system, delegates are assigned by percentage of the vote.

Former Maryland governor Martin O’Malley received less than 1 percent of the vote, according to the results released hours after he dropped out of the race.

[How Sanders caught fire and turned Iowa into a real race]

Like so many others, Givan Tichy was torn between Hillary Clinton and Bernie Sanders at the start of caucus night. But after a long night of debating, first time caucus-goer Tichy decided to go with his heart and feel the "Bern." (Alice Li/The Washington Post)

The outcome from Monday’s caucuses was a relief for Clinton loyalists confronted in recent weeks with the wrenching possibility that Clinton’s second-chance candidacy, like her first, might falter out of the gate and never recover.

It was also a shock to the system that a candidate universally known in Iowa, with deep pockets and long experience, could come close to losing to a relative unknown who was initially considered little more than a protest candidate.

Sanders claimed a kind of victory nonetheless, since he so far exceeded expectations. En route to New Hampshire, he said he was in the race for “the long haul.”

Sanders had erased Clinton’s once-commanding lead here in recent weeks, but then fell back. Although he could not overtake her, Sanders’s strong performance leaves Clinton more battered by the Iowa caucuses than she or her supporters ever expected. She now heads to New Hampshire, where Sanders is heavily favored to win next week’s primary.

[See the full results, county by county]

At the very least, Sanders’s competitiveness portends a longer, more costly and more difficult primary battle than predicted when Sanders entered the race six months ago. He has money and enthusiastic support to carry on his fight.

Clinton began her campaign in Iowa 40 points ahead of Sanders. She projected an aura of inevitability that, after her loss to Barack Obama eight years ago, her time had finally come. Her supporters believed that the party’s base would embrace her experience, as well as the chance to elect the first female president.

1 of 43 Full Screen Autoplay Close Skip Ad × What it looks like on the ground in Iowa for the caucuses View Photos A few hundred thousand Iowa residents gather in a couple thousand caucus sites and finally, finally kick-start the presidential nomination process. Caption A few hundred thousand Iowa residents gather in a couple thousand caucus sites and finally, finally kick-start the presidential nomination process. Feb. 1, 2016 Sen. Ted Cruz speaks during his election night watch party at the Iowa State Fairgrounds in Des Moines. Cruz placed first in the voting. Cassi Alexandra/For The Washington Post Buy Photo Wait 1 second to continue.

Sanders, 74, a long-serving independent in Congress, tapped into the electorate’s economic anxiety with a call for a “political revolution” aimed at curbing the outsize influence of the “billionaire class” and leveling the playing field for ordinary Americans.

His vision of a country with universal health care and free college tuition was dismissed by his critics — including Clinton and her allies — as unworkable. But it resonated with large swaths of voters disillusioned with the political process and wary of Clinton and the political establishment generally.

Over the summer, Sanders saw his crowds at rallies around the country swell into the thousands, with supporters turning out with homemade “Feel the Bern” signs at festival-like events where Sanders typically spoke for an hour or more.

“You want a radical idea? All right, here’s a radical idea,” the rumpled white-haired senator shouted at his audience at his final campaign rally Sunday night in Des Moines. “Together, we’re going to create an economy that works for all of us, not just the 1 percent.”

Despite her history-making potential and the magic of the Clinton name, the former secretary of state, senator from New York and first lady ran a one-foot-in-front-of-the-other campaign in Iowa that prized mechanics over majesty.

And in a political season of insurgent fervor, Clinton can struggle to expand her rationale for running much beyond her own lengthy résumé and the enduring popularity of her husband, former president Bill Clinton.

Clinton has also spent a good part of her time trying to get past, or explain away, her decision as secretary of state to use a private email system whose security the FBI is now examining.

“I don’t think she’s a saint,” said Cindy Roeser, 55, a new Iowa resident and first-time caucus-goer who supported Clinton. “She’s had to make some very difficult choices when there was no easy, good choice to make, but she’s always made the best choice. She’s committed to her causes.”

Sanders and Clinton will continue their battle in New Hampshire.

Clinton’s showing blunts Sanders’s momentum, but the close outcome sets up what is likely to be a prolonged Democratic race. Clinton remains the favorite to win the Democratic nomination next summer, but she starts the primary season hobbled by her close call here.

For his part, Sanders faces considerable obstacles once the nominating contest moves beyond New Hampshire. He has been rattled by attacks from Clinton and her allies that his record was too weak on gun control and women’s issues, charges he denied with increasing agitation.

And despite a long history of civil rights activism, Sanders has acknowledged he faces a challenge connecting with Latino and black voters, who will be crucial to the outcome of upcoming contests in Nevada and South Carolina. Vermont, the state Sanders has represented for than a quarter-century on Capitol Hill, is 95 percent white.

[The Fix’s winners and losers from Iowa caucuses]

Although Sanders has vowed to get money out of politics, his campaign has not suffered from a lack of resources. In the two most recent fundraising quarters, he nearly matched Clinton’s haul. And on Sunday, Sanders’s campaign announced it had taken in an eye-popping $20 million in January alone.

His take, fueled by hundreds of thousands of small online donations averaging $27 apiece, enabled Sanders to put on a robust television advertising campaign in Iowa that matched if not exceeded that of Clinton in the closing weeks. Aides said they expect a new wave of donations after the Iowa voting.

For much of the race, Sanders avoided direct criticism of Clinton. That changed in the fall, when he began to more aggressively draw contrasts with her on issues including Wall Street reform, expansion of Social Security and her late opposition of a pending trade deal he had vigorously opposed.

Clinton responded in the closing weeks of the contest, accusing Sanders of being too cozy with gun manufacturers and the National Rifle Association, unrealistic about health care and uninformed or misguided about foreign policy.

Clinton’s Iowa victory — narrow as it was — made good on nearly a year of dutiful campaigning and heavy investment in Iowa. She was determined not to repeat the mistakes of 2008, when Obama’s nimble, numbers-driven operation outmaneuvered her buttoned-down one.

At stops across the state, Clinton jumped easily from topic to topic — prescription drug price gouging, rapacious banks, crumbling bridges, Chinese cyberattacks, Iranian nuclear negotiations and more.

On Wednesday in Newton, Clinton sought to comfort Annette Bebout, a retiree who lost the home where she had raised five children. Clinton patted Bebout’s arm and spoke of her hopes to better protect widows who lose Social Security income when their husbands die.

“Hillary is a down-to-earth person and she just wants to help common people,” Bebout said afterward.

Bebout added that she would show up to caucus for Clinton, and joked that she had no choice because a young organizer for Clinton “calls me every day” to remind her.

That kind of ground-level organizing was at the heart of Clinton’s second effort here, and the defense her backers hoped would withstand Sanders’s insurgent enthusiasm among new and nontraditional caucus voters.

Clinton built a colossus of paid staff and volunteers, and spent millions on television advertising when no other Democrat loomed as a serious threat. She held scores of events, many of them small discussion groups.

She also pumped out a steady stream of policy proposals and big-name endorsements that Sanders has not matched. She promised to work hard and fight for better wages, fairer workplaces, lower prescription drug prices and more gun control.

For weeks, Republicans gleefully played up the improbability of Sanders, who calls himself a democratic socialist, becoming a giant-killer in Iowa. Now Republican opponents and their allies are sure to cast her near-miss in Iowa as evidence that Clinton has feet of clay.

The lingering questions surrounding Clinton’s State Department email have added grist to that argument and contributed to voter unease about her basic trustworthiness. Even when she was polling much better in Iowa, surveys found distrust and dislike for Clinton among many of the same voters who said they found her qualified.

The State Department said Friday that 22 emails that passed through Clinton’s un­or­tho­dox private email server contained “top secret” information. The messages were not marked as such at the time, and her campaign took the unusual step of accusing intelligence agencies of retroactive “overclassification run amok.”

Clinton has said she regrets her decision to exclusively use the separate communication system for her government work but maintains she did nothing wrong. The Justice Department is probing whether secrets were compromised, an open question that hangs over Clinton as presidential voting begins.

The Benghazi attacks blotted Clinton’s record at the State Department, and she has called the deaths of four Americans there her greatest regret. But Clinton campaigns on her foreign policy expertise, regularly noting that no other candidate on either side of the race has had to make decisions in the White House Situation Room.

Clinton also had a lift over the weekend from a laudatory New York Times endorsement, atop those of the Des Moines Register and several smaller Iowa newspapers.

The Register editorial, which came out slightly more than a week ahead of the caucus vote, said “no other candidate can match the depth or breadth of her knowledge and experience.”

“The presidency is not an entry-level position. Whoever is sworn into office next January must demonstrate not only a deep understanding of the issues facing America, but also possess the diplomatic skills that enable presidents to forge alliances to get things done,” the newspaper wrote.