NATS protocol

The NATS wire protocol is a simple, text-based publish/subscribe style protocol. Clients connect to and communicate with gnatsd (the NATS server) through a regular TCP/IP socket using a small set of protocol operations that are terminated by newline.

Unlike traditional messaging systems that use a binary message format that require an API to consume, the text-based NATS protocol makes it easy to implement clients in a wide variety of programming and scripting languages.

NATS protocol conventions

Subject names: Subject names, including reply subject (INBOX) names, are case-sensitive and must be non-empty alphanumeric strings with no embedded whitespace, and optionally token-delimited using the dot character (.), e.g.:

Wildcards: NATS supports the use of wildcards in subject subscriptions.

The asterisk character (*) matches any token at any level of the subject.

The greater than symbol (>), also known as the full wildcard, matches one or more tokens at the tail of a subject, and must be the last token. The wildcarded subject foo.> will match foo.bar or foo.bar.baz.1, but not foo.

Wildcards must be separate tokens (foo.*.baz or foo.> are syntactically valid; foo*.bar, f*o.b*r and foo> are not)

For example, the wildcard subscriptions foo.*.quux and foo.> both match foo.bar.quux, but only the latter matches foo.bar.baz. With the full wildcard,
it is also possible to express interest in every subject that may exist in NATS: sub > 1.

Field Delimiters: The fields of NATS protocol messages are delimited by whitespace characters ‘’ (space) or \t (tab).
Multiple whitespace characters will be treated as a single field delimiter.

Newlines: Like other text-based protocols, NATS uses CR followed by LF (CR+LF, \r\n, 0x0D0A) to terminate protocol messages.
This newline sequence is also used to mark the beginning of the actual message payload in a PUB or MSG protocol message.

auth_required: If this is set, then the client should try to authenticate upon connect.

ssl_required: If this is set, then the client must authenticate using SSL.

max_payload: Maximum payload size that the server will accept from the client.

connect_urls : An optional list of server urls that a client can connect to.

Description

As soon as the server accepts a connection from the client, it will send information about itself and the configuration and security requirements that are necessary for the client to successfully authenticate with the server and exchange messages.

When using the updated client protocol (see CONNECT below), INFO messages can be sent anytime by the server. This means clients with that protocol level need to be able to asynchronously handle INFO messages.

connect_urls

The connect_urls field is a list of urls the server may send when a client first connects, and when there are changes to server cluster topology. This field is considered optional, and may be omitted based on server configuration and client protocol level.

When a NATS server cluster expands, an INFO message is sent to the client with an updated connect_urls list. This cloud-friendly feature asynchronously notifies a client of known servers, allowing it to connect to servers not originally configured.

The connect_urls will contain a list of strings with an IP and port, looking like this: "connect_urls":["10.0.0.184:4333","192.168.129.1:4333","192.168.192.1:4333"]

Example

Below you can see a sample connection string from a telnet connection to the demo.nats.io site.

Description

The CONNECT message is analogous to the INFO message. Once the client has established a TCP/IP socket connection with the NATS server, and an INFO message has been received from the server, the client may send a CONNECT message to the NATS server to provide more information about the current connection as well as security information.

Example

Most clients set verbose to false by default. This means that the server should not confirm each message it receives on this connection with a +OK back to the client.

PUB

Syntax

PUB <subject> [reply-to] <#bytes>\r\n[payload]\r\n

where:

subject: The destination subject to publish to

reply-to: The reply inbox subject that subscribers can use to send a response back to the publisher/requestor

#bytes: The payload size in bytes

payload: The message payload data

Description

The PUB message publishes the message payload to the given subject name, optionally supplying a reply subject. If a reply subject is supplied, it will be delivered to eligible subscribers along with the supplied payload. Note that the payload itself is optional. To omit the payload, set the payload size to 0.

Description

SUB initiates a subscription to a subject, optionally joining a distributed queue group.

