Flexible caching (SWR) | laravel-responsecache-go | Spatie       

 SPATIE  

laravel-responsecache-go
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-responsecache-go](https://spatie.be/docs/laravel-responsecache-go/v1)  Basic-usage  Flexible caching (SWR)

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-responsecache-go/v1) 

  Flexible caching (SWR)    
- [ Introduction ](https://spatie.be/docs/laravel-responsecache-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-responsecache-go/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-responsecache-go/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-responsecache-go/v1/questions-issues)
- [ Testing ](https://spatie.be/docs/laravel-responsecache-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-responsecache-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-responsecache-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-responsecache-go/v1/support-us)
- [ About us ](https://spatie.be/docs/laravel-responsecache-go/v1/about-us)

Basic usage
-----------

- [ Caching responses ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/caching-responses)
- [ Flexible caching (SWR) ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/flexible-caching)
- [ Preventing caching ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/preventing-caching)
- [ Clearing the cache ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/clearing-the-cache)
- [ Using tags ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/using-tags)
- [ Events ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/events)

Advanced usage
--------------

- [ Custom cache profiles ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/custom-cache-profiles)
- [ Creating a replacer ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/creating-a-replacer)
- [ Customizing the serializer ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/customizing-the-serializer)
- [ Customizing the hasher ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/customizing-the-hasher)
- [ Configuration ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/configuration)

 Flexible caching (SWR)
======================

###  On this page 

1. [ Using middleware ](#content-using-middleware)
2. [ Using attributes ](#content-using-attributes)
3. [ Refresh lifecycle ](#content-refresh-lifecycle)

Sometimes you want fast responses without serving data that's too outdated. Flexible caching uses the stale-while-revalidate pattern. It serves a cached response while refreshing it after the response has been sent.

```
route.Get("/api/posts", posts.Index).
    Middleware(responsecache.FlexibleCacheResponse{
        Lifetime: time.Hour,
        Grace:    5 * time.Minute,
        Tags:     []string{"posts", "api"},
    })
```

This is what happens with the configuration above.

- For the first 60 minutes, the cached response is served directly.
- Between 60 and 65 minutes, the stale response is served and a refresh is scheduled after sending it.
- After 65 minutes, the cache has expired. The next request waits for a fresh response.

`Lifetime` is the fresh duration. `Grace` is additional time, not the total lifetime. Both are Go `time.Duration` values. The fresh and total-expiry boundaries are exact. Failed or ineligible refresh responses leave the stale entry intact until its original expiry. Bypass, excluded headers, custom profiles, tags, minimum requests and replacers apply to flexible caching too.

Using middleware
--------------------------------------------------------------------------------------------------------

Use the struct on a route or group.

```
stats := route.Middleware(responsecache.FlexibleCacheResponse{
    Lifetime: 5 * time.Minute,
    Grace:    time.Hour,
    Tags:     []string{"stats"},
})
stats.Get("/dashboard", dashboard.Show)
stats.Get("/stats", dashboard.Stats)
```

Using attributes
--------------------------------------------------------------------------------------------------------

Go has no attributes. A group applies the same middleware to multiple handlers.

Refresh lifecycle
-----------------------------------------------------------------------------------------------------------

The Go port uses `Request.OnFinish`, not a raw goroutine or a serialized queue job. The stale bytes are flushed first. Refresh invokes only the downstream handler and middleware with an uncanceled, one-minute context. A one-minute Laravel cache lock prevents simultaneous refreshes. The lock and entries must use a shared store to coordinate multiple processes.

Use read-only handlers. The original response is already sent and outer middleware is not rerun. Refresh must not depend on consuming request bodies, temporary uploads or changing session cookies. A process crash can lose a scheduled refresh. In that case a later stale request retries, or the next expired request regenerates synchronously.

Clearing while a refresh runs cannot resurrect the old entry. A refresh keeps the invalidation versions read by its request and writes only into that old namespace.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
