• Stars
    star
    155
  • Rank 240,864 (Top 5 %)
  • Language
    TypeScript
  • License
    ISC License
  • Created over 2 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

@isaacs/ttlcache

The time-based use-recency-unaware cousin of lru-cache

Usage

Essentially, this is the same API as lru-cache, but it does not do LRU tracking, and is bound primarily by time, rather than space. Since entries are not purged based on recency of use, it can save a lot of extra work managing linked lists, mapping keys to pointers, and so on.

TTLs are millisecond granularity.

If a capacity limit is set, then the soonest-expiring items are purged first, to bring it down to the size limit.

Iteration is in order from soonest expiring until latest expiring.

If multiple items are expiring in the same ms, then the soonest-added items are considered "older" for purposes of iterating and purging down to capacity.

A TTL must be set for every entry, which can be defaulted in the constructor.

Custom size calculation is not supported. Max capacity is simply the count of items in the cache.

const TTLCache = require('@isaacs/ttlcache')
const cache = new TTLCache({ max: 10000, ttl: 1000 })

// set some value
cache.set(1, 2)

// 999 ms later
cache.has(1) // returns true
cache.get(1) // returns 2

// 1000 ms later
cache.get(1) // returns undefined
cache.has(1) // returns false

Caveat Regarding Timers and Graceful Exits

On Node.js, this module uses the Timeout.unref() method to prevent its internal setTimeout calls from keeping the process running indefinitely. However, on other systems such as Deno, where the setTimeout method does not return an object with an unref() method, the process will stay open as long as any unexpired entry exists in the cache.

You may call cache.cancelTimer() to clear the timeout and allow the process to exit normally. Be advised that canceling the timer in this way will of course prevent anything from expiring.

API

const TTLCache = require('@isaacs/ttlcache') or import TTLCache from '@isaacs/ttlcache'

Default export is the TTLCache class.

new TTLCache({ ttl, max = Infinty, updateAgeOnGet = false, checkAgeOnGet = false, noUpdateTTL = false, noDisposeOnSet = false })

Create a new TTLCache object.

  • max The max number of items to keep in the cache. Must be positive integer or Infinity, defaults to Infinity (ie, limited only by TTL, not by item count).

  • ttl The max time in ms to store items. Overridable on the set() method. Must be a positive integer or Infinity (see note below about immortality hazards). If undefined in constructor, then a TTL must be provided in each set() call.

  • updateAgeOnGet Should the age of an item be updated when it is retrieved? Defaults to false. Overridable on the get() method.

  • checkAgeOnGet Check the TTL whenever an item is retrieved with get(). If the item is past its ttl, but the timer has not yet fired, then delete it and return undefined. By default, the cache will return a value if it has one, even if it is technically beyond its TTL.

  • noUpdateTTL Should setting a new value for an existing key leave the TTL unchanged? Defaults to false. Overridable on the set() method. (Note that TTL is always updated if the item is expired, since that is treated as a new set() and the old item is no longer relevant.)

  • dispose Method called with (value, key, reason) when an item is removed from the cache. Called once item is fully removed from cache. It is safe to re-add at this point, but note that adding when reason is 'set' can result in infinite recursion if noDisponseOnSet is not specified.

    Disposal reasons:

    • 'stale' TTL expired.
    • 'set' Overwritten with a new different value.
    • 'evict' Removed from the cache to stay within capacity limit.
    • 'delete' Explicitly deleted with cache.delete() or cache.clear()
  • noDisposeOnSet Do not call dispose() method when overwriting a key with a new value. Defaults to false. Overridable on set() method.

When used as an iterator, like for (const [key, value] of cache) or [...cache], the cache yields the same results as the entries() method.

cache.size

The number of items in the cache.

cache.set(key, value, { ttl, noUpdateTTL, noDisposeOnSet } = {})

Store a value in the cache for the specified time.

ttl and noUpdateTTL optionally override defaults on the constructor.

Returns the cache object.

