Spanish winger Fran Villalba crowned a man-of-the-match performance with his first goal in English football in the 33rd minute.
Birmingham started with real attacking intent and they were only prevented from taking the lead by their former goalkeeper Randolph.
The Republic of Ireland international made a truly spectacular save, flinging himself high to his left to tip away Villalba's venomous volley.
The chance – like many as Birmingham looked to expose their former defender Ryan Shotton at left-back time and again – came after a cross from right-back Maxime Colin was deflected and sat up perfectly for the 21-year-old.
Randolph was in action again soon after, tipping over to save the blushes of Middlesbrough centre back Dael Fry, who unintentionally diverted the ball goalwards.
Randolph had become the star attraction and got his fingertips to Colin's goal-bound cross which looped up off Shotton, before punching Villalba's corner behind.
Blues took a deserved lead when Villalba spread play to Colin down the right yet again and went for the return, the Spaniard sweeping a neat side-footed effort into the bottom corner from just inside the area.
Randolph continued to frustrate his former employers, getting his hands to headers from Pedersen and Harlee Dean – which he almost dropped into the net – before Jude Bellingham's deflected shot dropped just wide.
Another Pedersen header hit the bar and was frantically scrambled away.
But it was Birmingham who created the first opening as Villalba curled wide.
Gardner hit the inside of the post with a 20-yard shot and Ivan Sunjic whistled a drive just wide as the hosts looked to double their advantage.
But Middlesbrough scored a barely-deserved equaliser when Ayala forced the ball home from Assombalonga's cross.
Birmingham regained the lead in the last minute when substitute Bailey stabbed home Dan Crowley's deep cross.
The result leaves Jonathan Woodgate's side with just two wins from 11 games, while Birmingham move into the top half.