I can‚Äôt say much about tankless heaters, but there is one possibility on the problem you are experiencing with your current heater. It has happened several times with me.
Inside your tank is a long tube that connects to your cold water inlet, and channels that cold water to the bottom of your tank. This is so the cold water, coming in to replace the used hot water, doesn‚Äôt just get ****ed back up the hot water supply.
Well, when this tube gets rusty, it develops holes in it or gets fractured, and the cold water doesn‚Äôt reach the bottom of the tank, but rather, somewhere in their middle. Suddenly, you‚Äôre running out of hot water even though the heater doesn‚Äôt seem to be running much, and it doesn‚Äôt happen slowly, like you‚Äôre running out of water in a normal tank. You go from hot to cold real quick. Now those tubes can be replaced on some models. It happened to me twice, and in one instance I was able to change the tube, and in the other I was not. You can tell by looking at the top of the tank, and if you see a threaded flange bigger than the tube, you probably can. It‚Äôs a standard length of galvanized pipe.
Another possibility is if your tank is electric. At 40 gallons, I doubt it is, but if so, one of your heating elements may be out. Essentially, you‚Äôre heating only half the tank. Parts for this situation can be bought at most hardware stores.
There are some other possibilities for gas heaters, but they are remote, and possibly expensive to repair. Keep in mind on any repair that your current unit is 10 years old, and may not be worth any time, money, or energy to repair. Consider, if you go conventional replacement, to upgrade to at least 50 gallons if you have an electric unit.