# How RomM Uses X-Accel-Redirect for High-Performance File Serving

> Learn how RomM leverages X-Accel-Redirect for high-performance file serving. This header offloads transfers to Nginx for zero-copy I/O and byte-range support, controlled by Python authentication.

- Repository: [The RomM Project/romm](https://github.com/rommapp/romm)
- Tags: performance
- Published: 2026-07-07

---

**RomM uses the `X-Accel-Redirect` header to offload large ROM file transfers from the Python backend to Nginx, enabling zero-copy I/O and automatic byte-range support while maintaining full authentication control.**

RomM is a FastAPI-based retro game management application that serves large binary ROM files to clients. Rather than streaming these files through the Python process, the application returns a special HTTP header that instructs the Nginx reverse proxy to handle the actual file delivery, dramatically improving throughput and resource efficiency.

## What is X-Accel-Redirect?

`X-Accel-Redirect` is an Nginx-specific HTTP header that allows an upstream application server to trigger an internal redirect to a local file. When Nginx receives this header from the backend, it immediately begins serving the specified file directly from disk, bypassing the application server entirely for the actual data transfer. This mechanism is sometimes called "internal redirection" or "offloading" in web server terminology.

## Why RomM Uses X-Accel-Redirect

The RomM architecture documented in [`docs/BACKEND_ARCHITECTURE.md`](https://github.com/rommapp/romm/blob/main/docs/BACKEND_ARCHITECTURE.md) highlights three primary reasons for implementing this pattern:

- **Zero-copy I/O performance**: Nginx serves files directly from the kernel's page cache using `sendfile`, eliminating the need for Python to read data into memory and write it back out. This reduces CPU usage and memory pressure on the ASGI workers.

- **Automatic range request support**: Nginx natively handles HTTP `Range` headers, allowing clients to seek inside audio/video files or resume interrupted downloads without the backend implementing complex byte-range logic.

- **Security separation**: The FastAPI backend retains complete control over authentication and authorization checks before returning the header, while Nginx handles the unprivileged task of bit transmission.

## Implementation in the RomM Codebase

### The FileRedirectResponse Class

The core implementation resides in [`backend/utils/nginx.py`](https://github.com/rommapp/romm/blob/main/backend/utils/nginx.py), where the `FileRedirectResponse` class constructs the specialized response. This class inherits from FastAPI's `Response` and injects the necessary headers:

```python

# backend/utils/nginx.py (lines 55-82)

from fastapi import Response
from urllib.parse import quote

class FileRedirectResponse(Response):
    """Response class for serving a file download by using the X-Accel-Redirect header."""
    
    def __init__(
        self,
        download_path: Path,
        filename: str,
        disposition: str = "attachment",
        **kwargs,
    ):
        kwargs.setdefault("headers", {}).update(
            {
                "Content-Disposition": f"{disposition}; filename*=UTF-8''{quote(filename)}; "
                                        f"filename=\"{quote(filename)}\"",
                "X-Accel-Redirect": quote(str(download_path)),
            }
        )
        super().__init__(**kwargs)

```

The class takes a `download_path` (the absolute filesystem path), a `filename` for the client-side save dialog, and a `disposition` argument that can be set to `"inline"` for media streaming or `"attachment"` for downloads.

### The Download Endpoint

The ROM file serving endpoint in [`backend/endpoints/roms/files.py`](https://github.com/rommapp/romm/blob/main/backend/endpoints/roms/files.py) utilizes this response class. After verifying user permissions and locating the file, it returns an empty-body response with the redirect header:

```python

# backend/endpoints/roms/files.py (line 100 and surrounding context)

from backend.utils.nginx import FileRedirectResponse
from fastapi import APIRouter, Depends, HTTPException

router = APIRouter()

@router.get("/api/roms/download/{id}/{file_name}")
async def download_rom(
    id: int,
    file_name: str,
    # ... authentication dependencies

):
    # Authorization and file existence checks occur here

    
    return FileRedirectResponse(
        download_path=absolute_path_to_rom,
        filename=file_name,
        disposition="attachment",
    )

```

## How It Works at Runtime

The file serving process follows this specific sequence:

1. A client requests a ROM via the `/api/roms/download/{id}/{file_name}` endpoint.

2. The FastAPI endpoint performs authentication and authorization checks, verifying the user has access to the requested resource.

3. Upon validation, the endpoint instantiates `FileRedirectResponse` with the absolute filesystem path.

4. FastAPI returns an HTTP response with an empty body, containing only headers including `X-Accel-Redirect` with the internal file path.

5. Nginx intercepts the response, strips the `X-Accel-Redirect` header, and serves the file directly from disk to the client.

Because the Python process sends only a tiny header response, it immediately becomes available to handle new requests while Nginx efficiently manages the large file transfer.

## Summary

- RomM implements `X-Accel-Redirect` in [`backend/utils/nginx.py`](https://github.com/rommapp/romm/blob/main/backend/utils/nginx.py) via the `FileRedirectResponse` class.
- The header offloads file serving from FastAPI to Nginx, enabling zero-copy I/O.
- Nginx automatically handles byte-range requests for video/audio streaming without backend code changes.
- The backend maintains full control over authentication before delegating the file transfer.
- ROM files are served from the endpoint in [`backend/endpoints/roms/files.py`](https://github.com/rommapp/romm/blob/main/backend/endpoints/roms/files.py) using this mechanism.

## Frequently Asked Questions

### What is X-Accel-Redirect in RomM?

`X-Accel-Redirect` is an HTTP header returned by RomM's FastAPI backend that instructs the Nginx reverse proxy to serve a file directly from the filesystem. This allows the Python application to handle authentication and business logic while Nginx manages the efficient delivery of large ROM files.

### Does RomM stream ROM files through Python?

No. RomM explicitly avoids streaming large files through the Python process. Instead, the backend returns a tiny `X-Accel-Redirect` response, and Nginx performs the actual file delivery using kernel-level optimizations like `sendfile`.

### Where is the X-Accel-Redirect logic implemented in RomM?

The logic is implemented in [`backend/utils/nginx.py`](https://github.com/rommapp/romm/blob/main/backend/utils/nginx.py) within the `FileRedirectResponse` class. This class constructs the header and is consumed by the ROM download endpoint in [`backend/endpoints/roms/files.py`](https://github.com/rommapp/romm/blob/main/backend/endpoints/roms/files.py).

### How does X-Accel-Redirect improve performance?

By using `X-Accel-Redirect`, RomM eliminates the need for Python to read ROM data into memory and write it to the socket. Nginx serves files directly from disk with zero-copy I/O, reducing CPU usage and memory consumption while supporting concurrent downloads more efficiently.