Proxy Cache Troubleshooting: ARC, Nginx Locks, and X-Fetch
Proxy Cache Troubleshooting: ARC, Nginx Locks, and X-Fetch
Search
Ask the AI

Proxy Cache Troubleshooting: ARC, Nginx Locks, and X-Fetch

Reverse-proxy caches and CDNs reuse eligible responses across clients. Diagnose HTTP reuse rules, concurrent origin requests at expiry, and latency in cache metadata or storage separately. A HIT identifies a cache hit at one layer; it does not establish correct variants, user isolation, or freshness.

1. Cache Replacement and ARC

A cache may evict objects when it reaches a configured capacity limit, whether its storage is memory, disk, or a hierarchy. Least Recently Used (LRU) can use a doubly-linked list and a hash map. A one-time sequential scan may displace otherwise useful cached objects.

ARC (Adaptive Replacement Cache) and W-TinyLFU are possible cache policies; check which policy a particular proxy implements. ARC’s \(L_1\) tracks objects referenced only once in its recent history, while \(L_2\) tracks repeatedly accessed objects and their history. The resident portions are conventionally \(T_1\) and \(T_2\); the identifier-only ghost portions are \(B_1\) and \(B_2\). The parameter \(p\) is the target size of resident list \(T_1\).

ARC adjusts \(p\) in response to ghost-list hits: a hit in \(B_1\) increases it, and a hit in \(B_2\) decreases it. The following update applies only to the \(B_1\)-hit branch, where \(c\) counts equal-sized cache pages. The original paper evaluates hit rates on workload traces; measure deployment gains against the actual request sequence and cache capacity.

$$ p_{new} = \min\left(c, p_{old} + \max\left(1, \frac{|B_2|}{|B_1|}\right)\right) $$

2. Nginx Shared Memory (shm) Architecture & Lock Contention

In Nginx’s multiprocess model, a keys_zone shared-memory region holds cache-key and usage metadata, while response data is normally stored in files. Workers need synchronisation for shared metadata; this does not imply a kernel lock operation on every cache hit.

The Nginx slab allocator, including ngx_slab_alloc, allocates shared memory in size classes. Exhaustion and allocation failures remain possible. In builds with atomic-operation support, the Nginx 1.28.0 shared mutex ngx_shmtx_t tries to acquire the lock and spins, then waits on a POSIX semaphore when supported and available, or yields to the scheduler. It is not a fixed spin-then-futex path.

Preserved incorrect illustration; do not use as an implementation: the old block below is not Nginx source. It incorrectly puts ngx_shmtx_wakeup on the waiting path and omits the actual sem_wait and ngx_sched_yield branches. Its original source/futex comments are also inaccurate. See Nginx 1.28.0 ngx_shmtx.c for the implementation.


// Nginx Spinlock acquisition for Cache Key insertion
// Source: ngx_shmtx.c
void ngx_shmtx_lock(ngx_shmtx_t *mtx) {
    ngx_uint_t  i, n;
    for ( ;; ) {
        // Atomic compare-and-swap (fast path)
        if (*mtx->lock == 0 && ngx_atomic_cmp_set(mtx->lock, 0, ngx_pid)) {
            return;
        }
        // CPU Pause to reduce Cache Line Bouncing / MESI bus traffic
        for (n = 1; n < mtx->spin; n <<= 1) {
            for (i = 0; i < n; i++) {
                ngx_cpu_pause(); 
            }
            if (*mtx->lock == 0 && ngx_atomic_cmp_set(mtx->lock, 0, ngx_pid)) {
                return;
            }
        }
        // Fallback to kernel futex yield
        ngx_shmtx_wakeup(mtx);
    }
}

The shared metadata mutex and proxy_cache_lock solve different problems. The latter coordinates filling a new element by cache key and can reduce concurrent origin fetches for that key. Set proxy_cache_lock_timeout and proxy_cache_lock_age against origin latency: a timeout can release waiting requests, and lock age can admit another fetch. This is not a guarantee of one origin request across the whole system.

3. X-Fetch: Early Refresh Scaled by Recomputation Time

When a hot object expires, concurrent requests may recompute it together and cause a cache stampede. X-Fetch reduces that overlap through independent probabilistic early-expiration decisions. It comes from the paper by Vattani, Chierichetti, and Lowenstein. Using it in a particular cache or proxy requires the refresh decision and the associated per-object metadata. A missing object or an empty cache after restart still requires a cold-start strategy.

Let the current time be \(t\), expiry be \(t_{exp}\), and remaining lifetime be \(\Delta t = \max(0,t_{exp}-t)\). Let \(c_{rec} > 0\) be the previous recomputation duration and \(\beta > 0\) a tuning parameter. For each request, draw an independent uniform random value \(U\) from \((0,1)\). X-Fetch recomputes when \(t-\beta c_{rec}\log U \ge t_{exp}\). Its refresh probability is therefore:

$$ P(\text{fetch}) = \exp\left(-\frac{\Delta t}{\beta c_{rec}}\right). $$

Before expiry, the condition is equivalent to \(U \le \exp(-\Delta t/(\beta c_{rec}))\). The probability rises as remaining lifetime falls and reaches 1 at expiry. With remaining lifetime and recomputation duration fixed, increasing \(\beta\) triggers earlier, more frequent refreshes. TTL sets expiry; it does not replace recomputation time. The paper’s simple implementation recomputes synchronously in the requesting process; background refresh needs separate scheduling. The policy reduces overlapping recomputation risk, without guaranteeing a normal distribution of origin traffic or zero latency spikes.

The standalone Python example below implements that decision. Use one unit for all times and a positive measured recomputation duration; document a positive floor when timer resolution produces zero. The input u is this request’s independent random draw. The function schedules no background task and supplies no cross-process lock.

import math

def xfetch_should_refresh(now, expiry, recompute_seconds, beta, u):
    if recompute_seconds <= 0 or beta <= 0:
        raise ValueError("recompute_seconds and beta must be positive")
    if not 0 < u < 1:
        raise ValueError("u must be an independent draw in (0, 1)")
    remaining = expiry - now
    return remaining <= 0 or -beta * recompute_seconds * math.log(u) >= remaining

4. eBPF: Measuring Function-Call Duration

Pair a function-entry uprobe with a return uretprobe to measure the duration of a selected userspace function. This requires resolvable binary symbols or address offsets. With asynchronous I/O, ngx_http_file_cache_read can return NGX_AGAIN before I/O completes, so one invocation’s duration is not total disk-blocking time. Cache-node allocation may call ngx_slab_calloc_locked / ngx_slab_alloc_locked directly; probing only ngx_slab_alloc misses those paths.

If 10ms is chosen as a deployment-specific allocation-call alert, crossing it shows that the measured path is slow. Correlate it with scheduling, lock waits, allocation failures, and shared-zone occupancy before diagnosing fragmentation. Increasing keys_zone=name:size expands metadata space, not disk-cache capacity. Adjust it after establishing a capacity problem, then repeat the measurement under comparable load.

5. Configuration and Observation Checks

  • Vary and Variants: Match the request fields named by Vary before reusing a response. Check the proxy’s existing variant handling before changing an explicit cache key. Normalise Accept-Encoding only while preserving representation semantics; gzip and br responses are not interchangeable.
  • Cache-Fill Locks and Coalescing: Evaluate proxy_cache_lock for same-key misses, recording waits, timeouts, lock age, and actual origin fetches.
  • Early Refresh and Stale Serving: Evaluate X-Fetch, proxy_cache_background_update, and the conditions for serving stale responses separately. Choose them against freshness requirements and measure origin peaks.
  • Allocation-Path Observation: Select userspace allocation, lock, and I/O probes for the problem at hand. Record symbols, build version, coverage, and tracing overhead before choosing a sampling rate.

6. Cache Failure Troubleshooting Matrix

Old content can come from the browser, CDN edge, reverse proxy, or application cache. The matrix below lists a header or metric for each layer so readers can locate the source of stale content.

Symptom Evidence to collect Likely layer Fix or verification
Published page still shows old HTML cf-cache-status, Age, x-fastcgi-cache, and query-bypass result. CDN edge or origin FastCGI cache. Compare ordinary URL with a cache-busting URL, then purge the correct layer.
Cache HIT serves the wrong variant Vary, cache key, cookie use, language header, and device rule. Incorrect cache key normalization. Minimize Vary and explicitly include only required dimensions.
Origin load spikes after expiry MISS rate, concurrent requests, revalidation count, and lock contention. Cache stampede or missing stale-while-revalidate behavior. Add request coalescing, stale serving, or probabilistic early refresh.
Private data appears cached Cache-Control, cookies, authorization headers, and response key. Shared cache stored a personalized response. Use private, no-store, or bypass rules for authenticated content.

The matrix lists hypotheses to check against logs at each layer. Preserve every Vary dimension needed for correct variants. Response directives such as private and no-store restrict future storage; they do not purge previously cached copies. If a private response reached the wrong user, stop reusing and remove those objects, repair the key or bypass rules, and test again.

A cache-busting query returning newer content is a diagnostic lead, not proof that the edge is responsible. Cookie and query bypass depend on deployment rules. Request Cache-Control: no-cache asks for validation, not a universal bypass. HEAD can inspect response headers; use GET for the complete response and compare cache headers with origin logs.

References

Leave a Reply

Scroll down