Skip to content

Set Options

The third argument to cache.set() accepts three shapes — a positional TTL (number or string) for the common case, and a rich options object when you need more than just expiration.

import { cache } from "@warlock.js/cache";
// 1. Number of seconds (back-compat)
await cache.set("name", "John Doe", 600);
// 2. Human-readable duration string (parsed via ms)
await cache.set("name", "John Doe", "10m");
await cache.set("session", token, "1h");
await cache.set("report", report, "7d");
// 3. Rich options object
await cache.set("user.1", user, {
ttl: "1h",
tags: ["users", "active"],
onConflict: "create",
});

See Duration Strings for the full grammar of accepted string forms.

KeyTypePurpose
ttlnumber | stringRelative expiry. Mutually exclusive with expiresAt.
expiresAtnumber | DateAbsolute deadline. Must be in the future. Mutually exclusive with ttl.
tagsstring[]Inline tag list — equivalent to cache.tags([...]).set(...).
ttlJitternumberSpread the TTL by up to this many percent either way, per write, so entries written together do not expire together. 10 turns 1h into 54 to 66 minutes. Ignored for expiresAt and Infinity.
onConflict"create" | "update" | "upsert"Conditional-write policy. Defaults to "upsert".
driverstringPer-call driver override by registered name.
vectornumber[]Embedding indexed alongside the entry for similarity retrieval. Drivers without similarity support throw CacheUnsupportedError.

:::info Validation rules

  • Passing both ttl and expiresAt throws CacheConfigurationError.
  • An expiresAt in the past throws CacheConfigurationError.
  • Invalid duration strings ("2 weeksandahalf") throw CacheConfigurationError. :::

Use ttl for relative expiry (“cache for 1 hour from now”). Use expiresAt when the deadline is pinned to a specific wall-clock moment — JWT expiry, session close, scheduled campaign end.

// Relative — "1 hour from now"
await cache.set("session", session, { ttl: "1h" });
// Absolute — aligned to JWT expiry
await cache.set("session", session, { expiresAt: jwt.exp * 1000 });
// Absolute — aligned to a Date
await cache.set("campaign", data, {
expiresAt: new Date("2026-12-31T23:59:59Z"),
});

Passing both is rejected at the call site — two ways to say the same thing silently drift over time.

Entries written in one batch (a warm-up, a deploy, a burst of requests) share an expiry second, so they all miss together and hit the origin together. ttlJitter picks a random TTL within the given percentage for each write:

await cache.set("product.7", product, { ttl: "1h", ttlJitter: 10 }); // expires in 54-66 minutes
await cache.remember("report", { ttl: "1h", ttlJitter: 10 }, build);

The result is rounded to whole seconds and is at least one second. It applies to a relative ttl (or the driver default) and is skipped for expiresAt, Infinity and 0.

  • A number is seconds. Fractions round up to whole seconds, so 0.5 is 1 second, never “no expiry”.
  • A bare numeric string is also seconds: "3600" (for example from an env var) is one hour.
  • Duration strings ("500ms", "30m", "7d") are converted to seconds and rounded up, so "500ms" is 1 second.
  • 0 and Infinity mean no expiry. NaN, negative numbers and unparseable strings throw CacheConfigurationError.
  • cache.lock() is stricter: it refuses any TTL that never expires. See Locks.

:::caution Upgrading to 5.20 Numeric TTL strings used to be read as milliseconds ("3600" was 3 s), and "500ms" floored to 0 (never expires). Check any TTL that comes from configuration. :::

Controls what happens when the key already exists (or doesn’t).

// "create" — set only if the key is missing
const workerId = `worker.${process.pid}`; // any identifying value
const result = await cache.set("lock.orders", workerId, {
onConflict: "create",
ttl: "5m",
});
// { wasSet: true, existing: null } on acquire
// { wasSet: false, existing: <prior workerId> } if someone else holds it
if (!result.wasSet) {
throw new Error(`Another worker owns this lock: ${result.existing}`);
}
// "update" — set only if the key exists (don't resurrect expired entries)
await cache.set("user.1", patch, { onConflict: "update" });
// "upsert" — the default. Overwrites regardless.
await cache.set("user.1", user);

Conditional writes return a CacheSetResult:

type CacheSetResult<T = any> = {
wasSet: boolean;
existing: T | null; // only populated on "create" rejections
};

Unconditional "upsert" writes return the driver instance or the stored value, matching the legacy shape.

:::tip Redis equivalence "create" maps to Redis SET … NX natively; "update" maps to SET … XX. Other drivers emulate the behavior in-process. You get the same semantics regardless of driver. :::

Equivalent to the fluent form, terser at the call site:

// Inline
await cache.set("user.1", user, { tags: ["users", "tenant-42"] });
// Fluent (useful when you already have a tagged instance)
const users = cache.tags(["users"]);
await users.set("user.1", user);

Both invalidate via the same path:

await cache.tags(["users"]).invalidate();

See Cache Tags for the full invalidation workflow.

When most writes go to your default driver but one call needs a different one, pass driver in the options object. The manager loads (and connects) the override driver lazily on first use, then routes that single operation without mutating currentDriver.

// Audit events always land in Redis, regardless of default driver
await cache.set("audit.event", event, {
driver: "redis",
ttl: "30d",
});
// Normal usage still uses the default driver
await cache.set("user.1", user, "1h");

The override driver must be registered in your configuration:

cache.setCacheConfigurations({
default: "memory",
drivers: {
memory: MemoryCacheDriver,
redis: RedisCacheDriver,
},
options: {/* ... */},
});

A distributed lock makes sure only one process runs a block of code at a time, even across multiple servers. The onConflict: "create" pattern is the portable way to build one — native on Redis and Postgres (cross-server), single-process elsewhere. For real work prefer cache.lock(): it refuses a TTL that never expires and releases only its own lock, so a slow holder can’t delete its successor’s.

async function withLock<T>(key: string, ttl: string, work: () => Promise<T>): Promise<T | null> {
// process.pid is just an identifying value so you can see which worker
// holds the lock when debugging. Any unique string works.
const acquired = await cache.set(key, process.pid, {
onConflict: "create",
ttl, // safety net: auto-release if we crash before remove()
});
if (!acquired.wasSet) {
return null; // someone else holds the lock — skip this work
}
try {
return await work();
} finally {
// Not successor-safe: if the TTL expired, this deletes the next holder's lock.
await cache.remove(key);
}
}
// Usage — build a heavy report, but only run the job on one server even if
// three servers received the request at the same time.
const result = await withLock("lock.build-report.42", "2m", async () => {
const report = await db.reports.generate(42); // expensive
await cache.set("report.42", report, "1h");
return report;
});

See Stampede Prevention for the single-node variant using remember().

Every call site using the old positional-TTL shape still works:

await cache.set("k", v); // no TTL — driver default
await cache.set("k", v, 3600); // seconds
await cache.set("k", v, undefined); // same as no TTL