Skip to content

Instantly share code, notes, and snippets.

@hdknr
Created October 11, 2024 07:37
Show Gist options
  • Select an option

  • Save hdknr/d73630b702b019970f93f48d4fa6dbe2 to your computer and use it in GitHub Desktop.

Select an option

Save hdknr/d73630b702b019970f93f48d4fa6dbe2 to your computer and use it in GitHub Desktop.
gunicorn

Gunicorn

max_requests / max_requests_jitter

Gunicornでメモリリークを避けるために子プロセスを定期的に再起動するには、max_requestsmax_requests_jitterの設定を利用するのが効果的です。これにより、一定のリクエスト数を処理した後にワーカープロセスが自動的に再起動されます。

以下はその設定方法です:

  1. max_requests: 各ワーカープロセスが再起動される前に処理するリクエストの最大数を指定します。
  2. max_requests_jitter: 再起動のタイミングをランダム化するためのオプションです。これにより、全てのワーカープロセスが同時に再起動されるのを防ぎます。

Gunicornの設定ファイル(例:gunicorn.conf.py)に以下のように追加します:

# gunicorn.conf.py

max_requests = 1000  # 1000リクエストごとに再起動
max_requests_jitter = 50  # 再起動タイミングをランダム化

または、コマンドラインで起動する際にオプションとして指定することもできます:

gunicorn --max-requests 1000 --max-requests-jitter 50 myapp:app

これにより、各ワーカープロセスは1000回のリクエストを処理した後、ランダムに最大50回のリクエストを追加で処理してから再起動されます¹(https://qiita.com/ryu22e/items/2668a2243a5191bcdc78)²(https://zenn.dev/xknzw/articles/d2d337ae2f8966)³(https://qiita.com/_konishi_/items/1dc2bbfc386f57d06934)。

この設定により、メモリリークの影響を最小限に抑えつつ、サービスの安定性を保つことができます。

¹(https://qiita.com/ryu22e/items/2668a2243a5191bcdc78): gunicorn(>=19.2)ではmax_requestsと一緒にmax_requests_jitterも使おう - Qiita ²(https://zenn.dev/xknzw/articles/d2d337ae2f8966): gunicorn syncワーカーの全体像メモ - Zenn ³(https://qiita.com/_konishi_/items/1dc2bbfc386f57d06934): gunicornでディスク使用量が増え続ける現象への対処 - Qiita

(1) gunicorn(>=19.2)ではmax_requestsと一緒にmax_requests_jitterも使おう. https://qiita.com/ryu22e/items/2668a2243a5191bcdc78. (2) gunicorn syncワーカーの全体像メモ - Zenn. https://zenn.dev/xknzw/articles/d2d337ae2f8966. (3) gunicornでディスク使用量が増え続ける現象への対処 - Qiita. https://qiita.com/_konishi_/items/1dc2bbfc386f57d06934.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment