BOSTON — J.D. Martinez scored when Marlins shortstop JT Riddle threw away a potential double-play ball in the ninth inning, lifting the Boston Red Sox over Miami 8-7 on Tuesday night following a wild, back-and-forth final two innings.

Boston snapped a three-game skid and avoided its first four-game losing streak of the season — barely.

Miami scored five runs in the eighth inning to lead 6-4, allowed three runs to Boston in the bottom of the inning, then tied the game at 7 in the top of the ninth against closer Craig Kimbrel (4-1).

In the bottom of the inning, Martinez reached on a one-out single and went to second on Xander Bogaerts’ hit. Eduardo Nunez followed with a grounder to Riddle, who stepped on second but sailed his throw well past first baseman J.T. Realmuto. Drew Steckenrider (4-3) was stuck with the loss.

Nunez homered in the sixth to put Boston ahead 4-1, a lead that held until Matt Barnes’ melted down in the eighth. Realmuto and Starlin Castro hit back-to-back home runs during the five-run inning, which also included a two-run single by Rafael Ortega.

Jackie Bradley Jr. hit a two-run single with two outs in the eighth off Marlins reliever Tayron Guerrero, and Ian Kinsler then scored on Guerrero’s wild pitch to take a 7-6 lead.

Kimbrel walked two before allowing Magneuris Sierra’s tying single in the ninth.

Isaac Galloway homered for Miami in the third.

Jose Urena returned to Miami after a six-game suspension and allowed four runs and six hits and struck out two in six innings. Urena, suspended for hitting Atlanta’s Ronald Acuna Jr. with a pitch on Aug. 15, didn’t figure in the decision.

TRAINER’S ROOM: Marlins: OF Garrett Cooper will have surgery Friday in Miami to repair a tendon sheath in his right wrist, manager Don Mattingly said.

Red Sox: LHP Eduardo Rodriguez (right ankle sprain) will return from the DL and start Saturday when the Red Sox visit the Chicago White Sox. Manager Alex Cora said Rodriguez’s return will take some pressure off the starting rotation as well as the bullpen. … LHP Chris Sale (left shoulder inflammation) played catch Monday, which Cora described as a “good start” but didn’t offer a timetable for his return.

UP NEXT: RHP Trevor Richards (3-7, 4.23 ERA) starts for Miami against Boston LHP David Price (14-6, 3.50), who has won his last three starts.

Follow BDN Maine Sports on Facebook for the latest in Maine high school and college sports.