Tell us about a situation where you managed to improve the efficiency of a REST API.
sobes.tech AI
Answer from AI
In one of my Go projects, I improved REST API efficiency by optimizing request processing and reducing response time.
What was done:
-
Caching: added caching for frequently requested data using in-memory cache (e.g., Redis or built-in map with mutex) to reduce database load.
-
Parallel processing: used goroutines for parallel execution of independent operations within request handling.
-
Database query optimization: rewrote SQL queries, added indexes to reduce execution time.
-
Using context (context.Context): for timely cancellation of long-running requests and resource release.
Example code with caching and goroutines:
var cache = make(map[string]string)
var mu sync.RWMutex
func getData(key string) (string, error) {
mu.RLock()
if val, ok := cache[key]; ok {
mu.RUnlock()
return val, nil
}
mu.RUnlock()
// Simulate database request
data := "Data from DB for " + key
mu.Lock()
cache[key] = data
mu.Unlock()
return data, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
// Parallel data retrieval
var wg sync.WaitGroup
var result string
var err error
wg.Add(1)
go func() {
defer wg.Done()
result, err = getData(key)
}()
wg.Wait()
if err != nil {
http.Error(w, "Error", http.StatusInternalServerError)
return
}
w.Write([]byte(result))
}
As a result, the API response time decreased, and the load on the database was reduced, which increased the overall service performance.