Skip to content

STR-102: replace direct Kafka publishing with transactional outbox pattern and add missing ArchUnit rules - #123

Merged
Puneethkumarck merged 2 commits into
mainfrom
feature/STR-102-outbox-pattern-and-archunit-rules
Mar 31, 2026
Merged

Puneethkumarck merged 2 commits into
mainfrom
feature/STR-102-outbox-pattern-and-archunit-rules

Conversation

@Puneethkumarck

@Puneethkumarck Puneethkumarck commented Mar 31, 2026 •

Copy link
Copy Markdown
Owner

STR Issue

Closes #122

Changes

  • Replace KafkaTransactionEventPublisher (direct Kafka fire-and-forget) with transactional outbox pattern per ADR Section 6
  • Add outbox_event table via Flyway V13 migration with partial index on PENDING status
  • Add OutboxTransactionEventPublisher that persists events to DB within a transaction (implements TransactionEventPublisher port)
  • Add OutboxEventRelay scheduled poller that dispatches pending outbox events to Kafka with retry tracking (max 5 retries before FAILED)
  • Add outbox infrastructure: OutboxEventEntity, OutboxEventJpaRepository, OutboxEventPersister, OutboxEventReader
  • Wire outbox beans in KafkaConfig with @EnableScheduling
  • Add 3 missing ArchUnit rules: noClassesShouldAccessStandardStreams (excludes CLI KeyGenerator), noClassesShouldUseFieldInjection (scoped to production hexagonal layers), noClassesShouldThrowGenericExceptions
  • Scope ArchUnit analysis to production code via ImportOption.DoNotIncludeTests

Checklist

  • ./gradlew build passes
  • Unit tests added/updated
  • Integration tests added/updated
  • ArchUnit rules pass
  • Spotless formatting applied

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Event publishing now persists to database with automatic retry handling and delivery status tracking
    • Scheduled background job asynchronously relays persisted events to the message queue
  • Refactor

    • Redesigned event delivery architecture to use intermediate persistence pattern for improved reliability

…ttern and add missing ArchUnit rules

Event publishing now persists events to an outbox table within a transaction,
then a scheduled relay polls and dispatches to Kafka — ensuring no events are
lost if Kafka is unavailable. ArchUnit test gains three new rules: no standard
stream access, no field injection, no generic exceptions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Puneethkumarck Puneethkumarck self-assigned this Mar 31, 2026
@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR implements the transactional outbox pattern for event publishing, replacing direct Kafka calls with database-persisted events that are relayed asynchronously by a scheduled component. Additionally, three ArchUnit architecture validation rules are introduced: disallowing standard stream access (except KeyGenerator), field injection in production classes, and generic exceptions. Dependencies on ShedLock are added for distributed scheduler locking.

Changes

