Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A service sends messages with JmsTemplate in a loop and throughput is very poor; the broker shows a new connection and session for each message. What is wrong?

JmsTemplate opens a connection, a session and a producer for every send and closes them again, unless the ConnectionFactory it uses caches them. Here it is given the provider's raw factory, so each message pays for a full connection handshake. The fix is to wrap the factory in Spring's CachingConnectionFactory or a pooled connection factory, keep the listener container's consumers uncached by that wrapper, and measure again before reaching for batching or asynchronous sends.

Why this question is asked

This is one of the most common performance problems in JMS code, and it looks like a slow broker until we read the broker's statistics. The symptom in the question, a new connection and session for each message, points straight at the cause. Interviewers like it because the fix is one bean, but explaining why it works shows that we understand what JmsTemplate does on every call. In this answer, we will recap the JMS objects involved, reproduce the problem, see why JmsTemplate behaves this way, apply the fix, and look at what else can raise throughput once the basic waste is gone.

1A Quick Recap of Connections, Sessions and Producers

Sending a JMS message needs three objects. A Connection is the network link to the broker, with a TCP connection, authentication and usually a few round trips to set up. A Session is a single-threaded context on that connection in which messages are sent and received. A MessageProducer is created from a session for one destination and does the actual send. A ConnectionFactory is the object that creates connections, configured with the broker's address.

Connections are expensive to create and are meant to be long-lived and shared. Sessions and producers are cheaper but still involve calls to the broker. The JMS design assumes we create them once and send many messages through them.

2Reproducing the Problem

Here is the code from the question in its usual form. The ConnectionFactory bean is the provider's own class, created by hand.

Java
@Bean
ConnectionFactory connectionFactory() {
return new ActiveMQConnectionFactory("tcp://broker:61616"); // Artemis client, raw factory
}
@Bean
JmsTemplate jmsTemplate(ConnectionFactory cf) {
return new JmsTemplate(cf);
}
for (Order o : orders) { // 10,000 orders
jmsTemplate.convertAndSend("orders", o); // connect, session, producer, send, close all three
}
// broker: 10,000 connections opened and closed
// about 12 ms per message in our test, so about 2 minutes in total
Step throughOne convertAndSend with a raw factory
JmsTemplateRaw factoryBroker
createConnection()
TCP connect, authenticate
createSession, createProducer
send(message)
close producer, session, connection
repeat for the next message

6 messages in order. Play them, or step through them one at a time.

Everything except the send is repeated work.

The broker's console shows connection and session counts climbing and falling with every message. The send itself is a small part of each 12 milliseconds; the rest is the handshake.

3Why JmsTemplate Behaves This Way

JmsTemplate is written to be safe without assumptions. Each operation calls the ConnectionFactory for a connection, creates a session and producer, does its work and closes everything in a finally block. It never keeps state between calls, which makes it thread-safe and impossible to leak. The design expects the ConnectionFactory to make createConnection() cheap, by handing out a shared connection and treating close() as returning objects to a cache.

So JmsTemplate is not the bug. The bug is giving it a factory that really opens a new connection each time. In Spring Boot, this often happens because the application defines its own ConnectionFactory bean, as above. When a ConnectionFactory bean exists, Boot backs off and does not create its own, and Boot's own factory is the one it would have wrapped in a cache.

4The Fix: Cache or Pool the Factory

Spring's CachingConnectionFactory wraps the provider's factory. It keeps one shared connection, and when a session or producer is closed it keeps it in a cache for the next call instead of closing it. A pooled factory, such as JmsPoolConnectionFactory from the pooled-jms library, keeps several connections and pools sessions on them.

Java
@Bean
CachingConnectionFactory connectionFactory() {
var target = new ActiveMQConnectionFactory("tcp://broker:61616");
var caching = new CachingConnectionFactory(target);
caching.setSessionCacheSize(10); // sessions kept for reuse, default is 1
caching.setCacheProducers(true); // default true
caching.setCacheConsumers(false); // leave consumers to the listener container
return caching;
}
// broker: 1 connection, a few sessions
// about 0.4 ms per message in the same test, so about 4 seconds in total

