Skip to content

Instantly share code, notes, and snippets.

@yang-wei
Created November 16, 2015 05:33
Show Gist options
  • Save yang-wei/a052ce4d6a59c5118fef to your computer and use it in GitHub Desktop.
Save yang-wei/a052ce4d6a59c5118fef to your computer and use it in GitHub Desktop.
Why counterCache cannot be used

I realised the design of database becomes more and more trivial to me when it comes to refactoring of application or scaling. In web application frameworks like Ruby on rails and CakePHP there is a feature known as counterCache. This feature let you record the length of associated data, mostly when they have belongsTo relationship.

This feature is very convenient but it is not applicable to all database design. For example, when we never want to delete user data when she did it, most probably we will add a column like delete_flag in our table. So when user deletes the data, delete_flag will become 1 or true. Our select sql query looks like:

SELECT * FROM table_name WHERE delete_flag=0

Back to counterCache, it mainly do 2 thing.

  • increase the counter when data is inserted
  • decrease the counter when data is deleted

So based on above database design, although we can save users'data even if it is deleted but we cant use this feature.

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