NATS Server 2.11+ supports automatic key removal via Time-To-Live (TTL). To use per-key TTLs, you must first create the bucket with the markerTTL option (minimum 1000ms).
markerTTL defines how long the server keeps the 'tombstone' marker (the PURGE operation) in the bucket after a key is removed. This ensures watchers and get requests see the removal before the record disappears entirely.
TTL Methods
- On Create:
kv.create(key, value, "<duration>") sets the TTL for the initial write. - On Purge:
kv.purge(key, { ttl: "<duration>" }) sets the lifetime of the purge marker.
Duration Format
Durations are strings following the Go duration format (e.g., 2s, 2m, 1.5h). A bare number is treated as seconds. Minimum resolution is one second.
Note: kv.put() does not support TTL. Using put() for expiry can cause issues with historical revision visibility.
// 1. Create bucket with markerTTL (required for per-key TTL to work)
const kv = await new Kvm(js).create("A", { markerTTL: 2_000 });
// 2. Set TTL on creation (key expires in 5s)
await kv.create("k", "hello", "5s");
// 3. Or set TTL on purge (marker expires in 2s)
await kv.purge("k", { ttl: "2s" });