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.

const jsonData = {
    name: "xyz",
    players: [1,2,4,7],
    positions: [
        [/*position of 1*/],
        [/*position of 2*/],
        [/*position of 4*/],
        [/*position of 7*/]
    ],
    gameStart: true,
    fee: 100,
    turnIndex: 12
}
JSON data to store

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.

// storing the data
const jsonString = JSON.stringify(jsonData)
const gameName = "roomName12"
redis.set(gameName, jsonString)

// retrieving the data
const data = redis.get(gameName)
const parsedJsonData = JSON.parse(data)
Storing and Retrieving in Redis

Pros:

  1. easy to work
  2. JSON string and JSON parse was relatively easy to get started

Cons:

  1. heavy to parse and make string because my use-case would do that frequently
  2. if I needed to check one value, eg: turnIndex, I had to get the whole gameState from REDIS and again set the whole gameState 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:

  1. we can get all or individual fields based on our need
  2. it eliminates the whole parsing thing with the former approach

Cons:

  1. can store only numbers or strings as values
  2. 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:

  1. natively supports JSON

Cons:

  1. not a good npm package to work with
  2. 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!