Spring › Feature

Designing a multi-reaction toggle system with Spring Data JPA

Enforce one reaction per user with a composite unique key, avoid soft-delete index conflicts, and eliminate N+1 feed counts using a single GROUP BY query.

Designing a multi-reaction toggle system with Spring Data JPA

A single like_count column breaks down as soon as a community needs multiple reaction types, one-choice-per-user rules, and toggle/switch semantics. This post covers the JPA entity design, hard-delete trade-off, loose ID references, and GROUP BY aggregation queries I used to build a five-reaction system backed by PostgreSQL.

Tested with Spring Boot 3.4, Spring Data JPA, Kotlin 2.1, and PostgreSQL 17.

Why a simple counter column falls short

Most early blogs or forums start with a like_count BIGINT DEFAULT 0 column on the articles table and increment it on every click:

1
2
-- Fine for anonymous counters, broken for per-user multi-reactions
UPDATE articles SET like_count = like_count + 1 WHERE id = :articleId;

Once a community introduces five distinct reactions (ANGRY, RELIEVED, SAD, SURPRISED, EMPATHY) with a strict one-reaction-per-user rule, that single column breaks in four ways:

  1. No actor tracking: You can’t tell whether a user already reacted or which emotion they picked, so duplicate clicks go unchecked.
  2. No switch or cancel semantics: Switching from ANGRY to EMPATHY requires decrementing one bucket and incrementing another atomically.
  3. Race conditions under double-clicks: Enforcing “one reaction per user” only in application code fails when a user opens two tabs or double-taps on a flaky network, creating duplicate rows.
  4. N+1 feed queries: Rendering a feed of 20 articles with per-article COUNT(*) calls triggers 20 extra database round-trips per page load.

Five-emoji article reaction bar showing live counts and active selection Figure 1. Five-emotion reaction UI showing the active selection highlight, live counts per type, and single-click switch/cancel behavior.

To solve all four without introducing Redis locks or over-engineered event pipelines, I built the system around four rules: a composite unique constraint in PostgreSQL, hard deletes on cancel, loose ID references instead of @ManyToOne, and single-query GROUP BY aggregation.


Domain modeling: composite unique key and hard deletes

1. Defining the reaction enum

First, define the five reaction types with their display labels:

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/main/kotlin/com/example/server/reaction/domain/ReactionType.kt
package com.example.server.reaction.domain

/**
 * Available article reactions. A user may hold at most one reaction per article.
 */
enum class ReactionType(val label: String) {
    ANGRY("Angry"),
    RELIEVED("Relieved"),
    SAD("Sad"),
    SURPRISED("Surprised"),
    EMPATHY("Empathy"),
}

2. Entity design and database constraints

Three structural decisions shape the Reaction entity:

classDiagram
    class Reaction {
        +Long id PK
        +Long articleId
        +UUID userId
        +ReactionType type
        +Instant createdAt
        +Instant updatedAt
        +change(type: ReactionType)
    }
    note for Reaction "UK: (article_id, user_id)\n- Physical hard delete on cancel\n- Raw IDs only (no @ManyToOne FK)"
  1. Composite unique constraint (uk_article_reaction_user): Putting a unique constraint on (article_id, user_id) pushes concurrency control to PostgreSQL. Even across multiple app instances or rapid double-clicks, the database rejects a second insert for the same pair.
  2. Hard delete instead of soft delete: Most entities in this codebase inherit deleted_at soft-delete behavior for auditability. Reactions intentionally skip it. If a canceled reaction stayed in the table with deleted_at populated, re-reacting to the same article would collide with uk_article_reaction_user (a classic trap I wrote about in resolving JPA soft-delete unique index conflicts). A PostgreSQL partial unique index (WHERE deleted_at IS NULL) avoids the collision, but high-churn toggles still leave dead tombstone rows bloating the table and index. Reactions don’t require trash-bin recovery, so physical deletion is cleaner.
  3. Raw IDs instead of @ManyToOne associations: Storing articleId: Long and userId: UUID decouples reactions from the User lifecycle. When a member deletes their account, historical reaction totals on community articles stay intact instead of cascading deletes or tripping foreign-key errors.
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// src/main/kotlin/com/example/server/reaction/domain/Reaction.kt
package com.example.server.reaction.domain

import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table
import jakarta.persistence.UniqueConstraint
import java.time.Instant
import java.util.UUID

/**
 * Per-user article reaction.
 *
 * - (articleId, userId) unique key enforces one reaction per user per article.
 * - Cancel performs a physical hard delete so re-reacting never hits a unique constraint error.
 * - References article and user by raw ID so user withdrawal preserves reaction statistics.
 */
