Avoid Misusing Spring Event: 6 Hard‑Earned Best Practices from a Real‑World Failure
The article recounts a production incident caused by improper use of Spring Event, explains why graceful shutdown, correct startup timing, suitable business scenarios, and reliability measures such as retries and idempotency are essential, and presents six concrete best‑practice recommendations to prevent similar failures.
After a serious production incident caused by incorrect usage of Spring Event, the author shares valuable lessons and six concrete best‑practice recommendations.
1. Graceful shutdown is a prerequisite for Spring Event
When Spring broadcasts an event it looks up listeners in the ApplicationContext via getBean. During context shutdown, requesting beans throws an error ("Do not request a bean from a BeanFactory in a destroy method implementation"). Because the service still receives traffic during shutdown, publishing events can fail. The recommendation is to cut off all entry traffic (HTTP, MQ, RPC) before closing the Spring context.
2. Event loss can occur during service startup
In the author’s case a Kafka consumer started in the init-method began publishing events before the EventListener beans were registered, causing lost messages. The fix is to open inbound traffic only after Spring has fully started, e.g., by using SmartLifecycle or listening to ContextRefreshedEvent to register services.
3. Business characteristics that suit the publish‑subscribe model
The publisher does not need to know how the event is processed.
The publisher does not care about the processing result.
Multiple subscribers can exist, synchronously or asynchronously.
Subscribers are independent and do not depend on each other.
This decouples publishing and subscribing but is unsuitable for strong‑consistency requirements.
4. Strong‑consistency scenarios are not a good fit
For example, order placement requires inventory deduction and order creation to be atomically consistent. If a subscriber fails (e.g., inventory deduction), Spring Event cannot roll back the whole transaction because it lacks a mechanism to signal failure back to the publisher.
5. Eventual‑consistency scenarios are ideal for Spring Event
After an order is successfully placed, downstream actions such as sending MQ messages or releasing locks can be handled by Spring Event. These actions only need to succeed eventually; failures can be retried without affecting the primary transaction.
6. Ensure reliability and idempotency of subscribers
Publishers should use applicationContext.publishEvent(event) which throws an exception on subscriber failure, allowing the publisher to detect errors. Three reliability strategies are suggested:
Subscribers implement their own retry logic, e.g., using Spring Retry's @Retryable annotation (max 3 attempts, exponential back‑off).
Example:
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 100L, multiplier = 2))
public void performSuccess(PerformEvent event) {
// business logic
}Add the dependency:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>When using Kafka, let the consumer return a failure to trigger Kafka’s own retry mechanism or route the message to a dead‑letter queue. Additionally, report unrecoverable failures to a fault‑management platform, which can trigger manual retries.
Subscribers must be idempotent because on retry all listeners are invoked again; without idempotency duplicate processing can cause data inconsistency.
7. Why Spring Event is still useful alongside MQ
MQ excels at inter‑service communication and complex routing, while Spring Event provides lightweight intra‑application decoupling. Both can coexist: use MQ for cross‑service events and Spring Event for internal publish‑subscribe needs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer XiaoFu
xiaofucode.com – a programmer learning guide driven by the pursuit of profit
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
