Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis as cache for postgreSql nested data

I'm working on web app using nestJs/postgres/redis.
What is the best way (best data structure) to cache following postgres table (hierarchy) to Redis ?

space:

  • name
  • another attribute
  • users (one2many)

folders:

  • spaceId
  • name
  • users (one2many)

files:

  • folderId
  • spaceId
  • name
  • users (one2many).

I already tried to cache this using key-value where the key is hashed from request and value is response of say getAllMyFiles but there will be some problem Say i want to cache The route:

/my-files

key: users:[USER_ID]:documents:[QUERY-HASH]

the problem is that:

  • i have to cache this for every user and thus the cache will get bigger
  • when updating one file i have to invalidate the entire files-cache for all the users
like image 220
Mansouri Rayen Avatar asked Mar 13 '26 09:03

Mansouri Rayen


2 Answers

I think that the best solution is to use Redis graph

like image 85
Youssef Bourourou Avatar answered Mar 16 '26 03:03

Youssef Bourourou


Could this be a good candidate for RedisJSON? You could store the entire space and all its hierarchy in a single key as JSON using JSON.SET and then query portions of it using JSON.GET.

JSON.SET space:1234 $ '{
  "name": "foo",
  "users": [ "alice", "bob" ],
  "folders": [
    {
      "id": "5678",
      "files": [ 
        {
          "name": "bar"
        },
        ...other files...
      ]
    },
    ...other folders...
  }'

JSON.GET space:1234 $.          # returns the entire space
JSON.GET space:1234 $.folders   # returns the folders for the space
like image 28
Guy Royse Avatar answered Mar 16 '26 03:03

Guy Royse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!