Your prose will flow more smoothly if you narrate things in the order in which they happened.
This sentence is not technically incorrect, but it’s hard to comprehend because it zigzags through time, dragging a load of information:
Her back had ached for years until she finally bought a new mattress after realizing that when she had to sleep on the floor one night when her grandkids stayed over, she had a lot less pain.
Try this instead:
Her back had ached for years. One night when her grandkids stayed over, she had to sleep on the floor and she woke up feeling a lot better. She fed the kids breakfast, put them in the car, drove to the store and bought a new mattress.
The passage has grown by only ten words, but it contains a lot more information and the pace has slowed down to the point where the reader can comprehend everything in one go.