@Entity
@Table(
    name = "article_reactions",
    uniqueConstraints = [UniqueConstraint(name = "uk_article_reaction_user", columnNames = ["article_id", "user_id"])],
)
class Reaction(
    @Column(name = "article_id", nullable = false, updatable = false)
    val articleId: Long,

    @Column(name = "user_id", columnDefinition = "UUID", nullable = false, updatable = false)
    val userId: UUID,

    type: ReactionType,
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0L

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    var type: ReactionType = type
        protected set

    @Column(nullable = false, updatable = false)
    val createdAt: Instant = Instant.now()

    @Column(nullable = false)
    var updatedAt: Instant = createdAt
        protected set

    fun change(type: ReactionType) {
        if (this.type == type) return
        this.type = type
        updatedAt = Instant.now()
    }
}

The early return inside change(type) prevents Hibernate dirty checking from firing a redundant UPDATE when a user clicks the reaction they already selected.


Repository queries: prefix index reuse and zero N+1

The repository handles single-user lookups, direct DELETE on cancel, detail-page breakdown counts, and batched feed totals:

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
// src/main/kotlin/com/example/server/reaction/domain/ReactionRepository.kt
package com.example.server.reaction.domain

import java.util.UUID
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository

@Repository
interface ReactionRepository : JpaRepository<Reaction, Long> {
    fun findByArticleIdAndUserId(articleId: Long, userId: UUID): Reaction?

    @Modifying
    @Query("DELETE FROM Reaction r WHERE r.articleId = :articleId AND r.userId = :userId")
    fun deleteByArticleIdAndUserId(articleId: Long, userId: UUID): Int

    /** Per-type counts for the article detail page. */
    @Query("SELECT new com.example.server.reaction.domain.ReactionCount(r.type, COUNT(r)) FROM Reaction r WHERE r.articleId = :articleId GROUP BY r.type")
    fun countByType(articleId: Long): List<ReactionCount>

    /** Batched total counts for the article feed (prevents N+1). */
    @Query("SELECT new com.example.server.reaction.domain.ArticleReactionTotal(r.articleId, COUNT(r)) FROM Reaction r WHERE r.articleId IN :articleIds GROUP BY r.articleId")
    fun totalsByArticleIds(articleIds: Collection<Long>): List<ArticleReactionTotal>
}

data class ReactionCount(val type: ReactionType, val count: Long)

data class ArticleReactionTotal(val articleId: Long, val total: Long)

Notice there is no separate index on article_id. Because article_id is the leading column of the composite unique index uk_article_reaction_user(article_id, user_id), PostgreSQL reuses that B-Tree index for both WHERE article_id = ? and WHERE article_id IN (...) lookups (see composite B-Tree index column ordering). Skipping a redundant index keeps write amplification low.


Service layer and zero-filled DTOs

When a user switches reactions, the service updates the existing row in place rather than deleting and re-inserting it. Canceling a reaction that doesn’t exist deletes zero rows and still succeeds, keeping both PUT and DELETE idempotent.

sequenceDiagram
    autonumber
    actor User as "Client"
    participant Ctrl as "ReactionController"
    participant Svc as "ReactionService"
    participant DB as "PostgreSQL"
    User->>Ctrl: PUT /api/v1/articles/{id}/reaction (RELIEVED)
    Ctrl->>Svc: react(articleId, userId, RELIEVED)
    Svc->>DB: SELECT by (article_id, user_id)
    alt Existing reaction found (ANGRY)
        DB-->>Svc: Reaction entity
        Svc->>Svc: reaction.change(RELIEVED) [In-place UPDATE]
    else No existing reaction
        DB-->>Svc: null
        Svc->>DB: INSERT Reaction(articleId, userId, RELIEVED)
    end
    Svc->>DB: SELECT type, COUNT(*) GROUP BY type
    DB-->>Svc: List<ReactionCount>
    Svc-->>Ctrl: ReactionSummaryResponse (5 counts + myReaction)
    Ctrl-->>User: 200 OK
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
40
41
42
43
44
45
46
47
48
49
50
// src/main/kotlin/com/example/server/reaction/application/ReactionService.kt
package com.example.server.reaction.application

