π TTL & Max Uses
Understand how cache expiration works with TTL and Max Uses.
Overview
In caching, not all data should live forever. Toolkitify Cache gives you two ways to control when cached items expire:
- TTL (Time-To-Live) β This is the maximum duration an item can stay in the cache. For example, if you set a TTL of 30 seconds, the item will automatically be removed 30 seconds after it was stored. TTL ensures that stale data doesnβt stay in memory or local storage for too long.
TTL can be defined in milliseconds (e.g., 10000) or as a string ("30s", "1m", "1h").
- Max Uses β This is the maximum number of times an item can be retrieved from the cache using
get. Once this limit is reached, the item is removed, even if its TTL hasnβt expired yet. Max Uses is useful for limiting the number of times a value can be reused, for example, one-time tokens or temporary data.
Example
TTL & Max Uses ExampleCode Sandbox
import { Cache } from "toolkitify/cache";
const cache = new Cache({ ttl: "30s", maxUses: 3 });
cache.set("foo", "bar");
// Access the cache
console.log(cache.get("foo")); // "bar".
console.log(cache.getTTL("foo"));
// { msRemaining: 25000, expiresAt: "11/11/2025, 3:27:30 PM" } - shows remaining time and expiration.
console.log(cache.get("foo"));
console.log(cache.get("foo")); // null if maxUses reached.
Using getTTL function
The getTTL function returns a JSON object with:
msRemainingβ milliseconds remaining until the item expires.expiresAtβ the human-readable timestamp when the item will expire.
You can use this info to display countdowns, debug cache behavior, or make decisions based on the remaining life of a cached item.