How to Configure Backpressure Protection with BackpressureInterceptor in Atmosphere
Use the BackpressureInterceptor to limit pending messages per client by setting org.atmosphere.backpressure.highWaterMark and org.atmosphere.backpressure.policy via web.xml or programmatic AtmosphereConfig.
The Atmosphere Framework provides built-in backpressure protection through the BackpressureInterceptor class, which prevents server overload from slow or unresponsive clients. This interceptor tracks pending messages per client UUID and applies configurable policies when queue limits are exceeded, ensuring stable resource utilization in high-throughput real-time applications.
What Is Backpressure Protection in Atmosphere?
Backpressure protection in Atmosphere prevents memory exhaustion and performance degradation by capping the number of undelivered messages queued for each client connection. When a client cannot consume messages fast enough, the server-side queue grows; without intervention, this leads to OutOfMemoryErrors and cascading failures.
The BackpressureInterceptor implements this protection by extending AtmosphereInterceptorAdapter and maintaining atomic counters for each AtmosphereResource UUID.
Core Components
The implementation resides in modules/cpr/src/main/java/org/atmosphere/interceptor/BackpressureInterceptor.java and consists of:
Map<String, AtomicInteger> pendingCounts– Stores the current number of queued messages per client UUID.allowMessage(String uuid)– Called before queuing a message; increments the counter and enforces the high-water mark.AtmosphereResourceEventListenerAdapter– Registered on firstinspect()call to decrement counters ononBroadcastand clean up entries ononDisconnect/onClose.totalDropsandtotalDisconnects– Atomic counters exposing metrics for monitoring dropped messages and forced disconnections.
The Policy Enum
When the pending count exceeds highWaterMark, the interceptor applies one of three policies defined in the source:
DROP_OLDEST– Retains the new message and relies on the broadcaster to evict the oldest queued message. The counter remains incremented.DROP_NEWEST– Rejects the current message, decrements the counter, and records a drop intotalDrops.DISCONNECT– Records a disconnect intotalDisconnects, returnsfalse, and allows the application to close theAtmosphereResource.
Configuration Parameters
The interceptor reads two initialization parameters during its configure() method (lines 81-90 in the source).
| Parameter | Description | Default |
|---|---|---|
org.atmosphere.backpressure.highWaterMark |
Maximum pending messages allowed per client UUID before triggering the policy. | 1000 |
org.atmosphere.backpressure.policy |
Action when limit exceeded: drop-oldest, drop-newest, or disconnect. |
drop-oldest |
Web.xml Configuration
Add the parameters as servlet initialization parameters in web.xml:
<servlet>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.backpressure.highWaterMark</param-name>
<param-value>500</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.backpressure.policy</param-name>
<param-value>disconnect</param-value>
</init-param>
</servlet>
Programmatic Configuration
Configure via AtmosphereConfig when embedding Atmosphere or using Spring Boot:
AtmosphereConfig config = new AtmosphereConfig();
config.addInitParameter("org.atmosphere.backpressure.highWaterMark", "200");
config.addInitParameter("org.atmosphere.backpressure.policy", "drop-newest");
AtmosphereFramework framework = new AtmosphereFramework();
framework.setAtmosphereConfig(config);
framework.interceptor(new BackpressureInterceptor());
Runtime Behavior and Message Flow
Understanding the message lifecycle helps implement custom broadcast logic that respects backpressure signals.
The allowMessage() Method
Before queuing a message for a specific client, the application (or broadcaster) should check allowMessage(String uuid):
- Increment – The
pendingCountsmap for that UUID is atomically incremented. - Check – If the new count ≤
highWaterMark, returntrue(proceed with broadcast). - Policy Enforcement – If exceeded:
- DROP_NEWEST: Decrement counter, increment
totalDrops, returnfalse. - DROP_OLDEST: Keep counter incremented (oldest message will be dropped by broadcaster), return
true. - DISCONNECT: Increment
totalDisconnects, returnfalse(application should close resource).
- DROP_NEWEST: Decrement counter, increment
Event Listener Lifecycle
On the first call to inspect(AtmosphereResource), the interceptor registers an AtmosphereResourceEventListenerAdapter (lines 95-122 in the source):
onBroadcast– Decrements the pending counter when a message is successfully delivered to the client.onDisconnect/onClose– Removes the UUID entry frompendingCountsand unregisters the listener to prevent memory leaks.
This ensures the counter stays synchronized with actual delivery state regardless of transport type (WebSocket, SSE, or Long-Polling).
Practical Implementation Example
Complete integration requires registering the interceptor, configuring parameters, and checking backpressure before broadcasting.
Registering the Interceptor
public class AtmosphereConfigInitializer {
public AtmosphereFramework setupFramework() {
AtmosphereFramework framework = new AtmosphereFramework();
// Register backpressure protection
framework.interceptor(new BackpressureInterceptor());
// Additional interceptors...
return framework;
}
}
Broadcasting with Backpressure Checks
@Path("/chat")
public class ChatResource {
@Inject
private AtmosphereResource resource;
@POST
public Response broadcastMessage(String message) {
String uuid = resource.uuid();
AtmosphereFramework framework = resource.getAtmosphereConfig().framework();
BackpressureInterceptor bp = (BackpressureInterceptor)
framework.interceptor(BackpressureInterceptor.class);
if (bp != null && bp.allowMessage(uuid)) {
resource.getBroadcaster().broadcast(message);
return Response.ok().build();
} else {
// Message dropped or client disconnected based on policy
return Response.status(503).entity("Client overwhelmed").build();
}
}
}
Monitoring Metrics
Expose the built-in counters via JMX or a health endpoint:
public class BackpressureMetrics {
public Map<String, Long> getStats(AtmosphereFramework framework) {
BackpressureInterceptor bp = (BackpressureInterceptor)
framework.interceptor(BackpressureInterceptor.class);
Map<String, Long> stats = new HashMap<>();
if (bp != null) {
stats.put("totalDrops", bp.totalDrops());
stats.put("totalDisconnects", bp.totalDisconnects());
}
return stats;
}
}
Summary
- BackpressureInterceptor in
modules/cpr/src/main/java/org/atmosphere/interceptor/BackpressureInterceptor.javaprevents server overload by limiting pending messages per client UUID. - Configure via
org.atmosphere.backpressure.highWaterMark(default 1000) andorg.atmosphere.backpressure.policy(defaultdrop-oldest) inweb.xmlor programmaticAtmosphereConfig. - The Policy enum determines behavior when limits are exceeded:
DROP_OLDESTevicts old messages,DROP_NEWESTrejects new messages, andDISCONNECTsevers the connection. - Always check
allowMessage(uuid)before broadcasting; the interceptor automatically tracks delivery viaonBroadcastlisteners and cleans up resources on disconnect.
Frequently Asked Questions
How does BackpressureInterceptor track pending messages per client?
The interceptor maintains a ConcurrentHashMap<String, AtomicInteger> named pendingCounts that maps each client UUID to its current number of queued but undelivered messages. When allowMessage(uuid) is called, the counter increments; when the registered AtmosphereResourceEventListenerAdapter receives an onBroadcast event, it decrements the counter. On onDisconnect or onClose, the entry is removed to prevent memory leaks.
What is the difference between the DROP_OLDEST and DROP_NEWEST policies?
DROP_OLDEST (the default) accepts the new message into the queue and relies on the broadcaster implementation to evict the oldest pending message when the high-water mark is exceeded; the pending counter remains incremented. DROP_NEWEST rejects the current message, atomically decrements the pending counter back to its previous value, increments the totalDrops metric, and returns false from allowMessage(), signaling the application to skip the broadcast.
Can I use BackpressureInterceptor with Spring Boot or standalone Java configuration?
Yes. While web.xml is the traditional configuration method, you can instantiate and register the interceptor programmatically. Create an AtmosphereFramework instance, call framework.interceptor(new BackpressureInterceptor()), and supply parameters via AtmosphereConfig.addInitParameter("org.atmosphere.backpressure.highWaterMark", "500") before the framework initializes. This approach works for embedded servers and Spring Boot auto-configuration classes.
How do I monitor when messages are being dropped or clients disconnected?
The BackpressureInterceptor exposes two atomic counters: totalDrops() returns the number of messages dropped due to DROP_NEWEST policy, and totalDisconnects() returns the number of times the DISCONNECT policy triggered. Access these via framework.interceptor(BackpressureInterceptor.class) and expose them through JMX, Micrometer, or a REST health endpoint to track backpressure events in production.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →