You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Implement FIFO and LRU caches through a Map memory limit #1095
I would like to allow a max_bytesize to be set for a Concurrent::Map, which would stop the combination of the map and its entries from getting any bigger by automatically deleting entries when a new one is added. Deletion of the oldest entry is easy through Hash#shift. New entries would automatically make a FIFO cache, while an LRU cache would need each accessed entry to be deleted and re-added.
Is this something worth working up a PR for? If so, does anyone have any suggestions on what to do and what not to do?
Note that Concurrent::Map does not have ordering and no Hash#shift equivalent, so you probably mean Concurrent::Hash instead.
It sounds pretty easy to make your own on top of Concurrent::Hash so I guess the question is should that be part of concurrent-ruby or not. @byroot I think you have experiences with such caches, any thoughts?
max_bytesize is probably quite hard though because how would you find out the memory used by Ruby objects?
AFAIK such caches are typically bound by a number of entries instead.
I think you have experiences with such caches, any thoughts?
My experience is that most of the time they are heavily mis-used and make things worse (stressing the GC, causing majors to trigger more often, hence wasting more resources than it saves), but in a few case they're useful.
The memsize can indeed only be cooperative (entry must implement #bytesize) or limited to strings.
I'd looked at the code, and the (C) Map backend seemed to be a standard Hash. So I don't yet understand in what ways a Concurrent::Map can be non-order-preserving.
But yes, for Concurrent::Hash I could probably implement this separately through its standard API calls.
I need this, otherwise my caches will expand without bound. But I note your performance concerns. Perhaps the deletion of old keys should happen periodically rather than after most insertions, limiting memory usage to a range. But there's no bulk equivalent of shift.
I was going to sum the sizes of each Hash/Map entry (with support for a custom size-calc proc if one needs to go deeper) , maybe even not bothering to add the size of the Hash/Map itself.
Sorry, by C I meant MRI. A custom map implementation by other Rubies explains why Map disclaims ordering.
I like the Map API, and probably won't need its iteration methods. Are these the ones that are especially bad for concurrency? Would it be worthwhile to create an OrderedMap with a subset of the map API and a forced Hash backend that is relatively performant, on which I can build automatic size limits.
Then just use Concurrent::Hash.
The cost of ordering is all writes contend on the same pointer compare-and-swap, so the cache line needs to change from CPU core to CPU core for basically every write. With a LRU there is also a write for every get. So you end up with a collection that's anyway no faster than locking around every operation, and then Concurrent::Hash is fine enough for that.
Because I wanted to LRU the keys over a subset of all instantiated Concurrent::Map objects, I ended up implementing this as a LruMap < Map class that has an internal Map array and an LRU ::Hash with [map_number, map_key] keys and nil values. Because all my Map keys are integers, to save space I actually allow these keys to be compacted into native integers.
And because my map values are integer arrays, ObjectSpace.memsize_of is accurate. So I have a free_bytes class method that periodically recovers the requested number of bytes across the least-used entries of all Maps. This recovery quantity can be obtained from system memory usage to minimise swapping.
Because this is now a separate class, there's no need to do a PR — I can make it a separate Gem.
Thanks for all the earlier feedback. I still need to see in production whether I can perform the LRU deletions sufficiently softly to avoid the mentioned GC and CPU cache problems. But it has to be done to prevent unbounded growth.
I see now Benoit where you were going about CPU cache invalidation. Hopefully I'll avoid this with a separate LRU Hash that doesn't rewrite the actual Map values but instead rewrites nil to its map+key key.
Activity
eregon commentedon Dec 8, 2025
Note that
Concurrent::Mapdoes not have ordering and noHash#shiftequivalent, so you probably meanConcurrent::Hashinstead.It sounds pretty easy to make your own on top of
Concurrent::Hashso I guess the question is should that be part of concurrent-ruby or not.@byroot I think you have experiences with such caches, any thoughts?
max_bytesizeis probably quite hard though because how would you find out the memory used by Ruby objects?AFAIK such caches are typically bound by a number of entries instead.
byroot commentedon Dec 8, 2025
My experience is that most of the time they are heavily mis-used and make things worse (stressing the GC, causing majors to trigger more often, hence wasting more resources than it saves), but in a few case they're useful.
The memsize can indeed only be cooperative (entry must implement
#bytesize) or limited to strings.mrj commentedon Dec 8, 2025
Thank you Benoit and Jean for those thoughts.
I'd looked at the code, and the (C)
Mapbackend seemed to be a standardHash. So I don't yet understand in what ways aConcurrent::Mapcan be non-order-preserving.But yes, for
Concurrent::HashI could probably implement this separately through its standard API calls.I was planning to use
ObjectSpace.memsize_ofto calculate memory usage.I need this, otherwise my caches will expand without bound. But I note your performance concerns. Perhaps the deletion of old keys should happen periodically rather than after most insertions, limiting memory usage to a range. But there's no bulk equivalent of
shift.byroot commentedon Dec 8, 2025
You can't. This only give you the size of a single object. e.g.
ObjectSpace.memsize_of([1]) == ObjectSpace.memsize_of(["A" * 999999999]).mrj commentedon Dec 8, 2025
I was going to sum the sizes of each Hash/Map entry (with support for a custom size-calc proc if one needs to go deeper) , maybe even not bothering to add the size of the Hash/Map itself.
eregon commentedon Dec 8, 2025
There is no implementation of Concurrent::Map in C in this repository, what do you mean?
https://github.com/ruby-concurrency/concurrent-ruby/blob/master/lib/concurrent-ruby/concurrent/map.rb happens to use
Hashinternally on CRuby for simplicity, but it's not the case on other Ruby implementations which have a proper concurrent map and therefore no ordering (maintaining order kills concurrency for a map-like data structure).mrj commentedon Dec 8, 2025
Sorry, by C I meant MRI. A custom map implementation by other Rubies explains why Map disclaims ordering.
I like the Map API, and probably won't need its iteration methods. Are these the ones that are especially bad for concurrency? Would it be worthwhile to create an
OrderedMapwith a subset of the map API and a forcedHashbackend that is relatively performant, on which I can build automatic size limits.eregon commentedon Dec 8, 2025
Then just use
Concurrent::Hash.The cost of ordering is all writes contend on the same pointer compare-and-swap, so the cache line needs to change from CPU core to CPU core for basically every write. With a LRU there is also a write for every get. So you end up with a collection that's anyway no faster than locking around every operation, and then
Concurrent::Hashis fine enough for that.mrj commentedon Sep 20, 2026
Because I wanted to LRU the keys over a subset of all instantiated
Concurrent::Mapobjects, I ended up implementing this as aLruMap < Mapclass that has an internalMaparray and an LRU::Hashwith[map_number, map_key]keys andnilvalues. Because all my Map keys are integers, to save space I actually allow these keys to be compacted into native integers.And because my map values are integer arrays,
ObjectSpace.memsize_ofis accurate. So I have afree_bytesclass method that periodically recovers the requested number of bytes across the least-used entries of allMaps. This recovery quantity can be obtained from system memory usage to minimise swapping.Because this is now a separate class, there's no need to do a PR — I can make it a separate Gem.
Thanks for all the earlier feedback. I still need to see in production whether I can perform the LRU deletions sufficiently softly to avoid the mentioned GC and CPU cache problems. But it has to be done to prevent unbounded growth.
mrj commentedon Sep 21, 2026
I see now Benoit where you were going about CPU cache invalidation. Hopefully I'll avoid this with a separate LRU Hash that doesn't rewrite the actual Map values but instead rewrites
nilto its map+key key.