When drinking coffee or anything containing caffeine you should stop drinking the coffee or any other caffeinated drinks within 2 hours before going bed.
Ceasing drinking anything with caffeine including coffee 2 hours before bed will allow the caffeine enough time to leave your system.
If you drink coffee or any drinks containing caffeine too close to bed then the caffeine can keep you awake and cause insomnia.
I used to have trouble sleeping and after I stopped drinking coffee or anything with caffeine 2 hours before bed I now sleep much better and do not suffer much from insomnia.