Advertisement
Intermediate Redis, Sets & Sorted Sets in Redis

How do you retrieve a random member, or several random members, from a Redis set without removing them?

Short answer

You use the SRANDMEMBER command, optionally specifying a count of how many random members to retrieve, which returns one or more randomly selected members from the set without removing them, useful for features like randomly selecting a winner from a set of contest entries or…

Save Redis mock interview
Advertisement
AModel answer
You use the SRANDMEMBER command, optionally specifying a count of how many random members to retrieve, which returns one or more randomly selected members from the set without removing them, useful for features like randomly selecting a winner from a set of contest entries or showing a random sample of items.
Example

SRANDMEMBER contest_entries 1 SRANDMEMBER contest_entries 5 -- returns 5 random unique members

Real-world example
A contest application randomly selects a winner from a set of eligible entries using SRANDMEMBER, ensuring a fair, unbiased random selection process without needing to implement custom randomization logic.
Likely follow-ups
  • What is the difference between SRANDMEMBER and SPOP for this kind of use case?
  • What happens if you request more random members than actually exist in the set?
Related topics