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

  1. nc, err := nats.Connect("demo.nats.io")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. // Subscribe
  7. sub1, err := nc.Subscribe("updates", func(m *nats.Msg) {})
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. // Set limits of 1000 messages or 5MB, whichever comes first
  12. sub1.SetPendingLimits(1000, 5*1024*1024)
  13. // Subscribe
  14. sub2, err := nc.Subscribe("updates", func(m *nats.Msg) {})
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. // Set no limits for this subscription
  19. sub2.SetPendingLimits(-1, -1)
  20. // Close the connection
  21. nc.Close()

Java

  1. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  2. Dispatcher d = nc.createDispatcher((msg) -> {
  3. // do something
  4. });
  5. d.subscribe("updates");
  6. d.setPendingLimits(1_000, 5 * 1024 * 1024); // Set limits on a dispatcher
  7. // Subscribe
  8. Subscription sub = nc.subscribe("updates");
  9. sub.setPendingLimits(1_000, 5 * 1024 * 1024); // Set limits on a subscription
  10. // Do something
  11. // Close the connection
  12. nc.close();

JavaScript

  1. // slow pending limits are not configurable on node-nats

Python

  1. nc = NATS()
  2. await nc.connect(servers=["nats://demo.nats.io:4222"])
  3. future = asyncio.Future()
  4. async def cb(msg):
  5. nonlocal future
  6. future.set_result(msg)
  7. # Set limits of 1000 messages or 5MB
  8. await nc.subscribe("updates", cb=cb, pending_bytes_limit=5*1024*1024, pending_msgs_limit=1000)

Ruby

  1. # The Ruby NATS client currently does not have option to specify a subscribers pending limits.

C

  1. natsConnection *conn = NULL;
  2. natsSubscription *sub1 = NULL;
  3. natsSubscription *sub2 = NULL;
  4. natsStatus s = NATS_OK;
  5. s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
  6. // Subscribe
  7. if (s == NATS_OK)
  8. s = natsConnection_Subscribe(&sub1, conn, "updates", onMsg, NULL);
  9. // Set limits of 1000 messages or 5MB, whichever comes first
  10. if (s == NATS_OK)
  11. s = natsSubscription_SetPendingLimits(sub1, 1000, 5*1024*1024);
  12. // Subscribe
  13. if (s == NATS_OK)
  14. s = natsConnection_Subscribe(&sub2, conn, "updates", onMsg, NULL);
  15. // Set no limits for this subscription
  16. if (s == NATS_OK)
  17. s = natsSubscription_SetPendingLimits(sub2, -1, -1);
  18. (...)
  19. // Destroy objects that were created
  20. natsSubscription_Destroy(sub1);
  21. natsSubscription_Destroy(sub2);
  22. natsConnection_Destroy(conn);

{% endtabs %}

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

  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. // Do something with the connection

Java

  1. class SlowConsumerReporter implements ErrorListener {
  2. public void errorOccurred(Connection conn, String error)
  3. {
  4. }
  5. public void exceptionOccurred(Connection conn, Exception exp) {
  6. }
  7. // Detect slow consumers
  8. public void slowConsumerDetected(Connection conn, Consumer consumer) {
  9. // Get the dropped count
  10. System.out.println("A slow consumer dropped messages: "+ consumer.getDroppedCount());
  11. }
  12. }
  13. public class SlowConsumerListener {
  14. public static void main(String[] args) {
  15. try {
  16. Options options = new Options.Builder().
  17. server("nats://demo.nats.io:4222").
  18. errorListener(new SlowConsumerReporter()). // Set the listener
  19. build();
  20. Connection nc = Nats.connect(options);
  21. // Do something with the connection
  22. nc.close();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

JavaScript

  1. // slow consumer detection is not configurable on NATS JavaScript client.

Python

  1. nc = NATS()
  2. async def error_cb(e):
  3. if type(e) is nats.aio.errors.ErrSlowConsumer:
  4. print("Slow consumer error, unsubscribing from handling further messages...")
  5. await nc.unsubscribe(e.sid)
  6. await nc.connect(
  7. servers=["nats://demo.nats.io:4222"],
  8. error_cb=error_cb,
  9. )
  10. msgs = []
  11. future = asyncio.Future()
  12. async def cb(msg):
  13. nonlocal msgs
  14. nonlocal future
  15. print(msg)
  16. msgs.append(msg)
  17. if len(msgs) == 3:
  18. # Head of line blocking on other messages caused
  19. # by single message processing taking too long...
  20. await asyncio.sleep(1)
  21. await nc.subscribe("updates", cb=cb, pending_msgs_limit=5)
  22. for i in range(0, 10):
  23. await nc.publish("updates", "msg #{}".format(i).encode())
  24. await asyncio.sleep(0)
  25. try:
  26. await asyncio.wait_for(future, 1)
  27. except asyncio.TimeoutError:
  28. pass
  29. for msg in msgs:
  30. print("[Received]", msg)
  31. await nc.close()

Ruby

  1. # The Ruby NATS client currently does not have option to customize slow consumer limits per sub.

C

  1. static void
  2. errorCB(natsConnection *conn, natsSubscription *sub, natsStatus s, void *closure)
  3. {
  4. // Do something
  5. printf("Error: %d - %s", s, natsStatus_GetText(s));
  6. }
  7. (...)
  8. natsConnection *conn = NULL;
  9. natsOptions *opts = NULL;
  10. natsStatus s = NATS_OK;
  11. s = natsOptions_Create(&opts);
  12. if (s == NATS_OK)
  13. s = natsOptions_SetErrorHandler(opts, errorCB, NULL);
  14. if (s == NATS_OK)
  15. s = natsConnection_Connect(&conn, opts);
  16. (...)
  17. // Destroy objects that were created
  18. natsConnection_Destroy(conn);
  19. natsOptions_Destroy(opts);

{% endtabs %}