# MSETEX

> Set several keys in one step with a shared condition and time to live.

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

```
MSETEX numkeys key value [key value ...] [NX | XX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]
```

- Group: String
- Complexity: O(N) for N keys
- HotKV Cloud: all plans
- On-Premise: no license needed

`MSETEX` writes `numkeys` key-value pairs as one step and gives them all the
same time to live. With `NX` or `XX` the pairs are written only if the
condition holds for every key; otherwise nothing is written.

In a cluster, all keys must hash to the same slot.

## Options

| Option | Effect |
| --- | --- |
| `NX` | Write only if none of the keys exist. |
| `XX` | Write only if all of the keys exist. |
| `EX seconds` | Expire after this many seconds. |
| `PX milliseconds` | Expire after this many milliseconds. |
| `EXAT unix-time-seconds` | Expire at this Unix time, in seconds. |
| `PXAT unix-time-milliseconds` | Expire at this Unix time, in milliseconds. |
| `KEEPTTL` | Keep each key's current time to live. |

Options come after the pairs, in any order. `NX` and `XX` cannot be combined,
and only one kind of time can be given. Without a time option the keys have
no time to live. A time must be a positive integer; an absolute time that has
already passed writes the keys and they are gone at once.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| The keys were written | Integer `1` | Integer `1` |
| `NX` or `XX` prevented the write | Integer `0` | Integer `0` |

Errors:

- `ERR invalid numkeys value` when `numkeys` is not a positive integer.
- `ERR wrong number of key-value pairs` when fewer pairs follow than
  `numkeys` says.
- `ERR syntax error` for an unknown option, `NX` with `XX`, or two different
  kinds of time.
- `ERR value is not an integer or out of range` and
  `ERR invalid expire time in 'msetex' command` for a bad time.

## Examples

```
127.0.0.1:6379> MSETEX 2 rate:a 0 rate:b 0 EX 60
(integer) 1
127.0.0.1:6379> TTL rate:b
(integer) 60
127.0.0.1:6379> MSETEX 2 rate:a 5 rate:c 5 NX PX 500
(integer) 0
127.0.0.1:6379> MSETEX 2 rate:a 5 rate:b 5 XX KEEPTTL
(integer) 1
```

## Compatibility

Not available in Redis 7 or Valkey 8. It follows the `MSETEX` command added in
Redis 8.4.

## See also

[MSET](https://docs.hotkv.com/commands/mset/index.md), [MSETNX](https://docs.hotkv.com/commands/msetnx/index.md),
[SET](https://docs.hotkv.com/commands/set/index.md), [SETEX](https://docs.hotkv.com/commands/setex/index.md)