How would you design an API to fetch the top 20 sales records from a database, ensuring high performance and data freshness, especially when the data resides in a DMS?
💡 Model Answer
Designing a fast API to fetch the top 20 sales records requires careful consideration of query performance, caching, and data freshness. First, ensure the sales table has an index on the column(s) used for ranking (e.g., sales_amount, sale_date). Use a SELECT query with ORDER BY and LIMIT 20. If the data resides in a DMS (Data Migration Service) or a replicated read replica, route the API to the read replica to offload the primary. For caching, employ an in‑memory cache (Redis or Memcached) keyed by a consistent hash of the query parameters. Invalidate the cache on write events or after a short TTL (e.g., 30 seconds) to balance freshness and performance. Consider using a materialized view or a pre‑aggregated table if the top 20 changes infrequently. The API should expose pagination and filtering options, and use HTTP/2 or gRPC for lower latency. Finally, monitor query latency and cache hit rates, and adjust indexes or cache TTL accordingly.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500