Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

svdv22's avatar

Best practice/solution for caching filtered results

Hello,

I have a page on my website with about a 1000 records that barely change, like a blog. I would like to cache this. The thing is, users can filter and sort these records. A quick calculating thought me that there are 10.000 different filtered sets.

So there are 10.000 different ways to filter and order about 1000 records.

Question 1 Right now I'm thinking about creating a hash of the filterset and use that as part of the cachekey to cache all these items.

Is this the way to go? Or do you have other experiences/solutions to this problem?

Question 2 There's also the problem of pagination. I might have up to 10.000 different keys (shouldn't be a problem for redis) still, I do prefer storing the whole 1000 results unpaginated and then paginate the collection after retrieving everything from cache.

Is that okay, or again: is there a different approach I might consider? Quick sight question: how does Redis handle storing 1000 (pretty big) eloquent models in one kay/value pair? Should be fine?

Question 3 Also, people can search in very specific fields of my models. I intend to not cache search queries (just too many different options, users can type in anything), but instead fetch the results and perform a search on that (right before pagination, see questions 2). Everybody okay with that? :p

Question 4 Performing all the queries takes about a second, even after optimizing them. I think that's too long (keep in mind the whole page load is even longer!). Now this is mostly just the first time, after that, results are cached. Still, I would like to build the cache before the user gets there.

Thing is, saving 1 model, possible effects all 10.000 different sorting and filtering options. Any tips/best practices on this?

Any input and experiences from others is very welcome :)

0 likes
4 replies
jlrdw's avatar

Caching doesn't make any sense.

You are logged into your bank, while logged in wife makes a 1000.00 dollar deposit. You click on checking again, but sorry the 1000.00 isn't there.

Just use laravel and forget about caching, it is 99.9999 percent useless on dynamic data.

oraclec's avatar

@jlrdw you can cache with an observer to update your cache whenever there is a change in your database

svdv22's avatar

It's not dynamic data*. The filtering that sorts the data is dynamic. So I think caching does make sense!

  • Changes about twice a month (mostly an addition, not alteration of existing content)
phpboyza's avatar

Hi, I know this was a long time ago. However, I'm faced with a very similar issue. My SQL queries are heavily optimized but the load on the server occasionally spikes and sometimes causes the entire site to lag briefly. So my question is, was REDIS ultimately the solution to your issue here?

Please or to participate in this conversation.