When I connected LON-MAD-ALC last month on a GB passport, I also noticed long lines at 4S Immigration for non EU passport holders however there was a designated line for transit passengers guarded by a AENA minder. A quick flash of the connecting boarding pass ensured I avoided a very long line compared to those ending their journey at MAD. Like others have said follow signs carefully when you get off the train at T4 and don't necessarily follow the crowd. There's a dedicated transit security before taking escalators up to airside departures. If you're not careful you're on your way to baggage reclaim.
I'd entertain another MAD transit but knowing just how big the airport is, the absolute minimum connection I'd entertain would be 90 minutes. Anything less is courting trouble.