Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Redis · Module

HLEN

HLEN returns the number of fields in a Redis hash. It runs in O(1) time and returns 0 when the key does not exist.

Since
2.0.0

How it works

HLEN takes the key of a Redis hash and returns how many fields it currently contains. The count is constant-time, and a missing key behaves like an empty hash, so the result is 0; using a key with another data type produces a wrong-type error.

Syntax

HLEN key

Parameters

NameTypeDescription
keyRedis keyThe name of the key that holds the hash.

Returns

The number of fields in the hash, or 0 when the key does not exist.

Key points

  • HLEN is a read operation for hashes and is marked fast.
  • Its single argument is the key containing the hash.
  • The response is an integer field count, with zero for a nonexistent key.
  • Redis introduced HLEN in version 2.0.0.

Common mistakes

  • A missing key returns 0, not an error, because Redis treats it as an empty hash.
  • HLEN counts fields, not the total size of field names and values.

Example: Count hash fields

HSET user:42 name Ada language Redis
HLEN user:42

Creates two fields, then returns their count: 2.

When to use it

Presence and emptiness checks

Check whether a hash contains any fields without retrieving its contents.

Hash cardinality metrics

Track the number of attributes, counters, or members represented by a hash.

Interview questions

QWhat does HLEN return, and what is its time complexity?

HLEN returns the number of fields stored in the hash at the supplied key. Its command complexity is O(1), so the count does not require scanning every field.

Follow-up: What happens when the key is absent? Redis returns 0, treating the missing key as an empty hash.

QWhat is the syntax and required argument for HLEN?

The syntax is HLEN key. The key identifies the Redis hash whose field count should be returned.

Follow-up: How would you count values rather than fields? Use a command such as HVALS to retrieve the values, but that operation is O(N).

QWhen was HLEN introduced, and what does its result represent?

HLEN was introduced in Redis 2.0.0 and returns a long integer containing the number of hash fields. It is categorized as a read, hash, and fast command.

Follow-up: What should a client do if the key contains a string instead of a hash? Handle the WRONGTYPE response and correct the key's data-model usage.

  • HSET
  • HGETALL
  • HVALS

Source: HLEN | Docs - Redis. Checked 2026-10-16.