lifecycle_management.py
How to Run
lifecycle_management.py
What This Example Demonstrates
Initialization Phase (@on_boot
)
- Environment Validation - Checks required environment variables before starting
- Database Setup - Establishes database connections asynchronously
- Cache Initialization - Sets up in-memory caches for performance
- Metrics Collection - Starts background monitoring systems
Task Processing (@on_task
)
- Uses resources initialized during boot phase
- Demonstrates database queries and cache usage
- Shows how lifecycle management enables shared resources
Cleanup Phase (@on_shutdown
)
- Data Persistence - Saves cache data before shutdown
- Connection Cleanup - Gracefully closes database connections
- Metrics Finalization - Stops monitoring and saves reports
- Memory Cleanup - Clears sensitive data from memory
Key Features
Sequential Execution
Handlers execute in registration order, allowing proper dependency management
Mixed Async/Sync
Seamlessly combines synchronous and asynchronous initialization/cleanup tasks
Error Handling
Boot failures prevent startup, shutdown errors are logged but donβt block exit
Resource Management
Proper initialization and cleanup of shared resources like databases and caches
Best Practices Shown
- Environment Validation - Check requirements early in boot process
- Resource Dependencies - Initialize resources in correct order
- Graceful Cleanup - Properly close connections and save data on shutdown
- Error Resilience - Handle cleanup gracefully even if resources are unavailable
- Memory Management - Clear sensitive data during shutdown