# XTRIM

> Remove the oldest entries of a stream by length or by minimum ID.

URL: https://docs.hotkv.com/commands/xtrim/

```
XTRIM key MAXLEN | MINID [= | ~] threshold [LIMIT count]
```

- Group: Stream
- Complexity: O(N), N being the entries removed
- HotKV Cloud: all plans
- On-Premise: no license needed

`XTRIM` removes entries from the start of the stream at `key`, either until it
holds at most `threshold` entries (`MAXLEN`) or until no entry has an ID lower
than `threshold` (`MINID`). It returns the number of entries removed.

## Options

| Option | Effect |
| --- | --- |
| `MAXLEN threshold` | Keep at most `threshold` entries (a non-negative integer). |
| `MINID threshold` | Remove entries with an ID lower than `threshold` (a stream ID). |
| `=` | Trim exactly (the default). |
| `~` | Approximate trim: the server may keep some extra entries so the trim is cheaper. |
| `LIMIT count` | With `~`, remove at most `count` entries in this call (`0` means no cap). |

Exactly one of `MAXLEN` and `MINID` is required. `LIMIT` needs `~`. Without
`LIMIT`, an approximate trim removes at most 100 times
`stream-node-max-entries` entries per call (10,000 with the default setting),
so trimming a long stream can take several calls.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Always | Integer: the number of entries removed | Integer |

A missing key replies `0`.

Error replies:

- `ERR syntax error` when no strategy is given or an argument is not recognized.
- `ERR The MAXLEN argument must be >= 0.` and `ERR The LIMIT argument must be >= 0.`
- `ERR syntax error, MAXLEN and MINID options at the same time are not compatible`
- `ERR syntax error, LIMIT cannot be used without the special ~ option`
- `ERR Invalid stream ID specified as stream command argument` for a bad `MINID`.
- `WRONGTYPE` if the key holds another type.

## Examples

```
127.0.0.1:6379> XADD metrics 1700000000000-0 v 1
"1700000000000-0"
127.0.0.1:6379> XADD metrics 1700000000001-0 v 2
"1700000000001-0"
127.0.0.1:6379> XADD metrics 1700000000002-0 v 3
"1700000000002-0"
127.0.0.1:6379> XTRIM metrics MAXLEN 2
(integer) 1
127.0.0.1:6379> XTRIM metrics MINID 1700000000002
(integer) 1
127.0.0.1:6379> XLEN metrics
(integer) 1
```

## Compatibility

Same options and replies as Redis 7 and Valkey 8.

## See also

[XADD](https://docs.hotkv.com/commands/xadd/index.md), [XDEL](https://docs.hotkv.com/commands/xdel/index.md), [XLEN](https://docs.hotkv.com/commands/xlen/index.md)