SDKs
Six official clients, one behavior. Point any of them at a single node or at a discovery server — the SDK detects which from the server's own handshake, so development and production use identical code.
Every SDK ships the full feature set: authentication, TLS, discovery
replica lists, replication-aware routing (reads fail over, writes fan out
to all R owners), transparent reconnect (see below for what is retried),
always-on keep-alive, opt-in transparent value compression, opt-in fire-and-forget
replica writes, opt-in read repair, and the same rendezvous-hashing
pipeline verified against shared cross-language test vectors. Values are
strings first: every get returns a string, with a
get_bytes-style companion for raw byte values. The text
getter is strict UTF-8 in five SDKs (a stored value that is not valid
UTF-8 raises); in Go, where a string can hold any bytes,
Get returns the bytes unchanged and GetBytes
is the []byte form.
A connection found closed is redialed on its next use in every SDK and
mode. Whether a request that loses its connection while it is in flight is
sent again depends on the mode. In cluster mode every SDK retries it once,
after refreshing the node list from discovery, so a key whose primary died
is rerouted. In single-node and proxy mode Go, Rust, Java and .NET also
retry once: they redial and resend (a proxy client whose proxy is
unreachable fails over to another proxy from discovery’s roster).
Python does not retry in either mode, and TypeScript does not in
single-node mode: the call fails with the connection-lost error and the
next call redials. TypeScript in proxy mode re-fetches the proxy roster
and retries once, as in cluster mode. In every case a non-idempotent
request (incr/decr, the compare-and-set calls,
delete-if-matches) is resent only when the SDK can show that nothing was
sent.
A TTL is whole seconds; 0 (or omitting it) means no
expiry. The wire field is an unsigned 64-bit decimal, and the largest
value an SDK accepts is set by its integer type: 2^64 − 1
in Python and Rust, 2^63 − 1 in Go, Java and .NET, and
2^53 − 1 (Number.MAX_SAFE_INTEGER) in
TypeScript, which throws RangeError above that. Any value
up to 2^53 − 1 works in every SDK.
| Language | Requires | Package | Docs |
|---|---|---|---|
| TypeScript / Node.js | Node 22+ | nanocached (npm) | README |
| Python | 3.11+, asyncio | nanocached (PyPI) | README |
| Java | 17+ | org.nanocached:nanocached (Maven Central) | README |
| Rust | tokio | nanocached (crates.io) | README |
| .NET | .NET 10+ | Nanocached (NuGet) | README |
| Go | 1.26+ | github.com/nanocached/nanocached/sdk/go | README |
None of the SDKs has runtime dependencies outside its language's
standard library, except Rust: its client uses tokio, futures-util and
sha2, plus flate2 and rustls behind the default compression
and tls cargo features, which can be compiled out.
TypeScript
npm install nanocached
import { NanocachedClient } from "nanocached";
const client = await NanocachedClient.connect({
addresses: [{ host: "127.0.0.1", port: 8357 }],
});
await client.set("greeting", "hello", 60); // TTL seconds; omit = no expiry
const value = await client.get("greeting"); // string | null
const existed = await client.delete("greeting"); // boolean
await client.close();
Python
pip install nanocached
import asyncio
from nanocached import NanocachedClient
async def main():
async with await NanocachedClient.connect([("127.0.0.1", 8357)]) as client:
await client.set("greeting", "hello", ttl_seconds=60)
value = await client.get("greeting") # str | None
existed = await client.delete("greeting") # bool
asyncio.run(main())
Java
Group/artifact: org.nanocached:nanocached.
import org.nanocached.NanocachedClient;
import org.nanocached.NanocachedClient.Address;
import org.nanocached.NanocachedClient.Options;
import java.util.List;
import java.util.Optional;
try (NanocachedClient client = NanocachedClient.connect(
new Options().addresses(List.of(new Address("127.0.0.1", 8357))))) {
client.set("greeting", "hello", 60); // TTL seconds; omit = no expiry
Optional<String> value = client.get("greeting"); // empty when missing
boolean existed = client.delete("greeting");
}
Spring users: the separate org.nanocached:nanocached-spring
module implements Spring's CacheManager/Cache on
this SDK — named caches as namespaces, per-cache TTL, clear()
as the namespace's CLEAR. See
adapters/spring.
Spring Boot users can instead add
org.nanocached:nanocached-spring-boot-starter, which
autoconfigures both beans from nanocached.* properties — no
Java config. See
adapters/spring-boot-starter.
JSR-107 (javax.cache) users can instead add
org.nanocached:nanocached-jcache, an honest-subset
CachingProvider/CacheManager/Cache
implementation discoverable via Caching.getCachingProvider().
See
adapters/jcache.
Rust
cargo add nanocached
use nanocached::{NanocachedClient, Options};
let client = NanocachedClient::connect(
Options::new().addresses([("127.0.0.1", 8357)]),
).await?;
client.set("greeting", "hello", 60).await?; // TTL seconds; 0 = no expiry
let value: Option<String> = client.get("greeting").await?;
let existed: bool = client.delete("greeting").await?;
client.close().await;
.NET
dotnet add package Nanocached
using Nanocached;
using NanocachedClient client = await NanocachedClient.ConnectAsync(new NanocachedClient.Options {
Addresses = { ("127.0.0.1", 8357) },
});
await client.SetAsync("greeting", "hello", ttlSeconds: 60); // omit = no expiry
string? value = await client.GetAsync("greeting"); // null when missing
bool existed = await client.DeleteAsync("greeting");
Go
go get github.com/nanocached/nanocached/sdk/go
import nanocached "github.com/nanocached/nanocached/sdk/go"
client, err := nanocached.Connect(nanocached.Config{
Addresses: []nanocached.Address{{Host: "127.0.0.1", Port: 8357}},
})
if err != nil { /* ... */ }
defer client.Close()
err = client.Set("greeting", "hello", 60) // TTL seconds; 0 = no expiry
value, ok, err := client.Get("greeting") // ok=false when missing
existed, err := client.Delete("greeting")
Shared behavior, briefly
- Tuning knobs that tests can turn — each SDK exposes a handful of production constants (request timeout, keep-alive interval, the in-flight budgets for fire-and-forget replica writes and hedge legs, the late-leg count at which a hedged read tries an owner last, the batch-decompression cap) as mutable, documented-but-hidden values so its own test suite can shrink them. That is a deliberate convention, not an API: they are not part of any SDK's public surface, changing one affects every client in the process, and a test that lowers one is expected to restore it. Applications configure what they need through the connect options instead.
- Framework adapters — separate, ecosystem-specific packages on
top of the SDKs (outside the SDK parity policy), published at the same
version as the SDK they sit on and depending on that SDK release: Spring
(
org.nanocached:nanocached-spring, adapters/spring, plus a Spring Boot starter,org.nanocached:nanocached-spring-boot-starter, at adapters/spring-boot-starter), ASP.NET Core'sIDistributedCache(dotnet add package Nanocached.Caching, adapters/dotnet), a Django cache backend (pip install nanocached-django, adapters/django), a cache-manager v5 store for Node (npm install nanocached-cache-manager, adapters/cache-manager), a JSR-107 (javax.cache) provider (org.nanocached:nanocached-jcache, adapters/jcache), and a Keyv storage adapter for cache-manager v6+/NestJS 11, working with keyv 5 and keyv 6 (npm install nanocached-keyv, adapters/keyv). - Addresses — one list-shaped option in every SDK; list every discovery replica, and connect and refresh try them in order, skipping busy or unreachable replicas.
- Replication — R rides along with the node list, so there is nothing to configure; each client exposes the factor in use.
- Namespaces —
client.namespace("users")(Namespace(...)in .NET) returns a handle with the sameget/set/deleteoperations scoped to a flat, opaque namespace: the same key name in two namespaces is two entries. The handle shares the client's connections and routing; the un-namespaced API is unchanged and keeps the legacy wire frames, so it still works against pre-namespace servers. See the protocol for the wire form. A handle'sclear()wipes its namespace and the client'sclearAll()(clear_all/ClearAllAsync) wipes every namespace: both are sent to every member node, and on a node failure the SDK refreshes the node list once and retries before raising an error naming the node — never a silent partial clear. See c / F. - Counters —
client.incr(key, delta)(Incr/IncrAsyncin Go/.NET) adds a signeddeltato a key's stored value atomically on the node that owns it and returns the new value; a negativedeltadecrements, and every SDK'sdecrnegates the delta for you — there is no separate decrement command on the wire. Available on a namespace handle too. In TypeScript a counter is limited to the safe-integer range: a stored value beyond ±(2^53 − 1) makesincr/decrthrowCounterOutOfRangeErroreven though the node applied the increment. As volatile as a plainset— LRU eviction and TTL expiry reclaim a counter the same as any other entry, so this is a fit for rate limiting and approximate counters, not for counts that must survive. In a cluster only the primary owner runs the increment; the SDK writes the result to the remaining owners as an ordinaryset, never by replaying the increment itself (replaying it could drift a replica from the primary). For at least a minute after a node joins (the old owners forward writes for 60 s from the end of their handoff, plus 5 ms for each entry they sent), a counter incremented concurrently by several callers can lose a few increments (a replicated result forwarded back to the primary lands after a later increment). The same holds for one caller whose increments follow each other within a few milliseconds, since a forward can lag that long; with spacing well above that, increments are practically exact. The proxy does not change this. Two clients incrementing the same key at the same time can also leave a replica one or two increments behind the primary, because each writes its result to the replica on its own and the writes are not ordered — see accepted behaviour. Incompatible with value compression: the SDKs rejectincr/decroutright on a client withcompressenabled, since the protocol has no way to tell a compressed value from a plain integer. See i. - Batched reads and writes —
getManyandsetMany(get_many/set_many,GetManyAsync/SetManyAsync) fetch or store many keys in one round trip per owning node, available on a namespace handle too. A missing key is simply absent from the result, never an error, and so is a key the node could not include: the values in one batch reply total at most 16 MiB, and a hit past that budget is answered as a miss. A caller reading many large keys at once should not take an absent key for evicted; read it again on its own. Hedged reads and read repair apply to single-key reads only. A large batch is split into frames of at most 400 keys; forsetMany(andtouchMany/getManyAndTouchbelow) on a namespace handle, the SDKs also cap the keys per frame at min(400, floor(64 MiB / namespace length)), because the node refuses a frame whose namespace length times its number of keys exceeds 64 MiB. A long namespace therefore means more, smaller frames, never a refused batch. See m / o. - Compare-and-set —
putIfAbsent,replace(present-only and exact-match forms), and a digest-conditioned delete, all atomic on the node that owns the key. An expected value comes from a prior read (its content digest, an opaque token the SDK computes for you) rather than being resent whole. Same cluster rule as counters: only the primary evaluates the condition, and the SDK writes the result to the remaining owners as an ordinaryset/delete. Not a distributed lock — LRU eviction can still silently break a lock built on it. See k / x. - Touch —
touchreplaces an existing entry's TTL in place without rewriting its value, andgetAndTouch(get_and_touch/GetAndTouchAsync) reads the value and replaces the TTL in one step; both are on a namespace handle too. The TTL argument has no default and is notset's: omitting it (null/None, or theRemoveTTL/REMOVE_TTLconstant in Go and Java) removes the TTL and0expires the entry at once, wheresetreads0as no expiry. In Go and Java the constant is the number-1, so a TTL computed as a difference that comes out as exactly-1removes the TTL instead of being rejected like any other negative value. A miss creates nothing. Unlike counters and compare-and-set a touch is idempotent: it goes to every owner like aset, a request whose reply was lost is retried, and it cannot overwrite a write that lands at the same time.getAndTouchasks only the primary for the value (no hedging, no fallback to a replica on a miss) and sends the other owners the plain touch. With a TTL of0the other owners are sent theirs only once the primary has answered (sent together, a replica would expire its copy while the primary leg was still failing, and the reroute would then find nothing where the value was); those legs run outside the request order a pipelined connection otherwise keeps. Against a node that predates the command the SDK raises a "server too old" error (a node before 0.4.8 closes the connection without a reply instead); upgrade every node before using it. See t.
For many keys at once,touchManyandgetManyAndTouch(touch_many/get_many_and_touch,TouchMany,TouchManyAsync) take one TTL for the whole batch and cost one round trip per involved node. Every owner is sent the batch and the primary's answer is each key's; only a key's primary is asked for the value, so a node that is the primary of some keys and a replica of others receives two frames. With a TTL of0the primaries go first and the other owners are sent one plain batch afterwards, for the keys a primary answered, as for the single touch. Failures followgetMany:getManyAndTouchcarries the keys that resolved,touchManycarries none (a touch is idempotent, so the whole batch can be sent again). See y. - Failure recovery — a stale routing table (a node answers
W) or a dead primary both trigger one node-list refresh and one retry; recovery is bounded by discovery's liveness timeout. - Reconnect — nodes close idle connections after 60 s; SDKs
keep their connections warm automatically (an internal 30 s
keep-alive), and redial transparently if one does die. The keep-alive
is a real
getof a reserved 21-byte key (a leading NUL byte followed bynanocached-keepalive) — treat that key as reserved by the SDKs. - Observability — failures the SDKs deliberately swallow
(replica-leg writes, read-repair writes, node-list refreshes) are
counted in monotonic per-client counters, exposed via a
stats()-style accessor in every SDK, so silently degrading replication or a stuck refresh is detectable. The refresh counter increments once per refresh that did not produce a usable node list: every discovery address unreachable, an empty roster, or an answer from a node instead of a discovery server. A failed connection to a newly listed node during an otherwise successful refresh is not counted, and one refresh counts once however many addresses it tried. - Concurrency — every client is safe for concurrent use;
requests are pipelined per connection, so concurrent callers each pay
only their own network latency, not everyone else's ahead of them.
Concurrent writes to the same key are not ordered across its
owners, though: each owner keeps whichever write reached it last, so
two callers racing a
set, or asetagainst adelete, can leave the replicas disagreeing until the next write or TTL expiry, with nothing instats()— see the accepted behaviour list, and the same holds for writes sent through a proxy. Compare-and-set is unaffected; counters are, when two clients increment the same key at the same time (a replica can end one or two increments behind the primary). - Value compression — off by default; when enabled, values at
or above a configurable threshold are transparently DEFLATE-compressed
on write and decompressed on read. Every client touching a given
keyspace must agree on the setting; each SDK's README has a
"Value compression" section.
Also incompatible with counters: a client with
compressenabled raises immediately fromincr/decrrather than produce a value the protocol can't safely round-trip. - Fire-and-forget replica writes — off by default; when enabled, a write returns as soon as the primary owner acks instead of also waiting for replica legs, which finish in the background (bounded, with a synchronous fallback past the bound). A per-client latency trade-off, not a format decision — clients may mix settings freely; each SDK's README has a "Fire-and-forget replica writes" section.
- Read repair — off by default; when enabled, a clean miss probes the remaining owners before being accepted as final, repairing the primary in the background, with a fixed 60-second TTL, if one still holds the value. Closes the post-restart window client-side replication otherwise leaves open, at the cost of extra reads on the misses it applies to; each SDK's README has a "Read repair" section.
Where the SDKs differ on purpose
The SDKs behave the same; their surfaces follow each language. These differences are intended and part of what the compatibility page covers:
- Naming and units — option and method names use each
language’s case. Durations are a duration type in Rust, Go, Java and
.NET; TypeScript takes milliseconds (a
Mssuffix) and Python takes seconds. - Zero in Go’s
Config— a Go struct cannot tell “not set” from zero, so thereCompressionThreshold: 0means the default (256 bytes; use1to compress every non-empty value), and a negativeReconnectCooldownswitches the cooldown off. Every other SDK reads a compression threshold of0literally (compress everything) and has a separate switch for the cooldown (disableReconnectCooldownor its language’s spelling), with0meaning the default. - Closed state —
isClosed()(TypeScript, Java),IsClosed()(Go),is_closed()(Rust) and the propertyclosed(Python, as onioandasyncioobjects). The .NET client has none; it isIDisposable. - Errors — Rust returns one
Errorenum and Go matches sentinels witherrors.Is; the others raise exception classes. A caller mistake caught before anything is sent isError::InvalidArgument/ErrInvalidArgumentin those two and the language’s own argument error elsewhere (RangeError,ValueError,IllegalArgumentException,ArgumentException), not a nanocached error type. - Public surface — only what an SDK’s package exports
is API. Internals (for example
HashRing) are not exported in any SDK.