Skip to content
RED SAGSkills
mediumBackend Developer interview question

An API endpoint is slow because it runs a heavy database query. How would you add caching, and how do you keep the cache correct?

What the interviewer wants to hear

  • Measure first and choose what to cache
  • Cache-aside with Redis and a TTL
  • Invalidation on writes: delete or update keys
  • Cache key design including user or tenant where needed
  • Handle stampedes and stale data risks; HTTP caching where possible

Model answer

First I would measure, using EXPLAIN and traces, to see if the query can simply be fixed with an index. If it is still expensive and read often, I would use cache-aside with Redis: on a read, check the key; on a miss, run the query, store the result with a TTL, and return it. The key must include everything that changes the result, such as user id, tenant id and query parameters, otherwise one user may see another user data. On writes, I update the database and then delete the related keys, so the next read rebuilds fresh data; the TTL is a safety net. For hot keys I protect against stampedes with a short lock or serving stale while refreshing. For public data I would also use HTTP caching headers or a CDN. I would monitor hit rate and latency.

Can you answer it under time pressure?

Take a timed medium round and get scored on every answer.

Start mock interview

More medium Backend Developer questions