Chris
Chris

Reputation: 14218

Is it worth to cache simple queries with Redis?

  1. I was wondering if it is worth caching queries like:

    SELECT * FROM users WHERE id = 1

  2. If not, then the same should also be the case for complex queries, since they will be cached by the DB cache anyways.

  3. Would it ever make sense to cache a single DB query with Redis? Or would I only gain benefits from caching the results of multiple queries (e.g. an entire route)

  4. Is Redis (in memory) faster than the DB cache (also in memory). In that case it would also make sense to cache single queries in Redis, but I assume DB and Redis cache should perform similarly.

Upvotes: 5

Views: 2877

Answers (2)

Lowe Andaya
Lowe Andaya

Reputation: 15

I think caching data is worth it if you need to be more efficient. It can also reduce costs because you will have lesser reads in the database especially for me who love No-SQL databases. but the biggest benefit is how you're query becomes faster because there will be less traffic and lesser latency.

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562368

Query results are worth caching if your app is likely to read it from cache instead of running the SQL query again. Or if you need the result more quickly than any SQL query can run.

Also the cost of an SQL query is not necessarily detrimental to your app performance. An SQL query like SELECT * FROM users WHERE id = 1 is simple and efficient, being a primary key lookup of at most one row (assuming id is the primary key).

A complex query against large ranges of data can take a lot longer if you do it in SQL, so the relative benefit of reading the cached result will be greater.

But even a simple query run a million times per hour can be costly. If you run the query so frequently that it's holding back your app performance, a cache is a good strategy.

There are many variables, and they depend on your specific app behavior and constraints. There's no way someone can answer this for you.

  • How often does the data in the database change, making the cached copy out of date?
  • How efficient is the SQL query? Is it a simple query that will be pretty quick anyway, or is it a complex query that may take full seconds when you run the SQL version?
  • Is your app able to tolerate the time it takes to run the SQL query? Of course all apps say they want the results "as fast as possible" but that's not a measurable requirement. Is the SQL query fast enough?
  • How frequently do you run the query? At a certain scale, you need to use minor optimizations that would not be worth the time to code if the query is used infrequently.

Upvotes: 6

Related Questions