# MEMORY USAGE

> Estimate how many bytes a key and its value take in memory.

URL: https://docs.hotkv.com/commands/memory-usage/

```
MEMORY USAGE key [SAMPLES count]
```

- Group: Server
- Complexity: O(N) where N is the number of elements sampled
- HotKV Cloud: all plans
- On-Premise: no license needed

`MEMORY USAGE` estimates the memory a key uses, including its name, its value
and the bookkeeping around them. Use it to find out which keys are worth
shrinking, or to estimate the memory a data set will need.

For collections (lists, sets, hashes, sorted sets, streams), measuring every
element of a large value would be slow, so by default the first 5 elements
are measured and the rest are assumed to be the same size. Pass `SAMPLES` to
change that.

Looking a key up with `MEMORY USAGE` does not count as an access: it does not
change the key's last access time and is not counted as a hit or a miss.

## Options

| Option | Effect |
| --- | --- |
| `SAMPLES count` | Measure this many elements of a collection. `0` measures all of them. |

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Key exists | Integer: estimated bytes | Integer |
| Key does not exist | Nil bulk string | Null |

Errors: `ERR syntax error` for an option other than `SAMPLES`, a missing
count, or a negative count; `ERR value is not an integer or out of range`
for a count that is not an integer.

## Examples

```
127.0.0.1:6379> SET greeting "hello"
OK
127.0.0.1:6379> MEMORY USAGE greeting
(integer) 56
127.0.0.1:6379> MEMORY USAGE big:hash SAMPLES 0
(integer) 1843224
127.0.0.1:6379> MEMORY USAGE nosuchkey
(nil)
```

The numbers are estimates; they depend on the data and the HotKV version.

## Compatibility

Same syntax, sampling default and replies as Redis 7 and Valkey 8.

## See also

[MEMORY STATS](https://docs.hotkv.com/commands/memory-stats/index.md), [OBJECT ENCODING](https://docs.hotkv.com/commands/object-encoding/index.md),
[STRLEN](https://docs.hotkv.com/commands/strlen/index.md)