import com.example.server.article.domain.ArticleErrorCode
import com.example.server.article.domain.ArticleJpaRepository
import com.example.server.common.BusinessException
import com.example.server.reaction.domain.Reaction
import com.example.server.reaction.domain.ReactionRepository
import com.example.server.reaction.domain.ReactionType
import com.example.server.reaction.dto.ReactionSummaryResponse
import java.util.UUID
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional(readOnly = true)
class ReactionService(
    private val reactionRepository: ReactionRepository,
    private val articleRepository: ArticleJpaRepository,
) {

    @Transactional
    fun react(articleId: Long, userId: UUID, type: ReactionType): ReactionSummaryResponse {
        requireArticle(articleId)
        reactionRepository.findByArticleIdAndUserId(articleId, userId)?.change(type)
            ?: reactionRepository.save(Reaction(articleId = articleId, userId = userId, type = type))
        return summary(articleId, userId)
    }

    @Transactional
    fun cancel(articleId: Long, userId: UUID): ReactionSummaryResponse {
        requireArticle(articleId)
        reactionRepository.deleteByArticleIdAndUserId(articleId, userId)
        return summary(articleId, userId)
    }

    fun summary(articleId: Long, userId: UUID?): ReactionSummaryResponse =
        ReactionSummaryResponse.of(
            counts = reactionRepository.countByType(articleId),
            myReaction = userId?.let { reactionRepository.findByArticleIdAndUserId(articleId, it)?.type },
        )

    fun totals(articleIds: Collection<Long>): Map<Long, Long> =
        if (articleIds.isEmpty()) emptyMap()
        else reactionRepository.totalsByArticleIds(articleIds).associate { it.articleId to it.total }

    private fun requireArticle(articleId: Long) {
        if (!articleRepository.existsById(articleId)) throw BusinessException(ArticleErrorCode.ARTICLE_NOT_FOUND)
    }
}

Zero-filling missing reaction types in the response DTO

GROUP BY r.type omits any reaction type with zero rows. Returning that raw list forces every frontend consumer to write defensive .find(...)?.count ?? 0 lookups. Instead, ReactionSummaryResponse.of iterates over ReactionType.entries to guarantee all five buckets in a fixed order:

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
// src/main/kotlin/com/example/server/reaction/dto/ReactionResponses.kt
package com.example.server.reaction.dto

import com.example.server.reaction.domain.ReactionCount
import com.example.server.reaction.domain.ReactionType
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.NotNull

@Schema(description = "Create or switch a reaction")
data class ReactionRequest(
    @field:NotNull(message = "Please select a reaction type.")
    @Schema(description = "Reaction type", example = "ANGRY")
    val type: ReactionType?,
)

@Schema(description = "Article reaction summary")
data class ReactionSummaryResponse(
    @Schema(description = "Counts for every reaction type (0 when none)") val counts: List<Count>,
    @Schema(description = "Total reaction count", example = "12") val total: Long,
    @Schema(description = "Authenticated user's reaction, or null") val myReaction: ReactionType?,
) {
    data class Count(
        val type: ReactionType,
        @Schema(example = "Angry") val name: String,
        @Schema(example = "3") val count: Long,
    )

    companion object {
        fun of(counts: List<ReactionCount>, myReaction: ReactionType?): ReactionSummaryResponse {
            val byType = counts.associate { it.type to it.count }
            return ReactionSummaryResponse(
                counts = ReactionType.entries.map { Count(it, it.label, byType[it] ?: 0) },
                total = byType.values.sum(),
                myReaction = myReaction,
            )
        }
    }
}

Both PUT and DELETE endpoints return the updated ReactionSummaryResponse directly, so the client updates counts and active state in a single round-trip with no follow-up GET.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/main/kotlin/com/example/server/reaction/presentation/ReactionController.kt
@Tag(name = "Reaction", description = "Article reaction API (authenticated, one per article)")
@RestController
@RequestMapping("/api/v1/articles/{articleId}/reaction")
@SecurityRequirement(name = OpenApiConfig.BEARER_AUTHORIZATION)
class ReactionController(private val reactionService: ReactionService) {

    @PutMapping
    @Operation(summary = "Add or switch reaction", description = "Replaces any existing reaction and returns the updated summary.")
    fun react(
        @PathVariable articleId: Long,
        @Valid @RequestBody request: ReactionRequest,
        @AuthenticationPrincipal jwt: Jwt,
    ): ApiResponse<ReactionSummaryResponse> =
        ApiResponse.ok(reactionService.react(articleId, UUID.fromString(jwt.subject), request.type!!))

    @DeleteMapping
    @Operation(summary = "Cancel reaction", description = "Idempotent hard delete. Succeeds even if no reaction exists.")
    fun cancel(@PathVariable articleId: Long, @AuthenticationPrincipal jwt: Jwt): ApiResponse<ReactionSummaryResponse> =
        ApiResponse.ok(reactionService.cancel(articleId, UUID.fromString(jwt.subject)))
}

200 OK response from PUTapi/v1/articles/1024/reaction Figure 2. PUT /api/v1/articles/1024/reaction returning all five zero-filled counts, total, and myReaction in one response.


Verifying execution plans and integration tests

I verified both aggregation queries on PostgreSQL 17 using EXPLAIN (ANALYZE, BUFFERS).

PostgreSQL 17 EXPLAIN ANALYZE output for reaction aggregation queries Figure 3. PostgreSQL 17 execution plans confirming uk_article_reaction_user prefix scans for detail (0.058 ms) and batched feed (0.091 ms) queries.

