Skip to main content

NATS Client

A Python client for the NATS messaging system.

Features

  • Support for publish/subscribe
  • Support for request/reply
  • Support for queue groups
  • Support for multi-value message headers

Control lines, including large INFO discovery lists, are limited to 8 MiB. WebSocket messages are limited to 72 MiB, allowing a maximum 64 MiB NATS payload plus protocol overhead. Oversized input fails the connection rather than growing memory without a bound.

Installation

pip install nats-core

Usage

import asyncio
from nats.client import connect

async def main():
    client = await connect("nats://localhost:4222")

    # Subscribe
    async with await client.subscribe("foo") as subscription:
        # Publish
        await client.publish("foo", "Hello World!")

        # Receive message
        message = await subscription.next()
        print(f"Received: {message.data}")

    await client.close()

if __name__ == "__main__":
    asyncio.run(main())

Discovery and TLS names

Discovered TCP and WebSocket peers retain the transport and TLS of their reporting connection. Advertisements must be host:port entries; entries with a URL scheme or a malformed address are skipped. User information in an advertisement is ignored. Configured server URLs keep their own credentials.

When discovery arrives over verified TLS, an advertised IP address is verified against the DNS name used to verify the reporting server, including across multiple failovers. A discovered DNS name is verified against itself. Set tls_hostname to override the verified name for every server, for example when connecting through a proxy.

If the configured server is an IP address, there is no DNS name to inherit. Configure tls_hostname, or use tls_verify_discovered_by_ip=True for a cluster whose certificates contain IP subject alternative names. Use the IP option only with a CA that is not shared with others. An explicit tls_hostname takes precedence over this option. Both options request TLS unless tls_optional=True.

For nodes with individual DNS certificates, configure each node to advertise its DNS name instead of its IP address.

A nonempty list received on an established connection replaces discovered peers; configured servers and the current connection remain. Missing or empty lists do not change membership. Set ignore_discovered_servers=True to use only configured servers. A discovered peer keeps the credentials of its first reporter. It can gain TLS from a later report but cannot lose it.

For TCP connections that upgrade to TLS after INFO, the initial plaintext server list is discarded. On nats-server 2.12 and later, connection setup waits for the INFO after the first PONG, with its own timeout. Expiry of that wait still yields a connected client. On older servers, configure multiple seeds or use TLS first when initial failover targets are needed.

TLS options

Certificate chain and name verification are enabled by default. For a name mismatch, first check the certificate and set tls_hostname to the intended server name. One trailing dot is removed from the verification/SNI name while the address used to dial stays unchanged. Verification errors include the expected name and OpenSSL's verification reason, with bounded and escaped text. The message explicitly reports that presented certificate names are unavailable through this connection API after a failed handshake. Verification remains enabled; the client does not reconnect without verification to retrieve certificate names. This is a documented capability limit, not full presented-name diagnostic coverage.

As a last resort, tls_skip_verify=True explicitly disables chain and name verification. A supplied context that disables either check requires this flag. Caller-owned contexts are never modified. With this flag, omit tls to create a private unverified context, or supply a dedicated context already configured with check_hostname=False and verify_mode=ssl.CERT_NONE. Other supplied contexts are rejected before connecting.

Any TLS setting, or a secure URL in the configured list, requests TLS for the whole list. tls_optional=True opts out of that whole-list requirement and lets plain configured URLs stay plain. Secure URLs still require TLS. It cannot be combined with tls_required=True or tls_handshake_first=True.

Credentials, deadlines and reconnect

URL credentials take precedence over token, user/password and bare NKey options. They are percent-decoded once. JWT and credentials-file handlers remain active. Configured servers retain their own credentials; discovery cannot replace them.

The default connection timeout is 5 seconds. Direct TCP and WebSocket connections first resolve the configured name under a separate timeout of the same length. All resolved addresses then share one budget for TCP setup, TLS, the WebSocket upgrade, INFO, CONNECT and the first PONG. Resolution is repeated for reconnect; the original URL remains the source of TLS identity and credentials. Cancelling resolution stops the caller, though a system resolver already running in a thread may finish in the background. A direct attempt can therefore spend up to twice timeout before the first PONG, plus another timeout for post-PONG discovery when applicable. These budgets apply per server; wrap connect() in asyncio.timeout() if an application needs an overall wall-clock limit.

Proxy WebSocket connections retain the library's routing and resolution behavior; their DNS still falls within the transport budget. A direct connection uses a preconnected socket, so WebSocket HTTP redirects are rejected instead of dialing an unresolved redirect target. Those two paths require review before claiming complete resolution-budget conformance.

The first reconnect starts immediately; later attempts use bounded exponential backoff with jitter. no_randomize=True retains configured order. The current reconnect limit is 60 failed attempts per server; use zero for unlimited attempts. Removing or rediscovering an address does not reset its failure count. Closing stops recovery and bounds transport shutdown.

Metadata

Release files for nats-core 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nats-core 0.3.0
File Size Uploaded Provenance Actions
nats_core-0.3.0.tar.gz 44.2 kB Without provenance Details for nats_core-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nats-core 0.3.0
File Interpreter ABI Platform Actions
nats_core-0.3.0-py3-none-any.whl Python 3 none any Details for nats_core-0.3.0-py3-none-any.whl

Total release size: 93.1 kB

Release files / nats_core-0.3.0.tar.gz

Download URL nats_core-0.3.0.tar.gz
Size 44.2 kB
Tags Source
SHA-256 checksum
How to use checksums
c511459fb6cbdea356580c9227fae01b33dec17c7e27cd775d6f148ad0cf857d
BLAKE2b-256 checksum
How to use checksums
a50ad3c6cd2b11ad41de2f600a4f5592cb7c5d15a1e5d33628c4f5f8ebe836a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / nats_core-0.3.0-py3-none-any.whl

Download URL nats_core-0.3.0-py3-none-any.whl
Size 48.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c901a308bef6b12da8a4728b3b46d4c4eb934396f957f2e9af4802817861d050
BLAKE2b-256 checksum
How to use checksums
bc2a7dac87a201b7b7dd259ecb8c2daf6ec1c0610a094c6b975f31f0570540f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for nats-core 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page