Cohort / File(s) Summary
Outbox Data Model
src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventEntity.java, OutboxEventStatus.java
New JPA entity modeling outbox event records with fields for event metadata (eventId, intentId, topic, partitionKey), payload, status lifecycle (PENDING/PUBLISHED/FAILED), and retry tracking.
Outbox Persistence Layer
OutboxEventJpaRepository.java, OutboxEventPersister.java
Spring Data JPA repository with custom queries (findPendingOrderByCreatedAt, findByEventId, updateStatusAndPublishedAt) and a persister component that writes events to the outbox with PENDING status and zero retries.
Outbox Query & State Management
OutboxEventReader.java
Component providing transactional operations to find pending outbox entries, mark events as published, and increment retry counts or transition to failed status based on retry thresholds.
Event Publishing Architecture
OutboxTransactionEventPublisher.java, src/main/java/.../KafkaConfig.java
Replaces direct Kafka publishing (KafkaTransactionEventPublisher removed) with database-first approach. OutboxTransactionEventPublisher persists events; KafkaConfig now wires OutboxEventPersister instead of KafkaTemplate for the TransactionEventPublisher bean and adds OutboxEventRelay + ShedLock configuration.
Scheduled Event Relay
OutboxEventRelay.java
Scheduled component (fixed-delay 1000 ms with ShedLock) that polls up to 100 pending events, attempts Kafka dispatch with 30-second timeout, marks successful publishes, and increments retry counts or fails events on send errors.
Database Migrations
src/main/resources/db/migration/V13__STR_102_create_outbox_event.sql, V14__STR_102_create_shedlock.sql
Creates outbox_event table with UUID primary key, event metadata, status tracking, retry counter, and timestamps; adds unique constraint on event_id and partial index on pending entries. Creates shedlock table for distributed scheduler locking.
Architecture Validation
src/integration-test/java/com/stablebridge/txrecovery/ArchitectureTest.java
Enhanced @AnalyzeClasses to exclude test classes; added three ArchUnit rules: disallow KeyGenerator from accessing standard streams, disallow field injection in production classes (..application.., ..domain.., ..infrastructure..), and disallow generic exception throws across codebase.
Integration & Unit Tests
src/integration-test/java/.../KafkaConfigIntegrationTest.java, src/test/java/.../OutboxEventPersisterTest.java, OutboxEventRelayTest.java, OutboxEventReaderTest.java, OutboxTransactionEventPublisherTest.java
Updated integration test to validate outbox persistence and relay behavior using injected OutboxEventReader and OutboxEventRelay. Added unit tests for outbox components (persister, reader, relay) with mocked dependencies and assertions on DB and Kafka interactions.
Dependencies
gradle/libs.versions.toml, stablebridge-tx-recovery/build.gradle.kts
Added ShedLock library version 6.6.0 and two dependencies: shedlock-spring and shedlock-provider-jdbc-template.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant OutboxPub as OutboxTransactionEventPublisher
    participant DB as Database<br/>(outbox_event table)
    participant Relay as OutboxEventRelay<br/>(Scheduled)
    participant Kafka as Kafka

    App->>OutboxPub: publish(TransactionLifecycleEvent)
    OutboxPub->>OutboxPub: serialize event to JSON<br/>resolve topic & key
    OutboxPub->>DB: persist(eventId, intentId,<br/>topic, partitionKey, payload)<br/>status=PENDING
    DB-->>OutboxPub: persisted with UUID
    OutboxPub-->>App: return

    rect rgba(100, 200, 100, 0.5)
    Note over Relay,Kafka: Scheduled Relay Process (every 1s, locked via ShedLock)
    end

    Relay->>DB: findPending(batchSize=100)
    DB-->>Relay: List<PendingOutboxEvent>
    
    loop for each pending event
        Relay->>Kafka: send(topic, partitionKey, payload)<br/>timeout=30s
        
        alt Kafka send succeeds
            Kafka-->>Relay: SendResult with metadata
            Relay->>DB: updateStatusAndPublishedAt<br/>(eventId, PUBLISHED, now())
            DB-->>Relay: ✓ updated
            Relay->>Relay: log success (eventId, topic, key)
        else Send fails (InterruptedException<br/>or other exception)
            Kafka-->>Relay: exception
            Relay->>DB: incrementRetryOrFail<br/>(eventId, maxRetries=5)
            DB-->>Relay: retry count incremented<br/>or status=FAILED
            Relay->>Relay: log error & retry state
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

The PR spans 16 files with heterogeneous changes across multiple architectural layers: new outbox data model and persistence layer (6 classes), publishing pattern replacement (2 removed + 2 new classes), scheduled relay with ShedLock configuration, database migrations, architectural validation rules, and comprehensive test updates. Changes require understanding of transactional outbox semantics, Spring Data JPA repository patterns, scheduled task execution with distributed locking, and integration test refactoring.

Possibly related PRs

  • PR #61: Directly replaces the prior Kafka publishing implementation (KafkaTransactionEventPublisher and initial KafkaConfig producer wiring) with the new outbox-based publisher and relay pattern.
  • PR #54: Modifies the same ArchitectureTest class to add/enhance architecture validation rules using ArchUnit.
  • PR #96: Also updates ArchitectureTest integration-test class scanning annotations and test-class exclusion logic.

Suggested labels

phase:2-infrastructure, priority:high


🐰 Hopping through the outbox we go,
Events persist before the relays flow,
ShedLock keeps schedulers in harmony,
ArchUnit rules guard our symphony,
From DB to Kafka—resilient and free!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the two main changes: replacing direct Kafka publishing with the transactional outbox pattern and adding missing ArchUnit rules, matching the changeset content.
Description check ✅ Passed The PR description comprehensively covers all major changes (outbox pattern implementation, ArchUnit rules, infrastructure, wiring) and aligns with the provided template with all checklist items marked complete.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #122: transactional outbox pattern with persistence and scheduled relay, three new ArchUnit rules (standard streams, field injection, generic exceptions), outbox infrastructure, and test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #122 requirements: outbox pattern implementation, ArchUnit rule additions, infrastructure classes, tests, and dependencies are all in-scope with no unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/STR-102-outbox-pattern-and-archunit-rules

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfigIntegrationTest.java (1)

80-100: 🧹 Nitpick | 🔵 Trivial

Consider improving Kafka record assertion specificity.

The test asserts records.count() >= 1 and takes the first record, but in a parallel test environment, this could match records from other tests. Consider filtering records by the expected eventId or using a unique topic per test to ensure isolation.

         var records = consumer.poll(Duration.ofSeconds(10));
-        assertThat(records.count()).isGreaterThanOrEqualTo(1);
-        var record = records.iterator().next();
-        assertThat(record.key()).isEqualTo(event.toAddress());
-        assertThat(record.value()).contains(SOME_CHAIN);
+        var matchingRecords = StreamSupport.stream(records.spliterator(), false)
+                .filter(r -> r.value().contains(event.eventId()))
+                .toList();
+        assertThat(matchingRecords).hasSize(1);
+        var record = matchingRecords.get(0);
+        assertThat(record.key()).isEqualTo(event.toAddress());
+        assertThat(record.value()).contains(SOME_CHAIN);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfigIntegrationTest.java`
around lines 80 - 100, The test shouldRelayOutboxEventToKafka currently asserts
records.count() >= 1 and uses the first record which can pick up unrelated
messages; update the test to either publish to a unique topic per test (e.g.,
make TOPIC_PREFIX + SOME_CHAIN include a UUID when creating topic) or filter the
polled ConsumerRecords from createConsumer() for the specific event (match
record.key() == event.toAddress() and record.value() contains event.getEventId()
or another unique event identifier) and assert existence/contents only on that
filtered record after calling outboxEventRelay.relay() and
kafkaTemplate.flush(); this targets the exact record and prevents cross-test
interference.
stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfig.java (1)

54-66: 🧹 Nitpick | 🔵 Trivial

Consider adding explicit timeout configuration for the Kafka producer.

The producer is configured with RETRIES_CONFIG=3 but lacks explicit DELIVERY_TIMEOUT_MS and REQUEST_TIMEOUT_MS settings. The defaults (120s and 30s respectively) may be too long for the outbox relay's blocking .get() call, potentially stalling the scheduler.

Adding explicit timeout values would provide better control:

         props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
         props.put(ProducerConfig.ACKS_CONFIG, "all");
         props.put(ProducerConfig.RETRIES_CONFIG, 3);
+        props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 30000); // 30 seconds
+        props.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 10000);  // 10 seconds
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfig.java`
around lines 54 - 66, The kafkaProducerFactory bean sets RETRIES_CONFIG but
omits explicit timeouts, which can leave the producer stuck on the blocking
.get(); update kafkaProducerFactory to add
ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG and
ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG to props (e.g.,
DELIVERY_TIMEOUT_MS=30000, REQUEST_TIMEOUT_MS=10000 or values appropriate for
your scheduler) so producer send/get calls time out predictably; keep existing
RETRIES_CONFIG but ensure the timeout values align with scheduler expectations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/ArchitectureTest.java`:
- Around line 73-77: Replace the broad simple-name exclusion in the ArchUnit
rule: update the rule referenced by noClassesShouldAccessStandardStreams to use
a fully qualified class name instead of doNotHaveSimpleName("KeyGenerator");
locate the rule using the symbols noClassesShouldAccessStandardStreams and
doNotHaveSimpleName and change the exclusion to something like
.and().resideInAnyPackage(...) or use a predicate that matches the exact fully
qualified class (e.g., by comparing getName() to
"com.stablebridge.cli.KeyGenerator") so only the intended CLI KeyGenerator is
exempted.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventEntity.java`:
- Around line 18-55: Add a JPA lifecycle `@PrePersist` callback to
OutboxEventEntity to defensively set createdAt if it's null before insert;
implement a private method (e.g., prePersist or initializeTimestamps) annotated
with `@PrePersist` that assigns Instant.now() to the createdAt field when null
(refer to the OutboxEventEntity class and the createdAt field) so the entity
always has a creation timestamp even if the caller forgets to set it.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventJpaRepository.java`:
- Around line 24-30: The `@Modifying` update in OutboxEventJpaRepository (method
updateStatusAndPublishedAt) can leave stale entities in the persistence context;
update the annotation to `@Modifying`(clearAutomatically = true) so the
persistence context is cleared after the bulk update, ensuring subsequent reads
reflect the DB state for OutboxEventEntity and avoiding stale cache issues.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventReader.java`:
- Around line 29-32: The markPublished method in OutboxEventReader currently
ignores the integer returned by outboxRepository.updateStatusAndPublishedAt;
capture that returned affectedRows and if it's 0 (no row updated) either log a
warning with the eventId and context or throw an IllegalStateException to
surface the unexpected missing event; update the call site in markPublished to
check the result and use the class logger (or rethrow) so missing eventId cases
are observable.
- Around line 34-44: The method incrementRetryOrFail in OutboxEventReader
currently uses Optional.ifPresent and silently does nothing when
outboxRepository.findByEventId(eventId) is empty; change this to explicitly
handle the missing case by either logging a warning (using the class logger)
with the eventId and expected presence or by throwing an exception (e.g.,
IllegalStateException) to surface the invariant violation; keep the existing
logic that increments retry count, sets OutboxEventStatus.FAILED when retryCount
>= maxRetries, and saves via outboxRepository.save(e), and ensure the chosen
behavior is implemented in the else branch after checking the Optional.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelay.java`:
- Around line 22-26: The scheduled relay() method is vulnerable to
cross-instance races because outboxEventReader.findPending(BATCH_SIZE) can
return the same rows to multiple instances; update the code so pending rows are
locked or mutually exclusive before processing — either modify the repository
method outboxEventReader.findPending to use a row-locking query (FOR UPDATE SKIP
LOCKED) so relay() and processEvent operate on exclusively-claimed rows, or
annotate relay() with a distributed lock (e.g., use ShedLock on the `@Scheduled`
relay) to ensure only one instance runs the loop, or enforce single-instance
deployment for the relay; pick one approach and apply it consistently
(references: relay(), outboxEventReader.findPending(BATCH_SIZE), processEvent,
BATCH_SIZE).
- Around line 28-37: In processEvent, replace the blocking
kafkaTemplate.send(...).get() with a timed wait (e.g., .get(timeout,
TimeUnit.SECONDS)) and handle InterruptedException, TimeoutException and
ExecutionException separately: restore the thread interrupt status on
InterruptedException via Thread.currentThread().interrupt(),
log/timeout-specific messages for TimeoutException, and in all failure paths
call outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES) as
currently done; ensure the method imports TimeUnit and does not swallow
InterruptedException.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxTransactionEventPublisher.java`:
- Around line 35-37: resolveTopic currently calls chain.toLowerCase() and can
NPE when chain is null; update resolveTopic to validate chain first (e.g., use
Objects.requireNonNull(chain, "chain must not be null") or an explicit null
check and throw IllegalArgumentException) before calling toLowerCase(), then
return TOPIC_PREFIX + chain.toLowerCase(); reference the resolveTopic method and
TOPIC_PREFIX constant when making the change.

