Skip to content

node-cache - set() TTL parameter behavior differs from original node-cache #1582

@maxime-bc

Description

@maxime-bc

Describe the bug

Hello,

The ttl parameter in NodeCache.set(key, value, ttl) behaves differently from the original node-cache package.

  1. When ttl = 0: node-cache caches the key indefinitely. @cacheable/node-cache defaults to stdTTL. This means there is no way to set an infinite TTL per-key.
  2. When ttl < 0: node-cache rejects the value and doesn't create the key. @cacheable/node-cache accepts it and creates a key that immediately expires.

Additionally, the docs states "If the ttl is not set it will default to 0 (no ttl).", which is misleading as both omitting ttl and setting it to 0 default to stdTTL.

How To Reproduce

I am using node-cache@5.1.2 and @cacheable/node-cache@2.0.1.

Original node-cache behavior

Code

const NodeCache = require("node-cache");

const cache = new NodeCache({ stdTTL: 60 });

const startTs = Date.now();
console.log(`Start timestamp: ${startTs}ms`);

cache.set("a", "value");
const ts = cache.getTtl("a");
console.log(`ttl not set, timestamp=${ts}ms, effective ttl=${ts - startTs}ms (=stdTTL)`);

cache.set("b", "value", -1);
console.log(`ttl=-1, key not created (value=${cache.get("b")})`);

cache.set("c", "value", 0);
console.log(`ttl=0, timestamp=${cache.getTtl("c")}ms (=infinite)`);

Output

Start timestamp: 1772124629538ms
ttl not set, timestamp=1772124689541ms, effective ttl=60003ms (=stdTTL)
ttl=-1, key not created (value=undefined)
ttl=0, timestamp=0ms (=infinite)

@cacheable/node-cache behavior

Code

const { NodeCache } = require("@cacheable/node-cache");

const cache = new NodeCache({ stdTTL: 60 });

const startTs = Date.now();
console.log(`Start timestamp: ${startTs}ms`);

cache.set("a", "value");
const ts = cache.getTtl("a");
console.log(`ttl not set, timestamp=${ts}ms, effective ttl=${ts - startTs}ms (=stdTTL)`);

cache.set("b", "value", -1);
const ts1 = cache.getTtl("b");
console.log(`ttl=-1, timestamp=${ts1}ms, effective ttl=${ts1 - startTs}ms (=immediate expiry)`);

cache.set("c", "value", 0);
const ts2 = cache.getTtl("c");
console.log(`ttl=0, timestamp=${ts2}ms, effective ttl=${ts2 - startTs}ms (=stdTTL)`);

Output

Start timestamp: 1772124174973ms
ttl not set, timestamp=1772124234976ms, effective ttl=60003ms (=stdTTL)
ttl=-1, timestamp=1772124173977ms, effective ttl=-996ms (=immediate expiry)
ttl=0, timestamp=1772124234977ms, effective ttl=60004ms (=stdTTL)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions