How would you model a many to many relationship, such as users following other users, using Redis's native data types?
Short answer
You could use a set for each user storing the ids of users they follow, and a separate set for each user storing the ids of their followers, letting you efficiently check if one user follows another, count followers, or find the intersection of two users' follow lists, all using…
Advertisement
AModel answer
You could use a set for each user storing the ids of users they follow, and a separate set for each user storing the ids of their followers, letting you efficiently check if one user follows another, count followers, or find the intersection of two users' follow lists, all using Redis's native set operations.
Example
SADD following:user1 'user2' 'user3' SADD followers:user2 'user1' SINTER following:user1 following:user4 -- mutual follows
Real-world example
A social networking application models its follow relationships using sets for each user's following and followers lists, taking advantage of Redis's fast set intersection command to quickly find mutual connections between two users.
Likely follow-ups
- How do you keep both the following and followers sets consistent when a follow relationship changes?
- What are the memory implications of this approach for users with millions of followers?
Related topics