In
`@stablebridge-tx-recovery/src/main/resources/db/migration/V13__create_outbox_event.sql`:
- Around line 1-16: The outbox table and index are fine but the fetch logic can
cause duplicate processing under concurrency; update the repository/query that
selects pending OutboxEventEntity rows (the code that queries status = 'PENDING'
ordered by createdAt with :batchSize) to use row-level locking so concurrent
relay instances skip locked rows (i.e., add FOR UPDATE SKIP LOCKED or equivalent
in your JPA/SQL fetch), or alternatively implement a single-leader mechanism or
distributed lock around the relay so only one instance processes rows from
outbox_event at a time; ensure the change targets the fetch logic that reads
from outbox_event / OutboxEventEntity and keeps idx_outbox_event_pending intact.

In
`@stablebridge-tx-recovery/src/test/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelayTest.java`:
- Around line 40-91: Add two tests in OutboxEventRelayTest: one that creates
multiple PendingOutboxEvent instances returned by
outboxEventReader.findPending(OutboxEventRelay.BATCH_SIZE) and stubs
kafkaTemplate.send(...) to return completedFuture() for each, then verifies
outboxEventReader.markPublished(...) was called for all event IDs; and another
partial-failure test that returns a list of two events, stubs
kafkaTemplate.send(...) to return completedFuture() for the first and
failedFuture() for the second, then verifies markPublished(...) was called only
for the successful event and incrementRetryOrFail(...) was called for the failed
event (use the existing completedFuture()/failedFuture() helpers and reference
methods kafkaTemplate.send, outboxEventReader.markPublished,
outboxEventReader.incrementRetryOrFail, and OutboxEventRelay.BATCH_SIZE).

---

