This all sounds rather familiar to what was happening to my bike intermittently for ages, and it was only when the engine cut out while i was riding it that it led me down another path to investigate.
The fix for me, and it's been months now with zero issues, was to flood the ignition barrel (where you put the key in) with electrical Contact Cleaner Spray. I used the key to open up the top part then just sprayed away, also putting the key in and turning it about at the same time to make sure it got everywhere.
I learned that the barrel is not just a straightforward On/Off mechanism, but there are several different contacts connected to it that become live when turned on.
Over time, with different weathers abusing the bike, plus from memory i knew i had used WD40 before down the barrel, and also years later had used proper Graphite designed especially to free up sticky key locks, it had eventually become a bit gammy down there so the contacts were simply dirty causing all sorts of starting issues, backfiring, irregular running, then eventually cutting out, as you've mentioned.
Took me ages to get the answer i needed, after spending lots of time and money replacing and renewing other electrical parts, etc, but once i'd used that spray the bike has been spot on ever since.
You need to use a proper electrical contact spray that is specific for this sort of thing that won't leave any unwanted residue, i wouldn't recommend a full on degreaser spray as they can leave a powdery deposit that could still cause problems.
Have a go, it could be a very quick and cheap fix before you start going crazy like i did.
Just a note, make sure the engine is cool before you start soaking the lock with flammable liquid, for obvious reasons.