Expand description
Server-side HTTP response caching middleware for Tower.
This crate provides Tower middleware for caching HTTP responses on the server side. Unlike client-side caching, this middleware caches your own application’s responses to reduce load and improve performance.
§Key Features
- Response-first architecture: Caches based on response headers, not requests
- Preserves request context: Maintains all request extensions (path params, state, etc.)
- Handler-centric: Calls the handler first, then decides whether to cache
- RFC 7234 compliant: Respects Cache-Control, Vary, and other standard headers
- Reuses existing infrastructure: Leverages
CacheManagertrait fromhttp-cache
§Example
use http::{Request, Response};
use http_body_util::Full;
use bytes::Bytes;
use http_cache_tower_server::ServerCacheLayer;
use tower::{Service, Layer};
let manager = MemoryCacheManager::new();
let layer = ServerCacheLayer::new(manager);
// Apply the layer to your Tower service
let service = tower::service_fn(|_req: Request<Full<Bytes>>| async {
Ok::<_, std::io::Error>(
Response::builder()
.header("cache-control", "max-age=60")
.body(Full::new(Bytes::from("Hello, World!")))
.unwrap()
)
});
let mut cached_service = layer.layer(service);§Vary Header Support
This cache enforces Vary headers using http-cache-semantics. When a response includes
a Vary header, subsequent requests must have matching header values to receive the cached
response. Requests with different header values will result in cache misses.
For example, if a response has Vary: Accept-Language, a cached English response won’t be
served to a request with Accept-Language: de.
§Security Warnings
This is a shared cache - cached responses are served to ALL users. Improper configuration can leak user-specific data between different users.
§Authorization and Authentication
This cache does not check for Authorization headers or session cookies in requests.
Caching authenticated endpoints without proper cache key differentiation will cause
user A’s response to be served to user B.
Do NOT cache authenticated endpoints unless you use a CustomKeyer that includes
the user or session identifier in the cache key:
// Example: Include session ID in cache key
let keyer = CustomKeyer::new(|req: &Request<()>| {
let session = req.headers()
.get("cookie")
.and_then(|v| v.to_str().ok())
.and_then(|c| extract_session_id(c))
.unwrap_or("anonymous");
format!("{} {} session:{}", req.method(), req.uri().path(), session)
});§General Security Considerations
- Never cache responses containing user-specific data without user-specific cache keys
- Validate cache keys to prevent cache poisoning attacks
- Be careful with header-based caching due to header injection risks
- Consider the
privateCache-Control directive for user-specific responses (automatically rejected by this cache)
Structs§
- Cache
Metrics - Cache performance metrics.
- Cached
Response - A cached HTTP response with metadata.
- Custom
Keyer - Custom keyer that uses a user-provided function.
- Default
Keyer - Default keyer that uses HTTP method and path.
- Query
Keyer - Keyer that includes query parameters in the cache key.
- Server
Cache Layer - Tower layer for server-side HTTP response caching.
- Server
Cache Options - Configuration options for server-side caching.
- Server
Cache Service - Tower service that implements response caching.
Enums§
- Response
Body - Response body types.
Traits§
- Keyer
- A trait for generating cache keys from HTTP requests.