Connection
Connecting
NATS.connect — Functionconnect(; ...)
connect(url; options...)
Connect to the NATS server. The function is blocking until the connection is initialized. In case of an error during the initialization process connect will throw an exception if retry_on_init_fail is set to false (what is the default). Otherwise a handle will be returned and reconnect will continue in the background.
Options are:
verbose: turns on protocol acknowledgementspedantic: turns on additional strict format checking, e.g. for properly formed subjectstls_required: indicates whether the client requires an SSL connectiontls_ca_path: CA certificate file pathtls_cert_path: client public certificate filetls_key_path: client private certificate filetls_server_name: name the server certificate is verified against, defaults to the URL hosttls_verify_peer: verify the server certificate. Default istruetls_verify_hostname: verify the server certificate is issued fortls_server_name. Defaults totls_verify_peerauth_token: client authorization tokenuser: connection usernamepass: connection passwordname: client nameecho: if set tofalse, the server will not send originating messages from this connection to its own subscriptionsjwt: the JWT that identifies a user's 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 clientnkey_seed: the private NKey to authenticate the clientping_interval: interval in seconds how often the server should be pinged to check connection health. Default is 120.0 secondsmax_pings_out: how many pings in a row might fail before the connection will be restarted. Default is2retry_on_init_fail: if set a connection handle will be returned even if the initial connect fails. Otherwise the error causing failure will be thrown. Default isfalseignore_advertised_servers: ignores other cluster servers returned by the server. Default isfalseretain_servers_order: try to connect to the server in the order specified inurlor the list returned by the server. Default isfalsesend_enqueue_when_disconnected: allows buffering outgoing messages during disconnection. Default istruereconnect_delays: vector of delays in seconds (or anExponentialBackOff) 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 the buffer of messages pending. Default is2097152bytes, if too small operations that send messages to the server (e.g.publish) may throw an exceptiondrain_timeout: Timeout for the drain process. After the timeout in case of not everything is processed drain will stop and an error will be reported.drain_poll: Interval fordrainto check if all messages in buffers are processed.inbox_prefix: prefix of the subjects replies to requests come on, without a trailing dot. Default is"_INBOX", change it when server permissions allow replies only under another prefixmonitoring_throttle_seconds: How often problems of subscriptions (handler errors, full channel, too many handlers) are reported in logs. Default is5.0secondsmonitoring_handlers_limit: How many handlers of a subscription can run at once before a warning is reported in logs. Default is1000monitoring_channel_level: Fraction of the subscription channel in use above which a warning is reported in logs. Default is0.8
Reconnecting
Reconnect can be forced by a user with the reconnect function. This function can be also used for reconnect a connection in DISCONNECTED state after reconnect retries were exhausted.
NATS.reconnect — Functionreconnect(connection; should_wait)
Force a connection reconnect. If the 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 subscriptions restored. In case the connection is already CONNECTING this method has no effect. If called on a connection that is DRAINING or DRAINED an error will be thrown.
During the reconnect period some messages both published and received by the connection might be lost.
Optional keyword arguments:
should_wait: Iftruethe method will block until the reconnection process is started, default istrue.
Disconnecting
To gracefully close a connection the drain function is provided.
NATS.drain — Methoddrain(connection)
Unsubscribe all subscriptions, wait for processing all messages in the buffers, then close the connection. A drained connection is no more usable. This method is used to gracefully stop the process.
Underneath it periodically checks for the state of all buffers, the interval for checks is configurable per connection with the drain_poll parameter of the connect method. It can also be set globally with the NATS_DRAIN_POLL_INTERVAL_SECONDS environment variable. If not set explicitly the default polling interval is 0.2 seconds.
An error will be written to the log if the drain is not finished until the timeout expires. The default timeout value is configurable per connection on connect with drain_timeout. It can be also set globally with the NATS_DRAIN_TIMEOUT_SECONDS environment variable. If not set explicitly the default drain timeout is 5.0 seconds.
If connection is reconnecting, drain may wait for connection attempt to finish. Time spent reconnecting is not included in drain_timeout.
To use NATS it is needed to create a connection handle with the connect function. A connection creates asynchronous tasks to handle messages from the server, sending published messages, monitor the state of the TCP connection and reconnect on network failure.
Connection lifecycle
When connect is called it tries to initialize a connection with the NATS server. If this process fails two things may happen depending on retry_on_init_fail option:
- Rethrow the exception causing protocol initialization failure.
- Return a connection in state
CONNECTINGcontinuing the reconnect process in the background
Otherwise a connection in CONNECTED state is returned from connect.
In case of some critical failure like a TCP connection closing or a malformed protocol message the connection will enter CONNECTING and try reconnect according to the reconnect_delays specified. If it is unable to establish a connection with the allowed retries the connection will land in DISCONNECTED state and only manual invocation of reconnect may restore it.
Authentication
NATS supports several authentication schemes, including username/password, tokens, TLS certificates, and public-key authentication via NKeys.
NKeys
When connecting with an NKey private seed (nkey_seed), you can derive the corresponding public NKey (nkey) using public_key:
NATS.public_key — Functionpublic_key(nkey_seed::String) -> StringDerive the public NKey string (e.g. "U..." for a user seed) from a private NKey nkey_seed ("S..."). This is the identity the server authenticates via sign; useful for principal mapping and audit without exposing the seed. The role is taken from the seed's second character, so a user seed yields a U key, an account seed an A key, and so on.
NATS.sign — Functionsign(nonce::String, nkey_seed::String) -> StringSign a server challenge nonce with a private nkey_seed ("S...") using Ed25519. Returns the URL-safe Base64-encoded detached signature sent in the CONNECT protocol message.
Environment variables
There are several ENV variables defined to provide default parameters for connect. It is advised to rather define ENV variables and use a parameterless invocation like NATS.connect() for better code portability.
| Parameter | ENV variable | Default value | Sent to server |
|---|---|---|---|
url | NATS_CONNECT_URL | localhost:4222 | no |
verbose | NATS_VERBOSE | false | yes |
verbose | NATS_VERBOSE | false | yes |
pedantic | NATS_PEDANTIC | false | yes |
tls_required | NATS_TLS_REQUIRED | false | yes |
auth_token | NATS_AUTH_TOKEN | yes | |
user | NATS_USER | yes | |
pass | NATS_PASS | yes | |
jwt | NATS_JWT | yes | |
nkey | NATS_NKEY | yes | |
nkey_seed | NATS_NKEY_SEED | no | |
tls_ca_path | NATS_TLS_CA_PATH | no | |
tls_cert_path | NATS_TLS_CERT_PATH | no | |
tls_key_path | NATS_TLS_KEY_PATH | no | |
tls_server_name | NATS_TLS_SERVER_NAME | URL host | no |
tls_verify_peer | NATS_TLS_VERIFY_PEER | true | no |
tls_verify_hostname | NATS_TLS_VERIFY_HOSTNAME | tls_verify_peer | no |
tls_verify_peer = false accepts any server certificate, and tls_verify_hostname = false accepts any certificate signed by a trusted CA. Either allows a man-in-the-middle, so connect logs a warning. To connect by IP address to a server whose certificate names its host, set tls_server_name instead.
Additionally some parameters are provided to fine tune the client for a specific deployment setup.
| Parameter | ENV variable | Default value | Sent to server |
|---|---|---|---|
ping_interval | NATS_PING_INTERVAL_SECONDS | 120 | no |
max_pings_out | NATS_MAX_PINGS_OUT | 2 | no |
retry_on_init_fail | NATS_RETRY_ON_INIT_FAIL | false | no |
ignore_advertised_servers | NATS_IGNORE_ADVERTISED_SERVERS | false | no |
retain_servers_order | NATS_RETAIN_SERVERS_ORDER | false | no |
drain_timeout | NATS_DRAIN_TIMEOUT_SECONDS | 5.0 | no |
drain_poll | NATS_DRAIN_POLL_INTERVAL_SECONDS | 0.2 | no |
inbox_prefix | NATS_INBOX_PREFIX | _INBOX | no |
send_buffer_limit | NATS_SEND_BUFFER_LIMIT_BYTES | 2097152 | no |
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 an argument.
ENV variable | Default value |
|---|---|
NATS_RECONNECT_RETRIES | 220752000000000000 |
NATS_RECONNECT_FIRST_DELAY | 0.1 |
NATS_RECONNECT_MAX_DELAY | 5.0 |
NATS_RECONNECT_FACTOR | 5.0 |
NATS_RECONNECT_JITTER | 0.1 |