diff --git a/docs/how-to-guides/online-server-performance-tuning.md b/docs/how-to-guides/online-server-performance-tuning.md index 4807ab000ad..6826913d377 100644 --- a/docs/how-to-guides/online-server-performance-tuning.md +++ b/docs/how-to-guides/online-server-performance-tuning.md @@ -185,6 +185,10 @@ feast serve \ **Sizing rule of thumb:** Start with `workers = 2 × vCPU + 1` and allocate ~256–512 MB memory per worker. Monitor RSS per process and adjust. If p99 latency is high under load, add more workers or scale horizontally rather than increasing connections. {% endhint %} +### Garbage collection pauses + +Every full Python garbage collection walks all live objects, including the registry and feature definitions that live for the whole process. In a worker this blocks the event loop, and while it runs every waiting request stalls. The stall shows up as a slow online store read. With `--gc-freeze` (or `feature_server.gc_freeze: true` in `feature_store.yaml`) the server runs `gc.freeze()` after it has loaded the registry and before the workers start, so full collections skip these objects and stay short. Try it if p99.9 latency has spikes that the online store does not explain. + --- ## Registry cache tuning diff --git a/docs/reference/feature-servers/python-feature-server.md b/docs/reference/feature-servers/python-feature-server.md index bed50cb1cf0..f8b79e233d5 100644 --- a/docs/reference/feature-servers/python-feature-server.md +++ b/docs/reference/feature-servers/python-feature-server.md @@ -30,6 +30,7 @@ Key performance options: - `--max-requests-jitter`: Jitter to prevent thundering herd on worker restart (default: 50) - `--registry_ttl_sec, -r`: Registry refresh interval in seconds. Higher values reduce overhead but increase staleness (default: 60) - `--keep-alive-timeout`: Keep-alive connection timeout in seconds (default: 30) +- `--gc-freeze`: Run `gc.freeze()` after startup to shorten full garbage collection pauses. See [Garbage collection pauses](../../how-to-guides/online-server-performance-tuning.md#garbage-collection-pauses) (default: off) ### Performance Best Practices diff --git a/sdk/python/feast/cli/serve.py b/sdk/python/feast/cli/serve.py index 4cb676b9934..469aa4fdc62 100644 --- a/sdk/python/feast/cli/serve.py +++ b/sdk/python/feast/cli/serve.py @@ -116,6 +116,12 @@ show_default=True, help="Enable the Metrics Server", ) +@click.option( + "--gc-freeze", + is_flag=True, + show_default=True, + help="Run gc.freeze() after startup so full garbage collections skip the registry and other startup objects", +) @click.pass_context def serve_command( ctx: click.Context, @@ -132,6 +138,7 @@ def serve_command( tls_key_path: str, tls_cert_path: str, metrics: bool, + gc_freeze: bool, ): """Start a feature server locally on a given port.""" if (tls_key_path and not tls_cert_path) or (not tls_key_path and tls_cert_path): @@ -158,6 +165,7 @@ def serve_command( tls_key_path=tls_key_path, tls_cert_path=tls_cert_path, registry_ttl_sec=registry_ttl_sec, + gc_freeze=gc_freeze, ) diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index d408b1b0eb3..82b492f2ae6 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -14,6 +14,7 @@ import asyncio import functools +import gc import os import sys import threading @@ -1306,6 +1307,21 @@ def _gunicorn_child_exit(server, worker): feast_metrics.mark_process_dead(worker.pid) +def _freeze_gc() -> None: + """Move the objects that exist now out of the cyclic garbage collector. + + The registry, feature definitions and protobuf classes are built once and + live until the process exits, yet every full collection walks all of them. + In a worker that walk blocks the event loop, so the requests waiting on it + look like slow online store reads. gc.collect() runs first so no garbage is + frozen. Called in the gunicorn master before the workers are forked, so + every worker starts frozen, including one restarted by --max-requests. + """ + gc.collect() + gc.freeze() + logger.info(f"gc.freeze(): {gc.get_freeze_count()} objects frozen") + + def start_server( store: "feast.FeatureStore", host: str, @@ -1320,6 +1336,7 @@ def start_server( tls_key_path: str, tls_cert_path: str, metrics: bool, + gc_freeze: bool = False, ): if (tls_key_path and not tls_cert_path) or (not tls_key_path and tls_cert_path): raise ValueError( @@ -1331,6 +1348,7 @@ def start_server( metrics_from_config = getattr(metrics_cfg, "enabled", False) metrics_active = metrics or metrics_from_config + gc_freeze_active = gc_freeze or getattr(fs_cfg, "gc_freeze", False) uses_gunicorn = sys.platform != "win32" if metrics_active: flags = feast_metrics.build_metrics_flags(metrics_cfg) @@ -1369,13 +1387,18 @@ def start_server( if tls_key_path and tls_cert_path: options["keyfile"] = tls_key_path options["certfile"] = tls_cert_path - FeastServeApplication( + application = FeastServeApplication( store=store, metrics_enabled=metrics_active, **options - ).run() + ) + if gc_freeze_active: + _freeze_gc() + application.run() else: import uvicorn app = get_app(store, registry_ttl_sec) + if gc_freeze_active: + _freeze_gc() if tls_key_path and tls_cert_path: uvicorn.run( app, diff --git a/sdk/python/feast/feature_store.py b/sdk/python/feast/feature_store.py index 917454d19ad..6d9eb88b43a 100644 --- a/sdk/python/feast/feature_store.py +++ b/sdk/python/feast/feature_store.py @@ -4778,6 +4778,7 @@ def serve( tls_key_path: str = "", tls_cert_path: str = "", registry_ttl_sec: int = 60, + gc_freeze: bool = False, ) -> None: """Start the feature consumption server locally on a given port.""" type_ = type_.lower() @@ -4800,6 +4801,7 @@ def serve( tls_key_path=tls_key_path, tls_cert_path=tls_cert_path, registry_ttl_sec=registry_ttl_sec, + gc_freeze=gc_freeze, ) def get_feature_server_endpoint(self) -> Optional[str]: diff --git a/sdk/python/feast/infra/feature_servers/base_config.py b/sdk/python/feast/infra/feature_servers/base_config.py index b16d14686bb..9a0c678f720 100644 --- a/sdk/python/feast/infra/feature_servers/base_config.py +++ b/sdk/python/feast/infra/feature_servers/base_config.py @@ -143,6 +143,12 @@ class BaseFeatureServerConfig(FeastConfigBaseModel): """Prometheus metrics configuration. Set ``metrics.enabled: true`` or pass the ``feast serve --metrics`` CLI flag to activate.""" + gc_freeze: StrictBool = False + """Run ``gc.freeze()`` after the server has loaded the registry and before + the workers start. Full garbage collections then skip these long-lived + objects, which keeps the event loop pauses they cause short. Same as + ``feast serve --gc-freeze``.""" + feature_logging: Optional[FeatureLoggingConfig] = None """ Feature logging configuration """ diff --git a/sdk/python/tests/unit/test_feature_server_gc_freeze.py b/sdk/python/tests/unit/test_feature_server_gc_freeze.py new file mode 100644 index 00000000000..f2e7f445c37 --- /dev/null +++ b/sdk/python/tests/unit/test_feature_server_gc_freeze.py @@ -0,0 +1,63 @@ +import sys +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +pytestmark = pytest.mark.skipif( + sys.platform == "win32", reason="gunicorn is not used on Windows" +) + + +def _start_server(feature_server_config, gc_freeze: bool): + """Run start_server with the gunicorn app mocked; return the call order.""" + from feast.feature_server import start_server + + calls = MagicMock() + store = MagicMock() + store.config = SimpleNamespace( + feature_server=feature_server_config, auth_config=MagicMock() + ) + application = MagicMock() + application.run.side_effect = lambda: calls.run() + with ( + patch("feast.feature_server.feast_metrics"), + patch("feast.feature_server.str_to_auth_manager_type"), + patch("feast.feature_server.init_security_manager"), + patch("feast.feature_server.init_auth_manager"), + patch("feast.feature_server.FeastServeApplication", return_value=application), + patch("feast.feature_server.gc.collect", side_effect=calls.collect), + patch("feast.feature_server.gc.freeze", side_effect=calls.freeze), + ): + start_server( + store=store, + host="127.0.0.1", + port=6566, + no_access_log=True, + workers=1, + worker_connections=1000, + max_requests=1000, + max_requests_jitter=50, + keep_alive_timeout=30, + registry_ttl_sec=60, + tls_key_path="", + tls_cert_path="", + metrics=False, + gc_freeze=gc_freeze, + ) + return [name for name, _, _ in calls.mock_calls] + + +def test_cli_flag_freezes_before_workers_start(): + assert _start_server(None, gc_freeze=True) == ["collect", "freeze", "run"] + + +def test_config_enables_freeze(): + config = SimpleNamespace(metrics=None, gc_freeze=True) + assert _start_server(config, gc_freeze=False) == ["collect", "freeze", "run"] + + +def test_no_freeze_by_default(): + config = SimpleNamespace(metrics=None, gc_freeze=False) + assert _start_server(config, gc_freeze=False) == ["run"] + assert _start_server(None, gc_freeze=False) == ["run"]