Re: 21' Forester 351 ford
When I was working for Ford dealer a long time ago we always had the same symptoms you describe in many cars, mustangs, crown vics, and even the trucks. It usually ended up being the ignition module as well as the hall effect switch in the distributor. What would happen it when get heat soaked they fail and leave you stranded. Waiting a while for the components to cool off allowed the vehicle to restart. This usually would happen when the tow truck dropped off the car and it would start. In order to prevent comebacks when replacing an ignition module we would also replace the hall effect/stator/pickup inside the distributor. The required pulling the distributor, removing the gear, and pulling the shaft to remove the part.
You still need to properly diagnose your issue though as others have said. A cheap spark checker is your friend here. When it happens check Primary spark and secondary spark.