Powered By GitBook
Slow Consumers
NATS is designed to move messages through the server quickly. As a result, NATS depends on the applications to consider and respond to changing message rates. The server will do a bit of impedance matching, but if a client is too slow the server will eventually cut them off by closing the connection. These cut off connections are called slow consumers.
One way some of the libraries deal with bursty message traffic is to buffer incoming messages for a subscription. So if an application can handle 10 messages per second and sometimes receives 20 messages per second, the library may hold the extra 10 to give the application time to catch up. To the server, the application will appear to be handling the messages and consider the connection healthy. Most client libraries will notify the application that there is a SlowConsumer error and discard messages.
Receiving and dropping messages from the server keeps the connection to the server healthy, but creates an application requirement. There are several common patterns:
    Use request/reply to throttle the sender and prevent overloading the subscriber
    Use a queue with multiple subscribers splitting the work
    Persist messages with something like NATS streaming
Libraries that cache incoming messages may provide two controls on the incoming queue, or pending messages. These are useful if the problem is bursty publishers and not a continuous performance mismatch. Disabling these limits can be dangerous in production and although setting these limits to 0 may help find problems, it is also a dangerous proposition in production.
Check your libraries documentation for the default settings, and support for disabling these limits.
The incoming cache is usually per subscriber, but again, check the specific documentation for your client library.

Limiting Incoming/Pending Messages by Count and Bytes

The first way that the incoming queue can be limited is by message count. The second way to limit the incoming queue is by total size. For example, to limit the incoming cache to 1,000 messages or 5mb whichever comes first:
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
nc, err := nats.Connect("demo.nats.io")
2
if err != nil {
3
log.Fatal(err)
4
}
5
defer nc.Close()
6
7
// Subscribe
8
sub1, err := nc.Subscribe("updates", func(m *nats.Msg) {})
9
if err != nil {
10
log.Fatal(err)
11
}
12
13
// Set limits of 1000 messages or 5MB, whichever comes first
14
sub1.SetPendingLimits(1000, 5*1024*1024)
15
16
// Subscribe
17
sub2, err := nc.Subscribe("updates", func(m *nats.Msg) {})
18
if err != nil {
19
log.Fatal(err)
20
}
21
22
// Set no limits for this subscription
23
sub2.SetPendingLimits(-1, -1)
24
25
// Close the connection
26
nc.Close()
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
Dispatcher d = nc.createDispatcher((msg) -> {
4
// do something
5
});
6
7
d.subscribe("updates");
8
9
d.setPendingLimits(1_000, 5 * 1024 * 1024); // Set limits on a dispatcher
10
11
// Subscribe
12
Subscription sub = nc.subscribe("updates");
13
14
sub.setPendingLimits(1_000, 5 * 1024 * 1024); // Set limits on a subscription
15
16
// Do something
17
18
// Close the connection
19
nc.close();
Copied!
1
// slow pending limits are not configurable on node-nats
Copied!
1
nc = NATS()
2
3
await nc.connect(servers=["nats://demo.nats.io:4222"])
4
5
future = asyncio.Future()
6
7
async def cb(msg):
8
nonlocal future
9
future.set_result(msg)
10
11
# Set limits of 1000 messages or 5MB
12
await nc.subscribe("updates", cb=cb, pending_bytes_limit=5*1024*1024, pending_msgs_limit=1000)
Copied!
1
# The Ruby NATS client currently does not have option to specify a subscribers pending limits.
Copied!
1
// slow pending limits are not configurable on TypeScript NATS client.
Copied!
1
natsConnection *conn = NULL;
2
natsSubscription *sub1 = NULL;
3
natsSubscription *sub2 = NULL;
4
natsStatus s = NATS_OK;
5
6
s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
7
8
// Subscribe
9
if (s == NATS_OK)
10
s = natsConnection_Subscribe(&sub1, conn, "updates", onMsg, NULL);
11
12
// Set limits of 1000 messages or 5MB, whichever comes first
13
if (s == NATS_OK)
14
s = natsSubscription_SetPendingLimits(sub1, 1000, 5*1024*1024);
15
16
// Subscribe
17
if (s == NATS_OK)
18
s = natsConnection_Subscribe(&sub2, conn, "updates", onMsg, NULL);
19
20
// Set no limits for this subscription
21
if (s == NATS_OK)
22
s = natsSubscription_SetPendingLimits(sub2, -1, -1);
23
24
(...)
25
26
// Destroy objects that were created
27
natsSubscription_Destroy(sub1);
28
natsSubscription_Destroy(sub2);
29
natsConnection_Destroy(conn);
Copied!

