Implement a Kubernetes Readiness Probe in Go
In distributed systems, especially containerized environments like Kubernetes, ensuring that a service is ready to accept traffic before it's exposed is crucial. Readiness probes are a mechanism to achieve this. This challenge asks you to implement a basic HTTP readiness probe endpoint in a Go web application.
Problem Description
You need to build a simple Go HTTP server that exposes a /healthz endpoint. This endpoint will act as a readiness probe. The server should have an internal state that determines whether it's "ready" to serve requests. Initially, the server should not be ready. You will also implement a mechanism to transition the server's state to "ready" after a short delay or a specific event.
Key Requirements:
- Create an HTTP server using Go's standard
net/httppackage. - Implement a GET endpoint at
/healthz. - When
/healthzis called:- If the server is "ready", it should return an HTTP status code of
200 OKand an empty body. - If the server is not "ready", it should return an HTTP status code of
503 Service Unavailableand an empty body.
- If the server is "ready", it should return an HTTP status code of
- The server should start in a "not ready" state.
- Implement a mechanism to transition the server to a "ready" state after an initial delay of 5 seconds. This simulates a service starting up and performing initialization tasks.
Expected Behavior:
- When the server starts, calls to
/healthzwill result in a503 Service Unavailable. - After 5 seconds, the server's state will change to "ready".
- Subsequent calls to
/healthzwill result in a200 OK.
Edge Cases:
- Ensure concurrent access to the readiness state is handled safely (though for this simple example, a basic approach might suffice).
Examples
Example 1:
Scenario: Server starts and /healthz is called immediately.
Request: GET /healthz
Response:
Status Code: 503 Service Unavailable
Body: (empty)
Explanation: The server has just started and is not yet ready.
Example 2:
Scenario: Server starts, waits for 6 seconds, and then /healthz is called.
Request: GET /healthz
Response:
Status Code: 200 OK
Body: (empty)
Explanation: The server has completed its initialization and is now ready to serve traffic.
Constraints
- The server must listen on port
8080. - The readiness state transition must occur after a fixed delay of 5 seconds from the server's start.
- Use only Go's standard library.
Notes
- Consider how you will manage the "readiness" state of your application. A simple boolean flag protected by a mutex is a common approach for managing shared mutable state in Go.
- The
time.Sleep()function can be used to simulate the initialization delay. - The
http.ListenAndServe()function is key to starting your HTTP server. - Think about how Kubernetes would interact with this endpoint. It would periodically poll
/healthz. If it receives a503, it knows not to send traffic. If it receives a200, it knows the pod is ready.