The before code has no health checks, so the orchestrator cannot detect if the service is stuck or not ready. The after code adds two endpoints: /health/liveness to confirm the service is alive, and /health/readiness to indicate if it is ready to serve traffic. The readiness endpoint returns 503 until the service finishes initialization, preventing traffic routing prematurely.
### Before: No probes, service always assumed healthy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello World'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
### After: Adding liveness and readiness endpoints
from flask import Flask, jsonify
app = Flask(__name__)
service_ready = False
@app.route('/')
def home():
if not service_ready:
return 'Service not ready', 503
return 'Hello World'
@app.route('/health/liveness')
def liveness():
# Check if service process is alive
return jsonify(status='alive')
@app.route('/health/readiness')
def readiness():
# Check if service is ready to serve traffic
if service_ready:
return jsonify(status='ready')
else:
return jsonify(status='not ready'), 503
# Simulate readiness after some initialization
import threading, time
def set_ready():
global service_ready
time.sleep(5) # simulate startup delay
service_ready = True
threading.Thread(target=set_ready).start()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)