database/redis datastructures

Redis sorted sets | Docs

Introduction

A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically.

Features:

  • Unique values(No duplicates)
  • Sorted by score
  • Efficient ranking operations

Use Cases:

  • Leaderboards. For example, you can use sorted sets to easily maintain ordered lists of the highest scores in a massive online game.
  • Rate limiters. In particular, you can use a sorted set to build a sliding-window rate limiter to prevent excessive API requests.

You can think of sorted sets as a mix between a Set and a Hash. Like sets, sorted sets are composed of unique, non-repeating string elements, so in some sense a sorted set is a set as well.


Example (Redis CLI)

Add members

ZADD leaderboard 100 "Alice"
ZADD leaderboard 200 "Bob"
ZADD leaderboard 150 "Charlie"

Get by range

ZRANGE leaderboard 0 -1 WITHSCORES
 
ZREVRANGE leaderboard 0 2 WITHSCORES


Get Rank

ZRANK leaderboard "Charlie"
 
ZREVRANK leaderboard "Charlie"

Increment Score

ZINCRBY leaderboard 50 "Alice"

Remove member

ZREM leaderboard "Charlie"


LeaderBoard
Rate Limiting a Golang API using Redis - DEV Community
Redis: Leaky-bucket rate-limiting [no dependencies]
⭐ Go Redis Lua Scripting
GitHub - redis-developer/basic-redis-rate-limiting-demo-nodejs: This is a basic Redis Rate Limiting demo written in NodeJS