What is Varnish Cache?
In today’s e-commerce world, the number of popular products is increasing day by day. When users search using the best-seller or best-reviewed filters, the same product is clicked millions of times and often appears before users without any changes.
In this case, constantly making database requests for the same response or having the product come from Elasticsearch will be a method that will exhaust our resources and slow us down.In this phase, we need to integrate a technology that will allow us to bring our products to our users quickly and without tiring our resources. Yes, now we can meet Varnish Cache for our needs.
Varnish Cache is an HTTP accelerator used to speed up dynamic content generation on high-traffic websites.It typically caches static content (images, CSS, JS files) and dynamic content (such as database queries or API requests) on the server, thus reducing the load on the server.In this way, instead of responding to the same requests over and over again, it keeps these responses in memory. In this way, less server resources are used and the end user is given a faster response.
Get Zaidekaymak’s stories in your inbox
Join Medium for free to get updates from this writer.
The working principle of varnish cache, which is generally used for page caching, is as follows:
- The client sends a request.
- Varnish examines the incoming request and if it is in the cache, it has the capacity to respond directly to the request without going to the server.
- If the requested data is not in the cache, Varnish forwards the request to the backend server and caches the response from the server and sends the response to the client.
Now here is a short example in golang:
package main
import (
"fmt"
"net/http"
"time"
)
var cache = make(map[string]string)
func handler(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path
if content, found := cache[url]; found {
fmt.Fprintf(w, "Varnish cache aktif: %s\n", content)
} else {
content := fmt.Sprintf("İçerikler: %s", url, time.Now())
cache[url] = content
fmt.Fprintf(w, "Varnish cache aktif değil: %s\n", content)
}
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)
}We created a map called cache, which is used to cache URLs, just like Varnish does. The heandler function checks every incoming request. If there is cached content for the URL, it sends it directly. Otherwise, it creates new content, caches it, and responds.
Thank you…









