# RuntimeError: Cannot add middleware after an application has started

- **ID:** `python/starlette-middleware-order-500`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

add_middleware is called after the ASGI app has begun handling requests, e.g. inside a startup event or a route.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **** (93% success)
   ```
   Register middleware at module level before the app starts:
app.add_middleware(GZipMiddleware)
   ```
2. **** (85% success)
   ```
   Use lifespan for startup logic, not middleware registration.
   ```

## Dead Ends

- **** — Startup runs after the middleware stack is built; the error is raised. (90% fail)
- **** — The middleware is never applied, so behavior silently differs. (75% fail)