Outside diff comments:
In
`@stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfigIntegrationTest.java`:
- Around line 80-100: The test shouldRelayOutboxEventToKafka currently asserts
records.count() >= 1 and uses the first record which can pick up unrelated
messages; update the test to either publish to a unique topic per test (e.g.,
make TOPIC_PREFIX + SOME_CHAIN include a UUID when creating topic) or filter the
polled ConsumerRecords from createConsumer() for the specific event (match
record.key() == event.toAddress() and record.value() contains event.getEventId()
or another unique event identifier) and assert existence/contents only on that
filtered record after calling outboxEventRelay.relay() and
kafkaTemplate.flush(); this targets the exact record and prevents cross-test
interference.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfig.java`:
- Around line 54-66: The kafkaProducerFactory bean sets RETRIES_CONFIG but omits
explicit timeouts, which can leave the producer stuck on the blocking .get();
update kafkaProducerFactory to add ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG and
ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG to props (e.g.,
DELIVERY_TIMEOUT_MS=30000, REQUEST_TIMEOUT_MS=10000 or values appropriate for
your scheduler) so producer send/get calls time out predictably; keep existing
RETRIES_CONFIG but ensure the timeout values align with scheduler expectations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 756d3506-9915-4cad-af60-9e7280562ea0

📥 Commits

Reviewing files that changed from the base of the PR and between b4f00e3 and d3e8f08.

📒 Files selected for processing (14)
  • stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/ArchitectureTest.java
  • stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfigIntegrationTest.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventEntity.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventJpaRepository.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventPersister.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventReader.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventStatus.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfig.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaTransactionEventPublisher.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelay.java
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxTransactionEventPublisher.java
  • stablebridge-tx-recovery/src/main/resources/db/migration/V13__create_outbox_event.sql
  • stablebridge-tx-recovery/src/test/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelayTest.java
  • stablebridge-tx-recovery/src/test/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxTransactionEventPublisherTest.java
💤 Files with no reviewable changes (1)
  • stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaTransactionEventPublisher.java

Comment on lines +73 to +77
@ArchTest
static final ArchRule noClassesShouldAccessStandardStreams = noClasses()
.that()
.doNotHaveSimpleName("KeyGenerator")
.should(ACCESS_STANDARD_STREAMS);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider using fully qualified name for more precise exclusion.

Using doNotHaveSimpleName("KeyGenerator") excludes any class with that name from any package. If another KeyGenerator class is added elsewhere in the codebase, it would silently bypass this rule. Using the fully qualified name ensures only the intended CLI tool is exempted.

♻️ Proposed fix for more precise exclusion
 `@ArchTest`
 static final ArchRule noClassesShouldAccessStandardStreams = noClasses()
         .that()
-        .doNotHaveSimpleName("KeyGenerator")
+        .doNotHaveFullyQualifiedName("com.stablebridge.txrecovery.infrastructure.signer.keygen.KeyGenerator")
         .should(ACCESS_STANDARD_STREAMS);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@ArchTest
static final ArchRule noClassesShouldAccessStandardStreams = noClasses()
.that()
.doNotHaveSimpleName("KeyGenerator")
.should(ACCESS_STANDARD_STREAMS);
`@ArchTest`
static final ArchRule noClassesShouldAccessStandardStreams = noClasses()
.that()
.doNotHaveFullyQualifiedName("com.stablebridge.txrecovery.infrastructure.signer.keygen.KeyGenerator")
.should(ACCESS_STANDARD_STREAMS);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/ArchitectureTest.java`
around lines 73 - 77, Replace the broad simple-name exclusion in the ArchUnit
rule: update the rule referenced by noClassesShouldAccessStandardStreams to use
a fully qualified class name instead of doNotHaveSimpleName("KeyGenerator");
locate the rule using the symbols noClassesShouldAccessStandardStreams and
doNotHaveSimpleName and change the exclusion to something like
.and().resideInAnyPackage(...) or use a predicate that matches the exact fully
qualified class (e.g., by comparing getName() to
"com.stablebridge.cli.KeyGenerator") so only the intended CLI KeyGenerator is
exempted.

Comment on lines +24 to +30
@Modifying
@Query("""
UPDATE OutboxEventEntity e
SET e.status = :status, e.publishedAt = :publishedAt
WHERE e.eventId = :eventId
""")
int updateStatusAndPublishedAt(String eventId, OutboxEventStatus status, Instant publishedAt);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Add clearAutomatically = true to @Modifying to avoid stale persistence context.

