Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for keeping counter stats?

In an effort to add statistics and tracking for users on my site, I've been thinking about the best way to keep counters of pageviews and other very frequently occurring events. Now, my site obviously isn't the size of Facebook to warrant some of the strategies they've implemented (sharding isn't even necessary, for example), but I'd like to avoid any blatantly stupid blunders.

It seems the easiest way to keep track is to just have an integer column in the table. For example, each page has a pageview column that just gets incremented by 1 for each pageview. This seems like it might be an issue if people hit the page faster than the database can write.

If two people hit the page at the same time, for example, then the previous_pageview count would be the same prior to both updates, and each update would update it to be previous_pageview+1 rather than +2. However, assuming a database write speed of 10ms (which is really high, I believe) you'd need on the order of a hundred pageviews per second, or millions of pageviews per day.

Is it okay, then, for me to be just incrementing a column? The exact number isn't too important, so some error here and there is tolerable. Does an update statement on one column slow down if there are many columns for the same row? (My guess is no.)

I had this plan to use a separate No-SQL database to store pk_[stat]->value pairs for each stat, incrementing those rapidly, and then running a cron job to periodically update the MySQL values. This feels like overkill; somebody please reassure me that it is.

like image 431
munchybunch Avatar asked Jan 30 '26 23:01

munchybunch


2 Answers

UPDATE foo SET counter = counter + 1 is atomic. It will work as expected even if two people hit at the same time.

like image 60
Eli Avatar answered Feb 01 '26 13:02

Eli


It's also common to throw view counts into a secondary table, and then update the actual counts nightly (or at some interval).

INSERT INTO page_view (page_id) VALUES (1);

...

UPDATE page SET views = views + new_views WHERE id = 1;

This should be a little faster than X = X + 1, but requires a bit more work.

like image 39
Adrian Schneider Avatar answered Feb 01 '26 13:02

Adrian Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!