Pausing Between Reconnect Attempts

It doesn’t make much sense to try to connect to the same server over and over. To prevent this sort of thrashing, and wasted reconnect attempts, especially when using TLS, libraries provide a wait setting. Generally clients make sure that between two reconnect attempts to the same server at least a certain amount of time has passed. The concrete implementation depends on the library used.

This setting not only prevents wasting client resources, it also alleviates a thundering herd situation when additional servers are not available.

Go

  1. // Set reconnect interval to 10 seconds
  2. nc, err := nats.Connect("demo.nats.io", nats.ReconnectWait(10*time.Second))
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer nc.Close()
  7. // Do something with the connection

Java

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. reconnectWait(Duration.ofSeconds(10)). // Set Reconnect Wait
  4. build();
  5. Connection nc = Nats.connect(options);
  6. // Do something with the connection
  7. nc.close();

JavaScript

  1. const nc = await connect({
  2. reconnectTimeWait: 10 * 1000, // 10s
  3. servers: ["demo.nats.io"],
  4. });

Python

  1. nc = NATS()
  2. await nc.connect(
  3. servers=["nats://demo.nats.io:4222"],
  4. reconnect_time_wait=10,
  5. )
  6. # Do something with the connection
  7. await nc.close()

Ruby

  1. require 'nats/client'
  2. NATS.start(servers: ["nats://127.0.0.1:1222", "nats://127.0.0.1:1223", "nats://127.0.0.1:1224"], reconnect_time_wait: 10) do |nc|
  3. # Do something with the connection
  4. # Close the connection
  5. nc.close
  6. end

C

  1. natsConnection *conn = NULL;
  2. natsOptions *opts = NULL;
  3. natsStatus s = NATS_OK;
  4. s = natsOptions_Create(&opts);
  5. if (s == NATS_OK)
  6. // Set reconnect interval to 10 seconds (10,000 milliseconds)
  7. s = natsOptions_SetReconnectWait(opts, 10000);
  8. if (s == NATS_OK)
  9. s = natsConnection_Connect(&conn, opts);
  10. (...)
  11. // Destroy objects that were created
  12. natsConnection_Destroy(conn);
  13. natsOptions_Destroy(opts);

{% endtabs %}