Site icon JD Bots

Valkey Key Naming Conventions: How to Name Your Keys

Valkey® keeps all the keys of a database side by side. There are no tables or folders, so a key’s name is the only thing that tells you what it holds. A naming habit keeps thousands of keys readable and easy to find.

The Pattern: object:id:field

Valkey’s keyspace documentation recommends sticking to a pattern such as object-type:id, as in user:1000. Add a field when one object has several keys:

For a field with several words, the docs suggest a dot or a dash inside the part, as in comment:4321:reply-to.

Prerequisites

Step 1: Save a Book’s Details Under One Prefix

valkey-cli
SET book:4:title "Salt and Starlight"
OK
SET book:4:author "Nadia Quill"
OK
SET book:4:price 9.99
OK

Step 2: Find Them All with SCAN

SCAN 0 MATCH book:4:* COUNT 100
1) "0"
2) 1) "book:4:title"
   2) "book:4:author"
   3) "book:4:price"

Because every key about book 4 starts with book:4:, one pattern finds them all.

A shared prefix makes related keys easy to find.

Rules That Keep Key Names Useful

Clean Up

DEL book:4:title book:4:author book:4:price
(integer) 3
exit

Common Mistakes

MistakeWhat happensDo this instead
Mixing separators, as in book.4.title next to book:4:titleOne SCAN pattern no longer finds all the keys of a kindUse one separator everywhere
Short codes such as u1000flwNobody can tell what the key holdsSpell it out: user:1000:followers

FAQ

Do I have to use colons?

No. Valkey accepts any sequence of bytes as a key, even an empty string. The colon is simply the most common convention.

How long can a key be?

The docs give a maximum key size of 512 MB, but recommend keeping keys short, because long keys cost memory and slow down lookups.

Should a book be one hash instead of several keys?

Often, yes. Part 6 of the Valkey Tutorial stores each book as one hash with fields. The same naming habit applies to the hash’s key, book:4.

Conclusion

Name keys object:id:field, keep them readable and short, and stick to one separator. Then a single SCAN pattern finds everything about one object.

Related

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.

Exit mobile version