cache.get(key, {updateAgeOnGet, checkAgeOnGet, ttl} = {})

Get an item stored in the cache. Returns undefined if the item is not in the cache (including if it has expired and been purged).

If updateAgeOnGet is true, then re-add the item into the cache with the updated ttl value. All options default to the settings on the constructor.

If checkAgeOnGet, then an item will be deleted if it is found to be beyond its TTL, which can happen if the setTimeout timer has not yet fired to trigger its expiration.

Note that using updateAgeOnGet can effectively simulate a "least-recently-used" type of algorithm, by repeatedly updating the TTL of items as they are used. However, if you find yourself doing this, consider using lru-cache, as it is much more optimized for an LRU use case.

cache.getRemainingTTL(key)

Return the remaining time before an item expires. Returns 0 if the item is not found in the cache or is already expired.

cache.has(key)

Return true if the item is in the cache.

cache.delete(key)

Remove an item from the cache.

cache.clear()

Delete all items from the cache.

cache.entries()

Return an iterator that walks through each [key, value] from soonest expiring to latest expiring. (Items expiring at the same time are walked in insertion order.)

Default iteration method for the cache object.

cache.keys()

Return an iterator that walks through each key from soonest expiring to latest expiring.

cache.values()

Return an iterator that walks through each value from soonest expiring to latest expiring.

cache.cancelTimer()

Clear the internal timer, and stop automatically expiring items when their TTL expires.

This allows the process to exit normally on Deno and other platforms that lack Node's Timer.unref() method.

Internal Methods

You should not ever call these, they are managed automatically.

purgeStale

Internal

Removes items which have expired. Called automatically.

purgeToCapacity

Internal

Removes soonest-expiring items when the capacity limit is reached. Called automatically.

dispose

Internal

Called when an item is removed from the cache and should be disposed. Set this on the constructor options.

setTimer

Internal

Called when an with a ttl is added. This ensures that only one timer is setup at once. Called automatically.

Algorithm

The cache uses two Map objects. The first maps item keys to their expiration time, and the second maps item keys to their values. Then, a null-prototype object uses the expiration time as keys, with the value being an array of all the keys expiring at that time.

This leverages a few important features of modern JavaScript engines for fairly good performance:

  • Map objects are highly optimized for referring to arbitrary values by arbitrary keys.
  • Objects with solely integer-numeric keys are iterated in sorted numeric order rather than insertion order, and insertions in the middle of the key ordering are still very fast. This is true of all modern JS engines tested at the time of this module's creation, but most particularly V8 (the engine in Node.js).

When it is time to prune, we can always walk the null-prototype object in iteration order, deleting items until we come to the first key greater than the current time.

Thus, the start time doesn't need to be tracked, only the expiration time. When an item age is updated (either explicitly on get(), or by setting to a new value), it is deleted and re-inserted.

Immortality Hazards

It is possible to set a TTL of Infinity, in which case an item will never expire. As it does not expire, its TTL is not tracked, and getRemainingTTL() will return Infinity for that key.

If you do this, then the item will never be purged. Create enough immortal values, and the cache will grow to consume all available memory. If find yourself doing this, it's probably better to use a different data structure, such as a Map or plain old object to store values, as it will have better performance and the hazards will be more obvious.

More Repositories

1

node-glob

glob functionality for node.js
TypeScript
8,123
star
2

rimraf

A `rm -rf` util for nodejs
JavaScript
5,309
star
3

node-lru-cache

A fast cache that automatically deletes the least recently used items
TypeScript
4,844
star
4

minimatch

a glob matcher in javascript
JavaScript
3,074
star
5

github

Just a place to track issues and feature requests that I have for github
2,209
star
6

nave

Virtual Environments for Node
Shell
1,580
star
7

node-graceful-fs

fs with incremental backoff on EMFILE
JavaScript
1,267
star
8

sax-js

A sax style parser for JS
JavaScript
1,046
star
9

tshy

