You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> Because caching is the last mile for low latency distributed systems!
57
+
58
+
Enabling proper caching strategies will drastically reduce the latency of your system, as it reduces network round-trips, database calls and CPU processing.
59
+
For our services, we are talking here about improvements in response times from `X ms` to `~2ms`, as an example.
60
+
61
+
### Enabling cache for service endpoints
62
+
Enabling an response to be cached just requires the
63
+
`x-cache-timeout` header to be set:
64
+
```js
65
+
res.setHeader('x-cache-timeout', '1 hour')
66
+
```
67
+
> Here we use the [`ms`](`https://www.npmjs.com/package/ms`) package to convert timeout to seconds. Please note that `millisecond` unit is not supported!
68
+
69
+
Example on service using `restana`:
70
+
```js
71
+
service.get('/numbers', (req, res) => {
72
+
res.setHeader('x-cache-timeout', '1 hour')
73
+
74
+
res.send([
75
+
1, 2, 3
76
+
])
77
+
})
78
+
```
79
+
80
+
### Invalidating caches
81
+
Services can easily expire cache entries on demand, i.e: when the data state changes. Here we use the `x-cache-expire` header to indicate the cache entries to expire using a matching pattern:
82
+
```js
83
+
res.setHeader('x-cache-expire', '*/numbers')
84
+
```
85
+
> Here we use the [`matcher`](`https://www.npmjs.com/package/matcher`) package for matching patterns evaluation.
86
+
87
+
Example on service using `restana`:
88
+
```js
89
+
service.patch('/numbers', (req, res) => {
90
+
// ...
91
+
92
+
res.setHeader('x-cache-expire', '*/numbers')
93
+
res.send(200)
94
+
})
95
+
```
96
+
97
+
### Custom cache keys
98
+
Cache keys are generated using: `req.method + req.url`, however, for indexing/segmenting requirements it makes sense to allow cache keys extensions.
99
+
100
+
For doing this, we simply recommend using middlewares to extend the keys before caching checks happen:
101
+
```js
102
+
service.use((req, res, next) => {
103
+
req.cacheAppendKey= (req) =>req.user.id// here cache key will be: req.method + req.url + req.user.id
104
+
returnnext()
105
+
})
106
+
```
107
+
> In this example we also distinguish cache entries by `user.id`, very common case!
108
+
109
+
### Disable cache for custom endpoints
110
+
You can also disable cache checks for certain requests programmatically:
0 commit comments