DeployU
Interviews / Databases / What are the different data structures in Redis and when would you use them?

What are the different data structures in Redis and when would you use them?

conceptual Data Structures Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a social media company. You are designing a new service that needs to store a variety of different types of data, such as user profiles, posts, and timelines.

You have decided to use Redis for this service, but you are not sure which data structures to use for each type of data.

The Challenge

Explain the different data structures in Redis and when you would use them. What are the pros and cons of each data structure, and which one would you choose for each of the different types of data in this use case?

Wrong Approach

A junior engineer might try to store all the data as strings. This would work, but it would be very inefficient and would not take advantage of the powerful data structures that are available in Redis.

Right Approach

A senior engineer would know that Redis has a variety of different data structures that are each designed for a specific use case. They would be able to explain the pros and cons of each data structure and would have a clear plan for how to use them to model the data for this use case.

Step 1: Understand the Key Data Structures

Data StructureDescriptionUse Cases
StringsThe simplest data structure in Redis. Can store any type of data, such as a string, an integer, or a float.Caching, counters.
ListsA list of strings, sorted by insertion order.Queues, timelines.
SetsAn unordered collection of unique strings.Tags, unique visitors.
HashesA collection of key-value pairs.User profiles, product catalogs.
Sorted SetsA collection of unique strings that are sorted by a score.Leaderboards, rate limiting.

Step 2: Choose the Right Tool for the Job

Data TypeRecommended Data Structure
User profilesHashes
PostsHashes
TimelinesLists or Sorted Sets

Step 3: Code Examples

Here are some code examples that show how to use some of these data structures:

Hashes:

HSET user:123 name "John Smith"
HSET user:123 email "john.smith@example.com"

Lists:

LPUSH timeline:123 "post:456"
LPUSH timeline:123 "post:789"

Sorted Sets:

ZADD leaderboard 100 "user:123"
ZADD leaderboard 200 "user:456"

Practice Question

You are building a real-time leaderboard for a gaming application. Which of the following would be the most appropriate?