brotli-asgi
Brotli response-compression middleware for ASGI apps like Starlette and FastAPI
Repository Health
Technical Analysis
brotli-asgi provides BrotliMiddleware, an ASGI middleware that adds Brotli response compression to any ASGI application, including Starlette, FastAPI, and Quart. Brotli typically achieves faster and denser compression than GZip, so responses are smaller over the wire while remaining cheap to produce.
It is designed as a drop-in replacement for the GZipMiddleware bundled with Starlette, honoring the client’s Accept-Encoding header and applying compression only above a configurable minimum size. Streaming responses are handled correctly, making it a low-effort way to reduce bandwidth for JSON APIs and text-heavy endpoints.
What You Get
- BrotliMiddleware, an ASGI middleware that Brotli-compresses eligible responses
- A drop-in replacement for Starlette’s GZipMiddleware with familiar configuration
- Tunable quality, mode, and minimum-size thresholds to balance ratio against CPU
- Correct handling of standard and streaming responses, respecting Accept-Encoding
Common Use Cases
- Shrinking JSON API responses from FastAPI or Starlette services to save bandwidth
- Replacing GZip compression with denser Brotli on text-heavy HTTP endpoints
- Compressing large server responses before they cross slow or metered networks
- Adding response compression to any ASGI app without touching route handlers
Under The Hood
Architecture - The package is a single module, brotli_asgi/init.py (about 205 lines), implementing BrotliMiddleware as a pure ASGI callable that wraps an inner app. It intercepts the ASGI send channel: on the response-start message it inspects the client’s Accept-Encoding and buffers the body, then either passes it through unchanged (small or unsupported responses) or streams Brotli-compressed chunks while rewriting Content-Encoding and Content-Length headers. A dedicated responder path handles streaming bodies so compression works without buffering the entire response in memory.
Tech Stack - Pure Python built on the ASGI spec, using the official brotli (or brotlicffi) bindings to Google’s Brotli library for the actual compression. It has no framework lock-in and works with any ASGI server such as Uvicorn or Hypercorn; requirements are declared in requirements.txt and it is packaged with setup.py.
Code Quality - The project mirrors Starlette’s own GZipMiddleware structure, which keeps the implementation idiomatic and easy to audit, and ships a tests.py suite exercising compression, header handling, and streaming. CI runs via GitHub Actions. The codebase is small, mature, and stable, though development activity is now low.
API Design - Usage matches Starlette’s middleware convention exactly: add Middleware(BrotliMiddleware) with optional quality, mode, and minimum_size parameters. Developers already familiar with GZipMiddleware need no new concepts, and the README shows ready-to-copy Starlette and FastAPI examples.