You probably shouldn't have raced the second time when you saw it was going to be an issue. And/or your friend should not have gotten so far ahead of you when you horse was having an issue with it.
Horses very often will get "fired up" and excited when running with each other. But they still need to listen to you. We'll let our horses race in a safe area out on the trails (usually a dirt summer fallow field or a harvested crop field). But they know when I want them to walk calmly, and when they are allowed to race.
Either way, the next time you race (I actually encourage you do because you're going to need to fix this issue), make sure you do it in an area where you have room to turn him into a circle. If you can't ride through the buck, then you can at least get his head to your knee. He can't buck with his head at your knee. The instant you've regained control and he isn't bucking anymore, make him WORK in a circle for several minutes. He needs to know that 1) bucking is not acceptable 2) bucking will not get him out of hard work. If you always stop him when he bucks, he'll eventually learn he can get out of working, and he'll try it.
Or go ahead and let your friend run ahead. While you let your horse gallop slowly, then stop him. Let him gallop slowly, then stop him. Turn around. gallop slowly. Stop. Etc. Just make him LISTEN despite what the other rider is doing. He needs to know that you are the team leader, no matter what else is going on. And brace yourself for a tantrum and be ready to get his head to his knee and keep control, and keep him working.
∞•*˚ Βгįťţαňγ ˚*•∞
It is not enough to know how to ride; one must know how to fall.