The deal, which runs through the 2023 season, includes a club option for 2024.
Financial terms were not disclosed.
The 31-year-old right-hander is 4-2 and has 19 saves with a 2.68 ERA in 37 appearances this season. He was selected as an All-Star for the first time in his career.
"This is a dream come true for me and somewhere that I've always loved playing and love to continue to play. So I'm really excited to be able to get something done here and looking forward to the next couple seasons here in Boston," Barnes, who was a first-round draft pick of the Red Sox in 2011, told reporters.
He has spent his entire career with the Red Sox and is 30-23 with 34 saves and a 3.94 ERA and 500 strikeouts in 362 appearances. With 360 relief innings, he ranks fourth in franchise history behind Bob Stanley (552), Mike Timlin (394) and Jonathan Papelbon (393).
Barnes was a key piece of the Red Sox's 2018 World Series championship team, winning games in both the American League Championship Series and the World Series. He made 10 appearances in all that postseason and didn't allow a run in nine of them. Overall, he is 2-0 with a 0.87 ERA in 11 appearances in the playoffs.