When a @Modifying query updates rows directly in the database, any previously loaded entities in the persistence context become stale. Without clearAutomatically = true, subsequent reads may return outdated data from the first-level cache.

♻️ Proposed fix
-    `@Modifying`
+    `@Modifying`(clearAutomatically = true)
     `@Query`("""
             UPDATE OutboxEventEntity e
             SET e.status = :status, e.publishedAt = :publishedAt
             WHERE e.eventId = :eventId
             """)
     int updateStatusAndPublishedAt(String eventId, OutboxEventStatus status, Instant publishedAt);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Modifying
@Query("""
UPDATE OutboxEventEntity e
SET e.status = :status, e.publishedAt = :publishedAt
WHERE e.eventId = :eventId
""")
int updateStatusAndPublishedAt(String eventId, OutboxEventStatus status, Instant publishedAt);
`@Modifying`(clearAutomatically = true)
`@Query`("""
UPDATE OutboxEventEntity e
SET e.status = :status, e.publishedAt = :publishedAt
WHERE e.eventId = :eventId
""")
int updateStatusAndPublishedAt(String eventId, OutboxEventStatus status, Instant publishedAt);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventJpaRepository.java`
around lines 24 - 30, The `@Modifying` update in OutboxEventJpaRepository (method
updateStatusAndPublishedAt) can leave stale entities in the persistence context;
update the annotation to `@Modifying`(clearAutomatically = true) so the
persistence context is cleared after the bulk update, ensuring subsequent reads
reflect the DB state for OutboxEventEntity and avoiding stale cache issues.

Comment on lines +29 to +32
@Transactional
public void markPublished(String eventId) {
outboxRepository.updateStatusAndPublishedAt(eventId, OutboxEventStatus.PUBLISHED, Instant.now());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider logging or throwing when no row is updated.

updateStatusAndPublishedAt returns the affected row count, but it's ignored. If eventId doesn't exist (e.g., due to a race or bug), the failure is silent. At minimum, log a warning for observability.

♻️ Proposed improvement
     `@Transactional`
     public void markPublished(String eventId) {
-        outboxRepository.updateStatusAndPublishedAt(eventId, OutboxEventStatus.PUBLISHED, Instant.now());
+        int updated = outboxRepository.updateStatusAndPublishedAt(eventId, OutboxEventStatus.PUBLISHED, Instant.now());
+        if (updated == 0) {
+            log.warn("No outbox event found for eventId={} when marking published", eventId);
+        }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventReader.java`
around lines 29 - 32, The markPublished method in OutboxEventReader currently
ignores the integer returned by outboxRepository.updateStatusAndPublishedAt;
capture that returned affectedRows and if it's 0 (no row updated) either log a
warning with the eventId and context or throw an IllegalStateException to
surface the unexpected missing event; update the call site in markPublished to
check the result and use the class logger (or rethrow) so missing eventId cases
are observable.

