Skip to content

Instantly share code, notes, and snippets.

@samsch
Created May 14, 2019 18:50
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samsch/259517828ab4557c5c8b72ca1252992d to your computer and use it in GitHub Desktop.
Save samsch/259517828ab4557c5c8b72ca1252992d to your computer and use it in GitHub Desktop.
Stateless is a lie

There is no such thing as stateless authentication

The big "make everything stateless" hype is just that: hype. Your server-side application code, should usually be stateless, because this makes your application more resilient to errors, easier to scale, and easier to reason about. But there are exceptions to even that, especially for stuff like video game servers.

Your services are almost always going to be stateful, and should be. If you have a database, files, or literally anything that affects the responses the server sends, then the service is not stateless.

So building "stateless" services is a lie. You shouldn't strive to make your services stateless, you should make sure you're putting your state in the correct place.

Where does my state go?

Generic data

For most web sites and services, most of the "data" belongs in the database, or possibly a file-store for images or other large file-based data. This includes things like posts, user preferences, history, and relationships between entities. It definitely includes your users, except in the rare case your users are entirely coming from a third party service.

Authentication state, and sensitive data.

Your trusted authentication state belongs in the database. The browser can keep a cache of the user and authentication state in page memory (html/DOM and JavaScript variables, not sessionStorage or localStorage which are only for non-sensitive data), and the (httpOnly and secure) session cookie holds a signed session ID. The session data and everything about the user comes from the database.

Transient state

Transient state such as the current page, what item the user is currently editing or viewing, or user input will usually be "stored" in the browser, as the current url, the loaded html/DOM, and in JavaScript memory. This is the type of info you don't care about in the database, but you might persist is between page loads. For non-sensitive data, it's ok to cache some things in sessionStorage or localStorage. Some examples of non-sensitive data might be a css theme that should be applied, or a history of previous pages (just be careful you aren't storing something a different user shouldn't see).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment