Repository navigation
STR-102: replace direct Kafka publishing with transactional outbox pattern and add missing ArchUnit rules - #123
Conversation
…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>
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughThis 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 Changes
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
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
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🔵 TrivialConsider improving Kafka record assertion specificity.
The test asserts
records.count() >= 1and takes the first record, but in a parallel test environment, this could match records from other tests. Consider filtering records by the expectedeventIdor 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 | 🔵 TrivialConsider adding explicit timeout configuration for the Kafka producer.
The producer is configured with
RETRIES_CONFIG=3but lacks explicitDELIVERY_TIMEOUT_MSandREQUEST_TIMEOUT_MSsettings. 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
📒 Files selected for processing (14)
stablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/ArchitectureTest.javastablebridge-tx-recovery/src/integration-test/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfigIntegrationTest.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventEntity.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventJpaRepository.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventPersister.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventReader.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/db/outbox/OutboxEventStatus.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaConfig.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/KafkaTransactionEventPublisher.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelay.javastablebridge-tx-recovery/src/main/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxTransactionEventPublisher.javastablebridge-tx-recovery/src/main/resources/db/migration/V13__create_outbox_event.sqlstablebridge-tx-recovery/src/test/java/com/stablebridge/txrecovery/infrastructure/stream/OutboxEventRelayTest.javastablebridge-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
| @ArchTest | ||
| static final ArchRule noClassesShouldAccessStandardStreams = noClasses() | ||
| .that() | ||
| .doNotHaveSimpleName("KeyGenerator") | ||
| .should(ACCESS_STANDARD_STREAMS); |
There was a problem hiding this comment.
🧹 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.
| @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.
| @Modifying | ||
| @Query(""" | ||
| UPDATE OutboxEventEntity e | ||
| SET e.status = :status, e.publishedAt = :publishedAt | ||
| WHERE e.eventId = :eventId | ||
| """) | ||
| int updateStatusAndPublishedAt(String eventId, OutboxEventStatus status, Instant publishedAt); |
There was a problem hiding this comment.
🧹 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.
| @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.
| @Transactional | ||
| public void markPublished(String eventId) { | ||
| outboxRepository.updateStatusAndPublishedAt(eventId, OutboxEventStatus.PUBLISHED, Instant.now()); | ||
| } |
There was a problem hiding this comment.
🧹 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.
| 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); | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| static String resolveTopic(String chain) { | ||
| return TOPIC_PREFIX + chain.toLowerCase(); | ||
| } |
There was a problem hiding this comment.
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.
| 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'; |
There was a problem hiding this comment.
🧹 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 LOCKEDAlternatively, 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.
| @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")); | ||
| } | ||
| } |
There was a problem hiding this comment.
🧹 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>
STR Issue
Closes #122
Changes
KafkaTransactionEventPublisher(direct Kafka fire-and-forget) with transactional outbox pattern per ADR Section 6outbox_eventtable via Flyway V13 migration with partial index on PENDING statusOutboxTransactionEventPublisherthat persists events to DB within a transaction (implementsTransactionEventPublisherport)OutboxEventRelayscheduled poller that dispatches pending outbox events to Kafka with retry tracking (max 5 retries before FAILED)OutboxEventEntity,OutboxEventJpaRepository,OutboxEventPersister,OutboxEventReaderKafkaConfigwith@EnableSchedulingnoClassesShouldAccessStandardStreams(excludes CLI KeyGenerator),noClassesShouldUseFieldInjection(scoped to production hexagonal layers),noClassesShouldThrowGenericExceptionsImportOption.DoNotIncludeTestsChecklist
./gradlew buildpasses🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Refactor