Database – Storing an id of a shopping cart in a cookie for unauthenticated user

authenticationcookiesdatabaseSecurityuser-experience

I want to implement the "shopping cart" feature on my website. Both anonymous/unauthenticated and authenticated can have it.

While it's clear how to implement it for an authenticated user, it's not completely clear for the anonymous/unauthenticated user case. I believe that I'll have to create a long id, such as GUID or the like, in a database and install a cookie with that long id/GUID, right? Not just integer 32/64 id, because an integer id will be easy to guess or bruteforce, correct?

On the other hand, the threat model of guessing an integer id of a shopping cart isn't high — it's not a big issue if I guess a shopping card id of some anonymous/unauthenticated user, I think. Right?

Your advice?

Best Answer

Simply store the entire shopping cart and contents in a cookie or other client side storage.

Then you don't need the database and there is no risk of a user gaining unauthorised access.

Plus it will scale better.

The problem with shopping baskets in databases, especially for anonymous users is how long do you hold them for.

During peak times such as a sale you might have millions of users adding things to their shopping bag while browsing. You also have the millions of people who browsed in the last week/month/year.

You have two problems.

  1. The perennial question of auto int vs guid. Which I think has now been conclusively settled in favour of GUID.
  2. The volume of database/server calls simply to populate the shopping basket per user on every single page they view.

By storing the basket client side, you can draw the entire page from static or cached content on a CDN. Saving you a huge amount of server side processing. Which is at a critical premium at sale time.

You also solve the problem of how to keep track of the anon users, because they keep track of themselves via cookies.

Guessing a random anon users shopping basket might seem like a low value target. However auto incs can give away more than you might suspect.

If I am an investor in your stock for example, the growth in that number might be a good insight into your quarterly results before they come out.

Related Topic