MSETEX saves several keys and gives them all the same expiry in one step, like MSET and EXPIRE together. This guide saves two one-time codes in Valkey® that delete themselves after 60 seconds.
Type the commands at the valkey-cli prompt. To open it, run valkey-cli in a terminal.
Note: Every command and output on this page is real, run on Valkey 9.2 on an Apple silicon Mac with macOS 26.
Syntax
MSETEX numkeys key value [key value ...] [NX | XX]
[EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]
numkeys: how many key and value pairs follow.key value: each key and its value.NX: save only if none of the keys exist.XX: only if all of them exist.EX seconds,PX milliseconds,EXATorPXAT: when the keys expire.KEEPTTL: keep their current expiry.
From the MSETEX documentation (opens in a new tab).
Prerequisites
- Valkey 9.1 or later.
Step 1: Save Two Codes with One Expiry
MSETEX 2 code:a "4821" code:b "9307" EX 60
(integer) 1
1 means every key was saved.
Step 2: Read the Codes and Their Time Left
MGET code:a code:b
1) "4821"
2) "9307"
TTL code:a
(integer) 58
TTL code:b
(integer) 57
TTL shows the seconds left. When it reaches zero, Valkey deletes the key.
Step 3: Save Only If None Exist with NX
MSETEX 2 code:a "1111" code:c "2222" NX EX 60
(integer) 0
GET code:c
(nil)
0: code:a exists, so nothing was saved, and code:c wasn’t created.

Clean Up
The codes delete themselves after 60 seconds. To remove them now:
DEL code:a code:b
(integer) 2
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Giving a numkeys that doesn’t match the pairs | Valkey reads the arguments wrongly | Count the key and value pairs |
Expecting NX to save the free keys | Nothing is saved if any key exists | Check the reply: 1 saved, 0 not |
Troubleshooting
| Problem | Cause | Fix |
|---|---|---|
(error) ERR unknown command 'MSETEX', with args beginning with: '2' 'code:a' '4821' 'code:b' '9307' 'EX' '60' | Your Valkey is older than 9.1 | Upgrade to Valkey 9.1 or later |
FAQ
Do all the keys expire at the same moment?
Yes. MSETEX gives every key the same expiry.
Can I keep the expiry the keys already have?
Yes: use KEEPTTL instead of EX.
Conclusion
MSETEX saves several keys with one shared expiry in a single, all-or-nothing step.
Related
- Valkey Tutorial — Part 4: Strings and Counters
- Valkey Tutorial — Part 2: Your First Valkey Commands with valkey-cli
Additional Resources
Valkey® is a registered trademark of LF Projects, LLC. Redis® is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with the Valkey project, LF Projects or Redis Ltd., and isn’t endorsed, supported or certified by them.
0 comments