This video from Young Drivers of Canada shows the safest following distance on the road and how to adjust this distance depending on the road conditions.
Under normal driving conditions, a 2 second space cushion in front of you will generally be sufficient to protect against rear ending the leading vehicle.
However, when being tailgated by a vehicle that is closer than 2 seconds behind you, consider adding its cushion shortfall behind you to your cushion in front. Should the leading vehicle brake suddenly, the extra time will help you to control your stop so that you neither rear-end nor are rear-ended.
To the extent that the vehicle in front has less mass than yours, or the following vehicle has more mass than yours, increase your space cushion in front accordingly.