Skip to content

A failed SWR refresh deletes the stale entry #112

Closed

Description

@nathanchase

With swr: true, when the background refresh of an expired entry throws, ocache deletes that entry. The next request then has nothing to fall back on and gets the error.

So during an upstream outage, stale-while-revalidate serves the old value exactly once. Nitro 2 kept serving it until a refresh succeeded.

The same happens to defineCachedHandler when a refresh returns a 5xx: the cached 200 is deleted, and the next visitor gets the 5xx.

import { createMemoryStorage, defineCachedFunction } from 'ocache'

const storage = createMemoryStorage()
let down = false
const fn = defineCachedFunction(async () => {
  if (down) throw new Error('down')
  return 'ok'
}, { storage: () => storage, swr: true, maxAge: 1, onError() {} })

await fn()                                  // 'ok'
await new Promise(r => setTimeout(r, 1100))
down = true
await fn()                                  // 'ok' (stale), refresh fails
await new Promise(r => setTimeout(r, 20))
await fn()                                  // throws 'down'. Expected: 'ok' (stale)

Tested on ocache 0.3.1 (nitro 3.0.261103-rc).

The deletes are in get(): the catch around await current.promise, and the else if (hitIndex >= 0) branch after validate fails.

Suggested fix: when the refresh fails, keep the stale entry (bounded by staleMaxAge if set). Only delete it when the new response succeeded but isn't cacheable, as Nitro 2 did.

Activity

  1. unjica commented on Nov 9, 2026

    @unjica
    Contributor

    I looked into this and wanted to flag a conflict before anyone opens a PR: the eviction is currently intentional and pinned by two regression tests in test/index.test.ts, "SWR evicts stale entry from storage when background revalidation throws" and "... when revalidation result fails validation", both citing nitrojs/nitro#1992 and nitrojs/nitro#4060. Those issues asked for the opposite outcome: a route that now returns 404 or an empty body should stop serving the old page.

    At the same time, .agents/cache.md (the { swr: true, maxAge: 60 } ISR note) says "If refresh fails, the cache continues to serve the last success", which matches what this issue expects. So the code and the design notes disagree right now.

    One way to satisfy both, if that direction sounds right:

    • A refresh that throws (outage, timeout, network error) keeps the stale entry. It stays bounded by staleMaxAge through the existing isFullyExpired check and the storage TTL. ResponseTooLargeError would still evict, since that refresh actually succeeded.
    • A refresh that succeeds but fails validate keeps evicting. For handlers, that covers a 404 or a no-store response, which is the nitro#1992 case.
    • For handlers, a 5xx counts as a failed refresh rather than an uncacheable success, so it keeps the stale 200. This is the part that needs a decision, because cache.ts can't currently tell a 5xx apart from any other value validate rejects.

    Happy to put up a PR along these lines if a maintainer confirms which behavior the two existing tests should end up with.

  2. nathanchase commented on Nov 9, 2026

    @nathanchase
    Author

    .agents/cache.md (the { swr: true, maxAge: 60 } ISR note) says "If refresh fails, the cache continues to serve the last success", which matches what this issue expects. So the code and the design notes disagree right now.

    * A refresh that **throws** (outage, timeout, network error) keeps the stale entry. 
    

    This is exactly right, and was the behavior in Nitro 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions