Cookies, sessions, and application caching

~10 min

Here is a puzzle hiding inside almost every website you use.

In Module 4, you learned that web communication is built from separate requests and responses. Your browser sends one request, receives one response, and later sends another request.

But how does a website keep you logged in across hundreds of requests? How does it remember your shopping cart as you move between pages?

Something must connect those otherwise separate interactions.

The answer involves state, cookies, and sessions.

HTTP is stateless

HTTP is commonly described as a stateless protocol, meaning each HTTP request is treated as a separate message, one that does not automatically carry a memory of every request that came before it.

Imagine sending the same restaurant a series of separate notes:

  • “Show me the menu.”
  • “Add a latte to my cart.”
  • “Show me my cart.”

Unless the restaurant has some way to identify the notes as yours, it cannot know which cart belongs to you.

A website therefore needs a mechanism for connecting a new request to information it previously stored about the user.

Websites can still remember you. The stateless part means HTTP itself provides no automatic memory, so the application must deliberately create and manage it.

State on the client and server

In Module 1, you learned that Concept · lights on your mapapplication stateRe-encounter from Module 1: information describing a system’s current condition. In a web application it lives on both sides: client-side (open menus, unsent typing, a local cart copy) and server-side (accounts, orders, the authoritative cart). is information describing a system’s current condition.

In a web application, state can exist on both sides of the frontend–backend split.

Some state may live on the client, such as:

  • Which menu is currently open
  • What the user has typed into an unsent message
  • Which tab is selected
  • A temporary form value
  • A local copy of a shopping cart

Other state may live on the server, such as:

  • The user’s account
  • Saved orders
  • Subscription status
  • Permissions
  • The authoritative shopping cart
  • Whether a login session is still valid

The exact division varies by product, but either way the application needs a way to associate the client’s requests with the correct server-side information.

What is a cookie?

A Concept · lights on your mapcookieA small piece of information a website asks the browser to store and include with matching future requests. The mechanism behind staying logged in, subject to rules about domain, HTTPS, lifetime, and script access. is a small piece of information that a website asks a browser to store.

The server can include an instruction in a response that effectively says: save this value and include it with relevant future requests.

The browser stores the cookie and may attach it when sending later requests to the same website.

A simplified server response might contain: Set-Cookie: session_id=8k2f

The browser stores the value: session_id=8k2f

A later request may include: Cookie: session_id=8k2f

Now the server has a piece of information that can help it recognize the browser’s continuing visit.

Cookies follow rules

A browser does not attach every cookie to every request.

Cookies can have rules controlling:

  • Which domain can receive them
  • Which paths they apply to
  • Whether they may be sent only through HTTPS
  • How long they remain stored
  • Whether browser scripts can read them
  • Whether they are sent in certain cross-site situations

These restrictions help limit where cookies travel and reduce security risks.

You do not need to memorize the individual cookie settings yet. The important idea is: the browser stores cookies and sends them only when the cookie’s rules match the request.

What is a session?

A Concept · lights on your mapsessionA period of interaction during which an application remembers information associated with a user. Commonly: the cookie carries a session identifier, and the server holds the session’s information, like a coat-check ticket and the coat. Logging out invalidates the session. is a period of interaction during which an application remembers information associated with a particular user or client.

In a common session-based login system, the server creates a session after the user signs in.

The server might store information resembling:

What the server remembersServer-side session
1Session 8k2f:
2User: Erik
3Logged in: Yes
4Cart: 3 items

The browser does not need to store all of this information; it may store only the session identifier: 8k2f

When the browser sends that identifier back in a cookie, the server uses it to find the matching session.

A useful analogy is a coat-check ticket. It does not contain the coat, only an identifier that allows the attendant to retrieve the correct coat from storage.

Similarly: the cookie carries the session identifier. The server-side session holds the remembered information.

Following a login session

Imagine that Erik signs into the coffee app.

First, the browser sends Erik’s login information to the backend, which verifies it, creates a new session, stores information connecting that session to Erik’s account, and sends the browser a cookie containing the session identifier.

On the next request, the browser includes the cookie, and the server reads the identifier, finds Erik’s session, and recognizes that the request belongs to a logged-in user.

The simplified flow is:

  1. The user logs in.
  2. The server creates a session.
  3. The browser receives a cookie containing the session identifier.
  4. The browser includes the cookie with later requests.
  5. The server uses the identifier to retrieve the correct session.
  6. The application continues treating the user as logged in.