Example

To subscribe to the subject FOO with the connection-unique subscription identifier (sid) 1:

SUB FOO 1\r\n

To subscribe the current connection to the subject BAR as part of distribution queue group G1 with sid 44:

SUB BAR G1 44\r\n

UNSUB

Syntax

UNSUB <sid> [max_msgs]

where:

sid: The unique alphanumeric subscription ID of the subject to unsubscribe from

max_msgs: Number of messages to wait for before automatically unsubscribing

Description

UNSUB unsubcribes the connection from the specified subject, or auto-unsubscribes after the specified number of messages has been received.

Example

The following examples concern subject FOO which has been assigned sid 1. To unsubscribe from FOO:

UNSUB 1\r\n

To auto-unsubscribe from FOO after 5 messages have been received:

UNSUB 1 5\r\n

MSG

Syntax

MSG <subject> <sid> [reply-to] <#bytes>\r\n[payload]\r\n

where:

subject: Subject name this message was received on

sid: The unique alphanumeric subscription ID of the subject

reply-to: The inbox subject on which the publisher is listening for responses

#bytes: Size of the payload in bytes

payload: The message payload data

Description

The MSG protocol message delivers a message to the client.

Example

The following message delivers a message from subject FOO.BAR:

MSG FOO.BAR 9 11\r\nHello World\r\n

Deliver the same message along with a reply inbox:

MSG FOO.BAR 9 INBOX.34 11\r\nHello World\r\n

PING/PONG

Description

PING and PONG implement a simple keep-alive mechanism between client and server. Once a client establishes a connection to the NATS server, the server will continuously send PING messages to the client at a configurable interval. If the client fails to respond with a PONG message within the configured response interval, the server will terminate its connection. If your connection stays idle for too long, it is cut off:

If the server sends a ping request, you can reply with a pong message to notify the server that you are still interested. You can also ping the server and will receive a pong reply. The ping/pong interval is configurable.

+OK/ERR

Syntax

+OK

-ERR <error message>

When the verbose connection option is set to true (the default value), the server acknowledges each well-formed protocol message from the client with a +OK message. Most NATS clients set the verbose option to false using the CONNECT message

The -ERR message is used by the server indicate a protocol, authorization, or other runtime connection error to the client. Most of these errors result in the server closing the connection.

Handling of these errors usually has to be done asynchronously.

Some protocol errors result in the server closing the connection. Upon recieving these errors, the connection is no longer valid and the client should clean up relevant resources. These errors include:

-ERR 'Unknown Protocol Operation': Unknown protocol error

-ERR 'Attempted To Connect To Route Port': Client attempted to connect to a route port instead of the client port

-ERR 'Authorization Violation': Client failed to authenticate to the server with credentials specified in the CONNECT message

-ERR 'Authorization Timeout': Client took too long to authenticate to the server after establishing a connection (default 1 second)

-ERR 'Maximum Control Line Exceeded': Message destination subject and reply subject length exceeded the maximum control line value specified by the max_control_line server option. The default is 1024 bytes.

-ERR 'Parser Error': Cannot parse the protocol message sent by the client

-ERR 'Secure Connection - TLS Required': The server requires TLS and the client does not have TLS enabled.

-ERR 'Stale Connection': PING/PONG interval expired.

-ERR 'Maximum Connections Exceeded‘: This error is sent by the server when creating a new connection and the server has exceeded the maximum number of connections specified by the max_connections server option. The default is 64k.

-ERR 'Maximum Payload Violation': Client attempted to publish a message with a payload size that exceeds the max_payload size configured on the server. This value is supplied to the client upon connection in the initial INFO message. The client is expected to do proper accounting of byte size to be sent to the server in order to handle this error synchronously.

Protocol error messages where the connection remains open are listed below. The client should not close the connection in these cases.

Protocol demo

NATS License (The MIT License)

Copyright (c) 2012–2014 Apcera Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.