This is a common issue with X5 tail lamps, the circuit board in the tail lamp itself overheats, which melts the plastic housing of the tail lamp, enough that the circuit board bends and causes an arc between the bulb socket contact for the brake light and the circuit board.
You need to remove the brake light bulb socket, which is the lowest socket in the tail lamp and check the contact where the socket touches the circuit board of the tail lamp. You will likely find a burn mark on the circuit board.
Another indication is that you will find the plastic grey tabs as seen in the pic above will be melted.
If either of these symptoms is present, you will need to replace the tail lamp assembly.
Hope this helps, please use the accept button as this is the only way I receive credit for my work.