I had the exact same problem. Turns out it was
caused by insufficient water supply to the heater.
I had 3/4" supply to the garage (where I installed the water heater), but it was restricted at the source (off the house water tank) to 1/2". I took care of that, and the water now stays hot.