JavaScript
847
star
10

node-tar

tar for node
JavaScript
755
star
11

st

A node module for serving static files. Does etags, caching, etc.
JavaScript
376
star
12

inherits

Easy simple tiny inheritance in JavaScript
JavaScript
352
star
13

cluster-master

Take advantage of node built-in cluster module behavior
JavaScript
276
star
14

minipass

A stream implementation that does more by doing less
TypeScript
246
star
15

once

Run a function exactly one time
JavaScript
216
star
16

yallist

Yet Another Linked List
JavaScript
198
star
17

server-destroy

When close() is just not enough
JavaScript
184
star
18

semicolons

When you require("semicolons"), THEY ARE REQUIRED.
JavaScript
145
star
19

slide-flow-control

A flow control library that fits in a slideshow
JavaScript
134
star
20

treeverse

Walk any kind of tree structure depth- or breadth-first. Supports promises and advanced map-reduce operations with a very small API.
JavaScript
130
star
21

multipart-js

JavaScript
123
star
22

reading-list

a list of books I recommend
121
star
23

node-touch

touch(1) for node
JavaScript
121
star
24

catcher

TypeScript
119
star
25

async-cache

Cache your async lookups and don't fetch the same thing more than necessary.
JavaScript
119
star
26

core-util-is

The util.is* functions from Node core
JavaScript
98
star
27

dezalgo

Contain async insanity so that the dark pony lord doesn't eat souls
JavaScript
89
star
28

github-flavored-markdown

Deprecated. Use marked instead.
JavaScript
79
star
29

minizlib

A smaller, faster, zlib stream built on http://npm.im/minipass and Node.js's zlib binding.
JavaScript
71
star
30

node-bench

JavaScript
71
star
31

free-as-in-hugs-license

A (Not OSI-Approved) software license you may use if you wish
70
star
32

sigmund

Quick and dirty psychoanalysis for objects
JavaScript
67
star
33

inflight

Add callbacks to requests in flight to avoid async duplication
JavaScript
66
star
34

fast-list

A fast O(1) push/pop/shift/unshift thing
JavaScript
66
star
35

gist-cli

A gist cli client written in Node
JavaScript
64
star
36

dotfiles

My Dot Files
Shell
63
star
37

wrappy

Callback wrapping utility
JavaScript
56
star
38

block-stream

A stream of fixed-size blocks
JavaScript
52
star
39

isexe

Minimal module to check if a file is executable.
TypeScript
48
star
40

.vim

My vim settings
Vim Script
47
star
41

jackspeak

A very strict and proper argument parser.
TypeScript
44
star
42

char-spinner

Put a little spinner on process.stderr, as unobtrusively as possible.
JavaScript
43
star
43

st-example

an example of serving static files easily in node using the st module
JavaScript
40
star
44

templar

A lightweight template thing for node http servers
JavaScript
37
star
45

nosync

Prevent sync functions in your node programs after first tick
JavaScript
37
star
46

use-strict

Makes all subsequent modules in Node get loaded in strict mode.
JavaScript
37
star
47

path-scurry

TypeScript
35
star
48

ssh-key-decrypt

Decrypt and encrypted ssh private keys
JavaScript
35
star
49

ejsgi

Like JSGI, but using streams.
JavaScript
35
star
50

node-eliza

A Robotic Rogerian Therapist, on IRC
JavaScript
34
star
51

natives

Do stuff with Node.js's native JavaScript modules
JavaScript
31
star
52

goosh

Front-end old-style terminal interface, for web services like those provided by Google and Yahoo.
JavaScript
31
star
53

simple-node-server

A simple fast node http server toolkit.
JavaScript
30
star
54

util-extend

Node's internal object extension function, for you!
JavaScript
30
star
55

chownr

Like `chown -R`
JavaScript
28
star
56

csrf-lite

CSRF protection utility for framework-free node sites.
JavaScript
28
star
57

chmodr

Like `chmod -R` in node
JavaScript
28
star
58

