It's recommended that you should stop drinking coffee at least 6 hours to 8 hours before bed.
For example if you go to bed at 10:00 PM to 11:00 PM, you should stop drinking coffee by 2:00 PM to 3:00 PM.
For the best sleep quality, it's recommended by experts that you avoid caffeine and coffee with caffeine 10 to 12 hours before bed.
Caffeine in the coffee has a half life of 5 hours to 7 hours, which means that a great or significant amount of the caffeine remains in your system hours after you consume it.
And even if you can fall asleep after drinking the coffee before bed, the caffeine in the coffee can still reduce your deep sleep and total sleep time.
Studies also show that drinking coffee with caffeine 6 hours before you go to bed can also reduce your total sleep time by over 1 hour, even if you do not feel the disruption in your sleep.
If you're sensitive to the caffeine, then you may require a longer buffer time between the coffee and bed, like 8 to 10 hours.
And if you need to have an afternoon boost, you should switch to decaf coffee, herbal tea or even water after 2:00 PM for optimal sleep quality.
Caffeine clearance can also take longer in some people, depending on factors like diet and age.
For me I try to stop drinking coffee at least 6 hours before bed and it seems to help me.
Although sometimes I will indulge in a cup of coffee a few hours before bed and then realize I shouldn't have, but I still find that I sleep okay.
I also sometimes will take melatonin supplements to help me sleep when needed.