Many modern applications need to track events in real time, such as page views, product clicks, downloads, or API usage. Traditional databases can struggle with very high write rates, but Redis handles these workloads efficiently.
Redis provides
atomic counters, which allow applications to increment values safely and quickly even under heavy traffic. This article explains how to build real-time analytics counters using Redis and Spring Boot.
1. What Are Redis Counters
A Redis counter is simply a numeric value stored in Redis that can be incremented or decremented atomically.
Example counters:
pageviews:homepage
clicks:product:101
api:requests
Each event increases the counter.
Advantages:
- Extremely fast
- Atomic operations
- Works well under high concurrency
2. Creating a Counter Service
Create a service to manage counters.
@Service
public class AnalyticsService {
@Autowired
private RedisTemplate<String, Long> redisTemplate;
public Long incrementCounter(String key) {
return redisTemplate.opsForValue().increment(key);
}
}
This method increments the counter every time an event occurs.
3. Tracking Page Views
Example for counting page visits.
public Long trackPageView(String page) {
String key = "pageviews:" + page;
return redisTemplate.opsForValue().increment(key);
}
Example keys:
pageviews:home
pageviews:products
pageviews:contact
Each request increases the page view count.
4. Tracking Product Clicks
Example for product interaction analytics.
public Long trackProductClick(Long productId) {
String key = "clicks:product:" + productId;
return redisTemplate.opsForValue().increment(key);
}
Example result:
clicks:product:101 = 250
clicks:product:102 = 180
5. Setting Counter Expiration
For time-based analytics, counters can expire automatically.
Example:
redisTemplate.opsForValue()
.increment("pageviews:daily");
redisTemplate.expire("pageviews:daily",
Duration.ofDays(1));
This creates
daily counters that reset automatically.
6. Exposing Analytics via REST API
Example controller:
@RestController
@RequestMapping("/analytics")
public class AnalyticsController {
@Autowired
private AnalyticsService analyticsService;
@PostMapping("/pageview")
public Long trackPage(@RequestParam String page) {
return analyticsService.trackPageView(page);
}
}
Example request:
POST /analytics/pageview?page=home
Each request increases the counter.
7. Building Trending Metrics
Combine counters with Redis Sorted Sets to create trending data.
Example:
redisTemplate.opsForZSet()
.incrementScore("trending-products",
productId.toString(),
1);
Now Redis automatically ranks the most popular products.
8. Scaling Analytics Systems
Redis analytics can handle millions of events per second.
For large systems:
- Use Redis clusters
- Partition counters by date
- Archive historical data to a database
Example key design:
pageviews:2026-03-09
clicks:product:101:2026-03-09
api:requests:minute
image quote pre code