Event counters
Track page views, API requests, downloads, or other event totals in a hash.
Redis · Module
HINCRBY adds a signed integer to a field in a Redis hash and returns the updated value. Missing hashes and fields are created automatically, with a missing field starting at zero.
HINCRBY adds a signed integer to a field in a Redis hash and returns the field's new value. Redis creates the hash when its key is absent and treats an absent field as zero before applying the increment; values must fit a signed 64-bit integer.
HINCRBY key field increment| Name | Type | Description |
|---|---|---|
key | key | The name of the key that holds the hash. |
field | field | The field whose value to increment. |
increment | signed 64-bit integer | The integer amount to add to the field's value. |
An integer reply containing the field's value after the increment operation.
HSET counters page_views 10
HINCRBY counters page_views 1
HINCRBY counters page_views -2
HGET counters page_viewsCreates a numeric hash field, increments it, decrements it, then reads the resulting value.
Track page views, API requests, downloads, or other event totals in a hash.
Adjust inventory or balance-like integer quantities by positive or negative amounts.
Maintain several related integer counters under one Redis hash key.
HINCRBY takes a hash key, a field name, and a signed integer increment. It returns the field value after applying the operation.
Follow-up: What happens when either the hash key or field is missing? Redis creates the hash if the key is absent and initializes the missing field to zero.
The command supports negative increments, so it can decrement a counter as well as increment one. The returned integer is the updated field value.
Follow-up: How would you decrement by 10? Use HINCRBY key field -10.
HINCRBY has O(1) time complexity. The increment argument and resulting value are constrained to signed 64-bit integers.
Follow-up: What should be used for decimal values? Use the separate HINCRBYFLOAT command, which is intended for floating-point hash fields.
HDECRBYHINCRBYFLOATHGETHSET