Database – HTTP Session or Database approach

databasedesignsessionweb-applications

I am confused a little as what should be my approach, Working on a design of shopping cart and i need to store shopping cart either in session or in database but not sure which approach would be best.here are the use case

  1. User is not logged in and adding product to cart (Anonymous user)
  2. User is logged in and adding product to cart.

First case is more confusing to me, since there can be many cases where user just visiting web-shop and adding product without logging in and can be quite possible that he might not going for a checkout process.

But still we need to create a Shopping-Cart for this user, in order to create and save shopping-cart i have two option.

  1. When user adding a product, create a cart in the database and associate this cart with this user, moment he logged in move this cart to logged in user.
  2. Create Cart, add product to it and save it to the Session, when user logged in create Cart in the database and associated logged in user with this cart with User.

I know that both database driven Cart system as well Session based can have there positive as well negative aspects, but not sure which one might be the best approach taking in to account following points

  1. Scalability
  2. Flexibility
  3. Extensibility
  4. Application Should take care of speed

Looking for input on this aspect to decide the path.

Best Answer

I would go for a solution where an unique ID is assigned to all visitors when they first hit the site. It doesn't matter if they're anonymous or authenticated. When anonymous users register, retain the unique ID.

Store the shopping cart in the database. Storage is cheap, and it shouldn't be a problem performance-wise to do a query for the cart every now and then.