Each state has slightly different rules for recounts. In 27 states a recount is automatic if the vote is very close. In 43 states, a candidate can request (and pay for) a recount if the results are within a specific margin.
Recounts rarely change the outcome of a race. One study found that on average, recounts change the vote totals by just 188 votes per million votes cast, or 0.0188%. Out of 27 recent recounts, the winner changed in just three races: one for Senator, one for Governor, and one for State Auditor.