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:

{% tabs %} {% tab title=”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. }

{% endtab %}

{% tab title=”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();

{% endtab %}

{% tab title=”JavaScript” %}

  1. const sc = StringCodec();
  2. // `max` specifies the number of messages that the server will forward.
  3. // The server will auto-cancel.
  4. const subj = createInbox();
  5. const sub1 = nc.subscribe(subj, {
  6. callback: (_err, msg) => {
  7. t.log(`sub1 ${sc.decode(msg.data)}`);
  8. },
  9. max: 10,
  10. });
  11. // another way after 10 messages
  12. const sub2 = nc.subscribe(subj, {
  13. callback: (_err, msg) => {
  14. t.log(`sub2 ${sc.decode(msg.data)}`);
  15. },
  16. });
  17. // if the subscription already received 10 messages, the handler
  18. // won't get any more messages
  19. sub2.unsubscribe(10);

{% endtab %}

{% tab title=”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'...')

{% endtab %}

{% tab title=”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

{% endtab %}

{% tab title=”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);

{% endtab %} {% endtabs %}