I'm using redis lists and pushing to new items to a list. The problem is I really only need the most recent 10 items in a list.
I'm using lpush
to add items to a list and lrange
to get the most recent 10.
Is there anyway to drop items after a certain number? I'll end up with lists that may have 1,000's of items and can cause performance issues with latency.
Thank you!
You can use LTRIM intermittently after any LPUSH, no need to call LTRIM after every LPUSH as that would add to overall latency in your app ( though redis is really fast, but you can save lots of LPUSH operations )
Here is a pseudo code to achieve an LTRIM on approximately every 5th LPUSH:
Though your list may grow to be a few elements more than 10 elements at times, but it will surely get truncated at regular intervals. This approach is good for most practical purposes and saves a lot of LTRIM operations, keeping your pushes fast.
The following code,
in a transaction.
After every
lpush
, callltrim
to trim the list to 10 elementsSee http://redis.io/commands/ltrim
Just an alternative. According to official doc of
LPUSH
, it returns the length of the list after the push operations. You can set a threshold length likek
(in your case k > 10) and callLTRIM
when returned length is bigger thank
. Sample pseudo code as follows:It's more controllable than random method. Greater
k
triggers lessLTRIM
but with more memory cost. You can adjustk
according to how often you want to callLTRIM
since calling extra command is more expensive.