Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

migrated from stackoverflow.com Apr 6 '13 at 11:37

This question came from our site for professional and enthusiast programmers.

2  
Why? I run several hundred ecommerce websites and we store everything in either cookies or localStorage (HTML5). Also, sessions use up memory. When we do account login we use an encrypted cookie with a timestamp. We don't need a session because when a page loads, we use HTML5 techniques to store and use sessionStorage after a single load. This is IE8+ compatible standard web tech. –  Jason Sebring Apr 5 '13 at 3:44
    
@LuiggiMendoza ok why not. –  Jason Sebring Apr 5 '13 at 3:46
    
@zipstory.com: i would also like to have a look about HTML5 based solution, but still since its not supported by few browser, i am bit doubtful –  Umesh Awasthi Apr 5 '13 at 3:54
    
@UmeshAwasthi I suppose my clients do not care about the very small handful of people on lower browsers but obviously this is a bad approach if its a different case in your web traffic. I know still lots of the world uses XP on IE7 and sometimes IE6 but some of my clients products are found in stores such as Nordstroms and Macy's etc. and seem to not be concerned about that. –  Jason Sebring Apr 5 '13 at 4:00
    
@zipstory.com: I am working with a eCommerce application where client want even support for IE6, now what you will say abt it :) –  Umesh Awasthi Apr 5 '13 at 17:47

6 Answers 6

The question is assuming you need sessions at all which in my market of clients is not needed. I happen to run several hundred eCommerce websites and a handful of them are getting high traffic. We do not use sessions ever as they are not scalable unless farmed out then they are just slower or require more setup. Sessions use up memory and database fetching of session state is very slow and requires more moving parts.

Instead, we use HTML5 sessionStorage to persist any user information we need to pull again and again but without needing a cookie rountrip each time to increase bandwidth. This is IE8+ and all other modern browsers and mobile devices are compatible with this tech. BUT you could just easily store the cart in a cookie as a fallback as this is what we did previously. Here is a good cookie-cart: http://simplecartjs.org/

When users sign in or login we use an encrypted cookie with a time stamp baked in.

We are also moving toward using ApplicationCache where applicable which will further reduce web traffic as a side note since you can prefetch resources and even catalog data so the user perspective will be a super fast loading website and mobile will also work offline (minus transactions). Of course you must be careful to update the manifest when products change etc.

share|improve this 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.

share|improve this answer
    
what about when i need to show cart detail page? should we store/ fetch data from session or go for a database hit? –  Umesh Awasthi Oct 17 '13 at 18:38
    
If you store the cart details in the database, then yes, you would need to hit the database. –  Jakob Gade Oct 21 '13 at 3:32

Both methods have advantages and disadvantages, but the way I see it, database storage has two pretty large advantages.

  1. Reporting. You can't report on abandoned carts, conversion rates, etc. if the data is in the session.
  2. Session timeouts. I would be annoyed if I went to eat dinner and came back to find my cart was emptied because the session expired. I would imagine the retailer wouldn't like that either. We want to nudge the user toward buying, not toward giving up and leaving.
share|improve this answer

Let us consider the two use cases you have mentioned

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

In this case, you definitely want to save the user's cart information in a session to serve the user well during his/her session. If he/she does decide to log in/create an account, you can handle this based on the next use case. If he/she does not log in, you don't need to fill your database with this guest user's information as it was only used to serve the guest during the session. This data can be handled on a Stateless basis i.e. not the state is not saved from session to session.

User is logged in and adding product to cart.

In this case, you can handle it the same way as above (old school e-commerce sites) and also add this information to the database and associate it with the user. This is mainly used to provide stateful (state saved from session to session) information such as "Product Browsing History", "Recommendations" etc. i.e similar to Amazon.com.

Things to think about:

  • Is it necessary to save data?
  • If yes, what data is most critical to be saved to serve the user better?
  • Scalability + data storage - How will you save the cart information for fast lookup in your database to support many users?