Comment on lines +28 to +37
private void processEvent(PendingOutboxEvent event) {
try {
kafkaTemplate.send(event.topic(), event.partitionKey(), event.payload()).get();
outboxEventReader.markPublished(event.eventId());
log.info("Relayed event {} to topic {} partition-key {}",
event.eventId(), event.topic(), event.partitionKey());
} catch (Exception e) {
log.error("Failed to relay event {} to topic {}", event.eventId(), event.topic(), e);
outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add explicit timeout to the blocking .get() call to prevent scheduler thread starvation.

The kafkaTemplate.send(...).get() call blocks indefinitely (up to Kafka's default delivery.timeout.ms of 120 seconds). With BATCH_SIZE=100, this could block the scheduler thread for an extended period, preventing subsequent poll cycles.

Also, catching InterruptedException as a generic Exception loses the thread's interrupt status.

Proposed fix with explicit timeout and interrupt handling
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+    private static final long SEND_TIMEOUT_SECONDS = 30;
+
     private void processEvent(PendingOutboxEvent event) {
         try {
-            kafkaTemplate.send(event.topic(), event.partitionKey(), event.payload()).get();
+            kafkaTemplate.send(event.topic(), event.partitionKey(), event.payload())
+                    .get(SEND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
             outboxEventReader.markPublished(event.eventId());
             log.info("Relayed event {} to topic {} partition-key {}",
                     event.eventId(), event.topic(), event.partitionKey());
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            log.warn("Relay interrupted for event {}", event.eventId());
+        } catch (TimeoutException e) {
+            log.error("Timeout relaying event {} to topic {}", event.eventId(), event.topic(), e);
+            outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
         } catch (Exception e) {
             log.error("Failed to relay event {} to topic {}", event.eventId(), event.topic(), e);
             outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
         }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void processEvent(PendingOutboxEvent event) {
try {
kafkaTemplate.send(event.topic(), event.partitionKey(), event.payload()).get();
outboxEventReader.markPublished(event.eventId());
log.info("Relayed event {} to topic {} partition-key {}",
event.eventId(), event.topic(), event.partitionKey());
} catch (Exception e) {
log.error("Failed to relay event {} to topic {}", event.eventId(), event.topic(), e);
outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
}
private static final long SEND_TIMEOUT_SECONDS = 30;
private void processEvent(PendingOutboxEvent event) {
try {
kafkaTemplate.send(event.topic(), event.partitionKey(), event.payload())
.get(SEND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
outboxEventReader.markPublished(event.eventId());
log.info("Relayed event {} to topic {} partition-key {}",
event.eventId(), event.topic(), event.partitionKey());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Relay interrupted for event {}", event.eventId());
} catch (TimeoutException e) {
log.error("Timeout relaying event {} to topic {}", event.eventId(), event.topic(), e);
outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
} catch (Exception e) {
log.error("Failed to relay event {} to topic {}", event.eventId(), event.topic(), e);
outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES);
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelay.java`
around lines 28 - 37, In processEvent, replace the blocking
kafkaTemplate.send(...).get() with a timed wait (e.g., .get(timeout,
TimeUnit.SECONDS)) and handle InterruptedException, TimeoutException and
ExecutionException separately: restore the thread interrupt status on
InterruptedException via Thread.currentThread().interrupt(),
log/timeout-specific messages for TimeoutException, and in all failure paths
call outboxEventReader.incrementRetryOrFail(event.eventId(), MAX_RETRIES) as
currently done; ensure the method imports TimeUnit and does not swallow
InterruptedException.

Comment on lines +35 to +37
static String resolveTopic(String chain) {
return TOPIC_PREFIX + chain.toLowerCase();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Potential NPE if chain is null.

chain.toLowerCase() will throw NullPointerException if chain is null. Consider adding a null check or using Objects.requireNonNull with a descriptive message.

🛡️ Proposed fix
     static String resolveTopic(String chain) {
+        if (chain == null) {
+            throw new IllegalArgumentException("Chain must not be null for topic resolution");
+        }
         return TOPIC_PREFIX + chain.toLowerCase();
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxTransactionEventPublisher.java`
around lines 35 - 37, resolveTopic currently calls chain.toLowerCase() and can
NPE when chain is null; update resolveTopic to validate chain first (e.g., use
Objects.requireNonNull(chain, "chain must not be null") or an explicit null
check and throw IllegalArgumentException) before calling toLowerCase(), then
return TOPIC_PREFIX + chain.toLowerCase(); reference the resolveTopic method and
TOPIC_PREFIX constant when making the change.

Comment on lines +1 to +16
CREATE TABLE outbox_event (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id VARCHAR(255) NOT NULL,
intent_id VARCHAR(36) NOT NULL,
topic VARCHAR(255) NOT NULL,
partition_key VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ,
retry_count INT NOT NULL DEFAULT 0,

CONSTRAINT uq_outbox_event_event_id UNIQUE (event_id)
);

CREATE INDEX idx_outbox_event_pending ON outbox_event (created_at) WHERE status = 'PENDING';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Schema looks good, but consider adding concurrency handling for multi-instance deployments.

The table design is solid with appropriate column types and the partial index for efficient pending event retrieval. However, the current implementation (per context snippet 2) uses a plain SELECT without row-level locking (FOR UPDATE SKIP LOCKED). In a multi-pod deployment, concurrent relay instances may fetch and process the same pending rows, leading to duplicate Kafka publishes.

Consider updating the repository query to:

SELECT e FROM OutboxEventEntity e
WHERE e.status = 'PENDING'
ORDER BY e.createdAt ASC
LIMIT :batchSize
FOR UPDATE SKIP LOCKED

Alternatively, ensure only a single relay instance runs (e.g., via distributed lock or leader election).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/main/resources/db/migration/V13__create_outbox_event.sql`
around lines 1 - 16, The outbox table and index are fine but the fetch logic can
cause duplicate processing under concurrency; update the repository/query that
selects pending OutboxEventEntity rows (the code that queries status = 'PENDING'
ordered by createdAt with :batchSize) to use row-level locking so concurrent
relay instances skip locked rows (i.e., add FOR UPDATE SKIP LOCKED or equivalent
in your JPA/SQL fetch), or alternatively implement a single-leader mechanism or
distributed lock around the relay so only one instance processes rows from
outbox_event at a time; ensure the change targets the fetch logic that reads
from outbox_event / OutboxEventEntity and keeps idx_outbox_event_pending intact.

Comment on lines +40 to +91
@Test
void shouldRelayPendingEventsToKafkaAndMarkPublished() {
// given
var event = new PendingOutboxEvent("id-1", SOME_EVENT_ID, SOME_TOPIC, SOME_KEY, SOME_PAYLOAD);
given(outboxEventReader.findPending(OutboxEventRelay.BATCH_SIZE)).willReturn(List.of(event));
given(kafkaTemplate.send(SOME_TOPIC, SOME_KEY, SOME_PAYLOAD)).willReturn(completedFuture());

// when
relay.relay();

// then
then(outboxEventReader).should().markPublished(SOME_EVENT_ID);
}

@Test
void shouldIncrementRetryCount_whenKafkaSendFails() {
// given
var event = new PendingOutboxEvent("id-1", SOME_EVENT_ID, SOME_TOPIC, SOME_KEY, SOME_PAYLOAD);
given(outboxEventReader.findPending(OutboxEventRelay.BATCH_SIZE)).willReturn(List.of(event));
given(kafkaTemplate.send(SOME_TOPIC, SOME_KEY, SOME_PAYLOAD)).willReturn(failedFuture());

// when
relay.relay();

// then
then(outboxEventReader).should(never()).markPublished(SOME_EVENT_ID);
then(outboxEventReader).should().incrementRetryOrFail(SOME_EVENT_ID, OutboxEventRelay.MAX_RETRIES);
}

@Test
void shouldDoNothing_whenNoPendingEvents() {
// given
given(outboxEventReader.findPending(OutboxEventRelay.BATCH_SIZE)).willReturn(List.of());

// when
relay.relay();

// then
then(kafkaTemplate).shouldHaveNoInteractions();
then(outboxEventReader).should(never()).markPublished(SOME_EVENT_ID);
}

private CompletableFuture<SendResult<String, String>> completedFuture() {
var metadata = new RecordMetadata(new TopicPartition("topic", 0), 0, 0, 0, 0, 0);
var result = new SendResult<String, String>(null, metadata);
return CompletableFuture.completedFuture(result);
}

private CompletableFuture<SendResult<String, String>> failedFuture() {
return CompletableFuture.failedFuture(new RuntimeException("Kafka unavailable"));
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Good test coverage for core relay scenarios.

The tests appropriately cover success, failure, and empty-poll cases using BDD-style Mockito.

Consider adding tests for:

  • Multiple events in a single batch (verifying all are processed)
  • Partial batch failure (first succeeds, second fails) to ensure independent event handling
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stablebridge-tx-recovery/src/test/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelayTest.java`
around lines 40 - 91, Add two tests in OutboxEventRelayTest: one that creates
multiple PendingOutboxEvent instances returned by
outboxEventReader.findPending(OutboxEventRelay.BATCH_SIZE) and stubs
kafkaTemplate.send(...) to return completedFuture() for each, then verifies
outboxEventReader.markPublished(...) was called for all event IDs; and another
partial-failure test that returns a list of two events, stubs
kafkaTemplate.send(...) to return completedFuture() for the first and
failedFuture() for the second, then verifies markPublished(...) was called only
for the successful event and incrementRetryOrFail(...) was called for the failed
event (use the existing completedFuture()/failedFuture() helpers and reference
methods kafkaTemplate.send, outboxEventReader.markPublished,
outboxEventReader.incrementRetryOrFail, and OutboxEventRelay.BATCH_SIZE).

Add ShedLock to prevent duplicate outbox relay across replicas, timeout on
Kafka send to avoid blocking the scheduler, Clock injection for testability,
and unit tests for OutboxEventPersister/OutboxEventReader. Fix test naming,
reuse fixture constants, strengthen integration assertions, and rename V13
migration with ticket prefix.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Puneethkumarck
Puneethkumarck merged commit aa70549 into main Mar 31, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

STR-102: replace direct Kafka publishing with transactional outbox pattern and add missing ArchUnit rules

1 participant