django / django/new-features

Application lifespan hooks for managing long-lived async resources

Open
#132 1 comment 2 reactions 0 assignees View on GitHub
Async
Dominant language
No language data
Stars
188
Forks
7
PR merge metrics
No merged PRs in 30d

Description

### Code of Conduct

- [x] I agree to follow Django's Code of Conduct

### Feature Description

Django currently lacks a built-in mechanism for managing the lifecycle of async resources (e.g., Redis, Elasticsearch, HTTP clients).

### Problem

Although Django supports ASGI, it does not implement lifespan events (startup/shutdown), making it difficult to:

- initialize async clients once at application startup
- properly close connections during shutdown

As a result, developers are forced to rely on non-idiomatic and fragile solutions such as middleware workarounds or custom ASGI wrappers.

```python
class ASGILifespanMiddleware:
def __init__(
self,
app,
on_startup = None,
on_shutdown = None,
):
self.app = app
self.on_startup = on_startup or []
self.on_shutdown = on_shutdown or []

async def __call__(self, scope, receive, send):
if scope["type"] == "lifespan":
while True:
message = await receive()
if message["type"] == "lifespan.startup":
for callback in self.on_startup:
try:
await callback()
except Exception as e:
logging.exception(f"Startup callback failed: {e}")
await send({"type": "lifespan.startup.complete"})
elif message["type"] == "lifespan.shutdown":
for callback in self.on_shutdown:
try:
await callback()
except Exception as e:
logging.exception(f"Shutdown callback failed: {e}")
await send({"type": "lifespan.shutdown.complete"})
return
else:
await self.app(scope, receive, send)
```

### Request or proposal

proposal

### Additional Details

_No response_

### Implementation Suggestions

As an example, Django could add an `app_shutdown` signal to provide a native, consistent hook for cleaning up resources during application shutdown in `ASGI` environments.

Contributor guide

No contributing guide indexed for this repository

Research direction

No files, tests, or implementation entry points are named. Review Django's ASGI application lifecycle and lifespan events, then compare the proposal with existing signal and application-lifecycle mechanisms. Done requires an agreed design for native startup and shutdown handling before implementation can be scoped.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.