How to Use Redis for Real Time Analytics: Simple Guide
Use
Redis data structures like Sorted Sets, Hashes, and Streams to collect and analyze data instantly. Commands like ZINCRBY and XADD help track events and metrics in real time for fast analytics.Syntax
Redis uses simple commands to update and query data for real time analytics. Key commands include:
ZINCRBY key increment member: Increase score of a member in a sorted set.HINCRBY key field increment: Increment a field in a hash.XADD key ID field value: Add an entry to a stream.ZREVRANGE key start stop WITHSCORES: Get top members by score.
These commands let you count events, track scores, and store time-ordered data efficiently.
redis
ZINCRBY pageviews 1 homepage HINCRBY user:123 clicks 1 XADD events * type click user 123 ZREVRANGE pageviews 0 9 WITHSCORES
Example
This example shows how to track page views per page and get the top pages in real time.
redis
127.0.0.1:6379> ZINCRBY pageviews 1 homepage "1" 127.0.0.1:6379> ZINCRBY pageviews 1 about "1" 127.0.0.1:6379> ZINCRBY pageviews 1 homepage "2" 127.0.0.1:6379> ZREVRANGE pageviews 0 1 WITHSCORES 1) "homepage" 2) "2" 3) "about" 4) "1"
Output
1
1
2
1) "homepage"
2) "2"
3) "about"
4) "1"
Common Pitfalls
Common mistakes when using Redis for real time analytics include:
- Not using the right data structure for the task, causing slow queries.
- Ignoring data expiration, which can lead to memory overload.
- Using blocking commands that slow down real time processing.
- Not batching commands, which reduces performance.
Always choose data structures like sorted sets for ranking and streams for event logs, and set expiration when data is temporary.
redis
Wrong: Using a list to count events (slow to search)
LPUSH events click
Right: Use sorted set to count events
ZINCRBY events 1 clickQuick Reference
| Command | Purpose |
|---|---|
| ZINCRBY key increment member | Increment score in sorted set for ranking |
| HINCRBY key field increment | Increment numeric field in a hash |
| XADD key ID field value | Add event to a stream for time-ordered data |
| ZREVRANGE key start stop WITHSCORES | Get top scored members in descending order |
| EXPIRE key seconds | Set expiration time to free memory |
Key Takeaways
Use Redis sorted sets and streams to track and analyze events instantly.
Choose the right data structure to keep queries fast and memory efficient.
Set expiration on temporary data to avoid memory issues.
Batch commands when possible to improve performance.
Avoid blocking commands in real time analytics scenarios.