[PATCH 2 of 2] Upstream: improved stale-if-error handling

Maxim Dounin mdounin at mdounin.ru
Sun Jan 11 22:59:00 UTC 2026


# HG changeset patch
# User Maxim Dounin <mdounin at mdounin.ru>
# Date 1768085378 -10800
#      Sun Jan 11 01:49:38 2026 +0300
# Node ID a62443b2ea523cb2ce2ff5c4f964f15e3a12e94e
# Parent  59592781f10b2d4f7e63e4dfcf6b865b5ee19254
Upstream: improved stale-if-error handling.

Following 7702:7015f26aef90, "Cache-Control: stale-if-error=..." is
ignored for HTTP 4xx and 5xx responses, even if these are expected to
be treated as errors per u->conf->next_upstream configuration, notably
when switching to the next upstream server wasn't possible.

This makes it non-trivial to configure things with stale response usage
for a limited time per stale-if-error as long as an actual error is detected
not by the cache itself, but by an intermediate proxy, even if the
particular status code is configured to be mostly equivalent to network
errors, such as with "proxy_next_upstream error timeout http_502".

With this change, as long as the particular error is considered to be
a failure per u->conf->next_upstream, stale-if-error information from
the cached response is now used.

diff --git a/src/http/ngx_http_upstream.c b/src/http/ngx_http_upstream.c
--- a/src/http/ngx_http_upstream.c
+++ b/src/http/ngx_http_upstream.c
@@ -2626,7 +2626,9 @@ ngx_http_upstream_test_next(ngx_http_req
 #if (NGX_HTTP_CACHE)
 
         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
-            && (u->conf->cache_use_stale & un->mask))
+            && ((u->conf->cache_use_stale & un->mask)
+                || ((u->peer_state & NGX_PEER_FAILED)
+                    && r->cache->stale_error)))
         {
             ngx_int_t  rc;
 



More information about the nginx-devel mailing list