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.
More medium Backend Developer questions
- You need to rename a column in a large production table that the live app uses. How do you do it without downtime?
- How do you change a public API without breaking existing clients, such as old mobile app versions?
- Users say one API endpoint has become slow in production. How do you find and fix the cause?
- Sending emails and generating PDF invoices makes your checkout API slow. How would you move this work to the background?
- How would you add rate limiting to a public API that runs on many servers?
- You are asked to review the security of a REST API before launch. What would you check?
- Your service receives webhooks from a payment provider. How do you make handling them secure and reliable?
- When would you choose Kafka and when RabbitMQ for messaging between services?
- How would you design an API that lets users upload large files, such as videos of several gigabytes?