Ideal way to store product information in shopping cart in asp.net

Abbas picture Abbas · Aug 22, 2013 · Viewed 9.5k times · Source

I am creating an ecommerce application, wherein i have a shopping cart.

My current structure is, whenever user saves the product, i put the product in the datatable and datatable to the session, so until session is not timed out, user can have the list they have saved.

I have however increased the session timeout to 600mins(10Hours), but my concern is, is this is best approach for storing shopping cart information, because if there are say for example 1000 Users accessing the site simultaneously, there will be 1000 session object created on the server, won't it deteriorate the performance of my website.

I cannot store it in database because if the user is anonymous i don't have the unique thing about the user, that way, if 1000 users are accessing the site, all products will get merge, i won't be able to fetch the product saved by the current user.

Is there any other better approach for this problem.

Answer

glautrou picture glautrou · Aug 22, 2013

You shouldn't implement like this. Sessions of 10 hours are very long, if you have 1000 users on your website your server is going to suffer and will create some performance issues.

On our ecommerce websites we create a cookie for anonymous users. After doing this you have two solutions:

  1. Store the entire basket in the cookie (basically list of product ID + quantity, more depending on your needs/strategy) or other techniques (e.g. localStorage).
  2. Store a unique ID in the cookie and store the basket in the database (temporary table) with the unique cookie ID as identifier. Once the user log into the system you move those data to the user basket table.

You can easily change the expiration time of cookies (or remove it) without impacting the overall performance of your server. For IDs you can use Guid.NewGuid().

UPDATE:

More details about my second solution - scenario:

  1. User visit website
  2. You create a cookie with no expiration date: cartId with value Guid.NewGuid() (name and value are up to you).
  3. User click on "Buy"
  4. Get the cookie server-side and add the cartId,product/quantity to the "AnonymousBasket" table
  5. Imagine the user leaves the website and come back a month later the cookie will be still here
  6. If the anonymous user go to his basket you are able to get his products and quantities based on the value of the cookie.
  7. If the user log on you remove the cookie and move data from the table "AnonymousBasket" to "Basket"
  8. Now your logged in user can process to the checkout

With this solution everything is persisted in the database and doesn't require sessions. You can change the expiration of your cookies like you do for sessions, alternatively you can cleanup the temporary table without any risk or create statistics on anonymous users (why they didn't proceed to checkout, how many items in average, which item, ...).