[whatwg] Supporting eviction in WebStorage

Kyle Scholz kyle.scholz at gmail.com
Thu Dec 24 14:39:57 PST 2009


A common application of WebStorage will be clientside caching. Since
there are limits on store size, developers will be implementing
eviction schemes, but this is currently difficult because the
interface doesn't expose store size or get/set times for entries. Some
additions to the Storage interface would support most use cases:
totalSize() - Indicates the absolute size of the store.
availableSize() - Indicates available space in the store.
keysByAccessTime() - Returns a list of keys in ascending order by access time.
accessItem() - Sets the access time of an entry to now.

setItem() will always set the access time of an item. getItem() will
not set the access time of an item. This makes it possible for the
developer to determine whether they wish to enable a
least-recently-stored or least-recently-accessed eviction policy. A
developer should follow calls to getItem() with a call to accessItem()
if they wish eviction candidates to be ordered by access time.

A basic cache access / eviction implementation might look like this:

/**
 * Get an item from localStorage. Update it's access time.
 */
function getItem(key) {
 localStorage.getItem(key);
 localStorage.accessItem(key);
}

/**
 * Store an item in localStorage. Presumes arguments are stringified.
 */
function storeItem(key, value) {
  var entrySize = key.length + value.length;
  if (entrySize > localStorage.totalSize()) {
    throw "Entry exceeds total size.";
  }
  var spaceAfter = localStorage.availableSpace() - entrySize;
  if (spaceAfter < 0) {
    evictEvictEntries(spaceAfter * -1);
  }
 localStorage.setItem(key, value);
}

/**
 * Evict entries until needed space is available.
 */
function makeRoom(spaceNeeded) {
  while(localStorage.length && localStorage.spaceAvailable() < spaceNeeded) {
    var candidate = localStorage.keysByAccessTime()[0];
    // Insert any conditional logic to determine whether candidate
should be evicted.
    localStorage.removeItem(candidate);
  }
}

Thoughts? I'd considered whether Storage might implement cache
eviction internally, but that limits the developer's control over
which entries are candidates for eviction. In a given application, all
stored items may not be equal.


More information about the whatwg mailing list