How to Cache 502 and 504 Errors with a Web Accelerator
server web accelerator
Published: 2023-10-10

This is a method to cache 502 (Bad Gateway) and 504 (Gateway Timeout) errors using the Sakura Cloud Web Accelerator.

High access to non-cacheable content or even cacheable content can cause the origin server to return 502 (Bad Gateway) or 504 (Gateway Timeout) errors due to high server load.

Normally, error responses from nginx do not include Cache-Control headers, so they are not cached, which means the load on the origin server continues.

Therefore, by adding Cache-Control headers to error responses in the nginx configuration, you can cache them with the web accelerator to reduce the load on the origin server.

This assumes the use of nginx on the origin with an upstream app server, etc.

nginx Configuration

    location / {
        error_page 502 = @webaccel_handle_502;
        error_page 504 = @webaccel_handle_504;
        # omitted
    }
    location @webaccel_handle_502 {
        add_header Cache-Control "s-maxage=30" always;
        return 502;
    }
    location @webaccel_handle_504 {
        add_header Cache-Control "s-maxage=30" always;
        return 504;
    }

With the above configuration, when nginx returns a 502 or 504 error response, it will add the Cache-Control header with s-maxage=30, allowing the web accelerator to cache it for 30 seconds.

This helps to cache temporary errors and reduce the load on the origin server.

memo

  • When adding headers to responses, including error_page responses, you need to include the always parameter.