0
0
Redisquery~5 mins

Redis as cache vs data store vs message broker - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Redis as cache vs data store vs message broker
O(1) for cache SET/GET, O(log n) for sorted set add, O(m) for sorted set range, O(s) for publish
Understanding Time Complexity

When using Redis in different roles like cache, data store, or message broker, it's important to understand how the time it takes to do tasks changes as the amount of data or messages grows.

We want to see how Redis handles more data or messages in each role.

Scenario Under Consideration

Analyze the time complexity of these Redis commands in different roles.


# Cache: Set and Get operations
SET user:1 "Alice"
GET user:1

# Data Store: Sorted Set add and range query
ZADD leaderboard 100 "player1"
ZRANGE leaderboard 0 9 WITHSCORES

# Message Broker: Publish and Subscribe
PUBLISH channel1 "Hello"
SUBSCRIBE channel1
    

This code shows basic commands for Redis as a cache, data store, and message broker.

Identify Repeating Operations
  • Primary operation: Each command like SET, GET, ZADD, ZRANGE, PUBLISH, SUBSCRIBE.
  • How many times: These commands run once per request, but many requests happen over time.
  • For ZRANGE, the number of items requested affects how much work Redis does.
  • For PUBLISH, Redis sends messages to all subscribers, so work grows with subscriber count.
How Execution Grows With Input

Let's see how work grows when we increase data or messages.

Input Size (n)Approx. Operations
10About 10 commands, small data sets, few subscribers
100About 100 commands, larger sorted sets, more subscribers
1000About 1000 commands, big sorted sets, many subscribers

Pattern observation: For simple SET/GET, work grows linearly with requests. For sorted sets, work depends on how many items you ask for. For publish, work grows with number of subscribers.

Final Time Complexity

Time Complexity: O(1) for cache SET/GET, O(log n) for sorted set add, O(m) for sorted set range of m items, O(s) for publish with s subscribers

This means simple cache commands take the same time no matter data size, sorted sets take a bit more time as data grows, and publishing messages takes more time as subscribers increase.

Common Mistake

[X] Wrong: "All Redis commands take the same time no matter what."

[OK] Correct: Some commands like SET and GET are very fast and steady, but others like range queries or publishing messages depend on how much data or how many subscribers there are.

Interview Connect

Understanding how Redis handles different tasks helps you explain your choices clearly and shows you know how systems work as they grow. This skill is useful anytime you design or talk about fast data handling.

Self-Check

"What if we changed the number of subscribers in the message broker role? How would the time complexity of PUBLISH change?"