I am developing a web application (Nginx+PHP7.3) that will use Redis database to store some data (mainly to count things) and I have to decide how to store the data. What is important in my case is speed and performance and also keep operations per second low to be able to handle many concurrent connections with the web application.
Option 1: Store JSON data on a single key
To save the data I would use a single SET operation, i.e:
$redis->set("MyKey-UserID", '{"clicks":123,"downloads":1234,"views":123}');
Then to update the data I would use two operations (GET + SET), i.e:
$array = json_decode($redis->get("MyKey-UserID"), true);
$array['clicks']++;
$array['downloads']++;
$array['views']++;
$redis->set("MyKey-UserID", json_encode($array));
Option 2: Multiple keys with single value
To save the data I would use multiple SET operations, i.e:
$redis->set("MyKey-UserID-Clicks", 123);
$redis->set("MyKey-UserID-Downloads", 1234);
$redis->set("MyKey-UserID-Views", 123);
Then to update the data I would use multiple INCR operations, i.e:
$redis->incr("MyKey-UserID-Clicks");
$redis->incr("MyKey-UserID-Downloads");
$redis->incr("MyKey-UserID-Views");
My Selected Option + Questions
Personally I would use Option 1, what are your opinions?
Do you think it will still be fast using GET + SET as using INCR?
What do you think about Option 2?
My Pros/Cons for Option 1
Option 1 Pros:
- Better database organization as I will have only one key for each user
- With a single GET operation I will have all JSON data
- To update all JSON fields I will just use two operations (GET + SET)
- Database will be smaller in file size
Option 1 Cons:
- To increment just "Clicks" I need two operations (GET + SET) instead of one INCR
- Maybe Option 1 procedure (GET+SET) is slower than multiple INCR in Option 2?
Some Useful Answers
@Samveen (Link)
Option 1 is not a good idea if concurrent modification of the JSON payload is expected (a classic problem of non-atomic read-modify-write)
We have many concurrent connections, so maybe Option 2 is the winner.