Deduplicating article views with Redis SETNX and JPA
Use an atomic Redis write and a JPQL bulk update to count article views once per 24 hours while preserving article reads during cache failures.
Repeated refreshes were inflating article view counts. I used Redis to reserve one count per article and client for 24 hours, then left the increment itself to the database.
The examples use Kotlin 1.9, Java 21, Spring Boot 3.5, Spring Data Redis, and Spring Data JPA.
Choosing the deduplication window
| Approach | Storage | Advantage | Limitation |
|---|---|---|---|
| Cookie or localStorage | Client | No server-side record per visit | A client can discard the record or request the endpoint directly |
| Relational view log | Database | Durable history for aggregation | Each qualifying visit inserts a row, and retention requires cleanup |
| Redis keys with a TTL | In-memory store | Atomic claims and automatic expiration | Adds an infrastructure dependency to the count path |
I used a 24-hour Redis key to avoid keeping a permanent database log for a number displayed next to an article. The window starts when the first qualifying request writes the key. A visit 12 hours later won’t move the deadline.
The key includes the article ID, IP address, and a digest of the User-Agent. An IP address alone would group everyone behind the same public Wi-Fi router. A User-Agent narrows that grouping, although visitors on the same network can still share the same browser signature.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// article/domain/ArticleView.kt
package org.project.portfolio.article.domain
import java.security.MessageDigest
data class ArticleView(
val id: String,
val articleId: Long,
val ip: String,
val userAgent: String,
) {
companion object {
fun createKey(
articleId: Long,
ip: String,
userAgent: String,
): String {
val newIp: String = ip.replace(':', '.')
val hashUserAgent: String = MessageDigest.getInstance("SHA-256")
.digest(userAgent.toByteArray())
.joinToString("") { "%02x".format(it) }
.take(10)
return "$articleId:${newIp}_$hashUserAgent"
}
}
}
Replacing an IPv6 address’s colons keeps the address distinct from the key’s separators. Keeping the first 10 hexadecimal digits of the SHA-256 digest bounds the size of a long User-Agent string. Two visitors can still collide or change their identity by changing clients, so I treat this as approximate engagement data.
Making the claim atomic
The first implementation used @RedisHash and a CrudRepository. It called findByIdOrNull and saved a record when it found none. Two threads can both read a miss before either saves. That time-of-check to time-of-use race lets both requests increment the count.
The repository mapping also maintains an auxiliary set alongside the Redis hash. That set can outlive an individual hash entry and costs memory and additional work. A single string key is enough to represent this expiring claim.
Figure 1. The repository mapping creates a hash and a separate set.
I kept the JSON RedisTemplate for general caching and used the auto-configured StringRedisTemplate for view markers. opsForValue().setIfAbsent(viewKey, "1", Duration.ofHours(24)) issues SET key "1" NX EX 86400. Redis checks the key’s absence, writes the value, and assigns the expiration in one operation. One caller gets true for a given absent key. Requests arriving before expiration skip the write to the database. Redis SET command
flowchart TD
A["GET /api/v1/articles/{id}"] --> B["Redis SET NX EX 86400"]
B -->|"First view"| C["Increment count"]
B -->|"Duplicate"| D["Skip increment"]
B -.->|"Cache error"| E["Log and continue"]
C --> F["Return article"]
D --> F
E --> F
Incrementing the counter in the database
Two different clients can both have valid Redis claims for the same article. The database update still needs to handle that concurrency. With article.viewCount++, both transactions might read the same old value, and the later write can overwrite the earlier one. Updating the managed entity can also fire Spring Data JPA auditing and change updatedAt on a plain article read.
1
2
3
4
5
6
7
8
9
10
11
12
// article/domain/ArticleRepository.kt
@Repository
interface ArticleRepository : JpaRepository<Article, Long> {
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(
"""
update Article a
set a.viewCount = a.viewCount + 1
where a.id = :id""",
)
fun increaseViewCount(id: Long): Int
}
The JPQL update tells the database to add one to the current value in the row. It also bypasses entity auditing, so the modification date keeps describing content changes. Bulk updates bypass the persistence context as well. flushAutomatically = true writes pending entity changes before the update, and clearAutomatically = true detaches loaded instances afterward. A subsequent load can see the new count instead of returning an already-managed Article with a stale field. Spring Data JPA modifying queries
Keeping the article read available
I validate that the article exists before trying Redis so a missing article still returns 404. If Redis is unavailable, the view count is secondary to returning the article. The sample logs failures from the count attempt and lets the controller proceed with its separate read.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// article/application/ArticleQueryService.kt
@Service
@Transactional(readOnly = true)
class ArticleQueryService(
private val articleRepository: ArticleRepository,
private val stringRedisTemplate: StringRedisTemplate,
) {
@Transactional
fun increaseArticleViewCount(
articleId: Long,
ip: String,
userAgent: String,
) {
if (!articleRepository.existsById(articleId)) {
throw NotFoundException(Article::class.java, mapOf("articleId" to articleId))
}
try {
val viewKey = "$ARTICLE_VIEW_KEY_PREFIX${ArticleView.createKey(articleId, ip, userAgent)}"
val isFirstView = stringRedisTemplate.opsForValue()
.setIfAbsent(viewKey, "1", VIEW_TTL) == true
if (isFirstView) {
articleRepository.increaseViewCount(articleId)
logger.info {
mapOf("articleId" to articleId, "ip" to ip, "userAgent" to userAgent)
}
}
} catch (e: Exception) {
logger.warn(e) { "Could not update the article view count: articleId=$articleId" }
}
}
companion object {
private const val ARTICLE_VIEW_KEY_PREFIX = "article_views:"
private val VIEW_TTL: Duration = Duration.ofHours(24)
private val logger: KLogger = KotlinLogging.logger {}
}
}
The catch block in this sample also surrounds the database increment. A database failure can mark the write transaction rollback-only, which can still surface when Spring tries to commit it. Redis and JPA also commit independently. If the Redis claim succeeds and the SQL update fails, that visit can be undercounted until the key expires. Both behaviors matter when deciding whether this count is important enough to move to a durable pipeline.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// article/presentation/ArticleController.kt
@GetMapping("/{articleId}")
@Operation(summary = "Get article details")
fun getArticle(
@PathVariable @Parameter(description = "Article ID") articleId: Long,
request: HttpServletRequest,
): ResponseEntity<ArticleResponse> {
articleQueryService.increaseArticleViewCount(
articleId = articleId,
ip = request.remoteAddr,
userAgent = request.getHeader("User-Agent") ?: "Unknown User-Agent",
)
return ResponseEntity.ok(
articleQueryService.getArticle(articleId),
)
}
The controller calls the two service methods separately through the Spring proxy. That preserves the writable @Transactional boundary around the increment and the service’s readOnly = true boundary around the article lookup. Calling the write method from another method on the same service instance would skip proxy interception.
Testing the counter behind a proxy
Behind Nginx or an AWS Application Load Balancer, request.remoteAddr can identify the proxy. Spring Boot can process forwarded headers if the proxy sets them and the application is configured to use them. Spring Boot proxy configuration
1
2
3
# src/main/resources/application-prod.yml
server:
forward-headers-strategy: framework
The trusted proxy must sanitize incoming forwarding headers before adding its own values. Client-supplied
X-Forwarded-Forotherwise changes the apparent identity used for counting. For billing or other features where counts need an audit trail, use a durable identity and recorded events.
- Send concurrent requests with the same article ID, address, and User-Agent. Expect a single increment before the key expires.
- Change the article ID or the client identity and verify that the second claim is independent.
- Compare the article’s modification timestamp before and after a view to check that it retains its previous value.
- Stop Redis and verify that an existing article still loads and a missing one still returns
404.
