Files
cpp-httplib/docs-src/pages/ja/cookbook/s20-keep-alive.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
Bring the READMEs and the docs pages (en and ja) in line with the
current header:

- Fix the client sample that does not compile, the Transfer-Encoding
  statement for default headers, the verifier callback comment, the
  thread pool spawn rule, the sanitize_filename description, and the
  inverted Accept-Encoding sentence.
- Describe recent behaviour: TLS errors behind Read/Write failures,
  Host validation, Connection: close for a body without length,
  content_reader rules, refused CONNECT, WebSocketClient proxies,
  CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and
  the payload limit of the Stream API.
- Complete the API references of WebSocket, WebSocketClient and the
  stream:: helpers, and the SSE reconnect rules.
- Fix cookbook pages: keychain loading on every backend, received Close
  status, a multipart sample that trusted the client's file name, an
  echo sample that sent binary as text, SNI, pre-request handler scope,
  stop() with WebSocket handlers, and the thread pool notes.
- Restore the mutex in the LLM app's Chapter 5 code.
2026-10-18 10:13:57 -04:00

2.5 KiB

title, order, status
title order status
S20. Keep-Aliveを調整する 39 draft

httplib::ServerはHTTP/1.1のKeep-Aliveを自動で有効にしています。クライアントから見ると接続が再利用されるので、TCPハンドシェイクのコストを毎回払わずに済みます。挙動を細かく調整したいときは、2つのセッターを使います。

設定できる項目

API デフォルト 意味
set_keep_alive_max_count 100 1本の接続で受け付けるリクエストの最大数(0 で無制限)
set_keep_alive_timeout 5秒 アイドル状態の接続を閉じるまでの秒数

基本の使い方

httplib::Server svr;

svr.set_keep_alive_max_count(20);
svr.set_keep_alive_timeout(10); // 10秒

svr.listen("0.0.0.0", 8080);

set_keep_alive_timeout()はstd::chronoの期間を取るオーバーロードもあります。

using namespace std::chrono_literals;
svr.set_keep_alive_timeout(10s);

チューニングの目安

アイドル接続が多くてリソースを食う
タイムアウトを短めに設定すると、遊んでいる接続がすぐに切れてスレッドが解放されます。

svr.set_keep_alive_timeout(2s);

APIが集中的に呼ばれて接続再利用の効果を最大化したい
1接続あたりのリクエスト数を増やすと、ベンチマークの結果が良くなります。

svr.set_keep_alive_max_count(1000);

とにかく接続を使い回したくない
set_keep_alive_max_count(1)にすると、1リクエストごとに接続が閉じます。デバッグや互換性検証以外ではあまりおすすめしません。

スレッドプールとの関係

Keep-Aliveでつながりっぱなしの接続は、その間ずっとワーカースレッドを1つ占有します。スレッドプールは負荷に応じて最大スレッド数(デフォルトはベースの4倍)までスレッドを増やしますが、開いている接続数がそれを超えると、新しい接続はどれかが閉じるまでキューで待たされます。スレッド数の調整はS21. マルチスレッド数を設定するを参照してください。

Note: クライアント側の挙動はC14. 接続の再利用とKeep-Aliveの挙動を理解するを参照してください。サーバーがタイムアウトで接続を切っても、クライアントは自動で再接続します。