node-hexedit

hexadecimal editor in node
JavaScript
27
star
59

back-to-markdown.css

Turns any markdown editor into a WYSIWYG editor
CSS
26
star
60

node-async-simple

Multiply two numbers, slowly, on the thread pool.
C++
26
star
61

json-stringify-nice

Stringify an object sorting scalars before objects, and defaulting to 2-space indent
JavaScript
25
star
62

node-strict

Makes your Node programs strict about stuff when loaded
JavaScript
25
star
63

fs.realpath

Use node's fs.realpath, but fall back to the JS implementation if the native one fails
JavaScript
25
star
64

sock-daemon

TypeScript
24
star
65

promise-all-reject-late

Like Promise.all, but save rejections until all promises are resolved
JavaScript
24
star
66

promise-call-limit

Call an array of promise-returning functions, restricting concurrency to a specified limit.
TypeScript
24
star
67

node6-module-system-change

A demonstration of what changed in node 6's module loading logic
JavaScript
24
star
68

color-support

A module which will endeavor to guess your terminal's level of color support.
JavaScript
24
star
69

polite-json

TypeScript
23
star
70

ircretary

A note-taking IRC bot
JavaScript
23
star
71

yamlish

A parser for the yamlish format
JavaScript
22
star
72

fs-minipass

fs read and write streams based on minipass
JavaScript
21
star
73

pseudomap

Like `new Map` but for older JavaScripts
JavaScript
21
star
74

node-fuse

Fuse bindings for nodejs
21
star
75

slocket

A locking socket alternative to file-system mutex locks
JavaScript
21
star
76

proto-list

A list of objects bound by prototype chain
JavaScript
20
star
77

retry-until

A function that will keep running a function you give it as long as it throws for a period of time
JavaScript
20
star
78

node-srand

srand bindings for node - Seedable predictable pseudorandom number generator
C++
20
star
79

mutate-fs

Mutate the Node.js filesystem behavior for tests.
JavaScript
20
star
80

ryp

Featureless npm-package bundling.
Shell
19
star
81

filewatcherthing

a thing to watch a file and then run a command
JavaScript
19
star
82

gatsby-remark-tumble-media

A plugin for gatsby-transformer-remark to support photosets, video, and audio in markdown frontmatter.
JavaScript
19
star
83

sodn

SOcial DNodes
JavaScript
19
star
84

joyent-node-on-smart-example

A blog post.
JavaScript
18
star
85

error-page

Easily send errors in Node.js HTTP servers. Think like the `ErrorDocument` declarations in Apache config files.
JavaScript
17
star
86

_ify

an itty bitty curry utility
JavaScript
17
star
87

url-parse-as-address

Parse a URL assuming that it's http/https, even if protocol or // isn't present
JavaScript
17
star
88

http-https

A wrapper that chooses http or https for requests
JavaScript
17
star
89

perfalize

TypeScript
16
star
90

cssmin

A cross-platform regular-expression based minifier for CSS
16
star
91

duplex-passthrough

like a passthrough, but in both directions
JavaScript
16
star
92

mintee

a tiny module for piping an input to multiple output streams
JavaScript
16
star
93

create-isaacs

An npm init module to create modules like I do
JavaScript
16
star
94

tap-assert

An assert module that outputs tap result objects
JavaScript
16
star
95

domain-http-server

A module thingie to use domains in Express or Restify or just regular HTTP servers
JavaScript
15
star
96

fs-readstream-seek

A fs.ReadStream that supports seeking to arbtrary locations within a file.
JavaScript
15
star
97

canonical-host

Node module to redirect users to the canonical hostname for your site.
JavaScript
15
star
98

mcouch

Put your CouchDB in Manta, attachments and docs and all
JavaScript
14
star
99

hardhttps

Slightly hardened https for node
JavaScript
14
star
100

exit-code

`process.exitCode` behavior back-ported from io.js and Node.js 0.12+
JavaScript
14
star