Unsubscribing After N Messages

NATS provides a special form of unsubscribe that is configured with a message count and takes effect when that many messages are sent to a subscriber. This mechanism is very useful if only a single message is expected.

The message count you provide is the total message count for a subscriber. So if you unsubscribe with a count of 1, the server will stop sending messages to that subscription after it has received one message. If the subscriber has already received one or more messages, the unsubscribe will be immediate. This action based on history can be confusing if you try to auto-unsubscribe on a long running subscription, but is logical for a new one.

Auto-unsubscribe is based on the total messages sent to a subscriber, not just the new ones. Most of the client libraries also track the max message count after an auto-unsubscribe request. On reconnect, this enables clients to resend the unsubscribe with an updated total.

The following example shows unsubscribe after a single message:

Go

  1. nc, err := nats.Connect("demo.nats.io")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. // Sync Subscription
  7. sub, err := nc.SubscribeSync("updates")
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. if err := sub.AutoUnsubscribe(1); err != nil {
  12. log.Fatal(err)
  13. }
  14. // Async Subscription
  15. sub, err = nc.Subscribe("updates", func(_ *nats.Msg) {})
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. if err := sub.AutoUnsubscribe(1); err != nil {
  20. log.Fatal(err)
  21. }

Java

  1. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  2. Dispatcher d = nc.createDispatcher((msg) -> {
  3. String str = new String(msg.getData(), StandardCharsets.UTF_8);
  4. System.out.println(str);
  5. });
  6. // Sync Subscription
  7. Subscription sub = nc.subscribe("updates");
  8. sub.unsubscribe(1);
  9. // Async Subscription
  10. d.subscribe("updates");
  11. d.unsubscribe("updates", 1);
  12. // Close the connection
  13. nc.close();

JavaScript

  1. let nc = NATS.connect({
  2. url: "nats://demo.nats.io:4222"
  3. });
  4. // `max` specifies the number of messages that the server will forward
  5. // The server will auto-cancel.
  6. let opts = {max: 10};
  7. let sub = nc.subscribe(NATS.createInbox(), opts, (msg) => {
  8. t.log(msg);
  9. });
  10. // another way after 10 messages
  11. let sub2 = nc.subscribe(NATS.createInbox(), (err, msg) => {
  12. t.log(msg.data);
  13. });
  14. // if the subscription already received 10 messages, the handler
  15. // won't get any more messages
  16. nc.unsubscribe(sub2, 10);

Python

  1. nc = NATS()
  2. await nc.connect(servers=["nats://demo.nats.io:4222"])
  3. async def cb(msg):
  4. print(msg)
  5. sid = await nc.subscribe("updates", cb=cb)
  6. await nc.auto_unsubscribe(sid, 1)
  7. await nc.publish("updates", b'All is Well')
  8. # Won't be received...
  9. await nc.publish("updates", b'...')

Ruby

  1. require 'nats/client'
  2. require 'fiber'
  3. NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
  4. Fiber.new do
  5. f = Fiber.current
  6. nc.subscribe("time", max: 1) do |msg, reply|
  7. f.resume Time.now
  8. end
  9. nc.publish("time", 'What is the time?', NATS.create_inbox)
  10. # Use the response
  11. msg = Fiber.yield
  12. puts "Reply: #{msg}"
  13. # Won't be received
  14. nc.publish("time", 'What is the time?', NATS.create_inbox)
  15. end.resume
  16. end

TypeScript

  1. // `max` specifies the number of messages that the server will forward
  2. // The server will auto-cancel
  3. let opts = {max: 10};
  4. let sub = await nc.subscribe(createInbox(), (err, msg) => {
  5. t.log(msg.data);
  6. }, opts);
  7. // another way after 10 messages
  8. let sub2 = await nc.subscribe(createInbox(), (err, msg) => {
  9. t.log(msg.data);
  10. });
  11. // if the subscription already received 10 messages, the handler
  12. // won't get any more messages
  13. sub2.unsubscribe(10);

C

  1. natsConnection *conn = NULL;
  2. natsSubscription *sub = NULL;
  3. natsMsg *msg = NULL;
  4. natsStatus s = NATS_OK;
  5. s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
  6. // Subscribe
  7. if (s == NATS_OK)
  8. s = natsConnection_SubscribeSync(&sub, conn, "updates");
  9. // Unsubscribe after 1 message is received
  10. if (s == NATS_OK)
  11. s = natsSubscription_AutoUnsubscribe(sub, 1);
  12. // Wait for messages
  13. if (s == NATS_OK)
  14. s = natsSubscription_NextMsg(&msg, sub, 10000);
  15. if (s == NATS_OK)
  16. {
  17. printf("Received msg: %s - %.*s\n",
  18. natsMsg_GetSubject(msg),
  19. natsMsg_GetDataLength(msg),
  20. natsMsg_GetData(msg));
  21. // Destroy message that was received
  22. natsMsg_Destroy(msg);
  23. }
  24. (...)
  25. // Destroy objects that were created
  26. natsSubscription_Destroy(sub);
  27. natsConnection_Destroy(conn);