share|improve this answer
3  
It also helps the company analyze sales. How often is a product put in a cart but not bought. If the percentage is high, then they might want to look at how the product is presented or the price to see if changes can help imporve teh buy rate. Saving can also allow the user to see those items quickly if he didn't order tehm the day he looked rather than look for them again. So maybe you put them in your cart but wanted to wait til tomorrow (payday) to actually purchase them. So saving the data might result in your real customers buying more stuff. –  HLGEM Apr 8 '13 at 22:15
    
But in the end this is a requirements definition problem and you should tell your business what you plan to do and make sure it is what they expect before you build anything. –  HLGEM Apr 8 '13 at 22:15
    
Remeber you need to think about order and shopping carts from the perspective of what might the business need the data for inthe future. If they want to analyze data, it is best to store it. Developers get hung up onteh user interface and forget the data's purpose in being stored when desiging. –  HLGEM Apr 8 '13 at 22:17
    
@HLGEM: Very good point! I answered this question merely based upon the need for supporting the car functionality for a guest user versus a site member. From a business point of view, there should be a separate statistics system that is dependent on some sort of database system that tracks product(s) in terms of geography, # of users, related products, buy versus discards etc. –  GeekByte Apr 9 '13 at 22:36

You are assuming that session storage and database storage are exclusive. They aren't. But let's start by assuming they are.

The advantage to session storage is three-fold:

  1. No need to explicitly insert data into the database. You just simply set a session variable and you're done. Simple and low-risk functionally.
  2. No need to manage the lifecycle of a user visit and shopping cart as containers / frameworks do it for you
  3. Usually auto-cleanup of old idle sessions is done for you.

Disadvantages of session storage:

  1. Session affinity, unless you investigate replication
  2. No failover, unless you investigate replication or manual persistence of session state to disk, which can get complicated.
  3. All sessions must be stored in memory. This is amplified if you employ replication.

Advantages of database storage:

  1. No need to worry about session affinity or state replication. You can round-robin all requests.
  2. Less memory overhead in application.
  3. If the order is completed, everything ends up in the database anyway, so this could make completion easy because the data is already present.

Disadvantages of database storage:

  1. Abandoned carts - some anonymous user added an item to their shopping cart and disappeared. That data sticks around forever unless you have some sort of expiration process.
  2. You need to come up with a way to track users and figure out if, for a given request, this represents an existing or new browsing session. (yes, this is probably easy if you use a cookie, but how do you ensure two users don't end up with the same id?).
  3. More code

You didn't mention what platform you are using. I would seek an approach that uses a database-backed session where the session data only exists in memory during the life of a request/response cycle, loading it from the database and saving back to the database. This has served me well in the past.

Advantages of a database-backed session:

  1. No need for server affinity.
  2. Easy on the app server memory
  3. Idle / abandoned session data is cleaned up for you.
  4. Lifecycle of user first visit, repeat visit, session end is all figured out for you.
  5. Easy to code

Disadvantages of a database-backed session:

  1. Configuration - you need to investigate your container, whether it's PHP, Java EE (Tomcat, Jetty, JBoss, etc.), node.js + express.js or whatnot support this and supply the right configuration.
  2. You may need to load test this since you are adding 2 database operations per request.

There is a third possibility, which somebody touched on earlier. You could skip the use of sessions altogether and use client-side storage by either embedding everything in a cookie or html local storage.

I'll leave the pros/cons of that as an exercise to you, but I'll give you a hint that for html5 storage, browser compatibility may be something to review carefully.

I've outlined the facts for you. Hopefully this helps you make the right decision for your situation.

share|improve this answer
    
You missed an advantage of database storage, abilitly of the organzation to analyze buy rates of things placed in shopping carts. –  HLGEM Apr 10 '13 at 14:05
    
@HLGEM Excellent idea - I never thought of that! –  Brandon Apr 10 '13 at 14:13
    
I think of this stuff because I'm the one who does the analysis of the data in the database. When designing databases, one of the first questions should be what are we going to need this data for and hardly anyone ever asks it. –  HLGEM Apr 10 '13 at 14:19

Go for session when the user is not logged in. Even when logged in create the cart in the session first, and persist it into the database only when the user logs out or the session times out.

You need to keep a check on number of carts getting created in the session.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.