The 49ers dominated early in rainy New England, racing to a 31-3 advantage in the third quarter but Tom Brady and his top-ranked Patriots offense caught fire with 28 unanswered points to tie the game with a little under seven minutes remaining.
San Francisco's second-year quarterback Colin Kaepernick responded seconds later with a 38-yard touchdown pass to Michael Crabtree, his fourth TD throw of the game, to put the 49ers (10-3-1) back in front for good.
The visitors' vaunted defense were then finally able to stop the marauding Patriots and stalled Brady on two straight drives before David Akers added a San Francisco field goal for a 41-31 lead.
New England (10-4) added a field goal in the final minute but their onside kick attempt was unsuccessful as their seven-game winning streak came to a screeching halt.
Brady finished with 443 yards passing but he coughed up two interceptions and was sacked three times as the Patriots paid the price for giving up four turnovers.
Kaepernick had 216 passing yards to improve to 4-1 since taking over as starter from Alex Smith. San Francisco also compiled 181 rushing yards and kept their lead at the top of the NFC West.
(Writing by Jahmal Corner in Los Angeles; Editing by John O'Brien)