You cannot avoid problems like this when travelling. It is like trying to avoid traffic when driving. Maybe you live in a village and you travel to work at 5 am. Even so, one day you will get stuck in a jam. It happens.
If you're taking connecting flights, you will get delayed and at some point you will miss a flight. It is a normal thing.
The best you can do is to pad your connections by say 23 hours 59 minutes (providing schedules allow it). But frankly, yes I would pad very short connections before very long flights (let's say there's only one flight a week to the city, I will take that seriously), but you're talking about GRU-LIM which is served four times per day directly and many more times indirectly: I would not even think about it.
On a through ticket (a single ticket), the airline will accommodate you to your final destination, including if customs or immigration delayed you. There's no tricks about it. It's just how it works.
Beyond delivering you to your final destination, in most countries, the airline never guaranteed the schedule so it's your problem how you spend the time in the delay. Unless the airline caused the fault you might get a $10 voucher for food in the airport (which inevitably costs $12) and maybe a, maybe—if you're lucky—a room in some awful hotel somewhere very far away.
My advice is to take out reasonable travel insurance; invoice your insurer for reasonable costs your incur (meals and convenient hotel). The insurer will sort it out with the airline later.
The exception is within the EU on EU carriers, you are entitled to compensation for the delay in some circumstances. They also have a strict duty of care towards you, even if they are not responsible for the problem, which includes accommodation and food.