Limit list length in redis Limit list length in redis database database

Limit list length in redis


After every lpush, call ltrim to trim the list to 10 elements

See http://redis.io/commands/ltrim


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:

LPUSH mylist 1random_int = some random number between 1-5if random_int == 1:  # trim my list with 1/5 chance   LTRIM mylist 0 10

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,

  • pushes the item to the list,
  • keep the size fixed to 10,
  • and returns the most recent 10 elements

in a transaction.

MULTILPUSH list "item1"LTRIM list 0 9LRANGE list 0 9EXEC