Video in progress
Is it better to store a user profile in Redis as a String (JSON) or as a Hash?
If the object is always read and written as a whole, a JSON String is convenient. If individual fields change often or you only need part of the object, a Hash is better: you work with a single field using HGET, HSET, HINCRBY.
📖 Answer
The JSON variant:
SET user:7 '{"name":"Ali","balance":100}'
To change the balance you have to read the whole JSON, parse it and write it back, and two parallel requests can wipe out each other's changes.
The Hash variant:
HSET user:7 name Ali balance 100
HINCRBY user:7 balance -30
HGET user:7 name
In practice I store cached DTOs (the ones fetched as a whole) as JSON, and use a Hash when there are "live" counters or state fields. One more difference: TTL is set on the whole key, not on an individual field inside the Hash (Redis 7.4 added per-field TTL, but not every deployment runs that version yet).
Sign up to mark studied questions and save your progress.