1
2
3
4
5
6
7
8
-- Detail page: WHERE r.article_id = 1024 GROUP BY r.type
HashAggregate (cost=8.32..8.37 rows=5 width=16) (actual time=0.038..0.041 rows=5 loops=1)
  Group Key: r.type
  Buffers: shared hit=3
  ->  Index Scan using uk_article_reaction_user on article_reactions r
        Index Cond: (article_id = 1024)
        (actual time=0.012..0.024 rows=118 loops=1)
Execution Time: 0.058 ms
1
2
3
4
5
6
7
-- Feed page: WHERE r.article_id IN (1001..1020) GROUP BY r.article_id
HashAggregate (cost=18.45..18.50 rows=20 width=16) (actual time=0.072..0.075 rows=20 loops=1)
  Group Key: r.article_id
  ->  Bitmap Heap Scan on article_reactions r
        Recheck Cond: (article_id = ANY ('{1001,...,1020}'::bigint[]))
        ->  Bitmap Index Scan on uk_article_reaction_user
Execution Time: 0.091 ms

To lock down the contract end-to-end, I wrote MockMvc integration tests covering four scenarios: full add/switch/cancel/re-add lifecycle, detail and feed aggregation, user withdrawal preservation, and HTTP error responses (401, 400, 404).

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// src/test/kotlin/com/example/server/reaction/ReactionApiTest.kt
@DisplayName("Article Reaction API")
class ReactionApiTest : IntegrationTestSupport() {

    @Test
    fun `user can add, switch, cancel, and re-add a reaction`() {
        val article = createArticle()
        val token = bearer()

        // 1. Add ANGRY -> total 1, all 5 buckets present
        react(article.id, token, "ANGRY").andExpect {
            status { isOk() }
            jsonPath("$.data.myReaction") { value("ANGRY") }
            jsonPath("$.data.total") { value(1) }
            jsonPath("$.data.counts.length()") { value(5) }
        }

        // 2. Switch to RELIEVED -> total stays 1
        react(article.id, token, "RELIEVED").andExpect {
            jsonPath("$.data.myReaction") { value("RELIEVED") }
            jsonPath("$.data.total") { value(1) }
            jsonPath("$.data.counts[0].count") { value(0) }
            jsonPath("$.data.counts[1].count") { value(1) }
        }

        // 3. Cancel via DELETE -> total 0, myReaction null
        mockMvc.delete("/api/v1/articles/${article.id}/reaction") {
            header(HttpHeaders.AUTHORIZATION, token)
        }.andExpect {
            status { isOk() }
            jsonPath("$.data.myReaction") { value(nullValue()) }
            jsonPath("$.data.total") { value(0) }
        }

        // 4. Re-add SAD -> succeeds without UK collision thanks to hard delete
        react(article.id, token, "SAD").andExpect {
            status { isOk() }
            jsonPath("$.data.myReaction") { value("SAD") }
            jsonPath("$.data.total") { value(1) }
        }
    }

    @Test
    fun `reaction count persists after user withdraws`() {
        val article = createArticle()
        val leaver = createUser()
        react(article.id, "Bearer ${accessTokenOf(leaver)}", "SURPRISED")

        userService.withdraw(leaver.id!!)

        mockMvc.get("/api/v1/articles/${article.id}").andExpect {
            jsonPath("$.data.reactions.total") { value(1) }
        }
    }
}

Trade-offs and when not to use live GROUP BY

Design choiceApproachBenefit and trade-off
One reaction per userComposite unique key (article_id, user_id)DB-enforced concurrency safety without Redis locks; handle DataIntegrityViolationException on rare concurrent first-inserts
Cancel lifecyclePhysical hard deletePrevents unique index conflicts on re-react and avoids soft-delete bloat; loses cancel history
User couplingRaw userId: UUID columnKeeps totals intact after account withdrawal; skips unnecessary joins
Response shapeServer-side zero-fill across all 5 enumsRemoves null-guard boilerplate on the frontend; returns latest state in one round-trip
Feed countsBatched IN (...) GROUP BYSingle 0.09 ms query eliminates N+1 on paginated feeds

When not to use live GROUP BY aggregation
Live GROUP BY over an indexed table stays sub-millisecond for articles with hundreds or low thousands of reactions. If a viral post accumulates 100,000+ reactions under heavy read traffic, scanning that many index entries on every page view will heat up CPU. At that scale, move to a denormalized counter cache (or Redis hash) updated asynchronously, while keeping article_reactions as the source of truth.

Checklist

  • Put article_id first in (article_id, user_id) so WHERE article_id = ? and IN (...) reuse the unique index.
  • Use hard delete for toggleable reactions unless compliance strictly requires cancel history.
  • Guard change(type) against same-value updates so Hibernate doesn’t emit no-op UPDATE statements.
  • Return zero-filled counts and myReaction directly from PUT/DELETE to avoid extra client fetches.
This post is licensed under CC BY 4.0 by the author.