CodePark/ questions / Data types & commands
START PRACTICINGPRACTICE
Backend question · Redis & caching › Data types & commands

A user's profile is stored as a hash user:42. Which command atomically adds 1 to its loginCount field?

HINCRBY user:42 loginCount 1

HINCRBY adds to a hash field in one atomic command. It also creates the field if it is missing.

"
HGET the field, add 1 in the app, then HSET it" needs two round trips to Redis. If two requests do this at the same time, one update can be lost. "INCR user:42.loginCount" does not work, because INCR works on string keys, not on hash fields.