I'm building a system which tracks records of views of an image.
The main tables in this project are the view table and max_view table. The view table keeps the date, time and number of views. And the max_view table keep tracks of the maximum number that an image can be viewed.
Every time when an image is being loaded. I will store the date and time into the view table. And will minus 1 from total max views of the image in max_view table.
Table example:
View Table
id | image_id | datetime | username
1 1 2015-03-02 02:30:34 user1
2 1 2015-03-02 02:32:34 user2
3 2 2015-03-03 01:40:34 user1
Max_view Table
id | max_view | image_loc
1 1000 /image/image_1.jpg
2 500 /image/image_2.jpg
My SQL query in yii2 framework below:
Choose an image randomly:
$row = Yii::$app->db->createCommand("SELECT id FROM image_source ORDER BY RAND()")->queryOne();
Insert into view table:
Yii::$app->db->createCommand()->insert('view', [
'image_id' => $row['image_id'],
'datetime' => $datetime,
'username' => $user,
])->execute();
Update max view count:
Yii::$app->db->createCommand("UPDATE max_view SET max_view=max_view-1 WHERE id=$image_id")->execute();
My problem is, when there are large number of users view at the same time. The data is not consistence. The data inserted in view table tend to be more sometimes. For example, if there are 10 people viewed the same image. The view table supposedly to have 10 records and max_view table will minus 10 from the total of max view of that image. But somehow, it sometimes only minus 9 from the max_view.
If I test it on my local machine, it works flawlessly. May I know how do I solved this? I'm suspecting that the server is not fast enough to capture the max_view data. How do I make it more consistent ?