The project I was working on was a turn-based multiplayer game. It needed to store a game state. The game state had multiple fields to be stored for a single game. I had an object of the game state that needed to be accessed fast for players in other servers. So I chose Redis.
Storing as string
Redis stores data as key-value pair. One approach is to convert JSON to string and save it in the key. While getting and working, I had to parse the string back to JSON.
Pros:
- easy to work
- JSON string and JSON parse was relatively easy to get started
Cons:
- heavy to parse and make string because my use-case would do that frequently
- if I needed to check one value, eg:
turnIndex
, I had to get the wholegameState
from REDIS and again set the wholegameState
after being modified.
Storing as a hash set
Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects.
Pros:
- we can get all or individual fields based on our need
- it eliminates the whole parsing thing with the former approach
Cons:
- can store only numbers or strings as values
- eg: if I need to store an array, I need to store it as a string, then retrieve and parse the string again to the array.
Storing as JSON using Redis-JSON module
RedisJSON provides in-memory manipulation of JSON documents at high velocity and volume. With RedisJSON, you can natively store document data in a hierarchical, tree-like format to scale and query documents efficiently, significantly improving performance over storing and manipulating JSON with Lua and core Redis data structures.
Pros:
- natively supports JSON
Cons:
- not a good npm package to work with
- RedisJSON module doesn't come default with Redis installation, it is required to be installed as docker image or downloading and loading module into Redis.
Final thoughts
I shared just an experience and with not many details. If you want to try it out then you should clearly follow Redis documentation and modules. Thank you!