The striker's 88th-minute goal, which came courtesy of a rebound, was just enough to defeat the Premier League side after Conor McAleny also netted a double on his Brentford debut.
The 20-year-old, who has joined from Everton on a loan set to last until January, troubled Cardiff from the off and cancelled out efforts from Kim Bo-Kyung and Fraizer Campbell.
Mackay fielded a strong team including Craig Bellamy, Mark Hudson and Craig Noone but the visitors could not hold off the determined League One outfit, who showed great resolve to battle from 2-0 down to earn victory in the pre-season friendly.
|GOAL 50: THE TOP 10
|13/8||Cardiff City are 13/8 with PaddyPower to be relegated from the Premier League
Campbell got in on the act two minutes later as he netted from 12 yards to double his side's advantage.
McAleny, though, handed Brentford a lifeline as he smashed a shot past Joe Lewis to see the score delicately poised at 2-1 at half-time.
No changes were made for either side during the break, with McAleny on the scoresheet again within five minutes of the restart, hammering another well-drilled effort past Lewis.
The momentum generally seemed to drain from that point, though, and, despite nine changes for the visitors, Cardiff simply could not get that winning goal.
Brentford, on the other hand, did manage to sneak that important third as 29-year-old Hayes was on hand to take the rebound past Lewis late on.
After finishing 1-1 against League Two outfit Cheltenham Town on July 27, the Welsh side will be hoping to get their pre-season back on track when they face Chievo at home on Saturday.