The effects of caffeine are due to its competition with the neurotransmitter adenosine. Adenosine, put simply, is generated as a byproduct of energy consumption in the body. As it is created, it binds to receptors in the brain, generating a feeling of tiredness.
Parts of caffeine’s structure are similar to that of adenosine - because of this, it can also bind to some of the adenosine receptors, blocking them and preventing feelings of tiredness.
The average half-life of caffeine (the time it takes for half the ingested dose to wear off) is 5-6 hours for most people. It can vary for different groups of people, however; for instance, women metabolise (break down) caffeine marginally quicker than men, whilst smokers metabolise it twice as fast (smoking increases production of one of the enzymes that breaks down caffeine).
You can become tolerant of your intake of caffeine - studies have suggested that within 7-12 days, the body becomes tolerant of its daily dose. Exactly how this tolerance develops isn’t precisely known, but some research has suggested that the brain actively changes to try and redress the effect caffeine has, potentially by creating a greater number of adenosine receptors.
Adenosine is important for deep, restful sleep. Since caffeine can stay in your body for several hours after ingestion, whilst it won’t prevent you from falling asleep, it can impact on your total sleep time. The reason a coffee in the morning can be feel so essential is because it staves of the effects of caffeine withdrawal!
Hope that answers your question! I also previously made some graphics on the chemical compounds in both tea & coffee if you want to find out a little more about those.