Course outline

Redis / Basic: keys and bounded data structures / Lesson 5

Sets, sorted sets and ranked models

Choose membership or score ordering deliberately and define ties, uniqueness and score precision. Use bounded access patterns instead of assuming all collections are ordered lists.

About 4 min readContent reviewed
On this page

Lesson goals

  • Distinguish set membership from sorted-set scores and ranks.
  • Define deterministic ties and appropriate numeric domains.

A set represents unique members without sequence

Redis sets contain unique string members and support membership and set operations. Re-adding a member does not create a second copy, but no insertion-order contract follows. Use a set for participation or entitlement identifiers when membership is the intended fact, with appropriate authorization elsewhere. Fetching every member of a huge set can be expensive; bounded iteration and cardinality checks may be preferable. A set membership record can still be stale or lost under the chosen expiry, eviction and persistence policy, so a critical permission decision needs an explicit authority and freshness model.

Count new members rather than submitted arguments

Assume the synthetic set is absent. SADD adds two members, and adding member-a again returns zero new members. SCARD remains two and SISMEMBER reports that member-a is present. SMEMBERS could return the pair in either order, so the course does not fabricate a sorted result for an unordered structure. These replies are reasoned from the fixture. Deduplicating member names is not equivalent to deduplicating arbitrary business effects; a separate payment action needs its own stable event identity and outcome protocol.

redis Illustrative set membership fixture
SADD lab:participants member-a member-b
SADD lab:participants member-a
SCARD lab:participants
SISMEMBER lab:participants member-a
Expected output
2
0
2
1

Expected numeric replies are 2, 0, 2 and 1. No member ordering is implied.

A sorted set associates one score with each member

A sorted set keeps unique members with numeric scores. Updating an existing member’s score changes its position rather than adding another copy. Equal scores are ordered by binary lexicographic member comparison in the ordinary sorted-set model, so define whether that tie rule matches the report. Scores use floating-point representation; do not assume arbitrary large integers or exact money remain precise. A leaderboard score, a scheduled-time index and a financial balance have different requirements even if each looks like a number. Record rank direction and whether displayed ranks start at zero or one.

Check the intended score and tie contract locally

The offline model orders three synthetic members by descending integer score and ascending member name for ties. It is an application report policy, not an exact emulation of every Redis ZRANGE direction and tie behavior. In particular, reversing a Redis sorted-set range reverses its order, including the associated tie order. Select and test the real command form that matches the desired presentation, or transform a bounded result deliberately. Never infer ranking semantics from a screenshot that happens to contain no ties.

python Offline report-ranking policy
scores = {'member-b': 20, 'member-a': 20, 'member-c': 10}
report = sorted(scores, key=lambda member: (-scores[member], member))
assert report == ['member-a', 'member-b', 'member-c']
assert len(scores) == 3

The result demonstrates the stated application tie rule only. Redis reverse-range ties require their own verified command semantics.

Avoid converting every membership question into a full read

Use membership, cardinality or bounded rank/range operations when they answer the actual question. Large intersections, unions and complete result transfers can consume server time and client memory. Pagination over changing scores is not automatically a stable snapshot; members can move between pages. Expiry normally applies at key level for these core structures, so element lifecycle may need another model. Evaluate whether a key becomes a hot shared ranking or membership point, and align its durability and rebuild policy with the authoritative source before claiming the sorted structure is a permanent ledger.

Common errors and fixes

A set is displayed as insertion ordered

Why it happens
Unordered membership was treated as a list.
How to fix it
Choose an ordered structure or sort a bounded result under a stated policy.
Prevent it next time
Test output order rather than relying on one observed iteration.

Equal scores produce unexpected ranking order

Why it happens
Binary member tie order or REV behavior was overlooked.
How to fix it
Define ties and verify the selected command direction.
Prevent it next time
Include equal-score fixtures and rank-display rules.

A score loses numeric precision

Why it happens
An unsuitable numeric domain was stored as a floating score.
How to fix it
Use a representation and authoritative store appropriate to the exactness requirement.
Prevent it next time
Test score bounds and avoid treating scores as arbitrary exact financial values.

Check your understanding

1. A participant is added to a set twice. What does the second zero reply mean?

Show worked solution

No new member was added because that member already existed. It is not a transport failure or proof that a related external action occurred only once. Interpret the command’s new-member count according to the membership contract, then coordinate any separate notification or payment with its own event identity.

2. A descending leaderboard needs alphabetical ascending ties. Can a reverse Redis range be assumed to provide that?

Show worked solution

No. Reversing the sorted-set order also reverses its tie ordering. Verify the documented command behavior and choose an explicit bounded transformation or a model that implements the desired tie policy. Distinguish application display requirements from Redis’s native rank order and test multiple equal scores.

Key takeaways

  • Membership uniqueness, sequence and score ordering are different facts.
  • Tie rules, numeric precision and bounded reads belong in the model.

Official references