With Spring Boot, the simplest fix is often to delete the hand-made bean and let the starter configure the factory from properties such as spring.artemis.broker-url. For Artemis, Boot wraps its factory in a CachingConnectionFactory by default (spring.jms.cache.enabled=true), or uses a pooled factory when spring.artemis.pool.enabled=true. The exact properties differ per provider starter, so we check the one we use.

5Keeping Listeners Out of the Way

The same factory is usually shared with @JmsListener containers, and there we must be careful. A DefaultMessageListenerContainer manages its own long-lived consumers and caches them itself, with its cacheLevel setting. If the CachingConnectionFactory also caches consumers, a consumer the container closes stays open in the cache and keeps receiving messages that nobody processes, and dynamic scaling of the container stops working properly. That is why the example sets cacheConsumers to false, which is also Spring Boot's default for its own caching factory (spring.jms.cache.consumers=false).

6Measure Again, Then Batch or Send Asynchronously

After the fix, we measure again rather than assume. If throughput is still not enough, two further steps help. Sending many messages in one transacted session and committing once per batch lets the broker write them together. And with persistent messages, each send normally waits for the broker to confirm the write; the JMS 2.0 asynchronous send, with a CompletionListener, lets the producer keep going while confirmations arrive. Some providers have their own switches for this, so we check the provider's documentation.

Java
jmsTemplate.execute(session -> { // one session for the whole batch
MessageProducer p = session.createProducer(session.createQueue("orders"));
for (Order o : batch) {
p.send(session.createTextMessage(json(o)));
}
return null;
}, true);

Both steps trade something: batches widen the window of messages lost or redone if the sender crashes, and asynchronous sends move error handling into a callback. We take them only when the numbers show we need them.

7Follow-up questions

Is JmsTemplate thread-safe?

Yes. It keeps no state between calls, so one instance can be shared by all threads. Each call obtains its own session from the factory. With a CachingConnectionFactory, the cached sessions are handed to one thread at a time, and the session cache size should be at least the number of threads that send concurrently, or extra sessions are created and closed.

CachingConnectionFactory or a pooled connection factory?

CachingConnectionFactory uses a single connection, which is enough for most senders and is simple. A pool holds several connections, which helps when one connection becomes a bottleneck or when the provider limits sessions per connection. Both fix the per-message handshake; we pick by measuring and by what the provider recommends.

Why not cache consumers in the CachingConnectionFactory?

Because the listener container already manages its consumers. A cached consumer that the container thinks it closed can stay subscribed and receive messages that are never processed until it is closed for real. Leaving consumer caching to the container avoids this.

8Conclusion

In this answer, we saw that JmsTemplate creates and closes a connection, session and producer for every operation and relies on the ConnectionFactory to make that cheap. Given a raw provider factory, each message paid for a full handshake. Wrapping the factory in a CachingConnectionFactory or a pool, or letting Spring Boot configure it, cut the cost per message from about 12 to 0.4 milliseconds in our example. We kept consumer caching to the listener container and measured again before considering batching or asynchronous sends.

What to say in the interviewAbout 80 seconds aloud

Open with

The broker statistics give it away: a connection and session per message means JmsTemplate is working on a raw connection factory. JmsTemplate is stateless by design. For each send it asks the factory for a connection, creates a session and a producer, sends, and closes all three.

Then, if they want more

It expects the factory to make that cheap. If we pass the provider's own factory, every message pays for a TCP connection, authentication and session setup, which can be ten or more milliseconds when the send itself is under one.

The fix is to wrap the factory in Spring's CachingConnectionFactory, which shares one connection and caches sessions and producers, or to use a pooled factory.

In Spring Boot this usually happens because someone defined their own ConnectionFactory bean, so Boot backed off; often the cleanest fix is to remove it and configure the broker through the starter's properties, since Boot's Artemis support caches by default or pools when that's enabled.

One caution: I'd keep consumer caching off on that factory, because DefaultMessageListenerContainer caches its own consumers and double caching can leave orphaned consumers. Then I'd measure again. If it still isn't enough, I'd send batches in one transacted session or use async sends, knowing they change failure handling.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
RabbitMQ documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service sends messages with JmsTemplate in a loop and throughput is very poor; the...": https://scrivio-interview-library.netlify.app/spring-boot/rabbitmq-and-jms/6dfba35c3f/