This process creates continuity across separate HTTP requests.

What happens when you log out?

When a user logs out, the application should prevent the existing session from continuing to grant access.

The server may invalidate or delete the session, and the browser may also be instructed to remove the session cookie.

Afterward, presenting the old session identifier should no longer restore the logged-in state.

In the coat-check analogy, the ticket may still contain a number, but the number no longer retrieves anything useful because the corresponding record has been removed.

Different systems handle logout differently, but the intended result is the same: the previous proof of the login session should no longer provide access.

Sessions are not the only way to connect a request to an identity. Module 6 introduces tokens, some of which a backend can verify without a stored session. Either way, the cookie is often the browser’s mechanism for carrying the proof.

Cookies can store other information

Cookies are not used only for login sessions.

They may also store or identify:

  • Language preferences
  • Display preferences
  • Analytics identifiers
  • Shopping-cart information
  • Whether a notice has been dismissed
  • Experiment or feature-test groups

However, cookies are small and are stored on the user’s device, where their contents can potentially be inspected or modified.

Sensitive information such as passwords should not be stored directly in a normal cookie.

For important decisions, the backend must validate the cookie and rely on authoritative server-side information rather than blindly trusting whatever value the client sends.

This is another application of the principle: never trust client input without verification.

What is an application cache?

Cookies and sessions help an application remember users, while a different kind of memory helps the backend avoid repeating expensive work.

An Concept · lights on your mapcacheRe-encounter from Module 4, now on the backend: a store of data or previously calculated results the server can reuse instead of repeating expensive work. Speed, traded against freshness. Removing outdated entries is called cache invalidation. stores data or previously calculated results so that the backend can retrieve them more quickly.

Suppose the coffee company displays a list of today’s best-selling drinks, and calculating that list might require examining millions of orders.

Instead of repeating the calculation every time a user opens the page, the backend could:

  1. Calculate the bestseller list.
  2. Store the result in a cache.
  3. Reuse the cached result for several minutes.
  4. Calculate a new version after the cached copy expires.

The next request receives the saved answer, sparing the application the full calculation.

Browser cache versus application cache

In Module 4, you learned about the browser cache, which stores files or responses near the user so the browser can avoid downloading them again.

An application cache commonly exists within or near the backend, where it helps the server avoid repeatedly querying a database, calling another service, or performing an expensive calculation.

The locations differ, but the central idea is the same: keep a reusable copy close so the system can avoid slower work.

The cost of caching

Caching improves speed, but cached information can become outdated.

If the bestseller list is refreshed every five minutes, a newly popular drink may not appear immediately.

This creates a tradeoff between:

  • Speed: reuse an existing result
  • Freshness: retrieve or calculate the latest result

Applications need rules governing:

  • What may be cached
  • How long it may be reused
  • When it expires
  • When it must be updated
  • What happens if the source data changes early

Removing or replacing outdated cached information is called cache invalidation.

You only need to recognize that term for now. It describes one of caching’s central difficulties: knowing when a saved result is no longer safe to use.

Connecting the concepts

Imagine that Erik opens the coffee app while logged in.

The browser sends a cookie containing Erik’s session identifier, and the backend retrieves the matching session and recognizes his account.

The backend then prepares the page. It retrieves Erik’s authoritative cart from storage, but it may load the public bestseller list from an application cache because that result was recently calculated.

The same request therefore uses several forms of state:

  • A cookie stored in the browser
  • A session associated with Erik on the backend
  • Authoritative account and cart data
  • A cached bestseller result shared across users

Each one remembers something for a different purpose.

The mental model to remember

HTTP is stateless, meaning each request does not automatically remember the requests that came before it.

A cookie is a small value a website asks the browser to store and return with matching future requests.

A session is remembered information associated with a continuing interaction or logged-in user.

In a common session system, the cookie carries an identifier while the backend stores the actual session information.

An application cache stores reusable data or calculated results so that the backend can avoid repeating slower work.

Cookies and sessions create continuity. Caches create speed.

You should now understand how an application can recognize the same user across separate requests and how the backend can reuse previous results to respond more efficiently.

Check — then the lesson continues

You log into a site on your laptop, then open the same site on your phone and find yourself not logged in. Using this lesson's machinery, why?

▼ answer the check to continue ▼