Feed cache: Use circular queue for zero-alloc of memory #1384
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Why are these changes needed?
TL;DR: The cache performance can be improved by 11x with circular queue
The existing feed cache uses a plain slice for cached data.
When it has to be updated with newly fetched data from DB, it may involve in significant amount of memory allocation and movement, e.g. in the existing code:
c.setCacheSegment(append(segment.data, data...), segment.start, end)
for appending andc.setCacheSegment(append(data, segment.data...), start, segment.end)
for prepending.This PR introduces a circular queue for caching the data and completely eliminates the need to re-allocate the memory for the cache (it always operate on pre-allocated queue).
Perf Benchmark
Benchmarked the cache extension backward (i.e.
c.setCacheSegment(append(data, segment.data...), start, segment.end)
case) for different cache sizes.When there is 200k items in cache, performance improvement is 11x.
Note that 200k is a very practical number, for example, we cache for 2 days of batches, which will be 2 * 24 * 3600 = 172,800 batches in cache.
Before:
After:
Checks