Connection

Connecting

NATS.connectFunction
connect(; ...)
connect(url; options...)

Connect to NATS server. The function is blocking until connection is initialized. In case of error during initialization process connect will throw exception if retry_on_init_fail is set to false (what is default). Otherwise handle will be returned and reconnect will continue in background.

Options are:

  • verbose: turns on protocol acknowledgements
  • pedantic: turns on additional strict format checking, e.g. for properly formed subjects
  • tls_required: indicates whether the client requires SSL connection
  • tls_ca_path: CA certuficate file path
  • tls_cert_path: client public certificate file
  • tls_key_path: client private certificate file
  • auth_token: client authorization token
  • user: connection username
  • pass: connection password
  • name: client name
  • echo: if set to false, the server will not send originating messages from this connection to its own subscriptions
  • jwt: the JWT that identifies a user permissions and account.
  • no_responders: enable quick replies for cases where a request is sent to a topic with no responders.
  • nkey: the public NKey to authenticate the client
  • nkey_seed: the private NKey to authenticate the client
  • ping_interval: interval in seconds how often server should be pinged to check connection health. Default is 120.0 seconds
  • max_pings_out: how many pings in a row might fail before connection will be restarted. Default is 2
  • retry_on_init_fail: if set connection handle will be returned even if initial connect fails. Otherwise error causing failure will be trown. Default is false
  • ignore_advertised_servers: ignores other cluster servers returned by server. Default is false
  • retain_servers_order: try to connect server in order specified in url or list returned by the server. Defaylt is false
  • send_enqueue_when_disconnected: allows buffering outgoing messages during disconnection. Default is true
  • reconnect_delays: vector of delays that reconnect is performed until connected again, by default it will try to reconnect every second without time limit.
  • send_buffer_limit: soft limit for buffer of messages pending. Default is 2097152 bytes, if too small operations that send messages to server (e.g. publish) may throw an exception
  • drain_timeout: Timeout for drain process. After timeout in case of not everyting is processed drain will stop and error will be reported.
  • drain_poll: Interval for drain to check if all messages in buffers are processed.
source

Reconnecting

Reconnect can be forced by user with reconnect function. This function can be also used for reconnect a connection in DISCONNECTED state after reconnect retries were exhausted.

NATS.reconnectFunction
reconnect(connection; should_wait)

Force a connection reconnect. If connection is CONNECTED this will close it and reopen again resubscribing all existing subscriptions. If connection is DISCONNECTED it will try to connect with all previously existing subscription restored. In case connection is already CONNECTING this method have no effect. If called on connection that is DRAINING or DRAINED error will be thrown.

During reconnect period some messages both published and received by the connection might be lost.

Optional keyword aruguments:

  • should_wait: If true method will block until reconnection process is started, default is true.
source

Disconnecting

To gracefully close connection drain function is provided.

NATS.drainMethod
drain(connection)

Unsubscribe all subscriptions, wait for precessing all messages in buffers, then close connection. Drained connection is no more usable. This method is used to gracefuly stop the process.

Underneeth it periodicaly checks for state of all buffers, interval for checks is configurable per connection with drain_poll parameter of connect method. It can also be set globally with NATS_DRAIN_POLL_INTERVAL_SECONDS environment variable. If not set explicitly default polling interval is 0.2 seconds.

Error will be written to log if drain not finished until timeout expires. Default timeout value is configurable per connection on connect with drain_timeout. Can be also set globally with NATS_DRAIN_TIMEOUT_SECONDS environment variable. If not set explicitly default drain timeout is 5.0 seconds.

source

To use NATS it is needed to create connection handle with connect function. Connection creates asynchronous tasks to handle messages from server, sending published messages, monitor state of TCP connection and reconnect on network failure.

Connection lifecycle

When connect is called it tries to initialize connection with NATS server. If this process fails two things may happen depending on retry_on_init_fail option:

  1. Rethrow exception causing protocol initialization failure.
  2. Return connection in state CONNECTING continuing reconnect process in background

Other wise connection in CONNECTED state is returned from connect.

In case of some critical failure like TCP connection closing or mallformed protocol message conection will enter CONNECTING and try reconnect according reconnect_delays specified. If it is unable to establish connection with allowed retries connection will land in DISCONNECTED state and only manual invocation of reconnect may restore it.

Environment variables

There are several ENV variables defined to provide default parameters for connect. It is advised to rather define ENV variables and use parameter less invocation like NATS.connect() for better code portability.

ParameterENV variableDefault valueSent to server
urlNATS_CONNECT_URLlocalhost:4222no
verboseNATS_VERBOSEfalseyes
verboseNATS_VERBOSEfalseyes
pedanticNATS_PEDANTICfalseyes
tls_requiredNATS_TLS_REQUIREDfalseyes
auth_tokenNATS_AUTH_TOKENyes
userNATS_USERyes
passNATS_PASSyes
jwtNATS_JWTyes
nkeyNATS_NKEYyes
nkey_seedNATS_NKEY_SEEDno
tls_ca_pathNATS_TLS_CA_PATHno
tls_cert_pathNATS_TLS_CERT_PATHno
tls_key_pathNATS_TLS_KEY_PATHno

Additionally some parameters are provided to fine tune client for specific deployment setup.

ParameterENV variableDefault valueSent to server
ping_intervalNATS_PING_INTERVAL_SECONDS120no
max_pings_outNATS_MAX_PINGS_OUT2no
retry_on_init_failNATS_RETRY_ON_INIT_FAILfalseno
ignore_advertised_serversNATS_IGNORE_ADVERTISED_SERVERSfalseno
retain_servers_orderNATS_RETAIN_SERVERS_ORDERfalseno
drain_timeoutNATS_DRAIN_TIMEOUT_SECONDS5.0no
drain_pollNATS_DRAIN_POLL_INTERVAL_SECONDS0.2no
send_buffer_limitNATS_SEND_BUFFER_LIMIT_BYTES2097152no

Reconnect reconnect_delays default ExponentialBackOff also can be configured from ENV variables. This is recommended to configure it with them rather than pass delays as argument.

ENV variableDefault value
NATS_RECONNECT_RETRIES220752000000000000
NATS_RECONNECT_FIRST_DELAY0.1
NATS_RECONNECT_MAX_DELAY5.0
NATS_RECONNECT_FACTOR5.0
NATS_RECONNECT_JITTER0.1