Cache
A cache
section enables caching of responses from backend servers. The cache resides in memory and does not store state on the filesystem, which means that it will not persist beyond a reload.
- Cache limitations
-
The cache won't store and won't deliver objects in these cases:
If the response is not a 200
If the response contains a Vary header
If the Content-Length and the size of the headers is greater than
max-object-size
If the response is not cacheable
If the request is not a GET
If the HTTP version of the request is smaller than 1.1
If the request contains an Authorization header
Cache section examples
In the following configuration sample, we define a cache
section labeled mycache and adjust the total cache memory size, the maximum size of a single item in the cache, and how long an item should live in the cache.
cache mycache # Total size of the cache in MB total-max-size 4 # Max size of any single item in bytes max-object-size 10 # Time to live for each item in seconds # This can be overridden with a Cache-Control header max-age 30
When the load balancer serves a cached item, it can return the response directly to the client without needing to contact the backend server. To use the defined cache we add the http-response cache-store
directive on our backend section and the http-request cache-use
directive to use cached responses.
cache mycache
total-max-size 4095
max-object-size 10000
max-age 30
backend servers
# Use mycache for all requests
http-request cache-use mycache
# Store http requests in cache
http-response cache-store mycache
server s1 192.168.1.25:80 check
server s2 192.168.1.26:80 check
Conditionally caching requests
Often, caching all responses is unnecessary. You can select which resources to cache by using an if
statement on the http-request cache-use
directive.
Use the path_beg
fetch to check whether the requested path begins with /api/ and only cache the response if it does:
cache mycache
total-max-size 4095
max-object-size 10000
max-age 30
backend servers
# Use mycache if the request path begins with /api/
http-request cache-use mycache if { path_beg /api/ }
http-response cache-store mycache
server s1 192.168.1.25:80 check
server s2 192.168.1.26:80 check
See also
Next up
Http-errors