Creating Graceful Shutdown Handlers
Microservices need graceful shutdowns to flush logs, close DB pools, and finish active web requests before terminating 🛑.
class ServerLifecycle:
def __init__(self):
self.is_running = True
def shutdown(self):
print("Flushing buffers and closing DB pools... 🛑")
self.is_running = False
server = ServerLifecycle()
server.shutdown()
print(f"Running status: {server.is_running} ✅")
# 105. Creating Graceful Shutdown Handlers Microservices need graceful shutdowns to flush logs, close DB pools, and finish active web requests before terminating 🛑. ```python class ServerLifecycle: def __init__(self): self.is_running = True def shutdown(self): print("Flushing buffers and closing DB pools... 🛑") self.is_running = False server = ServerLifecycle() server.shutdown() print(f"Running status: {server.is_running} ✅") ``` Combining a lifecycle class with `signal.signal(signal.SIGTERM, ...)` ensures Docker containers stop gracefully within the standard termination grace period! 🛑 --- ### Question Why are graceful shutdown handlers critical in cloud container environments like Docker or Kubernetes? 🧠- [ ] a. To complete in-flight transactions and cleanly release database connections before SIGKILL 🛑 - [ ] b. To delete the Linux operating system kernel - [ ] c. To prevent the CPU from running at 100% clock speed - [ ] d. Because containers cannot restart unless explicitly shut down by Python --- ### Challenge Create class `GracefulApp` with `self.active = True` and method `terminate(self)` that sets `self.active = False`. Instantiate, call `terminate()`, print `app.active`. 🎯 <details> <summary>Solution</summary> ```python class GracefulApp: def __init__(self): self.active = True def terminate(self): self.active = False app = GracefulApp() app.terminate() print(app.active) ``` </details>