response_filesystem_cache
Synopsis
Response Filesystem Cache is a highly performant, general-purpose caching engine that allows Drupal to serve API endpoints and dynamic pages at the speed of static files.
By capturing Drupal responses and saving them as physical files in the public filesystem (with dynamically inferred MIME-type extensions), this module allows your web server (Nginx/Apache) to serve subsequent requests directly. This completely bypasses the PHP and Drupal bootstrap process, resulting in microsecond response times for your most heavily trafficked read-only endpoints.
How It Works
Instead of heavily modifying your controllers, this module uses a lightweight Event Subscriber architecture:
- Request Interception: When a configured path is requested, the module redirects the user to the expected physical file location.
- Web Server Delivery: If the file exists, Nginx/Apache serves it instantly.
- Dynamic Generation: If the file does not exist (resulting in a 404), the module catches the exception, processes the original Drupal request, infers the correct file extension using the
devanych/mime-typeslibrary based on theContent-Typeheader, saves the file to disk, and delivers the response. - Automatic Invalidation: Whenever standard Drupal caches are rebuilt (e.g.,
drush cr), the corresponding physical files and directories are automatically purged.
Requirements
- Drupal 10 or 11
devanych/mime-types(^2.1) - Automatically installed via Composer.
Configuration & Usage
This module acts as a silent engine. Out of the box, it does nothing until another module opts-in using Drupal's Plugin Discovery system.
To cache responses from your custom modules, simply create a {module_name}.response_cache.yml file in the root of your module.
Example (store_api.response_cache.yml):
store_api_products:
# The Drupal path to intercept
path_prefix: '/api/v1/products/'
# The physical location to store the generated files
uri_prefix: 'public://response_cache/store/products/'
store_api_categories:
path_prefix: '/api/v1/categories/'
# If uri_prefix is omitted, the system defaults to storing these in a directory
# matching the path (e.g., public://api/v1/categories/) with the appropriate
# MIME type extension (like .json).
store_static_pages:
path_prefix: '/pages/'
# HTML responses here will automatically be stored in public://pages/
# with a .html extension based on their Content-Type.Once configured and caches are rebuilt, a request to /api/v1/products/shoes will seamlessly generate and serve from public://response_cache/store/products/shoes.json.
Best Practices
For maximum performance, you can configure your web server (Nginx/Apache) with rewrite rules to map the incoming API requests directly to the sites/default/files/... directory. This allows the web server to handle the initial routing without Drupal even handling the first redirect event.