You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/source/build-with-bentoml/lifecycle-hooks.rst
+41Lines changed: 41 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -148,3 +148,44 @@ Use the ``@bentoml.on_shutdown`` decorator to specify a method as a shutdown hoo
148
148
@bentoml.on_shutdown
149
149
async def async_shutdown(self):
150
150
print("Async cleanup actions on Service shutdown.")
151
+
152
+
Health check hooks
153
+
^^^^^^^^^^^^^^^^^^
154
+
155
+
Health check hooks allow you to specify custom logic for determining when your Service is healthy and ready to handle requests.
156
+
This is particularly useful when your Service depends on external resources that need to be checked before the Service can be considered operational.
157
+
158
+
You can define the following methods in your service class to implement health checks:
159
+
160
+
- ``__is_alive__``: This method is called to check if the Service is alive. It should return a boolean value indicating the Service's health status. This responds to the ``/livez`` endpoint.
161
+
- ``__is_ready__``: This method is called to check if the Service is ready to handle requests. It should return a boolean value indicating the Service's readiness status. This responds to the ``/readyz`` endpoint.
162
+
163
+
Both can be asynchronous functions.
164
+
165
+
For example:
166
+
167
+
.. code-block:: python
168
+
169
+
import bentoml
170
+
171
+
@bentoml.service(workers=4)
172
+
class HookService:
173
+
def __init__(self) -> None:
174
+
self.db_connection = None
175
+
self.cache = None
176
+
177
+
@bentoml.on_startup
178
+
def init_resources(self):
179
+
self.db_connection = setup_database()
180
+
self.cache = setup_cache()
181
+
182
+
def __is_ready__(self) -> bool:
183
+
# Check if required resources are available
184
+
if self.db_connection is None or self.cache is None:
185
+
return False
186
+
returnself.db_connection.is_connected() and self.cache.is_available()
187
+
188
+
When you call the ``/readyz`` endpoint, it returns:
189
+
190
+
- HTTP 200 if the Service is ready (the hook returns ``True``)
191
+
- HTTP 503 if the Service is not ready (the hook returns ``False``)
0 commit comments