title: Caching vector addition over changing collections
body: <p>I have the following setup:</p>
  
  <p>I have a largish number of uuids (currently about 10k but expected to grow unboundedly - they're user IDs) and a function f : id -> sparse vector with 32-bit integer values (no need to worry about precision). The function is reasonably expensive (not outrageously so, but probably on the order of a few 100ms for a given id).  The dimension of the sparse vectors should be assumed to be infinite, as new dimensions can appear over time, but in practice is unlikely to ever exceed about 20k (and individual results of f are unlikely to have more than a few hundred non-zero values). </p>
  
  <p>I want to support the following operations efficiently: </p>
  
  <ul>
  <li>add a new ID to the collection</li>
  <li>invalidate an existing ID</li>
  <li>retrieve sum f(id) in O(changes since last retrieval)</li>
  </ul>
  
  <p>i.e. I want to cache the sum of the vectors in a way that's reasonable to do incrementally.</p>
  
  <p>One option would be to support a remove ID operation and treat invalidation as a remove followed by an add. The problem with this is that it requires us to keep track of all the old values of f, which is expensive in space. I potentially need to use many instances of this sort of cached structure, so I would like to avoid that. </p>
  
  <p>The likely usage pattern is that new IDs are added at a fairly continuous rate and are frequently invalidated at first. Ids which have been invalidated recently are much more likely to be invalidated again than ones which have remained valid for a long time, but in principle an old Id can still be invalidated. </p>
  
  <p>Ideally I don't want to do this in memory (or at least I want a way that lets me save the result to disk efficiently), so an idea which lets me piggyback off an existing DB implementation of some sort would be especially appreciated. </p>