Detect a Slow Consumer and Check for Dropped Messages

When a slow consumer is detected and messages are about to be dropped, the library may notify the application. This process may be similar to other errors or may involve a custom callback.
Some libraries, like Java, will not send this notification on every dropped message because that could be noisy. Rather the notification may be sent once per time the subscriber gets behind. Libraries may also provide a way to get a count of dropped messages so that applications can at least detect a problem is occurring.
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
// Set the callback that will be invoked when an asynchronous error occurs.
2
nc, err := nats.Connect("demo.nats.io", nats.ErrorHandler(logSlowConsumer))
3
if err != nil {
4
log.Fatal(err)
5
}
6
defer nc.Close()
7
8
// Do something with the connection
Copied!
1
class SlowConsumerReporter implements ErrorListener {
2
public void errorOccurred(Connection conn, String error)
3
{
4
}
5
6
public void exceptionOccurred(Connection conn, Exception exp) {
7
}
8
9
// Detect slow consumers
10
public void slowConsumerDetected(Connection conn, Consumer consumer) {
11
// Get the dropped count
12
System.out.println("A slow consumer dropped messages: "+ consumer.getDroppedCount());
13
}
14
}
15
16
public class SlowConsumerListener {
17
public static void main(String[] args) {
18
19
try {
20
Options options = new Options.Builder().
21
server("nats://demo.nats.io:4222").
22
errorListener(new SlowConsumerReporter()). // Set the listener
23
build();
24
Connection nc = Nats.connect(options);
25
26
// Do something with the connection
27
28
nc.close();
29
} catch (Exception e) {
30
e.printStackTrace();
31
}
32
}
33
}
Copied!
1
// slow consumer detection is not configurable on NATS JavaScript client.
Copied!
1
nc = NATS()
2
3
async def error_cb(e):
4
if type(e) is nats.aio.errors.ErrSlowConsumer:
5
print("Slow consumer error, unsubscribing from handling further messages...")
6
await nc.unsubscribe(e.sid)
7
8
await nc.connect(
9
servers=["nats://demo.nats.io:4222"],
10
error_cb=error_cb,
11
)
12
13
msgs = []
14
future = asyncio.Future()
15
async def cb(msg):
16
nonlocal msgs
17
nonlocal future
18
print(msg)
19
msgs.append(msg)
20
21
if len(msgs) == 3:
22
# Head of line blocking on other messages caused
23
# by single message processing taking too long...
24
await asyncio.sleep(1)
25
26
await nc.subscribe("updates", cb=cb, pending_msgs_limit=5)
27
28
for i in range(0, 10):
29
await nc.publish("updates", "msg #{}".format(i).encode())
30
await asyncio.sleep(0)
31
32
try:
33
await asyncio.wait_for(future, 1)
34
except asyncio.TimeoutError:
35
pass
36
37
for msg in msgs:
38
print("[Received]", msg)
39
40
await nc.close()
Copied!
1
# The Ruby NATS client currently does not have option to customize slow consumer limits per sub.
Copied!
1
// slow consumer detection is not configurable on NATS TypeScript client.
Copied!
1
static void
2
errorCB(natsConnection *conn, natsSubscription *sub, natsStatus s, void *closure)
3
{
4
5
// Do something
6
printf("Error: %d - %s", s, natsStatus_GetText(s));
7
}
8
9
(...)
10
11
natsConnection *conn = NULL;
12
natsOptions *opts = NULL;
13
natsStatus s = NATS_OK;
14
15
s = natsOptions_Create(&opts);
16
if (s == NATS_OK)
17
s = natsOptions_SetErrorHandler(opts, errorCB, NULL);
18
if (s == NATS_OK)
19
s = natsConnection_Connect(&conn, opts);
20
21
(...)
22
23
// Destroy objects that were created
24
natsConnection_Destroy(conn);
25
natsOptions_Destroy(opts);
Copied!
Last modified 1yr ago